diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/OWNERS_FORCE_SUBMIT_APPROVERS b/western_ai/usa/tensorflow/tensorflow/compiler/OWNERS_FORCE_SUBMIT_APPROVERS new file mode 100644 index 0000000000000000000000000000000000000000..59e7e4c0fd73166300333e4ddca88d7f03b41b8b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/OWNERS_FORCE_SUBMIT_APPROVERS @@ -0,0 +1,19 @@ +# This file contains the list of senior ICs in the XLA team who can +# approve force submits in addition to manager approval. See +# go/foundations-force-submit-policy for full policy. + +// go/keep-sorted start +andydavis +asabne +berkin +chenyin +jikimjikim +jsreeram +ksmurthy +majnemer +masonchang +mkuper +pifon +pizzud +// go/keep-sorted end + diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..94b93156c6701acbe263fc990ba90a0e83a3404a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.cc @@ -0,0 +1,183 @@ +/* Copyright 2021 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/mlir/tfrt/translate/mlrt/test_utils.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/tfrt/mlrt/attribute/attribute.h" +#include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h" +#include "tensorflow/core/tfrt/mlrt/bytecode/kernel.h" +#include "tensorflow/core/tfrt/mlrt/interpreter/context.h" +#include "tensorflow/core/tfrt/mlrt/interpreter/interpreter_testutil.h" + +namespace mlrt { +namespace testing { + +absl::StatusOr EncodeAttribute(const tensorflow::AttrValue& attr) { + if (attr.has_b()) { + std::string result; + result.resize(sizeof(uint8_t)); + uint8_t v = attr.b(); + std::memcpy(result.data(), &v, sizeof(v)); + return result; + } + + if (attr.has_i()) { + std::string result; + result.resize(sizeof(int64_t)); + int64_t v = attr.i(); + std::memcpy(result.data(), &v, sizeof(v)); + return result; + } + + if (attr.has_f()) { + std::string result; + result.resize(sizeof(float)); + float v = attr.f(); + std::memcpy(result.data(), &v, sizeof(v)); + return result; + } + + if (attr.has_s()) { + return attr.s(); + } + + if (attr.has_list()) { + if (attr.list().s_size() > 0) { + mlrt::bc::Buffer buffer; + mlrt::bc::Allocator allocator(&buffer); + auto ctor = mlrt::bc::New>( + &allocator, attr.list().s_size()); + + for (int i = 0; i < attr.list().s_size(); ++i) { + ctor.ConstructAt(i, attr.list().s(i)); + } + + return std::string(buffer.data(), buffer.size()); + } + } + + if (attr.has_tensor()) { + mlrt::bc::Buffer buffer; + mlrt::bc::Allocator allocator(&buffer); + + tensorflow::Tensor tensor; + if (!tensor.FromProto(attr.tensor())) { + return absl::InvalidArgumentError("Invalid tensor proto."); + } + + auto tensor_attr_ctor = mlrt::bc::New( + &allocator, tensor.dtype()); + + auto shape = tensor.shape().dim_sizes(); + + tensor_attr_ctor.construct_shape(shape.size()) + .Assign(shape.begin(), shape.end()); + + auto tensor_data = tensor.tensor_data(); + tensor_attr_ctor.construct_data(tensor_data.size()) + .Place(tensor_data.data(), tensor_data.size()); + + return std::string(buffer.data(), buffer.size()); + } + + // TODO(chky,rohitju): Add more attribute support. + + return absl::InvalidArgumentError("Unsupported attribute."); +} + +namespace { + +bool CanBeInlined(const tensorflow::AttrValue& attr) { + return attr.has_b() || attr.has_f(); +} + +} // namespace + +absl::Status EncodeAttributes(AttributeTable& attributes, + const tensorflow::AttrValueMap& attr_map) { + std::vector> attrs( + attr_map.begin(), attr_map.end()); + std::sort(attrs.begin(), attrs.end(), + [](const auto& x, const auto& y) { return x.first < y.first; }); + + for (int i = 0; i < attrs.size(); ++i) { + const tensorflow::AttrValue& attr = attrs[i].second; + TF_ASSIGN_OR_RETURN(auto attr_str, EncodeAttribute(attr)); + if (CanBeInlined(attr)) { + attributes.AddInline(absl::StrCat(i), attr_str); + } else { + attributes.Add(absl::StrCat(i), attr_str); + } + } + + return absl::OkStatus(); +} + +absl::StatusOr>> +CreateKernelAndAttrs(int num_inputs, int num_outputs, + mlrt::ExecutionContext& exec_ctx, mlrt::bc::Buffer* buffer, + const tensorflow::AttrValueMap& attrs) { + mlrt::bc::Allocator allocator(buffer); + auto attributes_ctor = mlrt::bc::New>( + &allocator, attrs.size()); + AttributeTable attribute_table(attributes_ctor); + TF_RETURN_IF_ERROR(EncodeAttributes(attribute_table, attrs)); + + auto kernel_ctor = mlrt::bc::New(&allocator); + kernel_ctor.set_code(0); + + std::vector input_indices(num_inputs); + std::iota(input_indices.begin(), input_indices.end(), 0); + kernel_ctor.construct_arguments(input_indices.size()) + .Assign(input_indices.begin(), input_indices.end()); + + std::vector output_indices(num_outputs); + std::iota(output_indices.begin(), output_indices.end(), num_inputs); + kernel_ctor.construct_results(output_indices.size()) + .Assign(output_indices.begin(), output_indices.end()); + + std::vector attr_indices; + attr_indices.reserve(attrs.size()); + for (int i = 0; i < attrs.size(); ++i) { + attr_indices.push_back(attribute_table.GetHandle(absl::StrCat(i))); + } + + kernel_ctor.construct_attributes(attr_indices.size()) + .Assign(attr_indices.begin(), attr_indices.end()); + + mlrt::bc::Vector attributes( + buffer->Get(attributes_ctor.address())); + mlrt::bc::Kernel kernel(buffer->Get(kernel_ctor.address())); + + return std::make_pair(kernel, attributes); +} + +} // namespace testing +} // namespace mlrt diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..f5a45d2df40eeaeb2e6b8a1de69a61e414a067b9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/test_utils.h @@ -0,0 +1,119 @@ +/* Copyright 2021 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_MLIR_TFRT_TRANSLATE_MLRT_TEST_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_MLRT_TEST_UTILS_H_ + +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/tfrt/graph_executor/sync_resource_state.h" +#include "tensorflow/core/tfrt/mlrt/attribute/attribute.h" +#include "tensorflow/core/tfrt/mlrt/bytecode/bytecode.h" +#include "tensorflow/core/tfrt/mlrt/bytecode/kernel.h" +#include "tensorflow/core/tfrt/mlrt/interpreter/context.h" +#include "tensorflow/core/tfrt/mlrt/interpreter/interpreter_testutil.h" +#include "tensorflow/core/tfrt/mlrt/interpreter/value.h" +#include "tensorflow/core/tfrt/stubs/tfrt_native_lowering_stub.h" +#include "tensorflow/core/tfrt/utils/tensor_util.h" +#include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime +#include "tfrt/host_context/execution_context.h" // from @tf_runtime +#include "tfrt/host_context/host_allocator.h" // from @tf_runtime +#include "tfrt/host_context/host_context.h" // from @tf_runtime +#include "tfrt/support/string_util.h" // from @tf_runtime +#include "tfrt/tensor/dense_host_tensor.h" // from @tf_runtime +#include "tfrt/tensor/dense_tensor_utils.h" // from @tf_runtime + +namespace mlrt { +namespace testing { + +absl::StatusOr EncodeAttribute(const tensorflow::AttrValue& attr); + +absl::Status EncodeAttributes(AttributeTable& attributes, + const tensorflow::AttrValueMap& attr_map); + +absl::StatusOr>> +CreateKernelAndAttrs(int num_inputs, int num_outputs, + mlrt::ExecutionContext& exec_ctx, mlrt::bc::Buffer* buffer, + const tensorflow::AttrValueMap& attrs = {}); + +template +absl::Status TestMlrtKernel( + absl::string_view kernel_name, absl::Span regs, + tfrt::HostContext* host, int num_inputs, int num_outputs, + absl::Span expected_outputs, + mlrt::KernelRegistry* registry, bool approx_equal = false, + const tensorflow::AttrValueMap& attrs = {}) { + mlrt::ExecutionContext execution_context(nullptr); + + mlrt::bc::Buffer buffer; + TF_ASSIGN_OR_RETURN(auto kernel_and_attrs, + CreateKernelAndAttrs(num_inputs, num_outputs, + execution_context, &buffer, attrs)); + + tensorflow::tfrt_stub::SyncResourceState sync_resource_state; + tfrt::AddSyncContext(execution_context, *host, &sync_resource_state); + + auto kernel_fn = registry->Get(kernel_name); + mlrt::KernelFrame::State state(regs, kernel_and_attrs.second, + &execution_context); + mlrt::KernelFrame frame(&state); + frame.set_kernel(kernel_and_attrs.first); + + kernel_fn(frame); + + TF_RETURN_IF_ERROR(execution_context.status()); + + for (int i = 0, j = num_inputs; i < expected_outputs.size(); ++i, ++j) { + const auto& expected_output = expected_outputs[i]; + auto expected_dht = tfrt::ConvertTfTensorToDHT(expected_output); + if (!expected_dht) { + return absl::InternalError(tfrt::StrCat(expected_dht.takeError())); + } + + if (!approx_equal) { + if (!tfrt::TensorEqual(regs[j].Get(), + *expected_dht)) { + return absl::InternalError( + absl::StrCat("wrong result for ", kernel_name)); + } + } else { + if (!tfrt::TensorApproxEqual(regs[j].Get(), + *expected_dht)) { + return absl::InternalError( + absl::StrCat("wrong result for ", kernel_name)); + } + } + } + + return absl::OkStatus(); +} + +} // namespace testing +} // namespace mlrt + +#endif // TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_MLRT_TEST_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async.mlir new file mode 100644 index 0000000000000000000000000000000000000000..67d503b225386ff2555ba5697c76d80ee51a1dab --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async.mlir @@ -0,0 +1,15 @@ +func.func @add_i32(%arg0: i32, %arg1: i32) -> i32 { + %0 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32 + func.return %0 : i32 +} + +func.func @main(%arg0: i32, %arg1: i32) -> i32 { + %handle = "mlrt.async"(%arg0, %arg1) {callee = @add_i32} : (i32, i32) -> !mlrt.async_handle + + "mlrt.await_handle"(%handle) : (!mlrt.async_handle) -> () + + %c1 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32 + %c2 = "test_mlbc.add.i32"(%c1, %c1) : (i32, i32) -> i32 + + func.return %c2 : i32 +} \ No newline at end of file diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async2.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async2.mlir new file mode 100644 index 0000000000000000000000000000000000000000..16947412fac47f46c22ec8fccffcd34686de9c31 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/async2.mlir @@ -0,0 +1,16 @@ +func.func @add_i32(%arg0: i32, %arg1: i32) -> i32 { + %0 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32 + func.return %0 : i32 +} + +func.func @main(%arg0: i32, %arg1: i32) -> i32 { + %c1 = "test_mlbc.add.i32"(%arg0, %arg1) : (i32, i32) -> i32 + + %handle = "mlrt.async"(%c1, %c1) {callee = @add_i32} : (i32, i32) -> !mlrt.async_handle + + "mlrt.await_handle"(%handle) : (!mlrt.async_handle) -> () + + %c2 = "test_mlbc.add.i32"(%c1, %c1) : (i32, i32) -> i32 + + func.return %c2 : i32 +} \ No newline at end of file diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic.mlir new file mode 100644 index 0000000000000000000000000000000000000000..644514bc5aa73e6da7d0495188c19e8af49016c1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic.mlir @@ -0,0 +1,13 @@ +func.func @add_i32_10(%c0: i32) -> (i32, i32, i32) { + %c1 = "test_mlbc.add.i32"(%c0, %c0) : (i32, i32) -> i32 + %c2 = "test_mlbc.sub.i32"(%c1, %c0) : (i32, i32) -> i32 + %c3 = "test_mlbc.add.i32"(%c2, %c0) : (i32, i32) -> i32 + %c4 = "test_mlbc.sub.i32"(%c3, %c0) : (i32, i32) -> i32 + %c5 = "test_mlbc.add.i32"(%c4, %c0) : (i32, i32) -> i32 + %c6 = "test_mlbc.sub.i32"(%c5, %c0) : (i32, i32) -> i32 + %c7 = "test_mlbc.add.i32"(%c6, %c0) : (i32, i32) -> i32 + %c8 = "test_mlbc.sub.i32"(%c7, %c0) : (i32, i32) -> i32 + %c9 = "test_mlbc.add.i32"(%c8, %c0) : (i32, i32) -> i32 + %c10, %c11, %c12 = call @add_i32_10(%c9) : (i32) -> (i32, i32, i32) + func.return %c0, %c10, %c10 : i32, i32, i32 +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic_attributes.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic_attributes.mlir new file mode 100644 index 0000000000000000000000000000000000000000..e1a2c0813be2eef06c5404da6901f69ff3519b7a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/basic_attributes.mlir @@ -0,0 +1,30 @@ +func.func @simple_attributes() { + "test_custom.attribute"() {value = "test string"} : () -> () + "test_custom.attribute"() {value = "ts"} : () -> () + "test_custom.attribute"() {value = 100 : i32} : () -> () + "test_custom.attribute"() {value = 200 : i64} : () -> () + "test_custom.attribute"() {value = 3.0 : f32} : () -> () + "test_custom.attribute"() {value = false} : () -> () + "test_custom.attribute"() {value = [0, 1, 2, 3, 4]} : () -> () + "test_custom.attribute"() {value = [0 : i32, 1 : i32, 2 : i32, 3 : i32]} : () -> () + "test_custom.attribute"() {value = ["string 0", "string 1"]} : () -> () + "test_custom.attribute"() {value = @callee} : () -> () + "test_custom.attribute"() {value = [@callee0, @callee1]} : () -> () + "test_custom.attribute"() {value = array} : () -> () + "test_custom.attribute"() {value = array} : () -> () + "test_custom.attribute"() {value = array} : () -> () + "test_custom.attribute"() {value = array} : () -> () + func.return +} + +func.func @callee() { + return +} + +func.func @callee0() { + return +} + +func.func @callee1() { + return +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/custom_attributes.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/custom_attributes.mlir new file mode 100644 index 0000000000000000000000000000000000000000..5cbf4fc1a45785216e117aeadf4bdd2a8790bce2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/custom_attributes.mlir @@ -0,0 +1,13 @@ +func.func @add_const_custom_dense_i32_10(%c0: i32) -> i32 { + %c1 = "test_custom.add.const.i32"(%c0) {value = dense<[0]> : tensor<1xi32>} : (i32) -> i32 + %c2 = "test_custom.add.const.i32"(%c1) {value = dense<[1]> : tensor<1xi32>} : (i32) -> i32 + %c3 = "test_custom.add.const.i32"(%c2) {value = dense<[2]> : tensor<1xi32>} : (i32) -> i32 + %c4 = "test_custom.add.const.i32"(%c3) {value = dense<[3]> : tensor<1xi32>} : (i32) -> i32 + %c5 = "test_custom.add.const.i32"(%c4) {value = dense<[4]> : tensor<1xi32>} : (i32) -> i32 + %c6 = "test_custom.add.const.i32"(%c5) {value = dense<[5]> : tensor<1xi32>} : (i32) -> i32 + %c7 = "test_custom.add.const.i32"(%c6) {value = dense<[6]> : tensor<1xi32>} : (i32) -> i32 + %c8 = "test_custom.add.const.i32"(%c7) {value = dense<[7]> : tensor<1xi32>} : (i32) -> i32 + %c9 = "test_custom.add.const.i32"(%c8) {value = dense<[8]> : tensor<1xi32>} : (i32) -> i32 + %c10 = "test_custom.add.const.i32"(%c9) {value = dense<[9]> : tensor<1xi32>} : (i32) -> i32 + func.return %c10 : i32 +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/unsupported_attributes.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/unsupported_attributes.mlir new file mode 100644 index 0000000000000000000000000000000000000000..b52eedaf8e178ba0b6a6be1516f77d1a41ef180e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/mlrt/testdata/unsupported_attributes.mlir @@ -0,0 +1,5 @@ +func.func @unsupported_attributes() { + "test_custom.attribute"() {unit} : () -> () + func.return +} + diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.cc new file mode 100644 index 0000000000000000000000000000000000000000..3d557915e0ed566398b4233a8c7dfb225bfa9244 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.cc @@ -0,0 +1,96 @@ +/* Copyright 2021 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/mlir/tfrt/translate/tfrt_compile_options.h" + +#include + +#include "absl/strings/str_join.h" + +namespace tensorflow { + +std::ostream& operator<<(std::ostream& os, + TfrtDeviceInfraTarget device_target) { + switch (device_target) { + case TfrtDeviceInfraTarget::kCpu: + return os << "Cpu"; + case TfrtDeviceInfraTarget::kTpurt: + return os << "Tpurt"; + case TfrtDeviceInfraTarget::kTfFallback: + return os << "TfFallback"; + case TfrtDeviceInfraTarget::kBridgeFallback: + return os << "BridgeFallback"; + case TfrtDeviceInfraTarget::kGpu: + return os << "Gpu"; + } +} + +std::ostream& operator<<(std::ostream& os, const TfrtCompileOptions& options) { + return os << "{" << "variable_device = " << options.variable_device + << ", default_device = " << options.default_device + << ", enable_optimizer = " << options.enable_optimizer + << ", enable_grappler = " << options.enable_grappler + << ", force_data_format = " << options.force_data_format + << ", device_target = " << options.device_target + << ", tpu_fuse_ops = " << options.tpu_fuse_ops + << ", tpu_move_resource_gather_to_host = " + << options.tpu_move_resource_gather_to_host + << ", tpu_gather_table_width_threshold_bytes = " + << options.tpu_gather_table_width_threshold_bytes + << ", use_tpu_host_allocator_for_inputs = " + << options.use_tpu_host_allocator_for_inputs + << ", hoist_invariant_ops = " << options.hoist_invariant_ops + << ", enable_while_parallel_iterations = " + << options.enable_while_parallel_iterations + << ", cost_threshold = " << options.cost_threshold + << ", min_num_batch_threads = " << options.min_num_batch_threads + << ", min_max_enqueued_batches = " + << options.min_max_enqueued_batches + << ", batch_padding_policy = " << options.batch_padding_policy + << ", num_batch_threads = " + << options.batch_options.num_batch_threads() + << ", max_batch_size = " << options.batch_options.max_batch_size() + << ", batch_timeout_micros = " + << options.batch_options.batch_timeout_micros() + << ", allowed_batch_sizes = " + << absl::StrJoin(options.batch_options.allowed_batch_sizes(), ",") + << ", max_enqueued_batches = " + << options.batch_options.max_enqueued_batches() + << ", low_priority_max_batch_size = " + << options.batch_options.low_priority_max_batch_size() + << ", low_priority_batch_timeout_micros = " + << options.batch_options.low_priority_batch_timeout_micros() + << ", low_priority_allowed_batch_sizes = " + << absl::StrJoin( + options.batch_options.low_priority_allowed_batch_sizes(), + ",") + << ", low_priority_max_enqueued_batches = " + << options.batch_options.low_priority_max_enqueued_batches() + << ", num_warmup_batch_threads = " + << options.batch_options.num_warmup_batch_threads() + << ", enable_large_batch_splitting = " + << options.batch_options.enable_large_batch_splitting() + << ", mixed_priority_batching_policy = " + << options.batch_options.mixed_priority_batching_policy() + << ", merge_inter_dependent_streams = " + << options.merge_inter_dependent_streams + << ", decompose_resource_ops = " << options.decompose_resource_ops + << ", compile_to_sync_tfrt_dialect = " + << options.compile_to_sync_tfrt_dialect + << ", batch_queue_global_prioritization_num_threads = " + << options.batch_queue_global_prioritization_num_threads << "}"; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h new file mode 100644 index 0000000000000000000000000000000000000000..20a2ea8ea40ba212adf25bd2534b6ef55fee1c6d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/translate/tfrt_compile_options.h @@ -0,0 +1,210 @@ +/* Copyright 2021 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_MLIR_TFRT_TRANSLATE_TFRT_COMPILE_OPTIONS_H_ +#define TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_TFRT_COMPILE_OPTIONS_H_ + +#include +#include +#include +#include +#include + +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +class BackendCompiler; + +enum class TfrtDeviceInfraTarget { + kCpu, // CPU only, no device support. + kTpurt, // Target TPURT dialect and kernels. + kTfFallback, // Target TPU kernels in TF Fallback. + kBridgeFallback, // TPU support but choose kTpurt or kTfFallback depending on + // whether the graph has unsupported feature in Bridge. + kGpu, // Target GPU specific compiler passes and runtime + // initializations. +}; + +std::ostream& operator<<(std::ostream& os, TfrtDeviceInfraTarget device_target); + +struct TfrtCompileOptions { + std::string saved_model_dir; + // TODO(tfrt-devs): Ideally, compiler should make the decision where + // to place the variable. + std::string variable_device = "/job:localhost/replica:0/task:0/device:CPU:0"; + std::string default_device = "/job:localhost/replica:0/task:0/device:CPU:0"; + + // Enable compiler optimization in TFRT dialect. + bool enable_optimizer = true; + + // If true, run grappler passes before compiling. + bool enable_grappler = true; + + // Graph rewrite options that will be applied on GraphDef before converting to + // MLIR. + GraphOptions graph_options; + + // Force data format for all layout sensitive operations, eg. setting it to + // "NHWC" will changes all data format in the graph to "NHWC" by inserting + // or removing related tf.Transpose op. Currently the supported formats are + // "NHWC" and "NCHW". + // + // TODO(tfrt-devs): Ideally compiler should figure out whether the + // data format should be changed, instead of controlled by users. + std::string force_data_format; + + // The target device infrastructure to use. This will trigger target specific + // compiler passes and runtime initialization. + TfrtDeviceInfraTarget device_target = TfrtDeviceInfraTarget::kCpu; + + // The custom compiler for device compilation. Instead of using the enum above + // to choose predefined device target, users can use this `backend_compiler` + // to inject their customized implementation. + BackendCompiler* backend_compiler = nullptr; + + // If true, use the fused TPU compile_and_execute kernel, which performs all + // TPU inference related operations, e.g. core selection, h2d/d2h transfers, + // compile and execute. + bool tpu_fuse_ops = false; + + // If true, resource gather ops in the device graph are moved to host graphs + // in order to saved TPU memory usage. This option is experimental. + bool tpu_move_resource_gather_to_host = false; + + // The threshold in bytes that controls whether a resource gather op on TPU + // should be moved to host. A negative value means there is no threshold. This + // option is experimental. + int64_t tpu_gather_table_width_threshold_bytes = -1; + + // If true, fallback executeops that produce inputs to tpu program will use + // tpu host allocator. This options is experimental. + bool use_tpu_host_allocator_for_inputs = false; + + // To allow unpadded batch for TPU execution. + enum class TpuAllowUnpaddedBatch { + // Disable this feature. + kDisabled, + // Enable this feature when in-graph batching is detected. + kAuto, + // Force to enable this feature. + kEnforced, + }; + TpuAllowUnpaddedBatch tpu_allow_unpadded_batch = + TpuAllowUnpaddedBatch::kDisabled; + + // If true, the compiler will try to hoist invariant ops (e.g., const ops and + // their non-side-effecting consumers) to loading phase, which avoids the + // runtime cost during later running. + // TODO(tfrt-devs): Set the default value to true after testing as it is + // supposed to be turned on by default. + bool hoist_invariant_ops = false; + + // If true, get_resource_op will be fused during hoisting. + bool fuse_get_resource_ops_in_hoisting = true; + + // If true, the compiler will try to sink in the invariant ops (e.g. const + // ops, var handle ops, etc.) to the nested function (e.g. batch function) to + // facilitate invariant ops hoisting. + // TODO(tfrt-devs): Set the default value to true after testing as it is + // supposed to be turned on by default. + bool sink_in_invariant_ops = false; + + // This flag behaves differently for TFRT and MLRT. + // For TFRT, if true, tf.While's iterations will be parallelized on a + // best-effort basis. This is currently experimental. MLRT attempts to convert + // tf.while to tf_mlrt.map_fn regardless of this flag. For tf.While that + // cannot be converted tf_mlrt.map_fn, MLRT try to parallelize tf.while's + // iterations on a best-effort basis. + bool enable_while_parallel_iterations = false; + + // The cost threshold to decide whether a sequence of operations is cheap, and + // then whether it can be executed inline. If the cost is smaller than the + // threshold, it will be considered as cheap operations. Since the cost must + // be positive integers, setting the threshold to 1 makes all operations + // expensive. + uint64_t cost_threshold = 1; + + // The minimum number of batch threads. This number provides a lower bound on + // the number of batch threads on top of what is specified in the model. If + // the number of batch threads is too small (e.g. smaller than the number of + // parallel hardware accelerator available), it can lead to under utilization + // of resources. + int64_t min_num_batch_threads = 1; + + // The minimum of the maximum number of enqueued batches. This number provides + // a lower bound on top of what is specified in the model. If the number of + // max_enqueued_batches is too small, it can lead to under utilization of + // resources. + int64_t min_max_enqueued_batches = 1; + + // If non-zero, all models on this server are switched to use a prioritized + // batching function using this number of global threads. + int64_t batch_queue_global_prioritization_num_threads = 0; + + // If true, the queue implementation will have a separate subqueue for each + // criticality. + bool enable_priority_aware_batch_scheduler = false; + + // If true, the queue implementation will resplit tasks for priority aware + // scheduling. + bool enable_priority_aware_batch_scheduler_resplit = false; + + // If true, enable lazy cancellation filtering in the priority-aware batch + // scheduler. + bool enable_batching_task_lazy_cancellation = false; + + // The policy used by a BatchScheduler to pad (or split) batches. + std::string batch_padding_policy; + + // Batching parameters to be rewritten in the existing BatchFunction ops. + BatchingOptions batch_options; + + // If true, streams with inter data dependencies will be preferred to be + // merged for inline execution. + bool merge_inter_dependent_streams = true; + + // Whether to enable the DecomposeResourceOpsPass. + bool decompose_resource_ops = true; + + // Whether to compile to sync TFRT dialect. + bool compile_to_sync_tfrt_dialect = false; + + // Whether to use gpurt.compile_and_execute for GPU. + // TODO(b/294895431): Remove the flag and default to the fused op. + bool use_gpu_compile_and_execute_op = false; + + // If true, MLIR module will be serialized to aot_packages. + bool serialize_mlir_module_to_aot_packages = false; + + // Serialized MLIR module file under aot_packages. + std::string aot_mlir_module_file; + + // If true, BEF will be serialized to aot_packages. + bool serialize_bef_to_aot_packages = false; + + // Serialized BEF file under aot_packages. + std::string aot_bef_file; + // If true, use XLA:CPU for CPU computations. + bool allow_xla_cpu = true; + // If true, enable asynchronous IFRT execution. + bool enable_async_ifrt = false; +}; + +std::ostream& operator<<(std::ostream& os, const TfrtCompileOptions& options); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_MLIR_TFRT_TRANSLATE_TFRT_COMPILE_OPTIONS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.cc new file mode 100644 index 0000000000000000000000000000000000000000..82d0c69ee68891406d97fd99121a47296af4697f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.cc @@ -0,0 +1,75 @@ +/* Copyright 2023 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/mlir/tfrt/utils/export.h" + +#include +#include + +#include "absl/functional/any_invocable.h" +#include "absl/status/status.h" +#include "absl/strings/string_view.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" +#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/tf_dialect_to_executor.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v2/tf_executor_to_graph.h" +#include "tensorflow/core/framework/function.pb.h" +#include "tsl/platform/errors.h" +#include "tsl/profiler/lib/traceme.h" + +namespace tensorflow { + +absl::Status ExportFunctionDefs( + mlir::ModuleOp module, + absl::AnyInvocable callback, + bool export_tf_original_func_name) { + tsl::profiler::TraceMe traceme([&]() { + return tsl::profiler::TraceMeEncode( + "ExportFunctionDefs", + {{"module_name", absl::string_view(module.getName().value_or("?"))}}); + }); + + TF_RETURN_IF_ERROR( + tensorflow::tf2xla::v1::ExportFromTensorflowDialectToExecutor(module)); + + { + mlir::StatusScopedDiagnosticHandler diag_handler(module.getContext()); + + mlir::PassManager pm(module.getContext()); + pm.addPass(mlir::CreateBreakUpIslandsPass()); + + if (mlir::failed(pm.run(module))) { + return diag_handler.ConsumeStatus(); + } + } + tensorflow::GraphExportConfig configs; + configs.export_original_tf_func_name = export_tf_original_func_name; + + for (auto func : module.getOps()) { + tensorflow::FunctionDef function_def; + TF_RETURN_IF_ERROR( + tensorflow::tf2xla::v2::ConvertMlirFunctionToFunctionLibraryDef( + func, configs, &function_def)); + TF_RETURN_IF_ERROR(callback(std::move(function_def))); + } + + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.h new file mode 100644 index 0000000000000000000000000000000000000000..847afbf8f80cdc2bf7acd0148ea9ae3cc5f68b79 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/export.h @@ -0,0 +1,36 @@ +/* Copyright 2023 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_MLIR_TFRT_UTILS_EXPORT_H_ +#define TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_EXPORT_H_ + + +#include "absl/functional/any_invocable.h" +#include "absl/status/status.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "tensorflow/core/framework/function.pb.h" + +namespace tensorflow { + +// Exports every function in `module` into `tensorflow.FunctionDef` and calls +// `callback` for each `tensorflow.FunctionDef`. Modifies `module` in place to +// be suitable for FunctionDef export. +absl::Status ExportFunctionDefs( + mlir::ModuleOp module, + absl::AnyInvocable callback, + bool export_tf_original_func_name = true); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_EXPORT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee7a7855b6e87af5cc151b2db29209dbef3ec993 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.cc @@ -0,0 +1,56 @@ +/* Copyright 2022 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/mlir/tfrt/utils/host_context.h" + +#include +#include + +#include "absl/log/log.h" +#include "tensorflow/core/platform/logging.h" +#include "tfrt/host_context/concurrent_work_queue.h" // from @tf_runtime +#include "tfrt/host_context/diagnostic.h" // from @tf_runtime +#include "tfrt/host_context/host_allocator.h" // from @tf_runtime +#include "tfrt/host_context/host_context.h" // from @tf_runtime + +namespace tensorflow { + +using ::tfrt::HostContext; + +const char* const kDefaultHostDeviceName = + "/job:localhost/replica:0/task:0/device:CPU:0"; + +std::unique_ptr CreateSingleThreadedHostContext() { + return std::make_unique( + [](const tfrt::DecodedDiagnostic& diag) { + LOG(FATAL) << "Runtime error: " << diag.message() << "\n"; + }, + tfrt::CreateMallocAllocator(), tfrt::CreateSingleThreadedWorkQueue(), + kDefaultHostDeviceName); +} + +std::unique_ptr CreateMultiThreadedHostContext( + int64_t num_threads) { + return std::make_unique( + [](const tfrt::DecodedDiagnostic& diag) { + LOG(FATAL) << "Runtime error: " << diag.message() << "\n"; + }, + tfrt::CreateMallocAllocator(), + tfrt::CreateMultiThreadedWorkQueue(num_threads, + /*num_blocking_threads=*/1), + kDefaultHostDeviceName); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.h new file mode 100644 index 0000000000000000000000000000000000000000..311a5557db8766919822bde8252174ab299d7019 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tfrt/utils/host_context.h @@ -0,0 +1,36 @@ +/* Copyright 2022 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_MLIR_TFRT_UTILS_HOST_CONTEXT_H_ +#define TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_HOST_CONTEXT_H_ + +#include +#include + +#include "absl/base/attributes.h" +#include "tfrt/host_context/host_context.h" // from @tf_runtime + +namespace tensorflow { + +// The name of the default host device for running fallback kernels. +ABSL_CONST_INIT extern const char* const kDefaultHostDeviceName; + +std::unique_ptr CreateSingleThreadedHostContext(); +std::unique_ptr CreateMultiThreadedHostContext( + int64_t num_threads); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_MLIR_TFRT_UTILS_HOST_CONTEXT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..f217c39511af152c56e625184a635053bdec3680 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/BUILD @@ -0,0 +1,58 @@ +load("@rules_cc//cc:cc_library.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [ + "//visibility:public", + ], + licenses = ["notice"], +) + +cc_library( + name = "translate_cl_options", + srcs = [ + "tf_mlir_translate_cl.cc", + ], + hdrs = [ + "tf_mlir_translate_cl.h", + ], + deps = [ + "@llvm-project//llvm:Support", + ], + alwayslink = 1, +) + +cc_library( + name = "translate_registration", + srcs = [ + "tf_mlir_translate_registration.cc", + ], + deps = [ + "//tensorflow/compiler/mlir/tensorflow", + "//tensorflow/compiler/mlir/tensorflow/translate:mlir_roundtrip_flags", + "//tensorflow/compiler/mlir/tensorflow/translate/tools:file_tf_mlir_translate", + "//tensorflow/compiler/mlir/tf2xla/api/v2:tf_executor_to_graph", + "//tensorflow/compiler/mlir/tools:translate_cl_options", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla/kernels:xla_ops", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:flat_hash_set", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:TranslateLib", + "@tsl//tsl/platform:protobuf", + "@xla//xla/client:client_library", + "@xla//xla/client:compile_only_client", + "@xla//xla/service/cpu:cpu_compiler", + "@xla//xla/service/cpu:cpu_transfer_manager", + "@xla//xla/stream_executor/host:host_platform", + "@xla//xla/stream_executor/host:host_platform_id", + ], + alwayslink = 1, +) + +cc_library( + name = "safe_cast", + hdrs = ["safe_cast.h"], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..0d7d467d1cdec145fd6de36ee0bff17cd4cf5431 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/BUILD @@ -0,0 +1,267 @@ +load( + "@local_config_rocm//rocm:build_defs.bzl", + "if_rocm_is_configured", +) +load("@rules_cc//cc:cc_library.bzl", "cc_library") +load( + "@xla//xla/stream_executor:build_defs.bzl", + "if_gpu_is_configured", +) +load( + "@xla//xla/tsl/platform/default:cuda_build_defs.bzl", + "if_cuda_is_configured", +) +load( + "//tensorflow:tensorflow.bzl", + "check_deps", + "tf_cc_binary", +) +load( + "//tensorflow/core/platform:build_config.bzl", + "tf_proto_library", +) +load( + "//tensorflow/core/platform:build_config_root.bzl", + "if_llvm_aarch32_available", + "if_llvm_aarch64_available", + "if_llvm_powerpc_available", + "if_llvm_system_z_available", + "if_llvm_x86_available", +) + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [":friends"], + licenses = ["notice"], +) + +package_group( + name = "friends", + packages = [ + "//tensorflow/compiler/...", + "//tensorflow/core/kernels/mlir_generated/...", + ], +) + +cc_library( + name = "kernel_creator", + srcs = ["kernel_creator.cc"], + hdrs = ["kernel_creator.h"], + copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured(["-DTENSORFLOW_USE_ROCM=1"]), + deps = [ + "//tensorflow/compiler/mlir/tensorflow:dump_mlir_util", + "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:bufferize", + "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:gpu_passes", # fixdeps: keep + "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:passes", + "//tensorflow/core:lib", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:AffineToStandard", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:ArithTransforms", + "@llvm-project//mlir:BufferizationTransforms", + "@llvm-project//mlir:BuiltinToLLVMIRTranslation", + "@llvm-project//mlir:ComplexDialect", + "@llvm-project//mlir:ComplexToStandard", + "@llvm-project//mlir:ControlFlowDialect", + "@llvm-project//mlir:DataLayoutInterfaces", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:GPUDialect", + "@llvm-project//mlir:GPUToGPURuntimeTransforms", + "@llvm-project//mlir:GPUToLLVMIRTranslation", + "@llvm-project//mlir:GPUToNVVMTransforms", + "@llvm-project//mlir:GPUTransforms", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:LLVMIRTransforms", + "@llvm-project//mlir:LLVMToLLVMIRTranslation", + "@llvm-project//mlir:LinalgTransforms", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:MemRefTransforms", + "@llvm-project//mlir:NVVMToLLVMIRTranslation", + "@llvm-project//mlir:NVVMTransforms", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:ROCDLToLLVMIRTranslation", + "@llvm-project//mlir:ReconcileUnrealizedCasts", + "@llvm-project//mlir:SCFToControlFlow", + "@llvm-project//mlir:SCFToGPU", + "@llvm-project//mlir:SCFTransforms", + "@llvm-project//mlir:ShapeDialect", + "@llvm-project//mlir:ShapeToStandard", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + "@stablehlo//:chlo_ops", + "@stablehlo//:linalg_passes", + "@stablehlo//:stablehlo_passes", + "@xla//xla/mlir_hlo", + "@xla//xla/mlir_hlo:all_passes", # fixdeps: keep + "@xla//xla/mlir_hlo:mhlo_passes", + "@xla//xla/mlir_hlo:transforms_gpu_passes", + "@xla//xla/mlir_hlo:transforms_passes", + ], +) + +check_deps( + name = "hlo_to_kernel_check_deps", + disallowed_deps = ["@xla//xla:literal"], + deps = [":hlo_to_kernel"], +) + +tf_cc_binary( + name = "hlo_to_kernel", + srcs = ["hlo_to_kernel.cc"], + visibility = [ + "//tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel:__pkg__", + "//tensorflow/core/kernels/mlir_generated:__pkg__", + ], + deps = [ + ":kernel_creator", + "//tensorflow/compiler/mlir:init_mlir", + "//tensorflow/compiler/mlir/tensorflow", + "//tensorflow/core:lib", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@llvm-project//llvm:Analysis", + "@llvm-project//llvm:CodeGen", + "@llvm-project//llvm:Core", + "@llvm-project//llvm:MC", + "@llvm-project//llvm:Support", + "@llvm-project//llvm:Target", + "@llvm-project//llvm:TargetParser", + "@llvm-project//mlir:BufferizationInterfaces", + "@llvm-project//mlir:ExecutionEngineUtils", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:LLVMToLLVMIRTranslation", + "@llvm-project//mlir:MemRefTransforms", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:ToLLVMIRTranslation", + "@xla//xla/service/llvm_ir:llvm_command_line_options", + ] + if_llvm_aarch32_available([ + "@llvm-project//llvm:ARMCodeGen", # fixdeps: keep + ]) + if_llvm_aarch64_available([ + "@llvm-project//llvm:AArch64CodeGen", # fixdeps: keep + ]) + if_llvm_powerpc_available([ + "@llvm-project//llvm:PowerPCCodeGen", # fixdeps: keep + ]) + if_llvm_system_z_available([ + "@llvm-project//llvm:SystemZCodeGen", # fixdeps: keep + ]) + if_llvm_x86_available([ + "@llvm-project//llvm:X86CodeGen", # fixdeps: keep + "@llvm-project//llvm:X86Disassembler", # fixdeps: keep + ]), +) + +tf_cc_binary( + name = "kernel-gen-opt", + srcs = ["tools/kernel-gen-opt/kernel-gen-opt.cc"], + visibility = ["//tensorflow/compiler/mlir/tools/kernel_gen/tests:__subpackages__"], + deps = [ + "//tensorflow/compiler/mlir/tensorflow", + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:gpu_passes", # fixdeps: keep + "//tensorflow/compiler/mlir/tools/kernel_gen/transforms:passes", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:AllPassesAndDialects", + "@llvm-project//mlir:MlirOptLib", + "@llvm-project//mlir:RegisterAllDialects", + "@llvm-project//mlir:RegisterAllPasses", + "@stablehlo//:register", + "@xla//xla/mlir_hlo:all_passes", + "@xla//xla/mlir_hlo:hlo_dialect_registration", + ], +) + +exports_files(["tf_framework_c_interface.h"]) + +cc_library( + name = "tf_framework_c_interface", + srcs = ["tf_framework_c_interface.cc"], + hdrs = ["tf_framework_c_interface.h"], + copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured(["-DTENSORFLOW_USE_ROCM=1"]), + deps = [ + ":compile_cache_item_proto_cc", + ":kernel_creator", + ":tf_gpu_runtime_wrappers", + ":tf_jit_cache", + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core/platform:refcount", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:string_view", + "@llvm-project//llvm:JITLink", + "@llvm-project//llvm:OrcShared", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:ExecutionEngine", + "@llvm-project//mlir:ExecutionEngineUtils", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:MemRefTransforms", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:mlir_c_runner_utils", + "@llvm-project//mlir:mlir_runner_utils", + "@xla//xla/stream_executor:stream", + ], +) + +cc_library( + name = "tf_jit_cache", + srcs = ["tf_jit_cache.cc"], + hdrs = ["tf_jit_cache.h"], + deps = [ + "//tensorflow/core:framework", + "//tensorflow/core:framework_lite", + "//tensorflow/core/framework:resource_base", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/status", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:ExecutionEngine", + "@tsl//tsl/platform:thread_annotations", + ], +) + +cc_library( + name = "tf_gpu_runtime_wrappers", + srcs = if_gpu_is_configured([ + "tf_gpu_runtime_wrappers.cc", + ]), + hdrs = + if_gpu_is_configured([ + "tf_gpu_runtime_wrappers.h", + ]), + copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured([ + "-DTENSORFLOW_USE_ROCM=1", + ]), + deps = [ + "//tensorflow/core:framework", + "//tensorflow/core/framework:resource_base", + "//tensorflow/core/platform:logging", + "//tensorflow/core/platform:mutex", + "//tensorflow/core/platform:refcount", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@llvm-project//mlir:mlir_runner_utils", + "@tsl//tsl/platform:hash", + "@tsl//tsl/platform:thread_annotations", + "@xla//xla/stream_executor:stream", + ] + if_cuda_is_configured([ + "@local_config_cuda//cuda:cuda_headers", + "@xla//xla/stream_executor/cuda:stream_executor_cuda", + ]) + if_rocm_is_configured([ + "@local_config_rocm//rocm:rocm_headers", + "@xla//xla/stream_executor/rocm:stream_executor_rocm", + ]), +) + +tf_proto_library( + name = "compile_cache_item_proto", + srcs = ["compile_cache_item.proto"], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.proto b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.proto new file mode 100644 index 0000000000000000000000000000000000000000..34bb11ad1d0d402cf2659514a279ab6e4917a671 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.proto @@ -0,0 +1,10 @@ +syntax = "proto3"; + +package mlir.kernel_gen; + +// Protocolbuffer representing a compilation input and output. This will be used +// for caching JIT compiles of kernels. +message CompilationCacheItem { + string original_module = 1; + string result_module = 2; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/hlo_to_kernel.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/hlo_to_kernel.cc new file mode 100644 index 0000000000000000000000000000000000000000..cb760e08dde1e791d02da72a49151e613140f7bd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/hlo_to_kernel.cc @@ -0,0 +1,250 @@ +// Copyright 2020 The TensorFlow Runtime Authors +// +// 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. + +//===- hlo_to_kernel.cc -----------------------------------------*- C++ -*-===// +// +// This file implements the entry point to compile a hlo op to a kernel. +// +//===----------------------------------------------------------------------===// +#include +#include +#include +#include + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "llvm/ADT/SmallString.h" +#include "llvm/Analysis/TargetLibraryInfo.h" +#include "llvm/CodeGen/CommandFlags.h" +#include "llvm/IR/LLVMContext.h" +#include "llvm/IR/LegacyPassManager.h" +#include "llvm/IR/Module.h" +#include "llvm/MC/TargetRegistry.h" +#include "llvm/Support/CodeGen.h" +#include "llvm/Support/CommandLine.h" +#include "llvm/Support/SourceMgr.h" +#include "llvm/Support/TargetSelect.h" +#include "llvm/Support/raw_ostream.h" +#include "llvm/Target/TargetMachine.h" +#include "llvm/TargetParser/Host.h" +#include "llvm/TargetParser/Triple.h" +#include "mlir/Dialect/MemRef/Transforms/AllocationOpInterfaceImpl.h" // from @llvm-project +#include "mlir/ExecutionEngine/OptUtils.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/Diagnostics.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Export.h" // from @llvm-project +#include "tensorflow/compiler/mlir/init_mlir.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h" +#include "xla/service/llvm_ir/llvm_command_line_options.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace kernel_gen { +namespace { + +static llvm::codegen::RegisterCodeGenFlags CGF; + +std::unique_ptr GetTargetMachine( + llvm::StringRef host_triple, llvm::Module* module) { + llvm::Triple triple(module->getTargetTriple()); + if (triple.getTriple().empty()) { + if (!host_triple.empty()) { + triple = llvm::Triple(host_triple); + } else { + triple = llvm::Triple(llvm::sys::getDefaultTargetTriple()); + } + module->setTargetTriple(llvm::Triple(triple.getTriple())); + } + + std::string error; + const llvm::Target* target = + llvm::TargetRegistry::lookupTarget("", triple, error); + if (!target) { + return nullptr; + } + + llvm::TargetOptions target_options = + llvm::codegen::InitTargetOptionsFromCodeGenFlags(llvm::Triple()); + return std::unique_ptr(target->createTargetMachine( + triple, "generic", "", target_options, llvm::Reloc::Model::PIC_)); +} + +// Compiles the given MLIR module via LLVM into an executable binary format. +absl::StatusOr EmitToBinary(llvm::StringRef host_triple, + mlir::ModuleOp module) { + // Translate the module. + llvm::LLVMContext llvm_context; + mlir::registerLLVMDialectTranslation(*module->getContext()); + std::unique_ptr llvm_module = + mlir::translateModuleToLLVMIR(module, llvm_context); + + auto target_machine = GetTargetMachine(host_triple, llvm_module.get()); + llvm_module->setDataLayout(target_machine->createDataLayout()); + + // Run LLVM's mid-level optimizer to clean up the IR. + if (mlir::makeOptimizingTransformer( + /*optLevel=*/2, /*sizeLevel=*/0, + target_machine.get())(llvm_module.get())) { + return absl::InternalError("Failed to run LLVM optimizer passess"); + } + + // Set up the output stream. + llvm::SmallString<8> outstr; + llvm::raw_svector_ostream ostream(outstr); + ostream.SetUnbuffered(); + + llvm::legacy::PassManager codegen_passes; + codegen_passes.add(new llvm::TargetLibraryInfoWrapperPass( + llvm::Triple(llvm_module->getTargetTriple()))); + + if (target_machine->addPassesToEmitFile(codegen_passes, ostream, nullptr, + llvm::CodeGenFileType::ObjectFile, + false)) { + return absl::InternalError("Failed add passes to emit file"); + } + codegen_passes.run(*llvm_module); + return ostream.str().str(); +} + +absl::Status Run(llvm::StringRef input_file, llvm::StringRef output_file, + llvm::StringRef host_triple, + llvm::ArrayRef architectures, + llvm::ArrayRef tile_sizes, + llvm::ArrayRef unroll_factors, bool print_ptx, + bool print_llvmir, bool enable_ftz, bool index_64bit, + bool jit_compile, bool jit_i64_indexed_for_large_tensors) { + // Read TF code. + std::string hlo_code; + TF_RETURN_IF_ERROR( + ReadFileToString(Env::Default(), input_file.str(), &hlo_code)); + + // Compile. + mlir::DialectRegistry registry; + mlir::memref::registerAllocationOpInterfaceExternalModels(registry); + mlir::MLIRContext context(registry); + + llvm::SourceMgr source_mgr; + mlir::SourceMgrDiagnosticHandler source_mgr_handler(source_mgr, &context); + + TF_ASSIGN_OR_RETURN( + mlir::OwningOpRef module, + GenerateKernelForHloCode(context, hlo_code, architectures, tile_sizes, + unroll_factors, print_ptx, print_llvmir, + enable_ftz, index_64bit, jit_compile, + jit_i64_indexed_for_large_tensors, + /*apply_cl_options=*/true)); + + // Get binary. + TF_ASSIGN_OR_RETURN(std::string binary, EmitToBinary(host_triple, *module)); + + // Write .a file. + TF_RETURN_IF_ERROR( + WriteStringToFile(Env::Default(), output_file.str(), binary)); + return absl::OkStatus(); +} + +} // namespace +} // namespace kernel_gen +} // namespace tensorflow + +int main(int argc, char** argv) { + llvm::cl::opt input_file("input", llvm::cl::desc("input file"), + llvm::cl::value_desc("filename"), + llvm::cl::init("foo.mlir")); + llvm::cl::opt output_file( + "output", llvm::cl::desc("output file"), llvm::cl::value_desc("filename"), + llvm::cl::init("foo.bin")); + llvm::cl::opt index_64bit("index_64bit", + llvm::cl::desc("enable 64 bit indexing"), + llvm::cl::init(false)); + llvm::cl::opt print_ptx( + "print-ptx", + llvm::cl::desc("print generated PTX code per target architecture."), + llvm::cl::init(false)); + llvm::cl::opt print_llvmir( + "print-llvmir", llvm::cl::desc("print llvm ir during lowering to ptx."), + llvm::cl::init(false)); + llvm::cl::opt enable_ftz( + "enable_ftz", + llvm::cl::desc( + "enable the denormal flush to zero mode when generating code."), + llvm::cl::init(false)); + llvm::cl::opt jit_compile( + "jit", llvm::cl::desc("Generate only a JIT compiler invocation."), + llvm::cl::init(false)); + llvm::cl::opt host_triple( + "host-triple", llvm::cl::desc("Override host triple for module")); + llvm::cl::list architectures( + "arch", llvm::cl::desc("target architectures (e.g. sm_70 or compute_75)"), + llvm::cl::ZeroOrMore, llvm::cl::CommaSeparated); + llvm::cl::list tile_sizes( + "tile_sizes", llvm::cl::desc("tile sizes to use"), llvm::cl::ZeroOrMore, + llvm::cl::CommaSeparated); + llvm::cl::list unroll_factors( + "unroll_factors", + llvm::cl::desc("factors to unroll by, separated by commas"), + llvm::cl::ZeroOrMore, llvm::cl::CommaSeparated); + llvm::cl::opt jit_i64_indexed_for_large_tensors( + "jit_i64_indexed_for_large_tensors", + llvm::cl::desc( + "Enable JIT compilation of i64-indexed kernels for large inputs."), + llvm::cl::init(false)); + + tensorflow::InitMlir y(&argc, &argv); + +#ifdef TF_LLVM_X86_AVAILABLE + LLVMInitializeX86Target(); + LLVMInitializeX86TargetInfo(); + LLVMInitializeX86TargetMC(); + LLVMInitializeX86AsmPrinter(); +#endif + +#ifdef TF_LLVM_AARCH64_AVAILABLE + LLVMInitializeAArch64Target(); + LLVMInitializeAArch64TargetInfo(); + LLVMInitializeAArch64TargetMC(); + LLVMInitializeAArch64AsmPrinter(); +#endif + + mlir::registerPassManagerCLOptions(); + mlir::registerMLIRContextCLOptions(); + + // Forward cli options to XLA, as it will reset llvm options internally + // during the first invocation. + auto& xla_llvm_global_options = + xla::llvm_ir::LLVMCommandLineOptionsLock::GetGlobalOptions(); + xla_llvm_global_options.insert(xla_llvm_global_options.end(), argv + 1, + argv + argc); + llvm::cl::ParseCommandLineOptions(argc, argv, "TF op kernel generator\n"); + + auto status = tensorflow::kernel_gen::Run( + input_file, output_file, host_triple, architectures, tile_sizes, + unroll_factors, print_ptx, print_llvmir, enable_ftz, index_64bit, + jit_compile, jit_i64_indexed_for_large_tensors); + if (!status.ok()) { + LOG(ERROR) << status; + return 1; + } + return 0; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..4a88fc67ca8c3f6ed5500bd5f684731faea82684 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/BUILD @@ -0,0 +1,81 @@ +load("@llvm-project//mlir:tblgen.bzl", "gentbl_cc_library", "td_library") +load("//tensorflow:tensorflow.default.bzl", "get_compatible_with_portable") +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [ + "//tensorflow/compiler/mlir/tools/kernel_gen:friends", + # Allow visibility from the mlir language server. + "//learning/brain/mlir/mlir_lsp_server:__pkg__", + ], + licenses = ["notice"], +) + +td_library( + name = "td_files", + srcs = [ + "tf_framework_ops.td", + "tf_status.td", + ], + compatible_with = get_compatible_with_portable(), + deps = [ + "@llvm-project//mlir:AllocationOpInterfaceTdFiles", + "@llvm-project//mlir:ControlFlowInterfacesTdFiles", + "@llvm-project//mlir:OpBaseTdFiles", + "@llvm-project//mlir:SideEffectInterfacesTdFiles", + ], +) + +gentbl_cc_library( + name = "tf_framework_ops_inc_gen", + compatible_with = get_compatible_with_portable(), + tbl_outs = { + "tf_framework_ops.h.inc": ["-gen-op-decls"], + "tf_framework_ops.cc.inc": ["-gen-op-defs"], + "tf_framework_dialect.h.inc": ["-gen-dialect-decls"], + "tf_framework_dialect.cc.inc": ["-gen-dialect-defs"], + }, + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "tf_framework_ops.td", + deps = [":td_files"], +) + +gentbl_cc_library( + name = "tf_status_inc_gen", + compatible_with = get_compatible_with_portable(), + tbl_outs = { + "tf_status.h.inc": ["-gen-enum-decls"], + "tf_status.cc.inc": ["-gen-enum-defs"], + }, + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "tf_status.td", + deps = [":td_files"], +) + +cc_library( + name = "tf_framework_ops", + srcs = [ + "tf_framework_ops.cc", + "tf_framework_ops.cc.inc", + "tf_framework_ops.h.inc", + ], + hdrs = ["tf_framework_ops.h"], + deps = [ + ":tf_framework_ops_inc_gen", + ":tf_status_inc_gen", + "//tensorflow/core/protobuf:error_codes_proto_impl_cc", + "@com_google_absl//absl/status", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:AllocationOpInterface", + "@llvm-project//mlir:BufferizationDialect", + "@llvm-project//mlir:BytecodeOpInterface", + "@llvm-project//mlir:ControlFlowInterfaces", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:SideEffectInterfaces", + "@llvm-project//mlir:Support", + "@xla//xla/tsl/protobuf:error_codes_proto_impl_cc", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..91571e9c5b6d5936707f0f30bae393e4c1b88e3c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc @@ -0,0 +1,174 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file defines the operations used in the tf_framework dialect. + +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" + +#include + +#include "absl/status/status.h" +#include "llvm/Support/ErrorHandling.h" +#include "mlir/Dialect/Bufferization/IR/Bufferization.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/DialectImplementation.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.cc.inc" + +// Generated dialect definitions. +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_dialect.cc.inc" +#include "xla/tsl/protobuf/error_codes.pb.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +void TFFrameworkDialect::initialize() { + addOperations< +#define GET_OP_LIST +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc.inc" + >(); + addTypes(); +} + +/// Parse a type registered to this dialect. +Type TFFrameworkDialect::parseType(DialectAsmParser &parser) const { + StringRef keyword; + if (parser.parseKeyword(&keyword)) return Type(); + + if (keyword == "op_kernel_context") { + return OpKernelContextType::get(getContext()); + } + if (keyword == "jit_callable") { + return JITCallableType::get(getContext()); + } + + parser.emitError(parser.getNameLoc(), "unknown TF Framework type: ") + << keyword; + return Type(); +} + +/// Print a type registered to this dialect. +void TFFrameworkDialect::printType(Type type, DialectAsmPrinter &os) const { + if (mlir::isa(type)) { + os << "op_kernel_context"; + return; + } + if (mlir::isa(type)) { + os << "jit_callable"; + return; + } + llvm_unreachable("unexpected TF Framework type kind"); +} + +//===----------------------------------------------------------------------===// +// TFAllocOp +//===----------------------------------------------------------------------===// +LogicalResult TFAllocOp::verify() { + TFAllocOp op = *this; + // Check that the total number of operands matches the number of dynamic + // dimensions specified in the memref type. + unsigned result_dyn_dims = op.getType().getNumDynamicDims(); + unsigned dyn_sizes_count = op.getDynSizes().size(); + if (dyn_sizes_count != result_dyn_dims) + return op.emitOpError() + << "`dyn_sizes` count " << dyn_sizes_count + << " does not match dynamic dimensions count in the result type" + << op.getType(); + return success(); +} + +std::optional TFAllocOp::buildDealloc(OpBuilder &builder, + Value alloc) { + auto funcop = alloc.getParentRegion()->getParentOfType(); + return TFDeallocOp::create(builder, alloc.getLoc(), funcop.getArgument(0), + alloc) + .getOperation(); +} + +std::optional TFAllocOp::buildClone(OpBuilder &builder, Value alloc) { + // TODO(herhut): We should have our own clone op if one of these survives. + return mlir::bufferization::CloneOp::create(builder, alloc.getLoc(), alloc) + .getResult(); +} + +//===----------------------------------------------------------------------===// +// JITExecuteOp +//===----------------------------------------------------------------------===// + +std::optional JITExecuteOp::buildDealloc(OpBuilder &builder, + Value alloc) { + auto funcop = alloc.getParentRegion()->getParentOfType(); + return TFDeallocOp::create(builder, alloc.getLoc(), funcop.getArgument(0), + alloc) + .getOperation(); +} + +std::optional JITExecuteOp::buildClone(OpBuilder &builder, Value alloc) { + // TODO(herhut): We should have our own clone op if one of these survives. + return mlir::bufferization::CloneOp::create(builder, alloc.getLoc(), alloc) + .getResult(); +} + +absl::StatusCode ConvertAttrToEnumValue(ErrorCode error_code) { + using ::tensorflow::error::Code; + switch (error_code) { + case ErrorCode::OK: + return absl::StatusCode::kOk; + case ErrorCode::CANCELLED: + return absl::StatusCode::kCancelled; + case ErrorCode::UNKNOWN: + return absl::StatusCode::kUnknown; + case ErrorCode::INVALID_ARGUMENT: + return absl::StatusCode::kInvalidArgument; + case ErrorCode::DEADLINE_EXCEEDED: + return absl::StatusCode::kDeadlineExceeded; + case ErrorCode::NOT_FOUND: + return absl::StatusCode::kNotFound; + case ErrorCode::ALREADY_EXISTS: + return absl::StatusCode::kAlreadyExists; + case ErrorCode::PERMISSION_DENIED: + return absl::StatusCode::kPermissionDenied; + case ErrorCode::UNAUTHENTICATED: + return absl::StatusCode::kUnauthenticated; + case ErrorCode::RESOURCE_EXHAUSTED: + return absl::StatusCode::kResourceExhausted; + case ErrorCode::FAILED_PRECONDITION: + return absl::StatusCode::kFailedPrecondition; + case ErrorCode::ABORTED: + return absl::StatusCode::kAborted; + case ErrorCode::OUT_OF_RANGE: + return absl::StatusCode::kOutOfRange; + case ErrorCode::UNIMPLEMENTED: + return absl::StatusCode::kUnimplemented; + case ErrorCode::INTERNAL: + return absl::StatusCode::kInternal; + case ErrorCode::UNAVAILABLE: + return absl::StatusCode::kUnavailable; + case ErrorCode::DATA_LOSS: + return absl::StatusCode::kDataLoss; + } +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir + +#define GET_OP_CLASSES +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.cc.inc" diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..81d8cda0c6bcdf5122e39b31aca68139605ba8ea --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h @@ -0,0 +1,69 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file defines the operations used in the TFFramework dialect. +// +#ifndef TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_IR_TF_FRAMEWORK_OPS_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_IR_TF_FRAMEWORK_OPS_H_ + +#include "absl/status/status.h" +#include "mlir/Bytecode/BytecodeOpInterface.h" // from @llvm-project +#include "mlir/Dialect/Bufferization/IR/AllocationOpInterface.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Dialect.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OpDefinition.h" // from @llvm-project +#include "mlir/IR/OpImplementation.h" // from @llvm-project +#include "mlir/IR/TypeSupport.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/Interfaces/ControlFlowInterfaces.h" // from @llvm-project +#include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.h.inc" +#include "tensorflow/core/protobuf/error_codes.pb.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +/// OpKernelContextType corresponds to C++ class OpKernelContext defined in +/// tensorflow/core/framework/op_kernel.h +class OpKernelContextType + : public Type::TypeBase { + public: + using Base::Base; + static constexpr StringLiteral name = + "kernel_gen.tf_framework.op_kernel_context"; +}; + +class JITCallableType + : public Type::TypeBase { + public: + using Base::Base; + static constexpr StringLiteral name = "kernel_gen.tf_framework.jit_callable"; +}; + +absl::StatusCode ConvertAttrToEnumValue(ErrorCode error_code); + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir + +#define GET_OP_CLASSES +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_dialect.h.inc" +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h.inc" + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_IR_TF_FRAMEWORK_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td new file mode 100644 index 0000000000000000000000000000000000000000..04b50eab1cc444f807b19cb074a6b1e0c2eaaed4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.td @@ -0,0 +1,335 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This is the operation definition file for TF Framework ops. + +#ifndef TF_FRAMEWORK_OPS +#define TF_FRAMEWORK_OPS + +include "mlir/IR/OpBase.td" +include "mlir/Dialect/Bufferization/IR/AllocationOpInterface.td" +include "mlir/Interfaces/ControlFlowInterfaces.td" +include "mlir/Interfaces/SideEffectInterfaces.td" +include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td" + +def TFFramework_Dialect : Dialect { + let name = "tf_framework"; + + let summary = "Types and operations for tf_framework dialect"; + let description = [{ + This dialect contains operations and types for that correspond to + TensorFlow C++ Framework. + }]; + let cppNamespace = "::mlir::kernel_gen::tf_framework"; + + let extraClassDeclaration = [{ + static constexpr StringRef kTFEntryAttrName = "tf_entry"; + static constexpr size_t kAllocationAlignment = 16; + }]; + + let useDefaultTypePrinterParser = 1; +} + +def TFFramework_OpKernelContextType : DialectType($_self)">, + "op_kernel_construction">, + BuildableType<"$_builder.getType<::mlir::kernel_gen::tf_framework::OpKernelContextType>()"> { + let description = [{ + OpKernelContextType corresponds to C++ class OpKernelContext defined in + tensorflow/core/framework/op_kernel.h + }]; +} + +def TFFramework_JITCallableType : DialectType($_self)">>, + BuildableType<"$_builder.getType<::mlir::kernel_gen::tf_framework::JITCallableType>()"> { + let description = [{ + A `callable` represents the result of JIT compilation. Conceptually, it + corresponds to a function pointer. + }]; +} + +// Base class for TF Framework dialect ops. +class TFFramework_Op traits = []> : + Op; + +//===----------------------------------------------------------------------===// +// TFAllocOp +//===----------------------------------------------------------------------===// +def TFFramework_TFAllocOp : TFFramework_Op<"alloc", [ + MemoryEffects<[MemAlloc]>, + DeclareOpInterfaceMethods + ]> { + let summary = "allocation of tensors that uses TF Framework"; + let description = [{ + Allocation of tensors during kernel execution in the Compute method. + + This should be used to allocate any temporary or output memref. If + `output_index` and `input_indices` are given, attempts to forward one of + the input tensors to the output by calling `OpKernelContext::forward_input`. + + If the attributes are missing or the forwarding fails, calls + `Allocator::AllocateRaw` in tensorflow/core/framework/allocator.h. + }]; + + let arguments = (ins + TFFramework_OpKernelContextType:$ctx, + Variadic:$dyn_sizes, + OptionalAttr:$input_indices, + OptionalAttr:$output_index + ); + let results = (outs Res]>:$result); + + let builders = [ + OpBuilder<(ins "MemRefType":$memref_type, "Value":$ctx), + [{ + $_state.addOperands(ctx); + $_state.types.push_back(memref_type); + }]>, + OpBuilder<(ins "MemRefType":$memref_type, "Value":$ctx, + "ValueRange":$dyn_sizes), + [{ + build($_builder, $_state, memref_type, ctx); + $_state.addOperands(dyn_sizes); + }]>]; + + let extraClassDeclaration = [{ + MemRefType getType() { return llvm::cast(getResult().getType()); } + static constexpr StringRef kReuseOutputAttrName = "reuse_output"; + static constexpr StringRef kReuseInputCandidatesAttrName = + "reuse_input_candidates"; + }]; + let assemblyFormat = [{ + `(` $ctx (`,` $dyn_sizes^ )? `)` attr-dict `:` type($result) + }]; + + let hasVerifier = 1; +} + +//===----------------------------------------------------------------------===// +// TFAssertOp +//===----------------------------------------------------------------------===// +def TFFramework_TFAssertOp : TFFramework_Op<"assert"> { + let summary = "Assert operation with message attribute and error code"; + let description = [{ + Assert operation that propagates the error message to TF Framework. + }]; + + let arguments = (ins + TFFramework_OpKernelContextType:$ctx, + I1:$arg, + TFFramework_ErrorCodeAttr:$error_code, + StrAttr:$msg + ); + + let assemblyFormat = "$ctx `,` $arg `,` $error_code `,` $msg attr-dict"; +} + +//===----------------------------------------------------------------------===// +// TFDeallocOp +//===----------------------------------------------------------------------===// +def TFFramework_TFDeallocOp : TFFramework_Op<"dealloc", + [MemoryEffects<[MemFree]>]> { + let summary = "deallocation of tensors that uses TF Framework"; + let description = [{ + Deallocation of tensors during kernel execution in the Compute method. + + This should be used to deallocate any temporary memref that was allocated + with `tf_framework.alloc`. + Corresponds to `Allocator::DeallocateRaw` in + tensorflow/core/framework/allocator.h. + }]; + + let arguments = (ins TFFramework_OpKernelContextType:$ctx, + Arg:$memref); + let assemblyFormat = "`(` $ctx `,` $memref `)` attr-dict `:` type($memref)"; +} + +//===----------------------------------------------------------------------===// +// IsValidMemRefOp +//===----------------------------------------------------------------------===// +def TFFramework_IsValidMemRefOp : TFFramework_Op<"is_valid_memref", []> { + let summary = "Op to check if the memref is valid."; + let description = [{ + The op checks if the allocation was successful so that the underlying ptr + in the descriptor is not equal to NULL. Also, we check if the number of + elements is not zero to support empty shapes inputs correctly. + + is_valid_memref(memref) = ptr(memref) != NULL || num_elements(memref) == 0 + }]; + + let arguments = (ins AnyMemRef:$arg); + let results = (outs I1:$result); + let assemblyFormat = [{ + `(` $arg `)` attr-dict `:` type($arg) `->` type($result) + }]; +} + +//===----------------------------------------------------------------------===// +// NullContextOp +//===----------------------------------------------------------------------===// +def TFFramework_NullContextOp : TFFramework_Op<"null_context", + [Pure]> { + let summary = "Creates a fake TF context that will be lowered to nullptr"; + let description = [{Needed for testing}]; + let results = (outs TFFramework_OpKernelContextType:$result); + let assemblyFormat = "attr-dict `:` type($result)"; +} + +//===----------------------------------------------------------------------===// +// NullMemRefOp +//===----------------------------------------------------------------------===// +def TFFramework_NullMemRefOp : TFFramework_Op<"null_memref", []> { + let summary = "Op to construct unranked memref with 0-rank"; + let description = [{ + The op is needed to construct a throw-away result after error reporting + happened. It constructs a ranked memref descriptor with 0-rank and + {NULL, NULL, 0} underlying ranked descriptor of type memref. + In ranked case it constructs a ranked memref descriptor depending on the + result type, but sets both allocated and aligned pointers to NULL. + }]; + + let results = (outs AnyRankedOrUnrankedMemRef:$result); + let assemblyFormat = "attr-dict `:` type($result)"; +} + +//===----------------------------------------------------------------------===// +// ReportErrorOp +//===----------------------------------------------------------------------===// +def TFFramework_ReportErrorOp : TFFramework_Op<"report_error", []> { + let summary = "Operation that propagates error message to TF Framework"; + let description = [{ + Error reporting operation that corresponds to + `OpKernelContext::CtxFailureWithWarning`. + }]; + + let arguments = (ins + TFFramework_OpKernelContextType:$ctx, + TFFramework_ErrorCodeAttr:$error_code, + StrAttr:$msg + ); + + let assemblyFormat = "$ctx `,` $error_code `,` $msg attr-dict"; +} + +//===----------------------------------------------------------------------===// +// JITCompileOp +//===----------------------------------------------------------------------===// + +def TFFramework_JITCompileOp : TFFramework_Op<"jit_compile", [SingleBlock]> { + let summary = "Invokes JIT compilation through the TF framework"; + let description = [{ + The op takes an optional TF context, so that it can be added at a later + stage in the compilation pipeline. The op's body corresponds to a function + body and the corresponding `tf_framework.jit_compile_yield` represents the + result value(s). + }]; + + let arguments = (ins + Optional:$ctx + ); + let results = (outs TFFramework_JITCallableType:$result); + let regions = (region SizedRegion<1>:$body); + + let assemblyFormat = "$ctx $body attr-dict"; +} + +//===----------------------------------------------------------------------===// +// JITCompileYieldOp +//===----------------------------------------------------------------------===// + +def TFFramework_JITCompileYieldOp : TFFramework_Op<"jit_compile_yield", [ + Pure, ReturnLike, Terminator, HasParent<"JITCompileOp">]> { + let summary = "Yields the results in a `tf_framework.jit_compile` op's body"; + let description = [{ + See `tf_framework.jit_compile`. + }]; + + let arguments = (ins + AnyTypeOf<[AnyRankedOrUnrankedMemRef, AnyTensor]>:$result + ); + + let assemblyFormat = "$result attr-dict `:` type($result)"; +} + +//===----------------------------------------------------------------------===// +// JITCompileFromStrOp +//===----------------------------------------------------------------------===// + +def TFFramework_JITCompileFromStrOp : TFFramework_Op<"jit_compile_from_str", + []> { + let summary = "Invokes JIT compilation through the TF framework"; + let description = [{ + This operation is similar to `tf_framework.jit_compile`. Instead of a body, + the to-be-compiled function is represented as a string attribute. The string + shall be the serialized form of a module with a single function named + `main`. + }]; + + let arguments = (ins + Optional:$ctx, + StrAttr:$code, + I64ArrayAttr:$tileSizes, + I64ArrayAttr:$unrollFactors, + BoolAttr:$enableFtz, + BoolAttr:$index64Bit, + BoolAttr:$cpuCodegen + ); + let results = (outs TFFramework_JITCallableType:$result); + + let extraClassDeclaration = [{ + static constexpr StringRef kJITEntryFunctionName = "main"; + }]; + + let assemblyFormat = "($ctx^ `,`)? $code attr-dict"; +} + +//===----------------------------------------------------------------------===// +// JITExecuteOp +//===----------------------------------------------------------------------===// + +def TFFramework_JITExecuteOp : TFFramework_Op<"jit_execute", [ + AttrSizedOperandSegments, + MemoryEffects<[MemAlloc]>, + DeclareOpInterfaceMethods]> { + let summary = "Executes a JIT-compiled function through the TF framework"; + let description = [{ + The op takes an optional TF context, so that it can be added at a later + stage in the compilation pipeline. The callable must be a JIT-compiled + function that is the result of either `tf_framework.jit_compile` or + `tf_framework.jit_compile_from_str`. The remaining operands must be tensor + or memref arguments and will be forwarded to the callable function. The + result types must match those of the callable function. Otherwise, the + execution behavior is undefined. + }]; + + let arguments = (ins + Optional:$ctx, + TFFramework_JITCallableType:$callable, + Variadic>:$inputs + ); + let results = (outs + Res , "", + [MemAlloc]>:$result); + + let assemblyFormat = [{ + (`ctx` `(` $ctx^ `)`)? $callable `(` $inputs `)` attr-dict + `:` type($inputs) `->` type($result) + }]; +} + +#endif // TF_FRAMEWORK_OPS diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td new file mode 100644 index 0000000000000000000000000000000000000000..b4db48e14b31137741398cdae2549326865c5848 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_status.td @@ -0,0 +1,81 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This is the enum definition file for TF Status attribute. + +#ifndef TF_FRAMEWORK_STATUS +#define TF_FRAMEWORK_STATUS + +include "mlir/IR/EnumAttr.td" +include "mlir/IR/OpBase.td" + +def TFFramework_ERROR_CODE_OK + : I32EnumAttrCase<"OK", 0>; +def TFFramework_ERROR_CODE_CANCELLED + : I32EnumAttrCase<"CANCELLED", 1>; +def TFFramework_ERROR_CODE_UNKNOWN + : I32EnumAttrCase<"UNKNOWN", 2>; +def TFFramework_ERROR_CODE_INVALID_ARGUMENT + : I32EnumAttrCase<"INVALID_ARGUMENT", 3>; +def TFFramework_ERROR_CODE_DEADLINE_EXCEEDED + : I32EnumAttrCase<"DEADLINE_EXCEEDED", 4>; +def TFFramework_ERROR_CODE_NOT_FOUND + : I32EnumAttrCase<"NOT_FOUND", 5>; +def TFFramework_ERROR_CODE_ALREADY_EXISTS + : I32EnumAttrCase<"ALREADY_EXISTS", 6>; +def TFFramework_ERROR_CODE_PERMISSION_DENIED + : I32EnumAttrCase<"PERMISSION_DENIED", 7>; +def TFFramework_ERROR_CODE_UNAUTHENTICATED + : I32EnumAttrCase<"UNAUTHENTICATED", 16>; +def TFFramework_ERROR_CODE_RESOURCE_EXHAUSTED + : I32EnumAttrCase<"RESOURCE_EXHAUSTED", 8>; +def TFFramework_ERROR_CODE_FAILED_PRECONDITION + : I32EnumAttrCase<"FAILED_PRECONDITION", 9>; +def TFFramework_ERROR_CODE_ABORTED + : I32EnumAttrCase<"ABORTED", 10>; +def TFFramework_ERROR_CODE_OUT_OF_RANGE + : I32EnumAttrCase<"OUT_OF_RANGE", 11>; +def TFFramework_ERROR_CODE_UNIMPLEMENTED + : I32EnumAttrCase<"UNIMPLEMENTED", 12>; +def TFFramework_ERROR_CODE_INTERNAL + : I32EnumAttrCase<"INTERNAL", 13>; +def TFFramework_ERROR_CODE_UNAVAILABLE + : I32EnumAttrCase<"UNAVAILABLE", 14>; +def TFFramework_ERROR_CODE_DATA_LOSS + : I32EnumAttrCase<"DATA_LOSS", 15>; + +def TFFramework_ErrorCodeAttr : I32EnumAttr<"ErrorCode", "error code", [ + TFFramework_ERROR_CODE_OK, + TFFramework_ERROR_CODE_CANCELLED, + TFFramework_ERROR_CODE_UNKNOWN, + TFFramework_ERROR_CODE_INVALID_ARGUMENT, + TFFramework_ERROR_CODE_DEADLINE_EXCEEDED, + TFFramework_ERROR_CODE_NOT_FOUND, + TFFramework_ERROR_CODE_ALREADY_EXISTS, + TFFramework_ERROR_CODE_PERMISSION_DENIED, + TFFramework_ERROR_CODE_UNAUTHENTICATED, + TFFramework_ERROR_CODE_RESOURCE_EXHAUSTED, + TFFramework_ERROR_CODE_FAILED_PRECONDITION, + TFFramework_ERROR_CODE_ABORTED, + TFFramework_ERROR_CODE_OUT_OF_RANGE, + TFFramework_ERROR_CODE_UNIMPLEMENTED, + TFFramework_ERROR_CODE_INTERNAL, + TFFramework_ERROR_CODE_UNAVAILABLE, + TFFramework_ERROR_CODE_DATA_LOSS +]> { + let cppNamespace = "::mlir::kernel_gen::tf_framework"; +} + +#endif // TF_FRAMEWORK_STATUS diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.cc new file mode 100644 index 0000000000000000000000000000000000000000..089cc4dc90b8cdd2f9263eb4f0ee4386e349f003 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.cc @@ -0,0 +1,506 @@ +/* Copyright 2020 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. +==============================================================================*/ + +//===- kernel_creator.cc ----------------------------------------*- C++ -*-===// +// +// This file implements the function to compile a TF kernel function to gpu +// binary (hsaco for AMD, cubin for NVIDIA) or to a gpu binary with host side. +// +//===----------------------------------------------------------------------===// +#include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h" + +#include + +#include "absl/status/status.h" +#include "llvm/ADT/ArrayRef.h" +#include "mlir/Conversion/AffineToStandard/AffineToStandard.h" // from @llvm-project +#include "mlir/Conversion/ComplexToStandard/ComplexToStandard.h" // from @llvm-project +#include "mlir/Conversion/GPUCommon/GPUCommonPass.h" // from @llvm-project +#include "mlir/Conversion/GPUToNVVM/GPUToNVVMPass.h" // from @llvm-project +#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" // from @llvm-project +#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" // from @llvm-project +#include "mlir/Conversion/SCFToGPU/SCFToGPUPass.h" // from @llvm-project +#include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" // from @llvm-project +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Arith/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Bufferization/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Complex/IR/Complex.h" // from @llvm-project +#include "mlir/Dialect/ControlFlow/IR/ControlFlow.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/GPU/IR/GPUDialect.h" // from @llvm-project +#include "mlir/Dialect/GPU/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Linalg/Passes.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/Dialect/MemRef/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/NVVM/Transforms/OptimizeForNVVM.h" // from @llvm-project +#include "mlir/Dialect/SCF/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project +#include "mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/Interfaces/DataLayoutInterfaces.h" // from @llvm-project +#include "mlir/Parser/Parser.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Dialect/Builtin/BuiltinToLLVMIRTranslation.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Dialect/GPU/GPUToLLVMIRTranslation.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Dialect/LLVMIR/LLVMToLLVMIRTranslation.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Dialect/NVVM/NVVMToLLVMIRTranslation.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Dialect/ROCDL/ROCDLToLLVMIRTranslation.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "mlir/Transforms/Passes.h" // from @llvm-project +#include "stablehlo/conversions/linalg/transforms/Passes.h" // from @stablehlo +#include "stablehlo/dialect/ChloOps.h" // from @stablehlo +#include "stablehlo/transforms/Passes.h" // from @stablehlo +#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" +#include "xla/mlir_hlo/deallocation/transforms/passes.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/mlir_hlo/mhlo/transforms/passes.h" +#include "xla/mlir_hlo/transforms/gpu_passes.h" +#include "xla/mlir_hlo/transforms/passes.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { +namespace kernel_gen { +namespace { + +using mlir::Value; +using mlir::func::FuncOp; +using mlir::memref::RankOp; + +constexpr llvm::StringRef kGpuBinaryAttrName = "gpu.binary"; + +/// Check if the size of the allocation is less than the given size. The +/// transformation is only applied to small buffers since large buffers could +/// exceed the stack space. +bool IsSmallAlloc(Value alloc) { + constexpr unsigned kMaximumSizeInBytes = 64; + constexpr unsigned kMaxRankOfAllocatedMemRef = 1; + + auto type = mlir::dyn_cast(alloc.getType()); + if (!type || !alloc.getDefiningOp()) return false; + if (!type.hasStaticShape()) { + // Check if the dynamic shape dimension of the alloc is produced by RankOp + // or SelectOp(_, RankOp, RankOp). + // If this is the case, it is likely to be small. Furthermore, the dimension + // is limited to the maximum rank of the allocated memref to avoid large + // values by multiplying several small values. + if (type.getRank() <= kMaxRankOfAllocatedMemRef) { + for (Value alloc_arg : alloc.getDefiningOp()->getOperands()) { + if (auto select = alloc_arg.getDefiningOp()) { + if (!select.getTrueValue().getDefiningOp() || + !select.getFalseValue().getDefiningOp()) + return false; + } else if (!alloc_arg.getDefiningOp()) { + return false; + } + } + return true; + } + return false; + } + unsigned bitwidth = mlir::DataLayout::closest(alloc.getDefiningOp()) + .getTypeSizeInBits(type.getElementType()); + return type.getNumElements() * bitwidth <= kMaximumSizeInBytes * 8; +} + +absl::Status LowerHloToJITInvocation(mlir::ModuleOp module, + llvm::ArrayRef tile_sizes, + llvm::ArrayRef unroll_factors, + bool enable_ftz, bool index_64bit, + bool jit_i64_indexed_for_large_tensors, + bool apply_cl_options) { + mlir::PassManager pm(module.getContext()); + if (apply_cl_options) applyTensorflowAndCLOptions(pm); + + pm.addNestedPass( + mlir::kernel_gen::transforms::CreateFuncToJITInvocationPass( + tile_sizes, unroll_factors, enable_ftz, index_64bit, + /*cpu_codegen=*/false, jit_i64_indexed_for_large_tensors)); + pm.addPass(mlir::kernel_gen::tf_framework::CreateEmbedTFFrameworkPass()); + pm.addNestedPass( + mlir::bufferization::createEmptyTensorToAllocTensorPass()); + pm.addPass(mlir::createComputeOpAndFuncBufferizePass()); + + pm.addPass(mlir::createFinalBufferizePass( + /*alignment=*/64, + mlir::kernel_gen::transforms::populateExtraBufferizeDialects, + mlir::kernel_gen::transforms::populateExtraBufferizePatterns)); + + if (failed(pm.run(module))) { + return absl::InternalError("Lowering HLO to JIT invocation failed."); + } + return absl::OkStatus(); +} + +absl::Status LowerHlotoLoops(mlir::ModuleOp module, + llvm::ArrayRef tile_sizes, + llvm::ArrayRef unroll_factors, + bool enable_ftz, bool index_64bit, + bool jit_i64_indexed_for_large_tensors, + bool apply_cl_options) { + mlir::PassManager pm(module.getContext()); + if (apply_cl_options) applyTensorflowAndCLOptions(pm); + if (jit_i64_indexed_for_large_tensors) { + pm.addNestedPass( + mlir::kernel_gen::transforms::CreateFuncToJITInvocationPass( + tile_sizes, unroll_factors, enable_ftz, index_64bit, + /*cpu_codegen=*/false, + /*jit_i64_indexed_for_large_tensors=*/true)); + } + + pm.addNestedPass( + mlir::stablehlo::createChloLegalizeToStablehloPass()); + pm.addPass(mlir::mhlo::createStablehloLegalizeToHloPass()); + + pm.addNestedPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(mlir::createCSEPass()); + pm.addNestedPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(mlir::kernel_gen::createShapeSimplificationPass()); + pm.addNestedPass(mlir::kernel_gen::createMergeAssumingOpsPass()); + pm.addNestedPass(mlir::kernel_gen::createBroadcastPropagationPass()); + pm.addNestedPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(mlir::createCSEPass()); + + // Transform HLO operations to Linalg and standard. + mlir::mhlo::HloLegalizeToStablehloPassOptions options; + options.allow_xla_features_ = true; // MinimumBroadcastOp + pm.addPass(mlir::mhlo::createHloLegalizeToStablehloPass(options)); + + // Allowing implicit captures of scalar inputs causes crashes in kernelgen + // JIT kernels. + mlir::stablehlo::StablehloLegalizeToLinalgPassOptions linalg_options; + linalg_options.captureScalarInputs = false; + pm.addNestedPass( + mlir::stablehlo::createStablehloLegalizeToLinalgPass(linalg_options)); + pm.addPass(mlir::mhlo::createStablehloLegalizeToHloPass()); + + // Convert tensor.reshape to MHLO before running any bufferization passes. + // We'll need to teach this pipeline how to properly handle tensor.reshape + // in order to fully deprecate MHLO but in the meantime this ublocks lots of + // cleanup. + pm.addNestedPass( + ::mlir::kernel_gen::createLegalizeTensorReshapePass()); + + // Remove the remaining references to unsigned types after all HLO compute + // operations were converted. + pm.addPass(mlir::stablehlo::createStablehloConvertToSignlessPass()); + + pm.addPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(mlir::createCSEPass()); + + // Convert operations from the Complex dialect to the Standard/Math dialects. + pm.addNestedPass(::mlir::createConvertComplexToStandardPass()); + + // Fuse linalg operations. + pm.addPass(mlir::memref::createResolveShapedTypeResultDimsPass()); + pm.addPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(mlir::createLinalgElementwiseOpFusionPass()); + + // Partial bufferization: Transforms in particular HLO and Linalg operations + // to their corresponding LHLO operations and converts the function signature. + // Leaves shape operations untouched. + // + // TODO(pifon): Rename the pass to CreateHloLinalgBufferizePass or bufferize + // in 2 steps: first Linalg, then Hlo. That would need refactoring of + // BufferizeTypeConverter. + pm.addNestedPass( + mlir::bufferization::createEmptyTensorToAllocTensorPass()); + pm.addPass(mlir::createComputeOpAndFuncBufferizePass()); + pm.addNestedPass(::mlir::createCanonicalizerPass()); + pm.addNestedPass(::mlir::createCSEPass()); + // Remove copies which are introduced by canonicalizing + // BufferCastOp(TensorLoadOp). + pm.addNestedPass( + mlir::kernel_gen::transforms::CreateCopyCleanupPass()); + // Find candidates for buffer reuse. This is only successful if buffer size + // equality can be determined based on `linalg.generic` operations. + pm.addNestedPass( + mlir::kernel_gen::transforms::CreateBufferReusePass()); + // Approximate Tanh using standard operations. + pm.addNestedPass( + ::mlir::mhlo::createLegalizeTrigonometricToApproximationPass()); + // Transform the Linalg ops inside of the loop nest into parallel loops. + pm.addNestedPass(::mlir::createConvertLinalgToParallelLoopsPass()); + + // Canonicalize the code to simplify index computations. This is needed so + // that loop bounds have the same value. + pm.addNestedPass(::mlir::createCanonicalizerPass()); + // Run CSE to ensure that loads and stores to the same subview get + // recognized as such. + pm.addNestedPass(::mlir::createCSEPass()); + // Collapse and tile parallel loops for GPU only. + pm.addNestedPass(mlir::createCollapseParallelLoopsTo1DPass()); + pm.addNestedPass( + mlir::createTileLoopsPass(tile_sizes, unroll_factors)); + + pm.addNestedPass(::mlir::createCanonicalizerPass()); + pm.addNestedPass(::mlir::createCSEPass()); + if (failed(pm.run(module))) { + return absl::InternalError("Lowering HLO to loops failed."); + } + return absl::OkStatus(); +} + +absl::Status LowerLoopsToGPU(mlir::ModuleOp module, bool index_64bit, + bool apply_cl_options) { + mlir::PassManager pm(module.getContext()); + if (apply_cl_options) applyTensorflowAndCLOptions(pm); + + // Greedily map the remaining loop to GPU hardware dimensions. + pm.addNestedPass(mlir::createGpuMapParallelLoopsPass()); + + // Expand memref_reshape to its ranked form so that we can propagate + // scalars and avoid allocation. + pm.addNestedPass(mlir::arith::createArithExpandOpsPass()); + pm.addNestedPass(mlir::memref::createExpandOpsPass()); + pm.addPass(mlir::createCanonicalizerPass()); + pm.addPass(mlir::kernel_gen::transforms::CreateShapeToDescriptorsPass()); + // Before bufferizing further, remove unused tensor_to_memref, so that we do + // not create allocations for tensor computations that are not actually + // needed. + pm.addPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(mlir::createCSEPass()); + // Before inserting more allocs, map the ones we already have to the + // tf runtime. That ensures that all allocations for the actual computation + // end up on the device, whereas allocations for shape computation and host + // side things remain on the host. + // Longer term, this should be handled by proper device placement. + pm.addPass(mlir::kernel_gen::tf_framework::CreateEmbedTFFrameworkPass()); + // Now lower the shape computations, bufferize all remaining ops and insert + // deallocs. + pm.addPass(mlir::createFinalBufferizePass( + /*alignment=*/64, + mlir::kernel_gen::transforms::populateExtraBufferizeDialects, + mlir::kernel_gen::transforms::populateExtraBufferizePatterns)); + pm.addNestedPass(::mlir::bufferization::createBufferHoistingPass()); + pm.addNestedPass(mlir::bufferization::createPromoteBuffersToStackPass( + [](Value alloc) { return IsSmallAlloc(alloc); })); + // Free all temporaries, + pm.addNestedPass(mlir::deallocation::createBufferDeallocationPass()); + pm.addPass(mlir::createCanonicalizerPass()); + pm.addNestedPass(::mlir::createConvertLinalgToLoopsPass()); + + // Apply the mapping and go to GPU. We cannot do this earlier as the GPU + // dialect requires memrefs. + pm.addNestedPass(mlir::createConvertParallelLoopToGpuPass()); + + // Some basic cleanup. + pm.addNestedPass(::mlir::createCanonicalizerPass()); + pm.addNestedPass(::mlir::createCSEPass()); + // Make loops with min bounds into a conditional plus static bounds. + pm.addNestedPass(mlir::createForLoopSpecializationPass()); + // Take launches to launches with kernels. + pm.addPass(mlir::createGpuLaunchSinkIndexComputationsPass()); + const std::string gpuDataLayoutSpec = + index_64bit ? "#dlti.dl_spec<#dlti.dl_entry>" + : "#dlti.dl_spec<#dlti.dl_entry>"; + pm.addPass( + mlir::createGpuKernelOutliningPass({.dataLayoutStr = gpuDataLayoutSpec})); + + pm.addPass(::mlir::createLowerAffinePass()); + // Constraints are removed as late as possible and before lowering to CFG. + pm.addNestedPass(::mlir::createConvertShapeConstraintsPass()); + pm.addNestedPass(::mlir::createCanonicalizerPass()); + pm.addPass(::mlir::createSCFToControlFlowPass()); + // Map asserts to the tensorflow framework. + pm.addPass(mlir::kernel_gen::tf_framework::CreateRewriteTFFrameworkAssert()); + if (failed(pm.run(module))) { + return absl::InternalError("Lowering to GPU kernels failed."); + } + return absl::OkStatus(); +} + +absl::Status LowerKernelBodiesToLowLevelIr(mlir::ModuleOp module, + bool apply_cl_options, + const std::string& architecture) { +#if !defined(TENSORFLOW_USE_ROCM) && !defined(GOOGLE_CUDA) + return absl::InternalError( + "Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined." + " Did you specify either --config=rocm or --config=cuda ?"); +#endif + +#if TENSORFLOW_USE_ROCM + auto gpu_modules = module.getOps<::mlir::gpu::GPUModuleOp>(); + for (::mlir::gpu::GPUModuleOp gpu_module : gpu_modules) { + gpu_module.walk([&](mlir::gpu::GPUFuncOp gpu_kernel) { + if (gpu_kernel.isKernel()) { + gpu_kernel->setAttr( + "rocdl.max_flat_work_group_size", + mlir::IntegerAttr::get( + mlir::IntegerType::get(module.getContext(), 32), 1024)); + } + }); + } +#endif + + mlir::PassManager pm(module.getContext()); + // We cannot verify as the signature of the kernel is rewritten. + // pm.enableVerifier(false); + if (apply_cl_options) tensorflow::applyTensorflowAndCLOptions(pm); + auto& kernelPm = pm.nest<::mlir::gpu::GPUModuleOp>(); + kernelPm.addPass(::mlir::createSCFToControlFlowPass()); +#if TENSORFLOW_USE_ROCM + kernelPm.addPass(mlir::createGpuKernelToRocdlPass(architecture)); +#elif GOOGLE_CUDA + kernelPm.addPass(mlir::createGpuKernelToNvvmPass()); + kernelPm.addPass(mlir::NVVM::createNVVMOptimizeForTargetPass()); +#endif + // Remove all location information to prevent a debug build. + pm.addPass(::mlir::createStripDebugInfoPass()); + + if (failed(pm.run(module))) { + return absl::InternalError("Lowering to low-level device IR failed."); + } + + return absl::OkStatus(); +} + +absl::Status AmendKernelLLVMIRWithStaticKnowledge(mlir::ModuleOp module, + bool apply_cl_options) { + mlir::PassManager pm(module.getContext()); + if (apply_cl_options) applyTensorflowAndCLOptions(pm); + + pm.addNestedPass( + mlir::kernel_gen::transforms::CreatePropagateShapeKnowledgeToKernels()); + pm.addNestedPass( + mlir::kernel_gen::transforms::CreatePropagateTfAbiKnowledgeToKernels()); + + return failed(pm.run(module)) + ? absl::InternalError( + "Amending LLVMIR with static knowledge failed.") + : absl::OkStatus(); +} + +absl::Status GenerateDeviceCode(mlir::ModuleOp module, + llvm::StringRef gpu_binary_attr_name, + llvm::ArrayRef architectures, + bool print_ptx, bool print_llvmir, + bool enable_ftz, bool apply_cl_options) { + mlir::PassManager pm(module.getContext()); + if (apply_cl_options) applyTensorflowAndCLOptions(pm); + mlir::registerLLVMDialectTranslation(*module->getContext()); + + auto& kernel_pm = pm.nest(); + // Remove debug information to ensure we do not create debug PTX. + kernel_pm.addPass(mlir::createStripDebugInfoPass()); + kernel_pm.addPass(mlir::kernel_gen::transforms::CreateGpuKernelToBlobPass( + gpu_binary_attr_name, architectures, print_ptx, print_llvmir, + enable_ftz)); + + return failed(pm.run(module)) + ? absl::InternalError("Generating device code failed.") + : absl::OkStatus(); +} + +absl::Status LowerHostSideToFinalForm(mlir::ModuleOp module, + bool apply_cl_options) { + mlir::PassManager pm(module.getContext()); + if (apply_cl_options) applyTensorflowAndCLOptions(pm); + + pm.addPass(mlir::kernel_gen::transforms::CreateTFKernelToLLVMPass( + kGpuBinaryAttrName)); + pm.addPass(mlir::createReconcileUnrealizedCastsPass()); + pm.addPass(mlir::createCanonicalizerPass()); + pm.addPass(mlir::createCSEPass()); + + return failed(pm.run(module)) + ? absl::InternalError("Final lowering of host side failed.") + : absl::OkStatus(); +} + +} // namespace + +absl::StatusOr> SetupContextAndParseModule( + mlir::MLIRContext& context, llvm::StringRef tf_code) { + mlir::DialectRegistry registry; + registry.insert(); + registry.insert(); + registry.insert(); + mlir::registerBuiltinDialectTranslation(registry); + mlir::registerGPUDialectTranslation(registry); + mlir::registerLLVMDialectTranslation(registry); + mlir::registerNVVMDialectTranslation(registry); + mlir::registerROCDLDialectTranslation(registry); + context.appendDialectRegistry(registry); + mlir::OwningOpRef module = + mlir::parseSourceString(tf_code, &context); + if (!module) { + return absl::Status(absl::StatusCode::kInvalidArgument, + "invalid kernel IR"); + } + return module; +} + +absl::StatusOr> GenerateKernelForHloCode( + mlir::MLIRContext& context, llvm::StringRef tf_code, + llvm::ArrayRef architectures, + llvm::ArrayRef tile_sizes, llvm::ArrayRef unroll_factors, + bool print_ptx, bool print_llvmir, bool enable_ftz, bool index_64bit, + bool jit_compile, bool jit_i64_indexed_for_large_tensors, + bool apply_cl_options) { + if (jit_compile && jit_i64_indexed_for_large_tensors) { + return absl::Status( + absl::StatusCode::kInvalidArgument, + "jit compilation for large tensors " + "(`jit_i64_indexed_for_large_tensors`) and unconditioned jit " + "compilation (`jit`) must not be requested together"); + } + + TF_ASSIGN_OR_RETURN(mlir::OwningOpRef module, + SetupContextAndParseModule(context, tf_code)); + + if (jit_compile) { + assert(!jit_i64_indexed_for_large_tensors && + "expect to have reported an error earlier"); + TF_RETURN_IF_ERROR(LowerHloToJITInvocation( + module.get(), tile_sizes, unroll_factors, enable_ftz, index_64bit, + /*jit_i64_indexed_for_large_tensors=*/false, apply_cl_options)); + } else { + TF_RETURN_IF_ERROR(LowerHlotoLoops( + module.get(), tile_sizes, unroll_factors, enable_ftz, index_64bit, + jit_i64_indexed_for_large_tensors, apply_cl_options)); + TF_RETURN_IF_ERROR( + LowerLoopsToGPU(module.get(), index_64bit, apply_cl_options)); + + // Note: we're just passing the first architecture out of the list. This + // should be sufficient for now, but in the future perhaps we'll need + // restructure this code to generate separate MLIR modules for each + // architecture. + const std::string& first_architecture = + !architectures.empty() ? architectures[0] : ""; + TF_RETURN_IF_ERROR(LowerKernelBodiesToLowLevelIr( + module.get(), apply_cl_options, first_architecture)); + TF_RETURN_IF_ERROR( + AmendKernelLLVMIRWithStaticKnowledge(module.get(), apply_cl_options)); + TF_RETURN_IF_ERROR(GenerateDeviceCode( + module.get(), kGpuBinaryAttrName, architectures, print_ptx, + print_llvmir, enable_ftz, apply_cl_options)); + } + + TF_RETURN_IF_ERROR(LowerHostSideToFinalForm(module.get(), apply_cl_options)); + + return module; +} + +} // namespace kernel_gen +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h new file mode 100644 index 0000000000000000000000000000000000000000..b5bf9da3c80fca7fcfb29d88bfda1ea9495d8ce6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h @@ -0,0 +1,58 @@ +/* Copyright 2020 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. +==============================================================================*/ + +//===- kernel_creator.h -----------------------------------------*- C++ -*-===// +// +// This file declares the function to compile a TF kernel function to gpu +// binary (hsaco for AMD, cubin for NVIDIA) or to a gpu binary with host side. +// +//===----------------------------------------------------------------------===// +#ifndef TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_KERNEL_CREATOR_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_KERNEL_CREATOR_H_ + +#include +#include +#include + +#include "absl/status/statusor.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/StringRef.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { +namespace kernel_gen { + +// Parses tf_code to create a module. An MLIRContext is taken in case any +// unexpected dialects are needed. +absl::StatusOr> SetupContextAndParseModule( + mlir::MLIRContext& context, llvm::StringRef tf_code); + +// Converts TF code to LLVM with or without GPU support. +absl::StatusOr> GenerateKernelForHloCode( + mlir::MLIRContext& context, llvm::StringRef tf_code, + llvm::ArrayRef architectures, + llvm::ArrayRef tile_sizes, llvm::ArrayRef unroll_factors, + bool print_ptx, bool print_llvmir, bool enable_ftz, bool index_64bit, + bool jit_compile, bool jit_i64_indexed_for_large_tensors, + bool apply_cl_options); + +} // namespace kernel_gen +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_KERNEL_CREATOR_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..870ac82a16218defab4674b5ebadfc6f4a85c7b9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/BUILD @@ -0,0 +1,27 @@ +load("//tensorflow:tensorflow.default.bzl", "filegroup") +load("//tensorflow/compiler/mlir:glob_lit_test.bzl", "glob_lit_tests") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + licenses = ["notice"], +) + +glob_lit_tests( + name = "all_tests", + data = [":test_utilities"], + driver = "//tensorflow/compiler/mlir:run_lit.sh", + test_file_exts = ["mlir"], +) + +# Bundle together all of the test utilities that are used by tests. +filegroup( + name = "test_utilities", + testonly = True, + data = [ + "//tensorflow/compiler/mlir:tf-opt", + "//tensorflow/compiler/mlir/tools/kernel_gen:kernel-gen-opt", + "@llvm-project//llvm:FileCheck", + "@llvm-project//mlir:run_lit.sh", + "@xla//xla/mlir_hlo:mlir-hlo-opt", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/broadcast_propagation.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/broadcast_propagation.mlir new file mode 100644 index 0000000000000000000000000000000000000000..0793c64f697b89832c37ea053e026fd77290ef99 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/broadcast_propagation.mlir @@ -0,0 +1,224 @@ +// RUN: kernel-gen-opt %s --split-input-file --mhlo-broadcast-propagation | \ +// RUN: FileCheck %s + +// CHECK-LABEL: @single_bcast +// CHECK-SAME: %[[ARG0:.*]]: tensor<16x?xf32>, %[[ARG1:.*]]: tensor<16x?xf32>, %[[SHAPE:.*]]: tensor<3xindex> +func.func @single_bcast(%arg0 : tensor<16x?xf32>, %arg1 : tensor<16x?xf32>, + %shape : tensor<3xindex>) -> tensor { + // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE]]) + // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE]]) + // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] : [[BCASTED_TY:tensor<\?x16x\?xf32>]] + // CHECK-DAG: %[[MUL:.*]] = mhlo.multiply %[[ADD]], %[[ADD]] : [[BCASTED_TY]] + // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[ADD]], %[[ADD]] : [[BCASTED_TY]] + // CHECK-DAG: %[[DIV:.*]] = mhlo.divide %[[MUL]], %[[SUB]] : [[BCASTED_TY]] + // CHECK: return %[[DIV]] : [[BCASTED_TY]] + %0 = mhlo.add %arg0, %arg1 : tensor<16x?xf32> + %1 = mhlo.multiply %0, %0 : tensor<16x?xf32> + %2 = mhlo.subtract %0, %0 : tensor<16x?xf32> + %3 = mhlo.divide %1, %2 : tensor<16x?xf32> + %4 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape) { + broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} : + (tensor<16x?xf32>, tensor<3xindex>) -> tensor + func.return %4 : tensor +} + +// ----- + +// CHECK-LABEL: @single_bcast_ensure_order +// CHECK-SAME: %[[ARG0:.*]]: tensor<16x?xf32>, %[[ARG1:.*]]: tensor<16x?xf32>, %[[SHAPE:.*]]: tensor<3xindex> +func.func @single_bcast_ensure_order(%arg0 : tensor<16x?xf32>, %arg1 : tensor<16x?xf32>, + %shape : tensor<3xindex>) -> tensor { + // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE]]) + // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE]]) + // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] : [[BCASTED_TY:tensor<\?x16x\?xf32>]] + // CHECK-DAG: %[[MUL:.*]] = mhlo.multiply %[[ADD]], %[[ADD]] : [[BCASTED_TY]] + // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[MUL]], %[[MUL]] : [[BCASTED_TY]] + // CHECK-DAG: %[[DIV:.*]] = mhlo.divide %[[ADD]], %[[SUB]] : [[BCASTED_TY]] + // CHECK: return %[[DIV]] : [[BCASTED_TY]] + %0 = mhlo.add %arg0, %arg1 : tensor<16x?xf32> + %1 = mhlo.multiply %0, %0 : tensor<16x?xf32> + %2 = mhlo.subtract %1, %1 : tensor<16x?xf32> + %3 = mhlo.divide %0, %2 : tensor<16x?xf32> + %4 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape) { + broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} : + (tensor<16x?xf32>, tensor<3xindex>) -> tensor + func.return %4 : tensor +} + +// ----- + +// CHECK-LABEL: @double_bcasts +// CHECK-SAME: %[[ARG0:.*]]: tensor<16x?xf32>, %[[ARG1:.*]]: tensor<16x?xf32>, %[[SHAPE0:.*]]: tensor<3xindex>, %[[SHAPE1:.*]]: tensor<3xindex> +func.func @double_bcasts(%arg0 : tensor<16x?xf32>, %arg1 : tensor<16x?xf32>, + %shape0 : tensor<3xindex>, %shape1 : tensor<3xindex>) + -> (tensor, tensor) { + // CHECK-DAG: %[[BCASTED_ARG00:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE0]]) [[BCAST_DIMS0:<{broadcast_dimensions = dense<\[1, 2\]> : tensor<2xi64>}>]] + // CHECK-DAG: %[[BCASTED_ARG01:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE1]]) [[BCAST_DIMS1:<{broadcast_dimensions = dense<\[0, 2\]> : tensor<2xi64>}>]] + // CHECK-DAG: %[[BCASTED_ARG10:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE0]]) [[BCAST_DIMS0]] + // CHECK-DAG: %[[BCASTED_ARG11:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE1]]) [[BCAST_DIMS1]] + // CHECK-DAG: %[[ADD0:.*]] = mhlo.add %[[BCASTED_ARG00]], %[[BCASTED_ARG10]] : [[BCAST_TY:tensor<\?x16x\?xf32>]] + // CHECK-DAG: %[[ADD1:.*]] = mhlo.add %[[BCASTED_ARG01]], %[[BCASTED_ARG11]] : [[BCAST_TY]] + // CHECK-DAG: %[[MUL0:.*]] = mhlo.multiply %[[ADD0]], %[[ADD0]] : [[BCAST_TY]] + // CHECK-DAG: %[[MUL1:.*]] = mhlo.multiply %[[ADD1]], %[[ADD1]] : [[BCAST_TY]] + // CHECK-DAG: %[[SUB0:.*]] = mhlo.subtract %[[ADD0]], %[[ADD0]] : [[BCAST_TY]] + // CHECK-DAG: %[[SUB1:.*]] = mhlo.subtract %[[ADD1]], %[[ADD1]] : [[BCAST_TY]] + // CHECK-DAG: %[[DIV0:.*]] = mhlo.divide %[[MUL0]], %[[SUB0]] : [[BCAST_TY]] + // CHECK-DAG: %[[DIV1:.*]] = mhlo.divide %[[MUL1]], %[[SUB1]] : [[BCAST_TY]] + // CHECK: return %[[DIV0]], %[[DIV1]] : [[BCAST_TY]], [[BCAST_TY]] + %0 = mhlo.add %arg0, %arg1 : tensor<16x?xf32> + %1 = mhlo.multiply %0, %0 : tensor<16x?xf32> + %2 = mhlo.subtract %0, %0 : tensor<16x?xf32> + %3 = mhlo.divide %1, %2 : tensor<16x?xf32> + %4 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape0) { + broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} : + (tensor<16x?xf32>, tensor<3xindex>) -> tensor + %5 = "mhlo.dynamic_broadcast_in_dim"(%3, %shape1) { + broadcast_dimensions = dense<[0, 2]> : tensor<2xi64>} : + (tensor<16x?xf32>, tensor<3xindex>) -> tensor + func.return %4, %5 : tensor, tensor +} + +// ----- + +// CHECK-LABEL: @late_output_dimensions +// CHECK: %[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor, %[[ARG2:.*]]: tensor +func.func @late_output_dimensions(%arg0 : tensor, %arg1 : tensor, + %arg2 : tensor) -> tensor { + // CHECK-DAG: %[[SHAPE:.*]] = shape.shape_of %[[ARG2]] + // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[SHAPE]]) <{broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>}> + // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[SHAPE]]) <{broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>}> + // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] : [[BCAST_TY:tensor<\?x\?x32xf32>]] + // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[SUB]], %[[SUB]] : [[BCAST_TY]] + // CHECK: return %[[ADD]] : [[BCAST_TY]] + %0 = mhlo.subtract %arg0, %arg1 : tensor + %1 = shape.shape_of %arg2 : tensor -> tensor<3xindex> + %2 = "mhlo.dynamic_broadcast_in_dim"(%0, %1) + {broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>} : + (tensor, tensor<3xindex>) -> tensor + %3 = mhlo.add %2, %2 : tensor + func.return %3 : tensor +} + +// ----- + +// CHECK-LABEL: @very_late_output_dimensions +// CHECK: (%[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor, %[[ARG2:.*]]: tensor) +func.func @very_late_output_dimensions(%arg0 : tensor, + %arg1 : tensor, %arg2 : tensor) -> tensor { + // CHECK-DAG: %[[S:.*]] = shape.shape_of %[[ARG2:.*]] + // CHECK-DAG: %[[BCASTED_ARG0:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG0]], %[[S]]) + // CHECK-DAG: %[[BCASTED_ARG1:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG1]], %[[S]]) + // CHECK-DAG: %[[ACC0:.*]] = mhlo.add %[[BCASTED_ARG0]], %[[BCASTED_ARG1]] + // CHECK-DAG: %[[ACC1:.*]] = mhlo.multiply %[[ACC0]], %[[BCASTED_ARG1]] + // CHECK-DAG: %[[ACC2:.*]] = mhlo.subtract %[[ACC1]], %[[BCASTED_ARG1]] + // CHECK-DAG: %[[ACC3:.*]] = mhlo.divide %[[ACC2]], %[[BCASTED_ARG1]] + // CHECK: return %[[ACC3]] + %acc0 = mhlo.add %arg0, %arg1 : tensor + %acc1 = mhlo.multiply %acc0, %arg1 : tensor + %acc2 = mhlo.subtract %acc1, %arg1 : tensor + %acc3 = mhlo.divide %acc2, %arg1 : tensor + %1 = shape.shape_of %arg2 : tensor -> tensor<3xindex> + %3 = "mhlo.dynamic_broadcast_in_dim"(%acc3, %1) <{broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>}> : (tensor, tensor<3xindex>) -> tensor + func.return %3 : tensor +} + +// ----- + +// CHECK-LABEL: @propagate_within_block +// CHECK: (%[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor, %[[ARG2:.*]]: tensor, %[[W:.*]]: !shape.witness, %[[SHAPE:.*]]: tensor<3xindex>) +func.func @propagate_within_block(%arg0 : tensor, %arg1 : tensor, + %arg2 : tensor, %w : !shape.witness, %shape : tensor<3xindex>) + -> tensor { + // CHECK-DAG: %[[SUB:.*]] = mhlo.subtract %[[ARG0]], %[[ARG1]] : tensor + // CHECK: %[[RESULT:.*]] = shape.assuming %[[W]] + // CHECK-DAG: %[[BCASTED_ARG2:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG2]], %[[SHAPE]]) + // CHECK-DAG: %[[BCASTED_SUB:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[SUB]], %[[SHAPE]]) + // CHECK-DAG: %[[ADD:.*]] = mhlo.add %[[BCASTED_SUB]], %[[BCASTED_ARG2]] : tensor + // CHECK: shape.assuming_yield %[[ADD]] + // CHECK: return %[[RESULT]] + %sub = mhlo.subtract %arg0, %arg1 : tensor + %result = shape.assuming %w -> tensor { + %add = mhlo.add %sub, %arg2 : tensor + %bcasted = "mhlo.dynamic_broadcast_in_dim"(%add, %shape) + {broadcast_dimensions = dense<[0, 1]> : tensor<2xi64>} : + (tensor, tensor<3xindex>) -> tensor + shape.assuming_yield %bcasted : tensor + } + func.return %result : tensor +} + +// ----- + +// CHECK-LABEL: @propagate_within_block_2 +// CHECK-SAME: %[[ARG:.*]]: tensor, %[[S:.*]]: tensor<3xindex>, %[[W:.*]]: !shape.witness +func.func @propagate_within_block_2(%arg : tensor, + %shape: tensor<3xindex>, %w: !shape.witness) -> tensor { + // CHECK-DAG: %[[TMP:.*]] = "mhlo.dynamic_broadcast_in_dim"(%arg0, %[[S]]) + // CHECK: %[[RES:.*]] = shape.assuming %[[W]] + // CHECK-DAG: %[[INNER_RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[TMP]], %[[S]]) + // CHECK: shape.assuming_yield %[[INNER_RES]] + // CHECK: return %[[RES]] + %0 = "mhlo.dynamic_broadcast_in_dim"(%arg, %shape) + {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>} + : (tensor, tensor<3xindex>) -> tensor + %1 = shape.assuming %w -> tensor { + %2 = "mhlo.dynamic_broadcast_in_dim"(%0, %shape) + {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>} + : (tensor, tensor<3xindex>) -> tensor + shape.assuming_yield %2 : tensor + } + func.return %1 : tensor +} + +// ----- + +// CHECK-LABEL: @propagate_across_bcasts_cst_src +// CHECK-SAME: %[[ARG:.*]]: tensor<1xindex> +func.func @propagate_across_bcasts_cst_src(%s : tensor<1xindex>) -> tensor { + // CHECK-DAG: %[[C1:.*]] = mhlo.constant dense : tensor + // CHECK-DAG: %[[RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[C1]], %[[ARG]]) <{broadcast_dimensions = dense<> : tensor<0xi64>}> : (tensor, tensor<1xindex>) -> tensor + // CHECK: return %[[RES]] + %0 = mhlo.constant dense : tensor + %1 = "mhlo.dynamic_broadcast_in_dim"(%0, %s) + {broadcast_dimensions = dense<> : tensor<0xi64>} + : (tensor, tensor<1xindex>) -> tensor + %2 = "mhlo.dynamic_broadcast_in_dim"(%1, %s) + {broadcast_dimensions = dense<0> : tensor<1xi64>} + : (tensor, tensor<1xindex>) -> tensor + func.return %2 : tensor +} + +// ----- + +// CHECK-LABEL: @compose_bcast_dims +// CHECK-SAME: %[[ARG:.*]]: tensor, %[[S0:.*]]: tensor<3xindex>, %[[S1:.*]]: tensor<4xindex> +func.func @compose_bcast_dims(%arg : tensor, %s0 : tensor<3xindex>, %s1 : tensor<4xindex>) -> tensor<1x?x1x?xi1> { + // CHECK-DAG: %[[RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG]], %[[S1]]) <{broadcast_dimensions = dense<[1, 3]> : tensor<2xi64>}> : (tensor, tensor<4xindex>) -> tensor<1x?x1x?xi1> + // CHECK: return %[[RES]] + %1 = "mhlo.dynamic_broadcast_in_dim"(%arg, %s0) + {broadcast_dimensions = dense<[1, 2]> : tensor<2xi64>} + : (tensor, tensor<3xindex>) -> tensor<1x?x?xi1> + %2 = "mhlo.dynamic_broadcast_in_dim"(%1, %s1) + {broadcast_dimensions = dense<[0, 1, 3]> : tensor<3xi64>} + : (tensor<1x?x?xi1>, tensor<4xindex>) -> tensor<1x?x1x?xi1> + func.return %2 : tensor<1x?x1x?xi1> +} + +// ----- + +// CHECK-LABEL: @propagate_across_bcasts +// CHECK-SAME: %[[ARG:.*]]: tensor, %[[S:.*]]: tensor<3xindex> +func.func @propagate_across_bcasts(%arg : tensor, %shape : tensor<3xindex>) -> tensor { + // CHECK-DAG: %[[RES:.*]] = "mhlo.dynamic_broadcast_in_dim"(%[[ARG]], %[[S]]) <{broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>}> : (tensor, tensor<3xindex>) -> tensor + // CHECK: return %[[RES]] + %0 = "mhlo.dynamic_broadcast_in_dim"(%arg, %shape) + {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>} + : (tensor, tensor<3xindex>) -> tensor + %1 = "mhlo.dynamic_broadcast_in_dim"(%0, %shape) + {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>} + : (tensor, tensor<3xindex>) -> tensor + %2 = "mhlo.dynamic_broadcast_in_dim"(%1, %shape) + {broadcast_dimensions = dense<[0, 1, 2]> : tensor<3xi64>} + : (tensor, tensor<3xindex>) -> tensor + func.return %2 : tensor +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_deallocation.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_deallocation.mlir new file mode 100644 index 0000000000000000000000000000000000000000..0bd46aaf2df18161583243c54ca269e7bca54f3d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_deallocation.mlir @@ -0,0 +1,31 @@ +// RUN: kernel-gen-opt %s --buffer-deallocation | FileCheck %s + +// CHECK-LABEL: @jit_execute_allocation +// CHECK-SAME: %[[CTX:.*]]: !tf_framework.op_kernel_context, %[[ARG:.*]]: memref<*xf32>, %[[PRED:.*]]: i1, %[[CALLABLE:.*]]: !tf_framework.jit_callable, %[[SIZE:.*]]: index, %[[SHAPE:.*]]: memref +func.func @jit_execute_allocation(%ctx: !tf_framework.op_kernel_context, + %arg: memref<*xf32>, %pred: i1, %callable: !tf_framework.jit_callable, + %size: index, %shape: memref) -> memref<*xf32> { + // CHECK: %[[RES:.*]] = scf.if %[[PRED]] + // CHECK: %[[JIT_EXECUTE:.*]] = tf_framework.jit_execute ctx(%[[CTX]]) %[[CALLABLE]](%[[ARG]]) + // CHECK: %[[INNER_RES:.*]] = bufferization.clone %[[JIT_EXECUTE]] + // CHECK: tf_framework.dealloc(%[[CTX]], %[[JIT_EXECUTE]]) + // CHECK: scf.yield %[[INNER_RES]] + // CHECK: else + // CHECK: %[[ALLOC:.*]] = tf_framework.alloc(%[[CTX]], %[[SIZE]]) + // CHECK: %[[RESHAPE:.*]] = memref.reshape %[[ALLOC]](%[[SHAPE]]) + // CHECK: %[[INNER_RES:.*]] = bufferization.clone %[[RESHAPE]] + // CHECK: tf_framework.dealloc(%[[CTX]], %[[ALLOC]]) + // CHECK: scf.yield %[[INNER_RES]] + // CHECK: return %[[RES]] + %res = scf.if %pred -> (memref<*xf32>) { + %inner_res = tf_framework.jit_execute ctx(%ctx) %callable(%arg) + : memref<*xf32> -> memref<*xf32> + scf.yield %inner_res : memref<*xf32> + } else { + %alloc = tf_framework.alloc(%ctx, %size) : memref + %inner_res = memref.reshape %alloc(%shape) + : (memref, memref) -> memref<*xf32> + scf.yield %inner_res : memref<*xf32> + } + return %res : memref<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_reuse.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_reuse.mlir new file mode 100644 index 0000000000000000000000000000000000000000..4c8e43f8e57ed2449f346381a18a71e8a59835a4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/buffer_reuse.mlir @@ -0,0 +1,541 @@ +// RUN: kernel-gen-opt %s --buffer-reuse | FileCheck %s + +// CHECK-LABEL: @unique_reuse_output +func.func @unique_reuse_output() -> (index, memref<2x3xi64>) attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_output = 1 : i32 + %result_0 = arith.constant 1 : index + %result_1 = memref.alloc() : memref<2x3xi64> + func.return %result_0, %result_1 : index, memref<2x3xi64> +} + +// CHECK-LABEL: @ambiguous_reuse_output +func.func @ambiguous_reuse_output(%pred : i1) + -> (memref<2x3xi64>, memref<2x3xi64>) attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK: reuse_output = -1 : i32 + %mem = memref.alloc() : memref<2x3xi64> + %other_mem = memref.alloc() : memref<2x3xi64> + cf.cond_br %pred, ^bb0, ^bb1 +^bb0: + func.return %mem, %other_mem : memref<2x3xi64>, memref<2x3xi64> +^bb1: + func.return %other_mem, %mem : memref<2x3xi64>, memref<2x3xi64> +} + +// CHECK-LABEL: @direct_reuse +func.func @direct_reuse(%not_a_memref : index, + %smaller : memref<5xi64>, + %greater : memref<7xi64>, + %different_element_type : memref<2x3xf32>, + %reusable_0 : memref<2x3xi64>, + %reusable_1 : memref<6xi64>) -> memref<2x3xi64> + attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32, 2 : i32, 3 : i32, 4 : i32, 5 : i32] + %result = memref.alloc() : memref<2x3xi64> + func.return %result : memref<2x3xi64> +} + +// CHECK-LABEL: @local_reuse_with_memref_maps +func.func @local_reuse_with_memref_maps( + %arg : memref>, %n : index) + -> memref> attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %result = memref.alloc(%n) : memref> + linalg.generic { + indexing_maps = [affine_map<(i) -> (i)>, affine_map<(i) -> (i)>], + iterator_types = ["parallel"] + } ins(%arg : memref>) + outs(%result : memref>) { + ^bb0(%a : i64, %b : i64): + linalg.yield %a : i64 + } + func.return %result : memref> +} + +// CHECK-LABEL: @local_reuse_with_broadcasting_memref_maps +func.func @local_reuse_with_broadcasting_memref_maps( + %arg0 : memref, %arg1 : memref, %n : index) + -> memref attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32] + %result = memref.alloc(%n) : memref + linalg.generic { + indexing_maps = [affine_map<(i) -> ()>, affine_map<(i) -> (i)>, affine_map<(i) -> (i)>], + iterator_types = ["parallel"] + } ins(%arg0, %arg1 : memref, memref) + outs(%result : memref) { + ^bb0(%a : i64, %b : i64, %c : i64): + %add = arith.addi %a, %b : i64 + linalg.yield %add : i64 + } + func.return %result : memref +} + +// CHECK-LABEL: @local_reuse_with_broadcasting_memref_maps2 +func.func @local_reuse_with_broadcasting_memref_maps2( + %arg0 : memref, %arg1 : memref) + -> memref attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32] + %result = memref.alloc() : memref + linalg.generic { + indexing_maps = [affine_map<(i) -> (i)>, affine_map<(i) -> (i)>, affine_map<(i) -> ()>], + iterator_types = ["parallel"] + } ins(%arg0, %arg1 : memref, memref) + outs(%result : memref) { + ^bb0(%a : i64, %b : i64, %c : i64): + %add = arith.addi %a, %b : i64 + linalg.yield %add : i64 + } + func.return %result : memref +} + +// CHECK-LABEL: @local_reuse_with_broadcasting_memref_maps3 +func.func @local_reuse_with_broadcasting_memref_maps3( + %arg0 : memref, %arg1 : memref) + -> memref attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32] + %result = memref.alloc() : memref + linalg.generic { + indexing_maps = [affine_map<(i) -> ()>, affine_map<(i) -> (i)>, affine_map<(i) -> ()>], + iterator_types = ["parallel"] + } ins(%arg0, %arg1 : memref, memref) + outs(%result : memref) { + ^bb0(%a : i64, %b : i64, %c : i64): + %add = arith.addi %a, %b : i64 + linalg.yield %add : i64 + } + func.return %result : memref +} + +// CHECK-LABEL: @nolocal_reuse_with_broadcasting_memref_maps +func.func @nolocal_reuse_with_broadcasting_memref_maps( + %arg0 : memref, %arg1 : memref, %n : index) + -> memref attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %result = memref.alloc(%n) : memref + linalg.generic { + indexing_maps = [affine_map<(i,j) -> (i)>, affine_map<(i,j) -> (i,j)>, affine_map<(i,j) -> (j)>], + iterator_types = ["parallel", "parallel"] + } ins(%arg0, %arg1 : memref, memref) + outs(%result : memref) { + ^bb0(%a : i64, %b : i64, %c : i64): + %add = arith.addi %a, %b : i64 + linalg.yield %add : i64 + } + func.return %result : memref +} + +// CHECK-LABEL: @nolocal_reuse_with_broadcasting_memref_maps2 +func.func @nolocal_reuse_with_broadcasting_memref_maps2( + %arg0 : memref, %arg1 : memref, %n : index) + -> memref attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %result = memref.alloc(%n, %n) : memref + linalg.generic { + indexing_maps = [affine_map<(i,j,k) -> (i,j,k)>, affine_map<(i,j,k) -> (i,j,k)>, affine_map<(i,j,k) -> (k,i)>], + iterator_types = ["parallel", "parallel", "parallel"] + } ins(%arg0, %arg1 : memref, memref) + outs(%result : memref) { + ^bb0(%a : i64, %b : i64, %c : i64): + %add = arith.addi %a, %b : i64 + linalg.yield %add : i64 + } + func.return %result : memref +} + +// CHECK-LABEL: @memref.reinterpret_cast_alias +func.func @memref.reinterpret_cast_alias(%arg : memref, %n : index) + -> memref attributes {tf_entry} { + %c0 = arith.constant 0 : index + %reinterpreted = memref.reinterpret_cast %arg to + offset: [0], + sizes: [%n], + strides: [%c0]: memref to memref> + + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %result = memref.alloc(%n) : memref + + // reinterpreted (arg) and result are of same size. + linalg.generic { + indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], + iterator_types = ["parallel"] + } ins(%reinterpreted : memref>) outs(%result : memref) { + ^bb0(%a : f32, %b : f32): + linalg.yield %a : f32 + } + + func.return %result : memref +} + +// CHECK-LABEL: @memref.cast_alias +func.func @memref.cast_alias(%arg : memref<*xf32>, %n : index) + -> memref attributes {tf_entry} { + %casted = memref.cast %arg : memref<*xf32> to memref + + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %result = memref.alloc(%n) : memref + + // reinterpreted (arg) and result are of same size. + linalg.generic { + indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], + iterator_types = ["parallel"] + } ins(%casted : memref) outs(%result : memref) { + ^bb0(%a : f32, %b : f32): + linalg.yield %a : f32 + } + + func.return %result : memref +} + +// CHECK-LABEL: @indirect_size_equality +func.func @indirect_size_equality(%arg0 : memref, + %arg1 : memref, + %n : index) -> memref + attributes {tf_entry} { + // arg0 and arg1 are equal in size. + linalg.generic { + indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], + iterator_types = ["parallel"] + } ins(%arg0 : memref) outs(%arg1 : memref) { + ^bb0(%a : i64, %b : i64): + linalg.yield %a : i64 + } + + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32, 1 : i32] + %result = memref.alloc(%n) : memref + + // arg0 and result are equal in size. + linalg.generic { + indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], + iterator_types = ["parallel"] + } ins(%arg0 : memref) outs(%result : memref) { + ^bb0(%a : i64, %b : i64): + linalg.yield %a : i64 + } + + func.return %result : memref +} + +// CHECK-LABEL: @livetimes_incompatible +func.func @livetimes_incompatible(%arg0 : memref<3xi64>) + -> memref<3xi64> attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %result = memref.alloc() : memref<3xi64> + + // Use newly allocated buffer. + %c0 = arith.constant 0 : index + %0 = memref.load %result[%c0] : memref<3xi64> + + // Use argument buffer again. + %1 = memref.load %arg0[%c0] : memref<3xi64> + + func.return %result : memref<3xi64> +} + +// CHECK-LABEL: @never_used +func.func @never_used(%arg0 : memref<3xi64>) -> memref<3xi64> attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %result = memref.alloc() : memref<3xi64> + %c0 = arith.constant 0 : index + %0 = memref.load %arg0[%c0] : memref<3xi64> + func.return %result : memref<3xi64> +} + +// CHECK-LABEL: @branching_reuse +func.func @branching_reuse(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64> + attributes {tf_entry} { + cf.cond_br %pred, ^bb0, ^bb1 +^bb0: + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %mem0 = memref.alloc() : memref<6xi64> + + // Keep buffer argument live in this branch. Reuse is still possible because + // the newly allocated buffer was not used yet. + %c0 = arith.constant 0 : index + memref.load %arg[%c0] : memref<6xi64> + + cf.br ^bb2(%mem0 : memref<6xi64>) +^bb1: + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %mem1 = memref.alloc() : memref<6xi64> + cf.br ^bb2(%mem1 : memref<6xi64>) +^bb2(%result : memref<6xi64>): + func.return %result : memref<6xi64> +} + +// CHECK-LABEL: @branching_no_reuse +func.func @branching_no_reuse(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64> + attributes {tf_entry} { + cf.cond_br %pred, ^bb0, ^bb1 +^bb0: + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %mem0 = memref.alloc() : memref<6xi64> + + // Use newly allocated memory immediately. + %c0 = arith.constant 0 : index + memref.load %mem0[%c0] : memref<6xi64> + + // Keep buffer argument live in this branch and prevent reuse. + memref.load %arg[%c0] : memref<6xi64> + + cf.br ^bb2(%mem0 : memref<6xi64>) +^bb1: + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %mem1 = memref.alloc() : memref<6xi64> + cf.br ^bb2(%mem1 : memref<6xi64>) +^bb2(%result : memref<6xi64>): + func.return %result : memref<6xi64> +} + +// CHECK-LABEL: @branching_reuse_if +func.func @branching_reuse_if(%pred : i1, %arg : memref<6xi64>) + -> memref<6xi64> attributes {tf_entry} { + %result = scf.if %pred -> (memref<6xi64>) { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %mem0 = memref.alloc() : memref<6xi64> + + // Keep buffer argument live in this branch. Reuse is still possible because + // the newly allocated buffer was not used yet. + %c0 = arith.constant 0 : index + memref.load %arg[%c0] : memref<6xi64> + + scf.yield %mem0 : memref<6xi64> + } else { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %mem1 = memref.alloc() : memref<6xi64> + scf.yield %mem1 : memref<6xi64> + } + func.return %result : memref<6xi64> +} + +// CHECK-LABEL: @branching_no_reuse_if +func.func @branching_no_reuse_if(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64> + attributes {tf_entry} { + %result = scf.if %pred -> (memref<6xi64>) { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %mem0 = memref.alloc() : memref<6xi64> + + // Use newly allocated memory immediately. + %c0 = arith.constant 0 : index + memref.load %mem0[%c0] : memref<6xi64> + + // Keep buffer argument live in this branch and prevent reuse. + memref.load %arg[%c0] : memref<6xi64> + + scf.yield %mem0 : memref<6xi64> + } else { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [1 : i32] + %mem1 = memref.alloc() : memref<6xi64> + scf.yield %mem1 : memref<6xi64> + } + func.return %result : memref<6xi64> +} + +// CHECK-LABEL: @alloc_before_branching +// New buffer is first used in the blocks succeeding its allocation block. In +// both/all cases the newly allocated buffer is used after the buffer argument +// is no longer live. Because these first uses are not block-local the analysis +// does not detect this case (yet). It is correct but incomplete. +func.func @alloc_before_branching(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64> + attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %mem = memref.alloc() : memref<6xi64> + %c0 = arith.constant 0 : index + cf.cond_br %pred, ^bb0, ^bb1 +^bb0: + // Last use of `arg` before first use of `mem` (can reuse). + memref.load %arg[%c0] : memref<6xi64> + memref.load %mem[%c0] : memref<6xi64> + func.return %mem : memref<6xi64> +^bb1: + // Last use of `arg` before first use of `mem` (can reuse). + memref.load %arg[%c0] : memref<6xi64> + memref.load %mem[%c0] : memref<6xi64> + func.return %mem : memref<6xi64> +} + +// CHECK-LABEL: @alloc_before_branching_2 +func.func @alloc_before_branching_2(%pred : i1, %arg : memref<6xi64>) + -> memref<6xi64> attributes {tf_entry} { + // CHECK: memref.alloc() + // CHECK-SAME: reuse_input_candidates = [] + %mem = memref.alloc() : memref<6xi64> + %c0 = arith.constant 0 : index + cf.cond_br %pred, ^bb0, ^bb1 +^bb0: + // Last use of `arg` after first use of `mem` (cannot reuse). + memref.load %mem[%c0] : memref<6xi64> + memref.load %arg[%c0] : memref<6xi64> + func.return %mem : memref<6xi64> +^bb1: + // Last use of `arg` before first use of `mem` (can reuse). + memref.load %arg[%c0] : memref<6xi64> + memref.load %mem[%c0] : memref<6xi64> + func.return %mem : memref<6xi64> +} + +// CHECK-LABEL: @alloc_before_branching_if +// New buffer is first used in the blocks succeeding its allocation block. In +// both/all cases the newly allocated buffer is used after the buffer argument +// is no longer live. Because these first uses are not block-local the analysis +// does not detect this case (yet). It is correct but incomplete. +func.func @alloc_before_branching_if(%pred : i1, %arg : memref<6xi64>) -> memref<6xi64> + attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %mem = memref.alloc() : memref<6xi64> + %result = scf.if %pred -> (memref<6xi64>) { + // Last use of `arg` before first use of `mem` (can reuse). + %c0 = arith.constant 0 : index + memref.load %arg[%c0] : memref<6xi64> + memref.load %mem[%c0] : memref<6xi64> + scf.yield %mem : memref<6xi64> + } else { + // Last use of `arg` before first use of `mem` (can reuse). + %c0 = arith.constant 0 : index + memref.load %arg[%c0] : memref<6xi64> + memref.load %mem[%c0] : memref<6xi64> + scf.yield %mem : memref<6xi64> + } + func.return %result : memref<6xi64> +} + +// CHECK-LABEL: @alloc_before_branching_2_if +func.func @alloc_before_branching_2_if(%pred : i1, %arg : memref<6xi64>) + -> memref<6xi64> attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %mem = memref.alloc() : memref<6xi64> + %result = scf.if %pred -> (memref<6xi64>) { + // Last use of `arg` after first use of `mem` (cannot reuse). + %c0 = arith.constant 0 : index + memref.load %mem[%c0] : memref<6xi64> + memref.load %arg[%c0] : memref<6xi64> + scf.yield %mem : memref<6xi64> + } else { + // Last use of `arg` before first use of `mem` (can reuse). + %c0 = arith.constant 0 : index + memref.load %arg[%c0] : memref<6xi64> + memref.load %mem[%c0] : memref<6xi64> + scf.yield %mem : memref<6xi64> + } + func.return %result : memref<6xi64> +} + +// CHECK-LABEL: @abs_unranked_i64 +func.func @abs_unranked_i64(%arg : memref<*xi64>, + %arg_shape : memref, + %flat_shape : memref<1xindex>, + %arg_size : index) -> memref<*xi64> + attributes {tf_entry} { + %flat_arg = memref.reshape %arg(%flat_shape) + : (memref<*xi64>, memref<1xindex>) -> memref + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32, 2 : i32], reuse_output = 0 : i32 + %flat_result = memref.alloc(%arg_size) : memref + linalg.generic { + indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], + iterator_types = ["parallel"] + } ins(%flat_arg : memref) outs(%flat_result : memref) { + ^bb0(%a : i64, %b : i64): + %c0 = arith.constant 0 : i64 + %a_pos = arith.cmpi sge, %a, %c0 : i64 + %a_neg = arith.subi %c0, %a : i64 + %a_abs = arith.select %a_pos, %a, %a_neg : i64 + linalg.yield %a_abs : i64 + } + %result = memref.reshape %flat_result(%arg_shape) + : (memref, memref) -> memref<*xi64> + func.return %result : memref<*xi64> +} + +// CHECK-LABEL: @old_buffer_alias_outside_block +func.func @old_buffer_alias_outside_block(%arg: memref<3xf32>) + attributes {llvm.emit_c_interface, tf_entry} { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %true = arith.constant true + + // Alias outside of the block with the new buffer allocation. + %alias = memref.cast %arg : memref<3xf32> to memref<3xf32> + + scf.if %true { + + // Allocation and use of new buffer. + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %mem = memref.alloc() : memref<3xf32> + %use = memref.load %mem[%c0] : memref<3xf32> + + } else { + } + func.return +} + +// CHECK-LABEL: @index_element_type +func.func @index_element_type(%arg : memref<2x3xindex>) -> memref<2x3xindex> + attributes {tf_entry} { + // CHECK: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %result = memref.alloc() : memref<2x3xindex> + func.return %result : memref<2x3xindex> +} + +// Example as it occurs in the `tf.Abs` kernel for `f32`. +// CHECK-LABEL: @abs_f32 +func.func @abs_f32(%arg0: memref<*xf32>) -> memref<*xf32> + attributes {llvm.emit_c_interface, tf_entry} { + %c0 = arith.constant 0 : index + %0 = shape.shape_of %arg0 : memref<*xf32> -> tensor + %1 = shape.num_elements %0 : tensor -> index + // CHECK-LABEL: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %2 = memref.alloc() : memref<1xindex> + memref.store %1, %2[%c0] : memref<1xindex> + %3 = memref.reshape %arg0(%2) + : (memref<*xf32>, memref<1xindex>) -> memref + %4 = memref.dim %3, %c0 : memref + %5 = arith.index_cast %4 : index to i64 + // CHECK-LABEL: memref.alloc + // CHECK-SAME: reuse_input_candidates = [] + %6 = memref.alloc() : memref<1xi64> + memref.store %5, %6[%c0] : memref<1xi64> + %7 = memref.load %6[%c0] : memref<1xi64> + %8 = arith.index_cast %7 : i64 to index + // CHECK-LABEL: memref.alloc + // CHECK-SAME: reuse_input_candidates = [0 : i32] + %9 = memref.alloc(%8) : memref + linalg.generic { + indexing_maps = [affine_map<(d0) -> (d0)>, affine_map<(d0) -> (d0)>], + iterator_types = ["parallel"] + } ins(%3 : memref) outs(%9 : memref) { + ^bb0(%arg1: f32, %arg2: f32): + %12 = math.absf %arg1 : f32 + linalg.yield %12 : f32 + } + %10 = bufferization.to_buffer %0 : tensor to memref + %11 = memref.reshape %9(%10) + : (memref, memref) -> memref<*xf32> + func.return %11 : memref<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/bufferize.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/bufferize.mlir new file mode 100644 index 0000000000000000000000000000000000000000..53e02960c149676ec0419a626f7b569808c06333 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/bufferize.mlir @@ -0,0 +1,20 @@ +// RUN: kernel-gen-opt %s --split-input-file --mlir-print-op-generic |\ +// RUN: mlir-hlo-opt --allow-unregistered-dialect \ +// RUN: --computeop-and-func-bufferize |\ +// RUN: kernel-gen-opt \ +// RUN: --kernelgen-final-bufferize | FileCheck %s +// RUN: kernel-gen-opt %s --split-input-file --mlir-print-op-generic |\ +// RUN: mlir-hlo-opt --allow-unregistered-dialect \ +// RUN: --computeop-and-func-bufferize |\ +// RUN: kernel-gen-opt \ +// RUN: --kernelgen-final-bufferize --promote-buffers-to-stack | FileCheck %s + +// CHECK-LABEL: @jit_execute +// CHECK-SAME: (%[[F:.*]]: !tf_framework.jit_callable, %[[ARG:.*]]: memref<*xf32>) -> memref<*xf32> +func.func @jit_execute(%f : !tf_framework.jit_callable, %arg : tensor<*xf32>) + -> tensor<*xf32> { + // CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[F]](%[[ARG]]) : memref<*xf32> -> memref<*xf32> + // CHECK: return %[[RES]] : memref<*xf32> + %0 = tf_framework.jit_execute %f(%arg) : tensor<*xf32> -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/copy_cleanup.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/copy_cleanup.mlir new file mode 100644 index 0000000000000000000000000000000000000000..11654cde8835bc3bf3c96ffb81ab410174fbab9f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/copy_cleanup.mlir @@ -0,0 +1,188 @@ +// RUN: kernel-gen-opt %s --copy-cleanup --split-input-file | FileCheck %s + +#map0 = affine_map<(d0)[s0] -> (d0 * s0)> +#map1 = affine_map<(d0) -> (d0)> +builtin.module { + func.func @Copy(%lhs: memref, %rhs: memref) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %size = memref.dim %rhs, %c0 : memref + %lhsCasted = memref.reinterpret_cast %lhs to offset: [0], sizes: [%size], strides: [%c0] : memref to memref + %lhsAlloc = memref.alloc(%size) : memref + memref.copy %lhsCasted, %lhsAlloc : memref to memref + %rhsCasted = memref.reinterpret_cast %rhs to offset: [0], sizes: [%size], strides: [%c1] : memref to memref + %rhsAlloc = memref.alloc(%size) : memref + memref.copy %rhsCasted, %rhsAlloc : memref to memref + %outputAlloc = memref.alloc(%size) : memref + linalg.generic {indexing_maps = [#map1, #map1, #map1], iterator_types = ["parallel"]} ins(%lhsAlloc, %rhsAlloc : memref, memref) outs(%outputAlloc : memref) { + ^bb0(%arg1: i16, %arg2: i16, %arg3 : i16): + %and = arith.andi %arg1, %arg2 : i16 + linalg.yield %and : i16 + } + func.return + } +} + +// CHECK-DAG: #[[$MAP0:.*]] = affine_map<(d0)[s0] -> (d0 * s0)> +// CHECK-DAG: #[[$MAP1:.*]] = affine_map<(d0) -> (d0)> +// CHECK-LABEL: func @Copy( +// CHECK-SAME: %[[LHS:.*]]: memref, %[[RHS:.*]]: memref) { +// CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index +// CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index +// CHECK: %[[SIZE:.*]] = memref.dim %[[RHS]], %[[C0]] : memref +// CHECK: %[[LHS_CASTED:.*]] = memref.reinterpret_cast %[[LHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C0]]] : memref to memref +// CHECK: %[[RHS_CASTED:.*]] = memref.reinterpret_cast %[[RHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C1]]] : memref to memref +// CHECK: %[[OUTPUT:.*]] = memref.alloc(%[[SIZE]]) : memref +// CHECK: linalg.generic {indexing_maps = [#[[$MAP1]], #[[$MAP1]], #[[$MAP1]]], iterator_types = ["parallel"]} ins(%[[LHS_CASTED]], %[[RHS_CASTED]] : memref, memref) outs(%{{.*}} : memref) { +// CHECK: ^bb0(%[[ARG1:.*]]: i16, %[[ARG2:.*]]: i16, %[[ARG3:.*]]: i16): +// CHECK: %[[AND:.*]] = arith.andi %[[ARG1]], %[[ARG2]] : i16 +// CHECK: linalg.yield %[[AND]] : i16 + +// ----- + +// The target of the copy is also used to write. + +#map0 = affine_map<(d0)[s0] -> (d0 * s0)> +#map1 = affine_map<(d0) -> (d0)> +builtin.module { + func.func @CopyWithWrite(%lhs: memref, %rhs: memref) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %size = memref.dim %rhs, %c0 : memref + %lhsCasted = memref.reinterpret_cast %lhs to offset: [0], sizes: [%size], strides: [%c0] : memref to memref + %lhsAlloc = memref.alloc(%size) : memref + memref.copy %lhsCasted, %lhsAlloc : memref to memref + %rhsCasted = memref.reinterpret_cast %rhs to offset: [0], sizes: [%size], strides: [%c1] : memref to memref + %rhsAlloc = memref.alloc(%size) : memref + memref.copy %rhsCasted, %rhsAlloc : memref to memref + linalg.generic {indexing_maps = [#map1, #map1, #map1], iterator_types = ["parallel"]} ins(%lhsAlloc, %rhsAlloc : memref, memref) outs(%rhsAlloc : memref) { + ^bb0(%arg1: i16, %arg2: i16, %arg3 : i16): + %and = arith.andi %arg1, %arg2 : i16 + linalg.yield %and : i16 + } + func.return + } +} + +// CHECK-DAG: #[[$MAP0:.*]] = affine_map<(d0)[s0] -> (d0 * s0)> +// CHECK-DAG: #[[$MAP1:.*]] = affine_map<(d0) -> (d0)> +// CHECK-LABEL: func @CopyWithWrite( +// CHECK-SAME: %[[LHS:.*]]: memref, %[[RHS:.*]]: memref) { +// CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index +// CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index +// CHECK: %[[SIZE:.*]] = memref.dim %[[RHS]], %[[C0]] : memref +// CHECK: %[[LHS_CASTED:.*]] = memref.reinterpret_cast %[[LHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C0]]] : memref to memref +// CHECK: %[[RHS_CASTED:.*]] = memref.reinterpret_cast %[[RHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C1]]] : memref to memref +// CHECK: %[[RHS_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref +// CHECK: memref.copy %[[RHS_CASTED]], %[[RHS_ALLOC]] +// CHECK: linalg.generic {indexing_maps = [#[[$MAP1]], #[[$MAP1]], #[[$MAP1]]], iterator_types = ["parallel"]} ins(%[[LHS_CASTED]], %[[RHS_ALLOC]] : memref, memref) outs(%[[RHS_ALLOC]] : memref) { +// CHECK: ^bb0(%[[ARG1:.*]]: i16, %[[ARG2:.*]]: i16, %[[ARG3:.*]]: i16): +// CHECK: %[[AND:.*]] = arith.andi %[[ARG1]], %[[ARG2]] : i16 +// CHECK: linalg.yield %[[AND]] : i16 + +// ----- + +// The source of the copy is mutated. + +#map0 = affine_map<(d0)[s0] -> (d0 * s0)> +#map1 = affine_map<(d0) -> (d0)> +builtin.module { + func.func @CopyWithMutation(%lhs: memref, %rhs: memref) { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %c42 = arith.constant 42 : i16 + %size = memref.dim %rhs, %c0 : memref + %lhsCasted = memref.reinterpret_cast %lhs to offset: [0], sizes: [%size], strides: [%c0] : memref to memref + %lhsAlloc = memref.alloc(%size) : memref + memref.copy %lhsCasted, %lhsAlloc : memref to memref + %rhsCasted = memref.reinterpret_cast %rhs to offset: [0], sizes: [%size], strides: [%c1] : memref to memref + %rhsAlloc = memref.alloc(%size) : memref + memref.copy %rhsCasted, %rhsAlloc : memref to memref + %outputAlloc = memref.alloc(%size) : memref + memref.store %c42, %lhs[%c0] : memref + linalg.generic {indexing_maps = [#map1, #map1, #map1], iterator_types = ["parallel"]} ins(%lhsAlloc, %rhsAlloc : memref, memref) outs(%outputAlloc : memref) { + ^bb0(%arg1: i16, %arg2: i16, %arg3 : i16): + %and = arith.andi %arg1, %arg2 : i16 + linalg.yield %and : i16 + } + func.return + } +} + +// CHECK-DAG: #[[$MAP0:.*]] = affine_map<(d0)[s0] -> (d0 * s0)> +// CHECK-DAG: #[[$MAP1:.*]] = affine_map<(d0) -> (d0)> +// CHECK-LABEL: func @CopyWithMutation( +// CHECK-SAME: %[[LHS:.*]]: memref, %[[RHS:.*]]: memref) { +// CHECK-DAG: %[[C0:.*]] = arith.constant 0 : index +// CHECK-DAG: %[[C1:.*]] = arith.constant 1 : index +// CHECK: %[[SIZE:.*]] = memref.dim %[[RHS]], %[[C0]] : memref +// CHECK: %[[LHS_CASTED:.*]] = memref.reinterpret_cast %[[LHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C0]]] : memref to memref +// CHECK: %[[LHS_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref +// CHECK: memref.copy %[[LHS_CASTED]], %[[LHS_ALLOC]] +// CHECK: %[[RHS_CASTED:.*]] = memref.reinterpret_cast %[[RHS]] to offset: [0], sizes: [%[[SIZE]]], strides: [%[[C1]]] : memref to memref +// CHECK: %[[RHS_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref +// CHECK: memref.copy %[[RHS_CASTED]], %[[RHS_ALLOC]] +// CHECK: %[[OUTPUT_ALLOC:.*]] = memref.alloc(%[[SIZE]]) : memref +// CHECK: linalg.generic {indexing_maps = [#[[$MAP1]], #[[$MAP1]], #[[$MAP1]]], iterator_types = ["parallel"]} ins(%[[LHS_ALLOC]], %[[RHS_ALLOC]] : memref, memref) outs(%[[OUTPUT_ALLOC]] : memref) { +// CHECK: ^bb0(%[[ARG1:.*]]: i16, %[[ARG2:.*]]: i16, %[[ARG3:.*]]: i16): +// CHECK: %[[AND:.*]] = arith.andi %[[ARG1]], %[[ARG2]] : i16 +// CHECK: linalg.yield %[[AND]] : i16 + +// ----- + +#map0 = affine_map<(d0) -> (d0)> +builtin.module { + func.func @testCopyAfterLinalg(%arg2: memref<4xi32>, %arg3: memref<4xi32>, %arg4: memref<4xi32>) { + %0 = memref.alloc() : memref<4xi32> + linalg.generic {indexing_maps = [#map0, #map0, #map0], iterator_types = ["parallel"]} ins(%arg2, %arg3 : memref<4xi32>, memref<4xi32>) outs(%0 : memref<4xi32>) { + ^bb0(%arg5: i32, %arg6: i32, %arg7: i32): + %1 = arith.addi %arg5, %arg6 : i32 + linalg.yield %1 : i32 + } + memref.copy %0, %arg4 : memref<4xi32> to memref<4xi32> + func.return + } +} + +// CHECK: #[[$MAP0:.*]] = affine_map<(d0) -> (d0)> +// CHECK-LABEL:func @testCopyAfterLinalg( +// CHECK-SAME: %[[ARG0:.*]]: memref<4xi32>, %[[ARG1:.*]]: memref<4xi32>, %[[ARG2:.*]]: memref<4xi32>) { +// CHECK: linalg.generic {indexing_maps = [#[[$MAP0]], #[[$MAP0]], #[[$MAP0]]], iterator_types = ["parallel"]} ins(%[[ARG0]], %[[ARG1]] : memref<4xi32>, memref<4xi32>) outs(%[[ARG2]] : memref<4xi32>) { +// CHECK: ^bb0(%[[ARG3:.*]]: i32, %[[ARG4:.*]]: i32, %[[ARG5:.*]]: i32): +// CHECK: %[[R1:.*]] = arith.addi %[[ARG3]], %[[ARG4]] : i32 +// CHECK: linalg.yield %[[R1]] : i32 +// CHECK: } +// CHECK: return +// CHECK: } + +// ----- + +#map0 = affine_map<(d0) -> (d0)> +builtin.module { + func.func @testCopyAfterLinalgMutated(%arg2: memref<4xi32>, %arg3: memref<4xi32>, %arg4: memref<4xi32>) { + %c0 = arith.constant 0 : index + %c42 = arith.constant 42 : i32 + %0 = memref.alloc() : memref<4xi32> + linalg.generic {indexing_maps = [#map0, #map0, #map0], iterator_types = ["parallel"]} ins(%arg2, %arg3 : memref<4xi32>, memref<4xi32>) outs(%0 : memref<4xi32>) { + ^bb0(%arg5: i32, %arg6: i32, %arg7: i32): + %1 = arith.addi %arg5, %arg6 : i32 + linalg.yield %1 : i32 + } + memref.copy %0, %arg4 : memref<4xi32> to memref<4xi32> + memref.store %c42, %0[%c0] : memref<4xi32> + func.return + } +} + +// CHECK: #[[$MAP0:.*]] = affine_map<(d0) -> (d0)> +// CHECK-LABEL:func @testCopyAfterLinalgMutated( +// CHECK-SAME: %[[ARG0:.*]]: memref<4xi32>, %[[ARG1:.*]]: memref<4xi32>, %[[ARG2:.*]]: memref<4xi32>) { +// CHECK: %[[ALLOC:.*]] = memref.alloc() : memref<4xi32> +// CHECK: linalg.generic {indexing_maps = [#[[$MAP0]], #[[$MAP0]], #[[$MAP0]]], iterator_types = ["parallel"]} ins(%[[ARG0]], %[[ARG1]] : memref<4xi32>, memref<4xi32>) outs(%[[ALLOC]] : memref<4xi32>) { +// CHECK: ^bb0(%[[ARG3:.*]]: i32, %[[ARG4:.*]]: i32, %[[ARG5:.*]]: i32): +// CHECK: %[[R1:.*]] = arith.addi %[[ARG3]], %[[ARG4]] : i32 +// CHECK: linalg.yield %[[R1]] : i32 +// CHECK: } +// CHECK: memref.copy %[[ALLOC]], %[[ARG2]] +// CHECK: return +// CHECK: } diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/embed_tf_framework.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/embed_tf_framework.mlir new file mode 100644 index 0000000000000000000000000000000000000000..f2b1cb876d63e746f5f184a014909936bdf50e73 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/embed_tf_framework.mlir @@ -0,0 +1,86 @@ +// RUN: kernel-gen-opt %s -split-input-file -verify-diagnostics -embed-tf-framework |\ +// RUN: FileCheck %s + +// CHECK-LABEL: func @tf_entry( +// CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context, +// CHECK-SAME: [[SIZE_0:%.*]]: index, +// CHECK-SAME: [[SIZE_2:%.*]]: index) -> index attributes {tf_entry} { +func.func @tf_entry(%size_0 : index , %size_2 : index) -> index + attributes {tf_entry} { + %buf = memref.alloc(%size_0, %size_2)[] : memref + memref.dealloc %buf : memref + func.return %size_0 : index +} +// CHECK-NEXT: [[BUF:%.*]] = tf_framework.alloc +// CHECK-SAME: ([[CTX]], [[SIZE_0]], [[SIZE_2]]) : memref + +// CHECK-NEXT: [[IS_VALID:%.*]] = tf_framework.is_valid_memref([[BUF]]) +// CHECK-SAME: memref -> i1 + +// CHECK-NEXT: tf_framework.assert [[CTX]], [[IS_VALID]], +// CHECK-SAME: RESOURCE_EXHAUSTED, "failed to allocate memory" + +// CHECK-NEXT: tf_framework.dealloc([[CTX]], [[BUF]]) : memref +// CHECK-NEXT: return [[SIZE_0]] : index + +// ----- + +// CHECK-LABEL: func @non_tf_entry( +// CHECK-SAME: [[SIZE_0:%.*]]: index, [[SIZE_2:%.*]]: index) -> index +func.func @non_tf_entry(%size_0 : index , %size_2 : index) -> index { + func.return %size_0 : index +} + +// ----- + +func.func @tf_entry_no_ctx(%size : index) attributes {tf_entry} { + // expected-error @+1 {{failed to legalize operation 'memref.alloc' that was explicitly marked illegal}} + %buf = memref.alloc()[%size] : memref<64xf32, affine_map<(d0)[s0] -> (d0 + s0)>> + memref.dealloc %buf : memref<64xf32, affine_map<(d0)[s0] -> (d0 + s0)>> + func.return +} + +// ----- + +// CHECK-LABEL: func @assert( +// CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context +func.func @assert(%arg0: !tf_framework.op_kernel_context) attributes {tf_entry} { + %true = arith.constant true + cf.assert %true, "the one and only" + func.return +} +// CHECK: [[TRUE:%.*]] = arith.constant true +// CHECK-NEXT: tf_framework.assert [[CTX]], [[TRUE]], INVALID_ARGUMENT + +// ----- + +// CHECK-LABEL: func @jit_execute +// CHECK-SAME: %[[CTX:.*]]: !tf_framework.op_kernel_context, +// CHECK-SAME: %[[F:.*]]: !tf_framework.jit_callable, +// CHECK-SAME: %[[ARG0:.*]]: tensor<2x?xf32>, +// CHECK-SAME: %[[ARG1:.*]]: tensor<2x?xf32> +func.func @jit_execute(%ctx : !tf_framework.op_kernel_context, + %f : !tf_framework.jit_callable, %arg0 : tensor<2x?xf32>, + %arg1 : tensor<2x?xf32>) -> tensor<2x?xf32> attributes {tf_entry} { + // CHECK: %[[RES:.*]] = tf_framework.jit_execute + // CHECK-SAME: ctx(%[[CTX]]) %[[F]](%[[ARG0]], %[[ARG1]]) + // CHECK: return %[[RES]] + %0 = tf_framework.jit_execute %f(%arg0, %arg1) + : tensor<2x?xf32>, tensor<2x?xf32> -> tensor<2x?xf32> + func.return %0 : tensor<2x?xf32> +} + +// ----- + +// CHECK-LABEL: func @jit_compile_from_str +// CHECK-SAME: (%[[CTX:.*]]: !tf_framework.op_kernel_context) +func.func @jit_compile_from_str(%ctx : !tf_framework.op_kernel_context) + -> !tf_framework.jit_callable attributes {tf_entry} { + // CHECK: %[[RES:.*]] = tf_framework.jit_compile_from_str %[[CTX]], "placeholder" + // CHECK: return %[[RES]] + %0 = tf_framework.jit_compile_from_str "placeholder" { + architectures = ["sm_123", "sm_456"], tileSizes = [1, 2, 3], + unrollFactors = [4], enableFtz = false, + index64Bit = false, cpuCodegen = false } + func.return %0 : !tf_framework.jit_callable +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/func_to_jit_invocations.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/func_to_jit_invocations.mlir new file mode 100644 index 0000000000000000000000000000000000000000..0dbec6c8cf8ec12ebafede81de1776058125b333 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/func_to_jit_invocations.mlir @@ -0,0 +1,174 @@ +// RUN: kernel-gen-opt %s --split-input-file \ +// RUN: --func-to-jit-invocation="tile-sizes=1,2,3 unroll-factors=3,2,1 \ +// RUN: enable-ftz=false cpu-codegen=false" | \ +// RUN: FileCheck %s + +// RUN: kernel-gen-opt %s --split-input-file \ +// RUN: --func-to-jit-invocation="tile-sizes=1,2,3 unroll-factors=3,2,1 \ +// RUN: enable-ftz=false cpu-codegen=false \ +// RUN: jit_i64_indexed_for_large_tensors=true" | \ +// RUN: FileCheck %s --check-prefix=CHECK-JFLT + +func.func @unary_tanh(%arg : tensor) -> tensor { + %0 = mhlo.tanh %arg : tensor + func.return %0 : tensor +} + +// CHECK-LABEL: @unary_tanh +// CHECK-SAME: %[[ARG:.*]]: tensor +// CHECK: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str +// CHECK-SAME: " +// CHECK-SAME: module { +// CHECK-SAME: func @main(%[[ARG_JIT:.*]]: tensor) -> tensor +// CHECK-SAME: attributes {tf_entry} +// CHECK-SAME: { +// CHECK-SAME: %[[RES_JIT:.*]] = mhlo.tanh %[[ARG_JIT]] +// CHECK-SAME: return %[[RES_JIT]] +// CHECK-SAME: } +// CHECK-SAME: } +// CHECK-SAME: " +// CHECK-SAME: { +// CHECK-SAME: cpuCodegen = false +// CHECK-SAME: enableFtz = false +// CHECK-SAME: tileSizes = [1, 2, 3] +// CHECK-SAME: unrollFactors = [3, 2, 1] +// CHECK-SAME: } +// CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG]]) +// CHECK: return %[[RES]] + +// CHECK-JFLT-LABEL: @unary_tanh +// CHECK-JFLT-SAME: %[[ARG0:.*]]: tensor +// CHECK-JFLT: %[[SHAPE:.*]] = shape.shape_of %[[ARG0]] +// CHECK-JFLT: %[[NUM:.*]] = shape.num_elements %[[SHAPE]] +// CHECK-JFLT: %[[LIMIT:.*]] = arith.constant 2147483647 +// CHECK-JFLT: %[[CMPI:.*]] = arith.cmpi sgt, %[[NUM]], %[[LIMIT]] +// CHECK-JFLT: %[[IF:.*]] = scf.if %[[CMPI]] +// CHECK-JFLT: %[[JIT:.*]] = tf_framework.jit_compile_from_str +// CHECK-JFLT-SAME: "module +// CHECK-JFLT-SAME: cpuCodegen = false +// CHECK-JFLT-SAME: enableFtz = false +// CHECK-JFLT-SAME: index64Bit = true +// CHECK-JFLT-SAME: tileSizes = [1, 2, 3] +// CHECK-JFLT-SAME: unrollFactors = [3, 2, 1] +// CHECK-JFLT: %[[JIT_0:.*]] = tf_framework.jit_execute %[[JIT]](%[[ARG0]]) +// CHECK-JFLT: scf.yield %[[JIT_0]] +// CHECK-JFLT: else +// CHECK-JFLT: %[[VAL:.*]] = mhlo.tanh %[[ARG0]] +// CHECK-JFLT: scf.yield %[[VAL]] +// CHECK-JFLT: return %[[IF]] + +// ----- + +func.func @binary_sub(%arg0 : tensor<*xf32>, %arg1 : tensor<*xf32>) -> tensor<*xf32> { + %0 = chlo.broadcast_subtract %arg0, %arg1 : (tensor<*xf32>, tensor<*xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// CHECK-LABEL: @binary_sub +// CHECK-SAME: %[[ARG0:.*]]: tensor<*xf32>, %[[ARG1:.*]]: tensor<*xf32> +// CHECK: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str +// CHECK-SAME: " +// CHECK-SAME: module { +// CHECK-SAME: func @main(%[[ARG0_JIT:.*]]: tensor<*xf32>, %[[ARG1_JIT:.*]]: tensor<*xf32>) -> tensor<*xf32> +// CHECK-SAME: attributes {tf_entry} +// CHECK-SAME: { +// CHECK-SAME: %[[RES_JIT:.*]] = chlo.broadcast_subtract %[[ARG0_JIT]], %[[ARG1_JIT]] +// CHECK-SAME: return %[[RES_JIT]] +// CHECK-SAME: } +// CHECK-SAME: } +// CHECK-SAME: " +// CHECK-SAME: { +// CHECK-SAME: cpuCodegen = false +// CHECK-SAME: enableFtz = false +// CHECK-SAME: tileSizes = [1, 2, 3] +// CHECK-SAME: unrollFactors = [3, 2, 1] +// CHECK-SAME: } +// CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG0]], %[[ARG1]]) +// CHECK: return %[[RES]] + +// CHECK-JFLT-LABEL: @binary_sub +// CHECK-JFLT: %[[ARG0:.*]]: tensor<*xf32>, %[[ARG1:.*]]: tensor<*xf32> +// CHECK-JFLT: %[[SHAPE1:.*]] = shape.shape_of %[[ARG0]] : tensor<*xf32> -> tensor +// CHECK-JFLT: %[[ELEMENTCOUNT1:.*]] = shape.num_elements %[[SHAPE1]] : tensor -> index +// CHECK-JFLT: %[[LIMIT:.*]] = arith.constant 2147483647 +// CHECK-JFLT: %[[COMP1:.*]] = arith.cmpi sgt, %[[ELEMENTCOUNT1]], %[[LIMIT]] : index +// CHECK-JFLT: %[[SHAPE2:.*]] = shape.shape_of %[[ARG1]] : tensor<*xf32> -> tensor +// CHECK-JFLT: %[[ELEMENTCOUNT2:.*]] = shape.num_elements %[[SHAPE2]] : tensor -> index +// CHECK-JFLT: %[[COMP2:.*]] = arith.cmpi sgt, %[[ELEMENTCOUNT2]], %[[LIMIT]] : index +// CHECK-JFLT: %[[COMPRES:.*]] = arith.ori %[[COMP1]], %[[COMP2]] : i1 +// CHECK-JFLT: %[[IFRES:.*]] = scf.if %[[COMPRES]] -> (tensor<*xf32>) { +// CHECK-JFLT: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str +// CHECK-JFLT-SAME: " +// CHECK-JFLT-SAME: module { +// CHECK-JFLT-SAME: func @main(%[[ARG0_JIT:.*]]: tensor<*xf32>, %[[ARG1_JIT:.*]]: tensor<*xf32>) -> tensor<*xf32> +// CHECK-JFLT-SAME: attributes {tf_entry} +// CHECK-JFLT-SAME: { +// CHECK-JFLT-SAME: %[[RES_JIT:.*]] = chlo.broadcast_subtract %[[ARG0_JIT]], %[[ARG1_JIT]] +// CHECK-JFLT-SAME: return %[[RES_JIT]] +// CHECK-JFLT-SAME: } +// CHECK-JFLT-SAME: } +// CHECK-JFLT-SAME: " +// CHECK-JFLT-SAME: { +// CHECK-JFLT-SAME: cpuCodegen = false +// CHECK-JFLT-SAME: enableFtz = false +// CHECK-JFLT-SAME: tileSizes = [1, 2, 3] +// CHECK-JFLT-SAME: unrollFactors = [3, 2, 1] +// CHECK-JFLT-SAME: } +// CHECK-JFLT: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG0]], %[[ARG1]]) +// CHECK-JFLT: scf.yield %[[RES]] : tensor<*xf32> +// CHECK-JFLT: } else { +// CHECK-JFLT: %[[RES2:.*]] = chlo.broadcast_subtract %[[ARG0]], %[[ARG1]] : (tensor<*xf32>, tensor<*xf32>) -> tensor<*xf32> +// CHECK-JFLT: scf.yield %[[RES2]] : tensor<*xf32> +// CHECK-JFLT: } +// CHECK-JFLT: return %[[IFRES]] + +// ----- + +func.func @reciprocal(%arg0: tensor<*xf32>) + -> tensor<*xf32> attributes {tf_entry, llvm.emit_c_interface} { + %0 = mhlo.constant dense<1.0> : tensor + %1 = chlo.broadcast_divide %0, %arg0 : (tensor, tensor<*xf32>) -> tensor<*xf32> + func.return %1 : tensor<*xf32> +} + +// CHECK-LABEL: @reciprocal +// CHECK-SAME: %[[ARG:.*]]: tensor<*xf32> +// CHECK: %[[CALLABLE:.*]] = tf_framework.jit_compile_from_str +// CHECK-SAME: module { +// CHECK-SAME: func.func @main(%[[ARG0_JIT:.*]]: tensor<*xf32>) -> tensor<*xf32> +// CHECK-SAME: %[[CST:.*]] = mhlo.constant dense<1.000000e+00> : tensor +// CHECK-SAME: %[[RES_JIT:.*]] = chlo.broadcast_divide %[[CST]], %[[ARG0_JIT]] : (tensor, tensor<*xf32>) -> tensor<*xf32> +// CHECK=SAME: return %[[RES_JIT]] : tensor<*xf32> +// CHECK-SAME: } +// CHECK-SAME: } +// CHECK-SAME: { +// CHECK-SAME: cpuCodegen = false, +// CHECK-SAME: enableFtz = false, +// CHECK-SAME: index64Bit = false, +// CHECK-SAME: tileSizes = [1, 2, 3], +// CHECK-SAME: unrollFactors = [3, 2, 1] +// CHECK-SAME: } +// CHECK: %[[RES:.*]] = tf_framework.jit_execute %[[CALLABLE]](%[[ARG]]) : tensor<*xf32> -> tensor<*xf32> +// CHECK: return %[[RES]] : tensor<*xf32> + +// CHECK-JFLT-LABEL: @reciprocal +// CHECK-JFLT-SAME: %[[ARG0:.*]]: tensor<*xf32> +// CHECK-JFLT: %[[SHAPE:.*]] = shape.shape_of %[[ARG0]] +// CHECK-JFLT: %[[NUM:.*]] = shape.num_elements %[[SHAPE]] +// CHECK-JFLT: %[[LIMIT:.*]] = arith.constant 2147483647 +// CHECK-JFLT: %[[CMPI:.*]] = arith.cmpi sgt, %[[NUM]], %[[LIMIT]] +// CHECK-JFLT: %[[IF:.*]] = scf.if %[[CMPI]] +// CHECK-JFLT: %[[JIT:.*]] = tf_framework.jit_compile_from_str +// CHECK-JFLT-SAME: "module +// CHECK-JFLT-SAME: cpuCodegen = false +// CHECK-JFLT-SAME: enableFtz = false +// CHECK-JFLT-SAME: index64Bit = true +// CHECK-JFLT-SAME: tileSizes = [1, 2, 3] +// CHECK-JFLT-SAME: unrollFactors = [3, 2, 1] +// CHECK-JFLT: %[[JIT_0:.*]] = tf_framework.jit_execute %[[JIT]](%[[ARG0]]) +// CHECK-JFLT: scf.yield %[[JIT_0]] +// CHECK-JFLT: else +// CHECK-JFLT: %[[CST:.*]] = mhlo.constant dense<1.000000e+00> : tensor +// CHECK-JFLT: %[[VAL:.*]] = chlo.broadcast_divide %[[CST]], %[[ARG0]] : (tensor, tensor<*xf32>) -> tensor<*xf32> +// CHECK-JFLT: scf.yield %[[VAL]] +// CHECK-JFLT: return %[[IF]] diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..8238084a3411de1842e5309a9a6121d5a6aa2a2a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/BUILD @@ -0,0 +1,31 @@ +load("//tensorflow/compiler/mlir:glob_lit_test.bzl", "glob_lit_tests") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + licenses = ["notice"], +) + +glob_lit_tests( + name = "all_tests", + data = [":test_utilities"], + default_tags = [ + # We need access to the CUDA SDK. + "gpu", + "no_rocm", + "nomsan", + "notsan", + ], + driver = "//tensorflow/compiler/mlir:run_lit.sh", + hermetic_cuda_data_dir = "%S/../../../../../../../../cuda_nvcc", + test_file_exts = ["mlir"], +) + +# Bundle together all of the test utilities that are used by tests. +filegroup( + name = "test_utilities", + testonly = True, + data = [ + "//tensorflow/compiler/mlir/tools/kernel_gen:hlo_to_kernel", + "@llvm-project//mlir:run_lit.sh", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2.mlir new file mode 100644 index 0000000000000000000000000000000000000000..c9b9d8f62e326dd412963ca89f67779095023f9e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2.mlir @@ -0,0 +1,132 @@ +// RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70 + +func.func @AddV2(%arg0: tensor<*xf32>, %arg1: tensor<*xf32>) -> tensor<*xf32> attributes {llvm.emit_c_interface, tf_entry} { + %0 = shape.const_shape [1, 1, 1, 1, 1] : tensor<5xindex> + %c5 = arith.constant 5 : index + %1 = shape.const_shape [1, 1, 1, 1] : tensor<4xindex> + %c4 = arith.constant 4 : index + %2 = shape.const_shape [1, 1, 1] : tensor<3xindex> + %c3 = arith.constant 3 : index + %3 = shape.const_shape [1, 1] : tensor<2xindex> + %c2 = arith.constant 2 : index + %4 = shape.const_shape [1] : tensor<1xindex> + %c1 = arith.constant 1 : index + %5 = shape.shape_of %arg0 : tensor<*xf32> -> tensor + %6 = shape.shape_of %arg1 : tensor<*xf32> -> tensor + %7 = shape.num_elements %5 : tensor -> index + %8 = arith.cmpi eq, %7, %c1 : index + %c_empty = arith.constant dense<> : tensor<0xindex> + %9 = scf.if %8 -> (tensor<*xf32>) { + %14 = shape.num_elements %6 : tensor -> index + %from_elements = tensor.from_elements %14 : tensor<1xindex> + %15 = tensor.reshape %arg0(%c_empty) : (tensor<*xf32>, tensor<0xindex>) -> tensor + %16 = tensor.reshape %arg1(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %17 = chlo.broadcast_add %15, %16 : (tensor, tensor) -> tensor + %cast = tensor.cast %17 : tensor to tensor<*xf32> + scf.yield %cast : tensor<*xf32> + } else { + %14 = shape.num_elements %6 : tensor -> index + %15 = arith.cmpi eq, %14, %c1 : index + %16 = scf.if %15 -> (tensor<*xf32>) { + %17 = shape.num_elements %5 : tensor -> index + %from_elements = tensor.from_elements %17 : tensor<1xindex> + %18 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %19 = tensor.reshape %arg1(%c_empty) : (tensor<*xf32>, tensor<0xindex>) -> tensor + %20 = chlo.broadcast_add %18, %19 : (tensor, tensor) -> tensor + %cast = tensor.cast %20 : tensor to tensor<*xf32> + scf.yield %cast : tensor<*xf32> + } else { + %17 = shape.shape_eq %5, %6 : tensor, tensor + %18 = scf.if %17 -> (tensor<*xf32>) { + %19 = shape.any %5, %6 : tensor, tensor -> tensor + %20 = shape.num_elements %19 : tensor -> index + %from_elements = tensor.from_elements %20 : tensor<1xindex> + %21 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %22 = tensor.reshape %arg1(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %23 = chlo.broadcast_add %21, %22 : (tensor, tensor) -> tensor + %cast = tensor.cast %23 : tensor to tensor<*xf32> + scf.yield %cast : tensor<*xf32> + } else { + %19:2 = mhlo.minimum_broadcast_shapes %5, %6 : tensor, tensor -> tensor, tensor + %20 = shape.rank %19#0 : tensor -> index + %21 = shape.rank %19#1 : tensor -> index + %22 = arith.cmpi sgt, %20, %21 : index + %23 = arith.select %22, %20, %21 : index + %24 = arith.cmpi ule, %23, %c1 : index + %25 = scf.if %24 -> (tensor<*xf32>) { + %26 = shape.broadcast %19#0, %4 : tensor, tensor<1xindex> -> tensor + %cast = tensor.cast %26 : tensor to tensor<1xindex> + %27 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %28 = shape.broadcast %19#1, %4 : tensor, tensor<1xindex> -> tensor + %cast_0 = tensor.cast %28 : tensor to tensor<1xindex> + %29 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %30 = chlo.broadcast_add %27, %29 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %30 : tensor to tensor<*xf32> + scf.yield %cast_1 : tensor<*xf32> + } else { + %26 = arith.cmpi ule, %23, %c2 : index + %27 = scf.if %26 -> (tensor<*xf32>) { + %28 = shape.broadcast %19#0, %3 : tensor, tensor<2xindex> -> tensor + %cast = tensor.cast %28 : tensor to tensor<2xindex> + %29 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<2xindex>) -> tensor + %30 = shape.broadcast %19#1, %3 : tensor, tensor<2xindex> -> tensor + %cast_0 = tensor.cast %30 : tensor to tensor<2xindex> + %31 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<2xindex>) -> tensor + %32 = chlo.broadcast_add %29, %31 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %32 : tensor to tensor<*xf32> + scf.yield %cast_1 : tensor<*xf32> + } else { + %28 = arith.cmpi ule, %23, %c3 : index + %29 = scf.if %28 -> (tensor<*xf32>) { + %30 = shape.broadcast %19#0, %2 : tensor, tensor<3xindex> -> tensor + %cast = tensor.cast %30 : tensor to tensor<3xindex> + %31 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<3xindex>) -> tensor + %32 = shape.broadcast %19#1, %2 : tensor, tensor<3xindex> -> tensor + %cast_0 = tensor.cast %32 : tensor to tensor<3xindex> + %33 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<3xindex>) -> tensor + %34 = chlo.broadcast_add %31, %33 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %34 : tensor to tensor<*xf32> + scf.yield %cast_1 : tensor<*xf32> + } else { + %30 = arith.cmpi ule, %23, %c4 : index + %31 = scf.if %30 -> (tensor<*xf32>) { + %32 = shape.broadcast %19#0, %1 : tensor, tensor<4xindex> -> tensor + %cast = tensor.cast %32 : tensor to tensor<4xindex> + %33 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<4xindex>) -> tensor + %34 = shape.broadcast %19#1, %1 : tensor, tensor<4xindex> -> tensor + %cast_0 = tensor.cast %34 : tensor to tensor<4xindex> + %35 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<4xindex>) -> tensor + %36 = chlo.broadcast_add %33, %35 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %36 : tensor to tensor<*xf32> + scf.yield %cast_1 : tensor<*xf32> + } else { + %32 = arith.cmpi ule, %23, %c5 : index + cf.assert %32, "Input for dynamic binary or n-ary op lowering was of a rank greater than 5" + %33 = shape.broadcast %19#0, %0 : tensor, tensor<5xindex> -> tensor + %cast = tensor.cast %33 : tensor to tensor<5xindex> + %34 = tensor.reshape %arg0(%cast) : (tensor<*xf32>, tensor<5xindex>) -> tensor + %35 = shape.broadcast %19#1, %0 : tensor, tensor<5xindex> -> tensor + %cast_0 = tensor.cast %35 : tensor to tensor<5xindex> + %36 = tensor.reshape %arg1(%cast_0) : (tensor<*xf32>, tensor<5xindex>) -> tensor + %37 = chlo.broadcast_add %34, %36 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %37 : tensor to tensor<*xf32> + scf.yield %cast_1 : tensor<*xf32> + } + scf.yield %31 : tensor<*xf32> + } + scf.yield %29 : tensor<*xf32> + } + scf.yield %27 : tensor<*xf32> + } + scf.yield %25 : tensor<*xf32> + } + scf.yield %18 : tensor<*xf32> + } + scf.yield %16 : tensor<*xf32> + } + %10 = shape.shape_of %arg0 : tensor<*xf32> -> tensor + %11 = shape.shape_of %arg1 : tensor<*xf32> -> tensor + %12 = shape.broadcast %10, %11 : tensor, tensor -> tensor + %13 = tensor.reshape %9(%12) : (tensor<*xf32>, tensor) -> tensor<*xf32> + return %13 : tensor<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2_unsigned.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2_unsigned.mlir new file mode 100644 index 0000000000000000000000000000000000000000..ceca5e3feaed6f9e1be9e8c39ac24f91ab649ac0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/add_v2_unsigned.mlir @@ -0,0 +1,132 @@ +// RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70 + +func.func @AddV2(%arg0: tensor<*xui32>, %arg1: tensor<*xui32>) -> tensor<*xui32> attributes {llvm.emit_c_interface, tf_entry} { + %0 = shape.const_shape [1, 1, 1, 1, 1] : tensor<5xindex> + %c5 = arith.constant 5 : index + %1 = shape.const_shape [1, 1, 1, 1] : tensor<4xindex> + %c4 = arith.constant 4 : index + %2 = shape.const_shape [1, 1, 1] : tensor<3xindex> + %c3 = arith.constant 3 : index + %3 = shape.const_shape [1, 1] : tensor<2xindex> + %c2 = arith.constant 2 : index + %4 = shape.const_shape [1] : tensor<1xindex> + %c1 = arith.constant 1 : index + %5 = shape.shape_of %arg0 : tensor<*xui32> -> tensor + %6 = shape.shape_of %arg1 : tensor<*xui32> -> tensor + %7 = shape.num_elements %5 : tensor -> index + %8 = arith.cmpi eq, %7, %c1 : index + %c_empty = arith.constant dense<> : tensor<0xindex> + %9 = scf.if %8 -> (tensor<*xui32>) { + %14 = shape.num_elements %6 : tensor -> index + %from_elements = tensor.from_elements %14 : tensor<1xindex> + %15 = tensor.reshape %arg0(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor + %16 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %17 = chlo.broadcast_add %15, %16 : (tensor, tensor) -> tensor + %cast = tensor.cast %17 : tensor to tensor<*xui32> + scf.yield %cast : tensor<*xui32> + } else { + %14 = shape.num_elements %6 : tensor -> index + %15 = arith.cmpi eq, %14, %c1 : index + %16 = scf.if %15 -> (tensor<*xui32>) { + %17 = shape.num_elements %5 : tensor -> index + %from_elements = tensor.from_elements %17 : tensor<1xindex> + %18 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %19 = tensor.reshape %arg1(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor + %20 = chlo.broadcast_add %18, %19 : (tensor, tensor) -> tensor + %cast = tensor.cast %20 : tensor to tensor<*xui32> + scf.yield %cast : tensor<*xui32> + } else { + %17 = shape.shape_eq %5, %6 : tensor, tensor + %18 = scf.if %17 -> (tensor<*xui32>) { + %19 = shape.any %5, %6 : tensor, tensor -> tensor + %20 = shape.num_elements %19 : tensor -> index + %from_elements = tensor.from_elements %20 : tensor<1xindex> + %21 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %22 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %23 = chlo.broadcast_add %21, %22 : (tensor, tensor) -> tensor + %cast = tensor.cast %23 : tensor to tensor<*xui32> + scf.yield %cast : tensor<*xui32> + } else { + %19:2 = mhlo.minimum_broadcast_shapes %5, %6 : tensor, tensor -> tensor, tensor + %20 = shape.rank %19#0 : tensor -> index + %21 = shape.rank %19#1 : tensor -> index + %22 = arith.cmpi sgt, %20, %21 : index + %23 = arith.select %22, %20, %21 : index + %24 = arith.cmpi ule, %23, %c1 : index + %25 = scf.if %24 -> (tensor<*xui32>) { + %26 = shape.broadcast %19#0, %4 : tensor, tensor<1xindex> -> tensor + %cast = tensor.cast %26 : tensor to tensor<1xindex> + %27 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %28 = shape.broadcast %19#1, %4 : tensor, tensor<1xindex> -> tensor + %cast_0 = tensor.cast %28 : tensor to tensor<1xindex> + %29 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %30 = chlo.broadcast_add %27, %29 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %30 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %26 = arith.cmpi ule, %23, %c2 : index + %27 = scf.if %26 -> (tensor<*xui32>) { + %28 = shape.broadcast %19#0, %3 : tensor, tensor<2xindex> -> tensor + %cast = tensor.cast %28 : tensor to tensor<2xindex> + %29 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<2xindex>) -> tensor + %30 = shape.broadcast %19#1, %3 : tensor, tensor<2xindex> -> tensor + %cast_0 = tensor.cast %30 : tensor to tensor<2xindex> + %31 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<2xindex>) -> tensor + %32 = chlo.broadcast_add %29, %31 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %32 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %28 = arith.cmpi ule, %23, %c3 : index + %29 = scf.if %28 -> (tensor<*xui32>) { + %30 = shape.broadcast %19#0, %2 : tensor, tensor<3xindex> -> tensor + %cast = tensor.cast %30 : tensor to tensor<3xindex> + %31 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<3xindex>) -> tensor + %32 = shape.broadcast %19#1, %2 : tensor, tensor<3xindex> -> tensor + %cast_0 = tensor.cast %32 : tensor to tensor<3xindex> + %33 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<3xindex>) -> tensor + %34 = chlo.broadcast_add %31, %33 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %34 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %30 = arith.cmpi ule, %23, %c4 : index + %31 = scf.if %30 -> (tensor<*xui32>) { + %32 = shape.broadcast %19#0, %1 : tensor, tensor<4xindex> -> tensor + %cast = tensor.cast %32 : tensor to tensor<4xindex> + %33 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<4xindex>) -> tensor + %34 = shape.broadcast %19#1, %1 : tensor, tensor<4xindex> -> tensor + %cast_0 = tensor.cast %34 : tensor to tensor<4xindex> + %35 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<4xindex>) -> tensor + %36 = chlo.broadcast_add %33, %35 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %36 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %32 = arith.cmpi ule, %23, %c5 : index + cf.assert %32, "Input for dynamic binary or n-ary op lowering was of a rank greater than 5" + %33 = shape.broadcast %19#0, %0 : tensor, tensor<5xindex> -> tensor + %cast = tensor.cast %33 : tensor to tensor<5xindex> + %34 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<5xindex>) -> tensor + %35 = shape.broadcast %19#1, %0 : tensor, tensor<5xindex> -> tensor + %cast_0 = tensor.cast %35 : tensor to tensor<5xindex> + %36 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<5xindex>) -> tensor + %37 = chlo.broadcast_add %34, %36 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %37 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } + scf.yield %31 : tensor<*xui32> + } + scf.yield %29 : tensor<*xui32> + } + scf.yield %27 : tensor<*xui32> + } + scf.yield %25 : tensor<*xui32> + } + scf.yield %18 : tensor<*xui32> + } + scf.yield %16 : tensor<*xui32> + } + %10 = shape.shape_of %arg0 : tensor<*xui32> -> tensor + %11 = shape.shape_of %arg1 : tensor<*xui32> -> tensor + %12 = shape.broadcast %10, %11 : tensor, tensor -> tensor + %13 = tensor.reshape %9(%12) : (tensor<*xui32>, tensor) -> tensor<*xui32> + return %13 : tensor<*xui32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/minimum.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/minimum.mlir new file mode 100644 index 0000000000000000000000000000000000000000..97e8d075ca4012b4d8c39b2e4d182f4c947bf338 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/minimum.mlir @@ -0,0 +1,132 @@ +// RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70 + +func.func @Minimum_GPU_DT_UINT32_DT_UINT32(%arg0: tensor<*xui32>, %arg1: tensor<*xui32>) -> tensor<*xui32> attributes {llvm.emit_c_interface, tf_entry} { + %0 = shape.const_shape [1, 1, 1, 1, 1] : tensor<5xindex> + %c5 = arith.constant 5 : index + %1 = shape.const_shape [1, 1, 1, 1] : tensor<4xindex> + %c4 = arith.constant 4 : index + %2 = shape.const_shape [1, 1, 1] : tensor<3xindex> + %c3 = arith.constant 3 : index + %3 = shape.const_shape [1, 1] : tensor<2xindex> + %c2 = arith.constant 2 : index + %4 = shape.const_shape [1] : tensor<1xindex> + %c1 = arith.constant 1 : index + %5 = shape.shape_of %arg0 : tensor<*xui32> -> tensor + %6 = shape.shape_of %arg1 : tensor<*xui32> -> tensor + %7 = shape.num_elements %5 : tensor -> index + %8 = arith.cmpi eq, %7, %c1 : index + %c_empty = arith.constant dense<> : tensor<0xindex> + %9 = scf.if %8 -> (tensor<*xui32>) { + %14 = shape.num_elements %6 : tensor -> index + %from_elements = tensor.from_elements %14 : tensor<1xindex> + %15 = tensor.reshape %arg0(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor + %16 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %17 = chlo.broadcast_minimum %15, %16 : (tensor, tensor) -> tensor + %cast = tensor.cast %17 : tensor to tensor<*xui32> + scf.yield %cast : tensor<*xui32> + } else { + %14 = shape.num_elements %6 : tensor -> index + %15 = arith.cmpi eq, %14, %c1 : index + %16 = scf.if %15 -> (tensor<*xui32>) { + %17 = shape.num_elements %5 : tensor -> index + %from_elements = tensor.from_elements %17 : tensor<1xindex> + %18 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %19 = tensor.reshape %arg1(%c_empty) : (tensor<*xui32>, tensor<0xindex>) -> tensor + %20 = chlo.broadcast_minimum %18, %19 : (tensor, tensor) -> tensor + %cast = tensor.cast %20 : tensor to tensor<*xui32> + scf.yield %cast : tensor<*xui32> + } else { + %17 = shape.shape_eq %5, %6 : tensor, tensor + %18 = scf.if %17 -> (tensor<*xui32>) { + %19 = shape.any %5, %6 : tensor, tensor -> tensor + %20 = shape.num_elements %19 : tensor -> index + %from_elements = tensor.from_elements %20 : tensor<1xindex> + %21 = tensor.reshape %arg0(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %22 = tensor.reshape %arg1(%from_elements) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %23 = chlo.broadcast_minimum %21, %22 : (tensor, tensor) -> tensor + %cast = tensor.cast %23 : tensor to tensor<*xui32> + scf.yield %cast : tensor<*xui32> + } else { + %19:2 = mhlo.minimum_broadcast_shapes %5, %6 : tensor, tensor -> tensor, tensor + %20 = shape.rank %19#0 : tensor -> index + %21 = shape.rank %19#1 : tensor -> index + %22 = arith.cmpi sgt, %20, %21 : index + %23 = arith.select %22, %20, %21 : index + %24 = arith.cmpi ule, %23, %c1 : index + %25 = scf.if %24 -> (tensor<*xui32>) { + %26 = shape.broadcast %19#0, %4 : tensor, tensor<1xindex> -> tensor + %cast = tensor.cast %26 : tensor to tensor<1xindex> + %27 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %28 = shape.broadcast %19#1, %4 : tensor, tensor<1xindex> -> tensor + %cast_0 = tensor.cast %28 : tensor to tensor<1xindex> + %29 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<1xindex>) -> tensor + %30 = chlo.broadcast_minimum %27, %29 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %30 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %26 = arith.cmpi ule, %23, %c2 : index + %27 = scf.if %26 -> (tensor<*xui32>) { + %28 = shape.broadcast %19#0, %3 : tensor, tensor<2xindex> -> tensor + %cast = tensor.cast %28 : tensor to tensor<2xindex> + %29 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<2xindex>) -> tensor + %30 = shape.broadcast %19#1, %3 : tensor, tensor<2xindex> -> tensor + %cast_0 = tensor.cast %30 : tensor to tensor<2xindex> + %31 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<2xindex>) -> tensor + %32 = chlo.broadcast_minimum %29, %31 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %32 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %28 = arith.cmpi ule, %23, %c3 : index + %29 = scf.if %28 -> (tensor<*xui32>) { + %30 = shape.broadcast %19#0, %2 : tensor, tensor<3xindex> -> tensor + %cast = tensor.cast %30 : tensor to tensor<3xindex> + %31 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<3xindex>) -> tensor + %32 = shape.broadcast %19#1, %2 : tensor, tensor<3xindex> -> tensor + %cast_0 = tensor.cast %32 : tensor to tensor<3xindex> + %33 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<3xindex>) -> tensor + %34 = chlo.broadcast_minimum %31, %33 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %34 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %30 = arith.cmpi ule, %23, %c4 : index + %31 = scf.if %30 -> (tensor<*xui32>) { + %32 = shape.broadcast %19#0, %1 : tensor, tensor<4xindex> -> tensor + %cast = tensor.cast %32 : tensor to tensor<4xindex> + %33 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<4xindex>) -> tensor + %34 = shape.broadcast %19#1, %1 : tensor, tensor<4xindex> -> tensor + %cast_0 = tensor.cast %34 : tensor to tensor<4xindex> + %35 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<4xindex>) -> tensor + %36 = chlo.broadcast_minimum %33, %35 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %36 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } else { + %32 = arith.cmpi ule, %23, %c5 : index + cf.assert %32, "Input for dynamic binary or n-ary op lowering was of a rank greater than 5" + %33 = shape.broadcast %19#0, %0 : tensor, tensor<5xindex> -> tensor + %cast = tensor.cast %33 : tensor to tensor<5xindex> + %34 = tensor.reshape %arg0(%cast) : (tensor<*xui32>, tensor<5xindex>) -> tensor + %35 = shape.broadcast %19#1, %0 : tensor, tensor<5xindex> -> tensor + %cast_0 = tensor.cast %35 : tensor to tensor<5xindex> + %36 = tensor.reshape %arg1(%cast_0) : (tensor<*xui32>, tensor<5xindex>) -> tensor + %37 = chlo.broadcast_minimum %34, %36 : (tensor, tensor) -> tensor + %cast_1 = tensor.cast %37 : tensor to tensor<*xui32> + scf.yield %cast_1 : tensor<*xui32> + } + scf.yield %31 : tensor<*xui32> + } + scf.yield %29 : tensor<*xui32> + } + scf.yield %27 : tensor<*xui32> + } + scf.yield %25 : tensor<*xui32> + } + scf.yield %18 : tensor<*xui32> + } + scf.yield %16 : tensor<*xui32> + } + %10 = shape.shape_of %arg0 : tensor<*xui32> -> tensor + %11 = shape.shape_of %arg1 : tensor<*xui32> -> tensor + %12 = shape.broadcast %10, %11 : tensor, tensor -> tensor + %13 = tensor.reshape %9(%12) : (tensor<*xui32>, tensor) -> tensor<*xui32> + return %13 : tensor<*xui32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/tanh.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/tanh.mlir new file mode 100644 index 0000000000000000000000000000000000000000..c9742adbd384e2e7c1f57ccb360e745a732e9c1e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/hlo_to_kernel/tanh.mlir @@ -0,0 +1,11 @@ +// RUN: hlo_to_kernel --input=%s --output=%t --unroll_factors=4 --tile_sizes=256 --arch=sm_70 + +func.func @tanh(%arg0: tensor<*xf32>) -> tensor<*xf32> attributes {tf_entry} { + %0 = shape.shape_of %arg0 : tensor<*xf32> -> tensor + %1 = shape.num_elements %0 : tensor -> index + %from_elements = tensor.from_elements %1 : tensor<1xindex> + %2 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %3 = mhlo.tanh %2 : tensor + %4 = tensor.reshape %3(%0) : (tensor, tensor) -> tensor<*xf32> + return %4 : tensor<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/invalid.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/invalid.mlir new file mode 100644 index 0000000000000000000000000000000000000000..0f5a0a37b0ca01229689fed354271b603f0d44e7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/invalid.mlir @@ -0,0 +1,7 @@ +// RUN: kernel-gen-opt %s -split-input-file -verify-diagnostics + +func.func @alloc_raw(%ctx: !tf_framework.op_kernel_context, %size : index) { + // expected-error @+1 {{`dyn_sizes` count 1 does not match dynamic dimensions}} + %buf = tf_framework.alloc(%ctx, %size) : memref + func.return +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/isinf.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/isinf.mlir new file mode 100644 index 0000000000000000000000000000000000000000..e3d4819313bce9ae3e94758a6815930b9a8aaf11 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/isinf.mlir @@ -0,0 +1,19 @@ +// RUN: tf-opt %s --test-tf-lower-tf --xla-legalize-tf | \ +// RUN: mlir-hlo-opt \ +// RUN: --hlo-legalize-to-stablehlo=allow-xla-features \ +// RUN: --stablehlo-legalize-to-linalg \ +// RUN: --empty-tensor-to-alloc-tensor \ +// RUN: --computeop-and-func-bufferize --canonicalize | \ +// RUN: kernel-gen-opt -allow-unregistered-dialect \ +// RUN: --shape-to-descriptors \ +// RUN: --canonicalize --kernelgen-final-bufferize | \ +// RUN: FileCheck %s + +// Test whether all shape computations required for isinf can be lowered to +// the standard dialect, scf and descriptors. +// CHECK-LABEL: @isinf +func.func @isinf(%arg0: tensor) -> tensor { + // CHECK-NOT: shape + %0 = "tf.IsInf"(%arg0) : (tensor) -> tensor + func.return %0 : tensor +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/legalize_tensor_reshape.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/legalize_tensor_reshape.mlir new file mode 100644 index 0000000000000000000000000000000000000000..6c8b0f7f41b1286e8425e881b3303f394ae977b5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/legalize_tensor_reshape.mlir @@ -0,0 +1,14 @@ +// RUN: kernel-gen-opt --split-input-file --legalize-tensor-reshape %s | FileCheck %s + +// CHECK-LABEL: func @tanh +func.func @tanh(%arg0: tensor<*xf32>) -> tensor<*xf32> attributes {tf_entry} { + %0 = shape.shape_of %arg0 : tensor<*xf32> -> tensor + %1 = shape.num_elements %0 : tensor -> index + %from_elements = tensor.from_elements %1 : tensor<1xindex> + // CHECK: mhlo.dynamic_reshape + // CHECK-NOT: tensor.reshape + %2 = tensor.reshape %arg0(%from_elements) : (tensor<*xf32>, tensor<1xindex>) -> tensor + %3 = mhlo.tanh %2 : tensor + %4 = tensor.reshape %3(%0) : (tensor, tensor) -> tensor<*xf32> + return %4 : tensor<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/merge_assuming_ops.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/merge_assuming_ops.mlir new file mode 100644 index 0000000000000000000000000000000000000000..57ad032a3313a4eb8cd65825b31f4d5a9a38f635 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/merge_assuming_ops.mlir @@ -0,0 +1,348 @@ +// RUN: kernel-gen-opt --split-input-file --allow-unregistered-dialect \ +// RUN: --mhlo-merge-assuming-ops --canonicalize --cse %s | \ +// RUN: FileCheck %s + +// Shape computations shall be reified. +// CHECK-LABEL: @shape_of_unary +// CHECK-SAME: (%[[ARG:.*]]: tensor) +func.func @shape_of_unary(%arg : tensor) { + // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG]] : tensor -> tensor + // CHECK: "use"(%[[SHAPE]]) + %0 = "mhlo.convert"(%arg) : (tensor) -> tensor + %1 = shape.shape_of %0 : tensor -> tensor + "use"(%1) : (tensor) -> () + func.return +} + +// ----- + +// Shape computations shall be reified. +// CHECK-LABEL: @shape_of_nary +// CHECK-SAME: (%[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor) +func.func @shape_of_nary(%arg0 : tensor, %arg1 : tensor) { + // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG0]] : tensor -> tensor + // CHECK: "use"(%[[SHAPE]]) + %0 = mhlo.subtract %arg0, %arg1 : tensor + %1 = mhlo.subtract %0, %arg1 : tensor + %2 = shape.shape_of %1 : tensor -> tensor + "use"(%2) : (tensor) -> () + func.return +} + +// ----- + +// CHECK-LABEL: @inline_bcasted_shape_operands +// CHECK-SAME: (%[[A:.*]]: tensor, %[[B:.*]]: tensor, %[[C:.*]]: tensor) +func.func @inline_bcasted_shape_operands(%a : tensor, %b : tensor, + %c : tensor) -> !shape.witness { + // CHECK-NOT: shape.broadcast + // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[A]], %[[B]], %[[C]] + // CHECK: return %[[WITNESS]] : !shape.witness + %0 = shape.broadcast %a, %b : tensor, tensor + -> tensor + %1 = shape.cstr_broadcastable %0, %c : tensor, tensor + func.return %1 : !shape.witness +} + +// ----- + +// CHECK-LABEL: @move_shape_of_into_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor) +func.func @move_shape_of_into_assuming(%arg0 : !shape.witness, + %arg1 : tensor) -> tensor<2xindex> { + // CHECK: %[[ASSUMING_RESULTS:.*]]:3 = shape.assuming %[[ARG0]] -> (tensor, tensor, tensor<2xindex>) { + // CHECK: %[[DUMMY_TENSOR:.*]] = "dummy.tensor"() : () -> tensor + // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[DUMMY_TENSOR]] + // CHECK: shape.assuming_yield %[[ARG1]], %[[DUMMY_TENSOR]], %[[SHAPE]] + // CHECK: } + // CHECK-NOT: shape_of + // CHECK: return %[[ASSUMING_RESULTS]]#2 + %0:2 = shape.assuming %arg0 -> (tensor, tensor) { + %1 = "dummy.tensor"() : () -> tensor + shape.assuming_yield %arg1, %1 : tensor, tensor + } + %2 = shape.shape_of %0#1 : tensor -> tensor<2xindex> + "use"(%0#0, %0#1) : (tensor, tensor) -> () + func.return %2 : tensor<2xindex> +} + +// ----- + +// CHECK-LABEL: @move_cstr_broadcastable_into_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2xindex>) +func.func @move_cstr_broadcastable_into_assuming(%arg0 : !shape.witness, + %arg1 : tensor<2xindex>) -> !shape.witness { + // CHECK: %[[ASSUMING_RESULTS:.*]]:3 = shape.assuming %[[ARG0]] -> (tensor<2xindex>, tensor<3xindex>, !shape.witness) { + // CHECK: %[[DUMMY_TENSOR:.*]] = "dummy.tensor"() : () -> tensor<3xindex> + // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[ARG1]], %[[DUMMY_TENSOR]] + // CHECK: shape.assuming_yield %[[ARG1]], %[[DUMMY_TENSOR]], %[[WITNESS]] + // CHECK: } + // CHECK-NOT: cstr_broadcastable + // CHECK: return %[[ASSUMING_RESULTS]]#2 + %0:2 = shape.assuming %arg0 -> (tensor<2xindex>, tensor<3xindex>) { + %1 = "dummy.tensor"() : () -> tensor<3xindex> + shape.assuming_yield %arg1, %1 : tensor<2xindex>, tensor<3xindex> + } + %1 = shape.cstr_broadcastable %arg1, %0#1 : tensor<2xindex>, tensor<3xindex> + "use"(%0#0, %0#1) : (tensor<2xindex>, tensor<3xindex>) -> () + func.return %1 : !shape.witness +} + +// ----- + +// CHECK-LABEL: @not_move_shape_of_into_assuming +// CHECK-SAME: (%[[W:.*]]: !shape.witness, %[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor) +func.func @not_move_shape_of_into_assuming(%arg0 : !shape.witness, + %arg1 : tensor, %arg2 : tensor) -> tensor<2xindex> { + // CHECK: %[[S:.*]] = shape.shape_of %[[ARG1]] + // CHECK: %[[ASS_RES:.*]] = shape.assuming %[[W]] + // CHECK: shape.assuming_yield %[[ARG0]] + // CHECK: } + // CHECK: "some.other.op"(%[[ASS_RES]]) + // CHECK: return %[[S]] + %0:2 = shape.assuming %arg0 -> (tensor, tensor) { + shape.assuming_yield %arg1, %arg2 : tensor, tensor + } + "some.other.op"(%0#0) : (tensor) -> () + %2 = shape.shape_of %0#1 : tensor -> tensor<2xindex> + func.return %2 : tensor<2xindex> +} + +// ----- + +// CHECK-LABEL: @move_cstr_broadcastable_out_of_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2xindex>, %[[ARG2:.*]]: tensor<3xindex>) +func.func @move_cstr_broadcastable_out_of_assuming(%arg0 : !shape.witness, + %arg1 : tensor<2xindex>, %arg2 : tensor<3xindex>) -> !shape.witness { + // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[ARG1]], %[[ARG2]] + // CHECK-NOT: assuming + // CHECK-NOT: cstr_broadcastable + // CHECK: return %[[WITNESS]] + %0 = shape.assuming %arg0 -> (!shape.witness) { + %1 = shape.cstr_broadcastable %arg1, %arg2 : tensor<2xindex>, tensor<3xindex> + shape.assuming_yield %1 : !shape.witness + } + func.return %0 : !shape.witness +} + +// ----- + +// CHECK-LABEL: @move_elementwise_into_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor) +func.func @move_elementwise_into_assuming(%arg0 : !shape.witness, + %arg1 : tensor) -> tensor { + // CHECK: %[[RES:.*]] = shape.assuming %[[ARG0]] + // CHECK: %[[SOME:.*]] = "some.op" + // CHECK: %[[TANH:.*]] = mhlo.tanh %[[ARG1]] + // CHECK: %[[BCAST_ADD:.*]] = chlo.broadcast_add %[[TANH]], %[[SOME]] + // CHECK: shape.assuming_yield %[[BCAST_ADD]] + // CHECK-NOT: tanh + // CHECK-NOT: broadcast_add + // CHECK: return %[[RES]] + %0:2 = shape.assuming %arg0 -> (tensor, tensor) { + %1 = "some.op"() : () -> tensor + shape.assuming_yield %arg1, %1 : tensor, tensor + } + %1 = mhlo.tanh %arg1 : tensor + %2 = chlo.broadcast_add %1, %0#1 + : (tensor, tensor) -> tensor + func.return %2 : tensor +} + +// ----- + +// CHECK-LABEL: @move_shape_of_out_of_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2x?xf32>) +func.func @move_shape_of_out_of_assuming(%arg0 : !shape.witness, + %arg1 : tensor<2x?xf32>) -> tensor<2xindex> { + // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG1]] + // CHECK-NOT: assuming + // CHECK-NOT: cstr_broadcastable + // CHECK: return %[[SHAPE]] + %0 = shape.assuming %arg0 -> (tensor<2xindex>) { + %1 = shape.shape_of %arg1 : tensor<2x?xf32> -> tensor<2xindex> + shape.assuming_yield %1 : tensor<2xindex> + } + func.return %0 : tensor<2xindex> +} + +// ----- + +// CHECK-LABEL: @move_shape_of_out_of_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2x?xf32>) +func.func @move_shape_of_out_of_assuming(%arg0 : !shape.witness, + %arg1 : tensor<2x?xf32>) -> tensor<2xindex> { + // CHECK: %[[SHAPE:.*]] = shape.shape_of %[[ARG1]] + // CHECK: %{{.*}} = shape.assuming %[[ARG0]] -> (tensor<2x?xf32>) { + // CHECK: %[[SOME_VAL:.*]] = "some.op"() : () -> tensor<2x?xf32> + // CHECK: shape.assuming_yield %[[SOME_VAL]] : tensor<2x?xf32> + // CHECK: } + // CHECK: return %[[SHAPE]] + %0:2 = shape.assuming %arg0 -> (tensor<2x?xf32>, tensor<2xindex>) { + %1 = "some.op"() : () -> (tensor<2x?xf32>) + %2 = shape.shape_of %arg1 : tensor<2x?xf32> -> tensor<2xindex> + shape.assuming_yield %1, %2 : tensor<2x?xf32>, tensor<2xindex> + } + "use"(%0#0, %0#1) : (tensor<2x?xf32>, tensor<2xindex>) -> () + func.return %0#1 : tensor<2xindex> +} + +// ----- + +// CHECK-LABEL: @not_move_shape_of_out_of_assuming +// CHECK-SAME: (%[[ARG0:.*]]: !shape.witness, %[[ARG1:.*]]: tensor<2x?xf32>) +func.func @not_move_shape_of_out_of_assuming(%arg0 : !shape.witness, + %arg1 : tensor<2x?xf32>) -> tensor<2xindex> { + // CHECK-NOT: shape_of + // CHECK: shape.assuming + // CHECK-SAME: { + // CHECK: "some.tensor" + // CHECK: shape_of + // CHECK: } + %0 = shape.assuming %arg0 -> (tensor<2xindex>) { + %1 = "some.tensor"() : () -> tensor<2x?xf32> + %2 = shape.shape_of %1 : tensor<2x?xf32> -> tensor<2xindex> + shape.assuming_yield %2 : tensor<2xindex> + } + func.return %0 : tensor<2xindex> +} + +// ----- + +// CHECK: @merge_assuming_ops +// CHECK: (%[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor, %[[ARG2:.*]]: tensor) +func.func @merge_assuming_ops(%arg0: tensor, %arg1 : tensor, + %arg2: tensor) -> tensor { + // CHECK: %[[SHAPE0:.*]] = shape.shape_of %[[ARG0]] + // CHECK: %[[SHAPE1:.*]] = shape.shape_of %[[ARG1]] + // CHECK: %[[SHAPE2:.*]] = shape.shape_of %[[ARG2]] + // CHECK: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[SHAPE0]], %[[SHAPE1]], %[[SHAPE2]] + // CHECK: %[[MERGED:.*]]:2 = shape.assuming %[[WITNESS]] + // CHECK-SAME: { + // CHECK: "some.op" + // CHECK: %[[RESULT0:.*]] = "some.producer" + // CHECK: "another.op" + // CHECK: %[[RESULT1:.*]] = "another.producer" + // CHECK: shape.assuming_yield %[[RESULT0]], %[[RESULT1]] + // CHECK: } + // CHECK: return %[[MERGED]]#1 + %0 = shape.shape_of %arg0 : tensor -> tensor<2xindex> + %1 = shape.shape_of %arg1 : tensor -> tensor<2xindex> + %2 = shape.shape_of %arg2 : tensor -> tensor<3xindex> + %3 = shape.cstr_broadcastable %0, %1 : tensor<2xindex>, tensor<2xindex> + %4 = shape.cstr_broadcastable %0, %1, %2 : tensor<2xindex>, tensor<2xindex>, + tensor<3xindex> + %5 = shape.assuming %3 -> (tensor) { + "some.op"() : () -> () + %6 = "some.producer"() : () -> tensor + shape.assuming_yield %6 : tensor + } + %7 = shape.assuming %4 -> (tensor) { + "another.op"() : () -> () + %8 = "another.producer"() : () -> tensor + shape.assuming_yield %8 : tensor + } + "use"(%5, %7) : (tensor, tensor) -> () + func.return %7 : tensor +} + +// ----- + +// Do not merge assuming ops if witness will not dominate use. +// CHECK: @do_not_merge_assuming_ops +func.func @do_not_merge_assuming_ops() { + // CHECK: shape.assuming + // CHECK: shape.assuming + %0 = "some.witness"() : () -> !shape.witness + %1 = shape.assuming %0 -> (!shape.witness) { + %2 = "some.witness"() : () -> !shape.witness + shape.assuming_yield %2 : !shape.witness + } + shape.assuming %1 { + "some.op"() : () -> () + shape.assuming_yield + } + func.return +} + +// ----- + +// CHECK: @eliminate_extent_tensor_cast +// CHECK-SAME: (%[[ARG:.*]]: tensor<2x?x4xf32>) +func.func @eliminate_extent_tensor_cast(%arg : tensor<2x?x4xf32>) { + // CHECK-NOT: shape_of + // CHECK: %[[RESULT:.*]] = shape.shape_of %[[ARG]] : tensor<2x?x4xf32> -> tensor<3xindex> + // CHECK-NEXT: "use"(%[[RESULT]]) : (tensor<3xindex>) -> () + %0 = shape.shape_of %arg : tensor<2x?x4xf32> -> tensor + %1 = tensor.cast %0 : tensor to tensor<3xindex> + "use"(%1) : (tensor<3xindex>) -> () + func.return +} + +// ----- + +// CHECK-LABEL: @redundant_cstr_broadcastable +// CHECK-SAME: (%[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor) +func.func @redundant_cstr_broadcastable(%arg0: tensor, + %arg1 : tensor) { + // CHECK-DAG: %[[WITNESS:.*]] = shape.cstr_broadcastable %[[ARG0]], %[[ARG1]] + // CHECK: shape.assuming %[[WITNESS]] + %0 = shape.cstr_broadcastable %arg0, %arg1 : tensor, tensor + %1 = shape.cstr_broadcastable %arg0, %arg1 : tensor, tensor + %2 = shape.assuming_all %0, %1 + shape.assuming %2 -> () { + "some.op"() : () -> () + shape.assuming_yield + } + func.return +} + +// ----- + +// CHECK-LABEL: @move_assuming_all_over_assuming_region +// CHECK-SAME: %[[ARG0:.*]]: tensor, %[[ARG1:.*]]: tensor, %[[ARG2:.*]]: tensor, %[[ARG3:.*]]: tensor, %[[ARG4:.*]]: tensor +func.func @move_assuming_all_over_assuming_region(%arg0: tensor, + %arg1 : tensor, %arg2 : tensor, %arg3 : tensor, + %arg4 : tensor) { + // CHECK-DAG: %[[CSTR0:.*]] = shape.cstr_broadcastable %[[ARG0]], %[[ARG1]] + // CHECK-DAG: %[[CSTR1:.*]] = shape.cstr_broadcastable %[[ARG1]], %[[ARG2]] + // CHECK-DAG: %[[CSTR2:.*]] = shape.cstr_broadcastable %[[ARG2]], %[[ARG3]] + // CHECK-DAG: %[[CSTR3:.*]] = shape.cstr_broadcastable %[[ARG3]], %[[ARG4]] + // CHECK-DAG: %[[CSTR_ALL:.*]] = shape.assuming_all %[[CSTR0]], %[[CSTR1]], %[[CSTR2]], %[[CSTR3]] + // CHECK: shape.assuming %[[CSTR_ALL]] { + // CHECK: "some.op"() + // CHECK: "some.op"() + // CHECK: } + // CHECK: return + %0 = shape.cstr_broadcastable %arg0, %arg1 : tensor, tensor + %1 = shape.cstr_broadcastable %arg1, %arg2 : tensor, tensor + %2 = shape.assuming_all %0, %1 + shape.assuming %2 -> () { + "some.op"() : () -> () + } + %3 = shape.cstr_broadcastable %arg2, %arg3 : tensor, tensor + %4 = shape.cstr_broadcastable %arg3, %arg4 : tensor, tensor + %5 = shape.assuming_all %3, %4 + shape.assuming %5 -> () { + "some.op"() : () -> () + } + func.return +} + +// ----- + +// CHECK-LABEL: @move_down_into_assuming +// CHECK-SAME: (%[[ARG:.*]]: tensor, %[[W:.*]]: !shape.witness) +func.func @move_down_into_assuming(%arg0: tensor, %w: !shape.witness) -> tensor { + // CHECK: %[[RES:.*]] = shape.assuming %[[W]] + // CHECK: %[[INNER_RES:.*]] = mhlo.convert %[[ARG]] + // CHECK: shape.assuming_yield %[[INNER_RES]] + // CHECK: } + // CHECK: return %[[RES]] + %0 = mhlo.convert %arg0 : (tensor) -> tensor + "some.possibly_side_effecting_op"() : () -> () + %4 = shape.assuming %w -> (tensor) { + shape.assuming_yield %0 : tensor + } + func.return %4 : tensor +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/ops.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/ops.mlir new file mode 100644 index 0000000000000000000000000000000000000000..c7f111647e9ee6ab409f3487feebcf50bf923dcf --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/ops.mlir @@ -0,0 +1,115 @@ +// RUN: kernel-gen-opt %s | FileCheck %s +// Verify the printed output can be parsed. +// RUN: kernel-gen-opt %s | kernel-gen-opt | FileCheck %s +// Verify the generic form can be parsed. +// RUN: kernel-gen-opt -mlir-print-op-generic %s | kernel-gen-opt | FileCheck %s + +// CHECK-LABEL: func @alloc +func.func @alloc(%ctx: !tf_framework.op_kernel_context, + %size_0 : index , %size_2 : index) { + %buf_0 = tf_framework.alloc(%ctx) : memref<10xi8> + %buf_1 = tf_framework.alloc(%ctx, %size_0, %size_2) : memref + func.return +} + +// CHECK-LABEL: func @forwarding_alloc +func.func @forwarding_alloc(%ctx: !tf_framework.op_kernel_context, + %size_0 : index , %size_2 : index) { + %buf = tf_framework.alloc(%ctx, %size_0, %size_2) { + input_indices = [0 : i32, 1 : i32], + output_index = 0 : i32 + } : memref + func.return +} + +// CHECK-LABEL: func @dealloc +func.func @dealloc(%ctx: !tf_framework.op_kernel_context, + %memref : memref) { + tf_framework.dealloc(%ctx, %memref) : memref + func.return +} + +// CHECK-LABEL: func @assert +func.func @assert(%ctx: !tf_framework.op_kernel_context, %cond: i1) { + tf_framework.assert %ctx, %cond, "ALREADY_EXISTS", "Or maybe not" + func.return +} + +// CHECK-LABEL: func @report_error +func.func @report_error(%ctx: !tf_framework.op_kernel_context) { + tf_framework.report_error %ctx, "INVALID_ARGUMENT", "Everything is awesome" + func.return +} + +// CHECK-LABEL: func @null_memref +func.func @null_memref() { + tf_framework.null_memref : memref<*xf32> + func.return +} + +// CHECK-LABEL: func @null_context +func.func @null_context() { + tf_framework.null_context : !tf_framework.op_kernel_context + func.return +} + +// CHECK-LABEL: func @is_valid_memref +func.func @is_valid_memref(%buf: memref) -> i1 { + %pred = tf_framework.is_valid_memref(%buf) : memref -> i1 + func.return %pred : i1 +} + +// CHECK-LABEL: func @jit_compile_wo_ctx +func.func @jit_compile_wo_ctx() -> !tf_framework.jit_callable { + %callable = tf_framework.jit_compile { + ^bb0(%arg : tensor<2x?xf32>): + tf_framework.jit_compile_yield %arg : tensor<2x?xf32> + } + func.return %callable : !tf_framework.jit_callable +} + +// CHECK-LABEL: func @jit_compile +func.func @jit_compile(%ctx : !tf_framework.op_kernel_context) + -> !tf_framework.jit_callable { + %callable = tf_framework.jit_compile %ctx { + ^bb0(%arg : tensor<2x?xf32>): + tf_framework.jit_compile_yield %arg : tensor<2x?xf32> + } + func.return %callable : !tf_framework.jit_callable +} + +// CHECK-LABEL: func @jit_compile_from_str_wo_ctx +func.func @jit_compile_from_str_wo_ctx() -> !tf_framework.jit_callable { + %callable = tf_framework.jit_compile_from_str "placeholder" { + architectures = ["sm_123", "sm_456"], tileSizes = [1, 2, 3], + unrollFactors = [4], enableFtz = false, + index64Bit = false, cpuCodegen = false } + func.return %callable : !tf_framework.jit_callable +} + +// CHECK-LABEL: func @jit_compile_from_str +func.func @jit_compile_from_str(%ctx : !tf_framework.op_kernel_context) + -> !tf_framework.jit_callable { + %callable = tf_framework.jit_compile_from_str %ctx , "placeholder" { + architectures = ["sm_123", "sm_456"], tileSizes = [1, 2, 3], + unrollFactors = [4], enableFtz = false, + index64Bit = false, cpuCodegen = false } + func.return %callable : !tf_framework.jit_callable +} + +// CHECK-LABEL: func @jit_execute_wo_ctx +func.func @jit_execute_wo_ctx(%callable : !tf_framework.jit_callable, + %arg : tensor<2x?xf32>) -> tensor<2x?xf32> { + %0 = tf_framework.jit_execute %callable(%arg) + : tensor<2x?xf32> -> tensor<2x?xf32> + func.return %0 : tensor<2x?xf32> +} + +// CHECK-LABEL: func @jit_execute +func.func @jit_execute(%ctx : !tf_framework.op_kernel_context, + %callable : !tf_framework.jit_callable, %arg : tensor<2x?xf32>) + -> tensor<2x?xf32> { + %0 = tf_framework.jit_execute ctx(%ctx) %callable(%arg) + : tensor<2x?xf32> -> tensor<2x?xf32> + func.return %0 : tensor<2x?xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/parallel_loops_to_sequential.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/parallel_loops_to_sequential.mlir new file mode 100644 index 0000000000000000000000000000000000000000..b8731308681a2f9be84e0cd29b035844e69fcb9f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/parallel_loops_to_sequential.mlir @@ -0,0 +1,17 @@ +// RUN: kernel-gen-opt %s --parallel-loops-to-sequential | FileCheck %s + +// CHECK-LABEL: @parallel_loop +func.func @parallel_loop(%lb_0 : index, %lb_1 : index, + %ub_0 : index, %ub_1 : index, + %s_0 : index, %s_1 : index, + %buf: memref) { + scf.parallel (%i0, %i1) = (%lb_0, %lb_1) to (%ub_0, %ub_1) step (%s_0, %s_1) { + %sum_elem = arith.addi %i0, %i1 : index + memref.store %sum_elem, %buf[%i0, %i1] : memref + } + func.return +} +// CHECK: scf.for [[I_0:%.*]] = [[LB_0:%.*]] to [[UB_0:%.*]] step [[S_0:%.*]] +// CHECK: scf.for [[I_1:%.*]] = [[LB_1:%.*]] to [[UB_1:%.*]] step [[S_1:%.*]] +// CHECK: [[SUM:%.*]] = arith.addi [[I_0]], [[I_1]] : index +// CHECK: memref.store [[SUM]], {{%.*}}{{\[}}[[I_0]], [[I_1]]] : memref diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/rewrite_tf_framework_assert.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/rewrite_tf_framework_assert.mlir new file mode 100644 index 0000000000000000000000000000000000000000..06f87f17f314ce53131ae95be602c9275a563c98 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/rewrite_tf_framework_assert.mlir @@ -0,0 +1,63 @@ +// RUN: kernel-gen-opt %s -rewrite-tf-framework-assert -split-input-file |\ +// RUN: FileCheck %s + +// CHECK-LABEL: func @assert( +// CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context +func.func @assert(%ctx: !tf_framework.op_kernel_context) + -> (memref<*xf32>, memref<*xi32>) attributes {tf_entry} { + %true = arith.constant true + tf_framework.assert %ctx, %true, INVALID_ARGUMENT, "the one and only" + %buf_f32 = tf_framework.alloc(%ctx) : memref<2xf32> + %unranked_f32 = memref.cast %buf_f32 : memref<2xf32> to memref<*xf32> + %buf_i32 = tf_framework.alloc(%ctx) : memref<3xi32> + %unranked_i32 = memref.cast %buf_i32 : memref<3xi32> to memref<*xi32> + func.return %unranked_f32, %unranked_i32 : memref<*xf32>, memref<*xi32> +} +// CHECK: [[TRUE:%.*]] = arith.constant true +// CHECK: cf.cond_br [[TRUE]], ^bb1, ^bb2 +// CHECK: ^bb1: +// CHECK: [[BUF_F32:%.*]] = tf_framework.alloc([[CTX]]) : memref<2xf32> +// CHECK: [[OUT_F32:%.*]] = memref.cast [[BUF_F32]] +// CHECK: [[BUF_I32:%.*]] = tf_framework.alloc([[CTX]]) : memref<3xi32> +// CHECK: [[OUT_I32:%.*]] = memref.cast [[BUF_I32]] +// CHECK: return [[OUT_F32]], [[OUT_I32]] : memref<*xf32>, memref<*xi32> +// CHECK: ^bb2: +// CHECK: tf_framework.report_error [[CTX]], INVALID_ARGUMENT, +// CHECK-SAME: "the one and only" +// CHECK: [[NULL_F32:%.*]] = tf_framework.null_memref : memref<*xf32> +// CHECK: [[NULL_I32:%.*]] = tf_framework.null_memref : memref<*xi32> +// CHECK: return [[NULL_F32]], [[NULL_I32]] : memref<*xf32>, memref<*xi32> + +// ----- + +// CHECK-LABEL: func @double_assert( +// CHECK-SAME: [[CTX:%.*]]: !tf_framework.op_kernel_context +func.func @double_assert(%ctx: !tf_framework.op_kernel_context) + -> memref<*xf32> attributes {tf_entry} { + %true = arith.constant true + %false = arith.constant false + tf_framework.assert %ctx, %true, INVALID_ARGUMENT, "first assertion" + tf_framework.assert %ctx, %false, INVALID_ARGUMENT, "second assertion" + %buf = tf_framework.alloc(%ctx) : memref<2xf32> + %unranked_buf = memref.cast %buf : memref<2xf32> to memref<*xf32> + func.return %unranked_buf : memref<*xf32> +} +// CHECK-DAG: [[TRUE:%.*]] = arith.constant true +// CHECK-DAG: [[FALSE:%.*]] = arith.constant false +// CHECK: cf.cond_br [[TRUE]], ^bb1, ^bb3 +// CHECK: ^bb1: +// CHECK: cf.cond_br [[FALSE]], ^bb2, ^bb4 +// CHECK: ^bb2: +// CHECK: [[BUF:%.*]] = tf_framework.alloc([[CTX]]) : memref<2xf32> +// CHECK: [[OUT:%.*]] = memref.cast [[BUF]] +// CHECK: return [[OUT]] : memref<*xf32> +// CHECK: ^bb3: +// CHECK: tf_framework.report_error [[CTX]], INVALID_ARGUMENT, +// CHECK-SAME: "first assertion" +// CHECK: [[NULL:%.*]] = tf_framework.null_memref : memref<*xf32> +// CHECK: return [[NULL]] : memref<*xf32> +// CHECK: ^bb4: +// CHECK: tf_framework.report_error [[CTX]], INVALID_ARGUMENT, +// CHECK-SAME: "second assertion" +// CHECK: [[NULL:%.*]] = tf_framework.null_memref : memref<*xf32> +// CHECK: return [[NULL]] : memref<*xf32> diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/shape_simplification.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/shape_simplification.mlir new file mode 100644 index 0000000000000000000000000000000000000000..940002eccc1159c4ba64a4da3a3be47c2a152f96 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/shape_simplification.mlir @@ -0,0 +1,143 @@ +// RUN: kernel-gen-opt -split-input-file -shape-simplification %s | FileCheck %s + +// Incompatible shapes. No folding. +// CHECK-LABEL: func @f +func.func @f() -> !shape.shape { + // CHECK: shape.broadcast + %0 = shape.const_shape [2] : !shape.shape + %1 = shape.const_shape [7] : !shape.shape + %2 = shape.broadcast %0, %1 : !shape.shape, !shape.shape -> !shape.shape + func.return %2 : !shape.shape +} + +// ----- + +// Broadcast of partially dynamic shapes yields a static shape. +// CHECK-LABEL: func @f +func.func @f(%arg0 : tensor<42x?x42x?xf32>, %arg1 : tensor<42x?x?xf32>) -> !shape.shape { + // CHECK: %[[CST:.*]] = shape.const_shape [42, 42, 42, 256] : !shape.shape + // CHECK: return %[[CST]] + %0 = shape.const_shape [256] : !shape.shape + %1 = shape.shape_of %arg0 : tensor<42x?x42x?xf32> -> !shape.shape + %2 = shape.shape_of %arg1 : tensor<42x?x?xf32> -> !shape.shape + %3 = shape.broadcast %0, %1, %2 : !shape.shape, !shape.shape, !shape.shape -> !shape.shape + func.return %3 : !shape.shape +} + +// ----- + +// Remove operands that don't contribute to the result. +// CHECK-LABEL: func @f +func.func @f(%arg0 : tensor, %arg1 : tensor<42x42xf32>) -> tensor { + // CHECK: %[[SHAPE0:.*]] = shape.shape_of %arg0 : tensor -> tensor + // CHECK: return %[[SHAPE0]] + %0 = shape.const_shape [42, 1] : tensor<2xindex> + %1 = shape.shape_of %arg0 : tensor -> tensor + %2 = shape.shape_of %arg1 : tensor<42x42xf32> -> tensor<2xindex> + %3 = shape.broadcast %0, %1, %2 : tensor<2xindex>, tensor, tensor<2xindex> -> tensor + func.return %3 : tensor +} + +// ----- + +// The constant shape needs to stay alive or the result will be smaller. +// CHECK-LABEL: func @f +func.func @f(%arg0 : tensor) -> !shape.shape { + // CHECK: shape.broadcast + %0 = shape.const_shape [1, 1] : !shape.shape + %1 = shape.shape_of %arg0 : tensor -> !shape.shape + %2 = shape.broadcast %0, %1 : !shape.shape, !shape.shape -> !shape.shape + func.return %2 : !shape.shape +} + +// ----- + +// [256] is the only contributor of that constant, keep it. +// CHECK-LABEL: func @f +func.func @f(%arg0 : tensor) -> !shape.shape { + // CHECK: shape.broadcast + %0 = shape.const_shape [256] : !shape.shape + %1 = shape.shape_of %arg0 : tensor -> !shape.shape + %2 = shape.broadcast %0, %1 : !shape.shape, !shape.shape -> !shape.shape + func.return %2 : !shape.shape +} + +// ----- + +// CHECK-LABEL: func @static_non1_succeeds +// CHECK-NEXT: %[[C2:.*]] = arith.constant 2 +// CHECK-NEXT: return %[[C2]] +func.func @static_non1_succeeds(%arg0 : tensor, %arg1 : tensor, + %arg2: tensor) -> index { + %c1 = arith.constant 1 : index + %1 = shape.shape_of %arg0 : tensor -> tensor<2xindex> + %2 = shape.shape_of %arg1 : tensor -> tensor<2xindex> + %3 = shape.shape_of %arg2 : tensor -> tensor<2xindex> + %4 = shape.broadcast %1, %2, %3 : tensor<2xindex>, tensor<2xindex>, + tensor<2xindex> -> tensor<2xindex> + %result = tensor.extract %4[%c1] : tensor<2xindex> + func.return %result : index +} + +// ----- + +// CHECK-LABEL: func @all_static_1s_succeeds +// CHECK-NEXT: %[[C1:.*]] = arith.constant 1 +// CHECK-NEXT: return %[[C1]] +func.func @all_static_1s_succeeds(%arg0 : tensor, %arg1 : tensor) + -> index { + %c1 = arith.constant 1 : index + %1 = shape.shape_of %arg0 : tensor -> tensor<2xindex> + %2 = shape.shape_of %arg1 : tensor -> tensor<2xindex> + %3 = shape.broadcast %1, %2 : tensor<2xindex>, tensor<2xindex> + -> tensor<2xindex> + %result = tensor.extract %3[%c1] : tensor<2xindex> + func.return %result : index +} + +// ----- + +// CHECK-LABEL: func @single_non_static_1_succeeds +// CHECK-SAME: %[[ARG0:.*]]: tensor +// CHECK: %[[C1:.*]] = arith.constant 1 +// CHECK: %[[DIM:.*]] = tensor.dim %[[ARG0]], %[[C1]] +// CHECK: return %[[DIM]] +func.func @single_non_static_1_succeeds(%arg0 : tensor, + %arg1 : tensor) -> index { + %c0 = arith.constant 1 : index + %1 = shape.shape_of %arg0 : tensor -> tensor<2xindex> + %2 = shape.shape_of %arg1 : tensor -> tensor<2xindex> + %3 = shape.broadcast %1, %2 : tensor<2xindex>, tensor<2xindex> + -> tensor<2xindex> + %result = tensor.extract %3[%c0] : tensor<2xindex> + func.return %result : index +} + +// ----- + +// CHECK-LABEL: func @multiple_non_static_1_fails +// CHECK-NEXT: constant 0 +// CHECK-NEXT: shape.shape_of +// CHECK-NEXT: shape.shape_of +// CHECK-NEXT: shape.broadcast +// CHECK-NEXT: %[[RESULT:.*]] = tensor.extract +// CHECK-NEXT: return %[[RESULT]] +func.func @multiple_non_static_1_fails(%arg0 : tensor, + %arg1 : tensor) -> index { + %c0 = arith.constant 0 : index + %1 = shape.shape_of %arg0 : tensor -> tensor<2xindex> + %2 = shape.shape_of %arg1 : tensor -> tensor<2xindex> + %3 = shape.broadcast %1, %2 : tensor<2xindex>, tensor<2xindex> + -> tensor<2xindex> + %result = tensor.extract %3[%c0] : tensor<2xindex> + func.return %result : index +} + +// ----- + +// CHECK-LABEL: func @extract_no_crash +// CHECK-NEXT: tensor.extract +func.func @extract_no_crash(%arg0 : tensor) -> index { + %result = tensor.extract %arg0[] : tensor + func.return %result : index +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_abi_knowledge.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_abi_knowledge.mlir new file mode 100644 index 0000000000000000000000000000000000000000..531c5855e7b3bee40182fa63bd001a0c153d2bf3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_abi_knowledge.mlir @@ -0,0 +1,355 @@ +// RUN: kernel-gen-opt %s -allow-unregistered-dialect -propagate-tf-abi-knowledge-to-kernels -split-input-file | FileCheck %s --check-prefixes=CHECK,ABI +// RUN: kernel-gen-opt %s -allow-unregistered-dialect -propagate-shape-knowledge-to-kernels -split-input-file | FileCheck %s --check-prefixes=CHECK,SHAPE + +// The input is taken from what is actually used in kernel generator lowering +// for unary operations. + +// CHECK-LABEL: module attributes {gpu.container_module} +module attributes {gpu.container_module} { + // CHECK-LABEL: func @abs + func.func @abs(%ctx: !tf_framework.op_kernel_context, %arg0: memref<*xf32>, %size: index) + attributes {tf_entry} { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %13 = memref.alloca() : memref<1xindex> + memref.store %size, %13[%c0] : memref<1xindex> + %14 = memref.reshape %arg0(%13) : (memref<*xf32>, memref<1xindex>) -> memref + %15 = memref.dim %14, %c0 : memref + %16 = tf_framework.alloc(%ctx, %15) : memref + gpu.launch_func @abs_kernel::@abs_kernel + blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) + args(%14 : memref, %16 : memref) + func.return + } + + // CHECK-LABEL: gpu.module @abs_kernel + gpu.module @abs_kernel { + // CHECK-LABEL: llvm.func @abs_kernel + // ABI-SAME: %[[ARG0:.*]]: !llvm.ptr, %[[ARG1:.*]]: !llvm.ptr {llvm.align = 16 : index}, + // ABI-SAME: %[[ARG2:.*]]: i64, %[[ARG3:.*]]: i64, %[[ARG4:.*]]: i64, %[[ARG5:.*]]: !llvm.ptr, %[[ARG6:.*]]: !llvm.ptr {llvm.align = 16 : index, llvm.noalias}, + // ABI-SAME: %[[ARG7:.*]]: i64, %[[ARG8:.*]]: i64, %[[ARG9:.*]]: i64 + // SHAPE-SAME: %[[ARG0:.*]]: !llvm.ptr, %[[ARG1:.*]]: !llvm.ptr, %[[ARG2:.*]]: i64, %[[ARG3:.*]]: i64, %[[ARG4:.*]]: i64, %[[ARG5:.*]]: !llvm.ptr, %[[ARG6:.*]]: !llvm.ptr, %[[ARG7:.*]]: i64, %[[ARG8:.*]]: i64, %[[ARG9:.*]]: i64 + llvm.func @abs_kernel(%arg0: !llvm.ptr, %arg1: !llvm.ptr, %arg2: i64, %arg3: i64, %arg4: i64, %arg5: !llvm.ptr, %arg6: !llvm.ptr, %arg7: i64, %arg8: i64, %arg9: i64) attributes {gpu.kernel} { + // ABI: %[[ZERO:.*]] = llvm.mlir.constant(0 : index) + // ABI: %[[ONE:.*]] = llvm.mlir.constant(1 : index) + // CHECK: llvm.mlir.undef + %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ARG1]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG0]] + %1 = llvm.insertvalue %arg0, %0[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // CHECK-NEXT: llvm.insertvalue %[[ARG1]] + %2 = llvm.insertvalue %arg1, %1[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ZERO]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG2]] + %3 = llvm.insertvalue %arg2, %2[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // CHECK-NEXT: llvm.insertvalue %[[ARG3]] + %4 = llvm.insertvalue %arg3, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ONE]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG4]] + %5 = llvm.insertvalue %arg4, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // CHECK-NEXT: llvm.mlir.undef + %6 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ARG6]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG5]] + %7 = llvm.insertvalue %arg5, %6[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // CHECK-NEXT: llvm.insertvalue %[[ARG6]] + %8 = llvm.insertvalue %arg6, %7[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ZERO]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG7]] + %9 = llvm.insertvalue %arg7, %8[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ARG8]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG3]] + %10 = llvm.insertvalue %arg8, %9[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[ONE]] + // SHAPE-NEXT: llvm.insertvalue %[[ARG4]] + %11 = llvm.insertvalue %arg9, %10[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + llvm.return + // CHECK-NEXT: llvm.return + } + } +} + +// ----- + +// Binary op without broadcasting (same shape). + +// CHECK-LABEL: module attributes {gpu.container_module} +module attributes {gpu.container_module} { + // CHECK-LABEL: func @add_same_shape + func.func @add_same_shape(%arg0: !tf_framework.op_kernel_context, %arg1: memref<*xf32>, %arg2: memref<*xf32>, %size: index) + attributes {tf_entry} { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %82 = memref.reinterpret_cast %arg1 to offset: [0], sizes: [%size], strides: [%c1]: memref<*xf32> to memref> + %83 = memref.reinterpret_cast %arg2 to offset: [0], sizes: [%size], strides: [%c1]: memref<*xf32> to memref> + %84 = tf_framework.alloc(%arg0, %size) : memref + gpu.launch_func @AddV2_kernel_1::@AddV2_kernel blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) args(%size : index, %82 : memref>, %83 : memref>, %84 : memref) + func.return + } + + // CHECK-LABEL: gpu.module @AddV2_kernel_1 + gpu.module @AddV2_kernel_1 { + // CHECK-LABEL: llvm.func @AddV2_kernel + // ABI-SAME: {llvm.align = 16 : index} + // ABI-SAME: {llvm.align = 16 : index} + // ABI-SAME: {llvm.align = 16 : index, llvm.noalias} + llvm.func @AddV2_kernel(%arg0: i64, %arg1: !llvm.ptr, %arg2: !llvm.ptr, %arg3: i64, %arg4: i64, %arg5: i64, %arg6: !llvm.ptr, %arg7: !llvm.ptr, %arg8: i64, %arg9: i64, %arg10: i64, %arg11: !llvm.ptr, %arg12: !llvm.ptr, %arg13: i64, %arg14: i64, %arg15: i64) attributes {gpu.kernel} { + // ABI: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64 + // ABI: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64 + %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %1 = llvm.insertvalue %arg1, %0[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %2 = llvm.insertvalue %arg2, %1[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %3 = llvm.insertvalue %arg3, %2[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %4 = llvm.insertvalue %arg4, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %5 = llvm.insertvalue %arg5, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP:.*]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[STR:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %6 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %7 = llvm.insertvalue %arg6, %6[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %8 = llvm.insertvalue %arg7, %7[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %9 = llvm.insertvalue %arg8, %8[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %10 = llvm.insertvalue %arg9, %9[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %11 = llvm.insertvalue %arg10, %10[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR1:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR1]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %12 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %13 = llvm.insertvalue %arg11, %12[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %14 = llvm.insertvalue %arg12, %13[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %15 = llvm.insertvalue %arg13, %14[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %16 = llvm.insertvalue %arg14, %15[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %17 = llvm.insertvalue %arg15, %16[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR2:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR2]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[STR1:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + llvm.return + // CHECK-NEXT: llvm.return + } + } +} + +// ----- + +// Test binary op with broadcasting - 2d case. + +// CHECK-LABEL: module attributes {gpu.container_module} +module attributes {gpu.container_module} { + // CHECK-LABEL: func @add_same_shape + func.func @add_same_shape(%arg0: !tf_framework.op_kernel_context, %arg1: memref<*xf32>, %arg2: memref<*xf32>, %size0: index, %size1: index, %stride0: index, %stride1: index) + attributes {tf_entry} { + %c1 = arith.constant 1 : index + %216 = memref.reinterpret_cast %arg1 to offset: [0], sizes: [%size1, %size0], strides: [%size0, %c1]: memref<*xf32> to memref> + %241 = memref.reinterpret_cast %arg2 to offset: [0], sizes: [%size1, %size0], strides: [%size0, %c1]: memref<*xf32> to memref> + %304 = memref.reinterpret_cast %216 to offset: [0], sizes: [%size1, %size0], strides: [%stride1, %stride0]: memref> to memref (d0 * s0 + d1 * s1)>> + %309 = memref.reinterpret_cast %241 to offset: [0], sizes: [%size1, %size0], strides: [%stride0, %stride1]: memref> to memref (d0 * s0 + d1 * s1)>> + %310 = tf_framework.alloc(%arg0, %size1, %size0) : memref + gpu.launch_func @AddV2_kernel_3::@AddV2_kernel blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) args(%size0 : index, %size1 : index, %310 : memref, %304 : memref (d0 * s0 + d1 * s1)>>, %309 : memref (d0 * s0 + d1 * s1)>>) + func.return + } + + // CHECK-LABEL: gpu.module @AddV2_kernel_3 + gpu.module @AddV2_kernel_3 { + // CHECK-LABEL: llvm.func @AddV2_kernel + // ABI-SAME: {llvm.align = 16 : index, llvm.noalias} + // ABI-SAME: {llvm.align = 16 : index} + // ABI-SAME: {llvm.align = 16 : index} + llvm.func @AddV2_kernel(%arg0: i64, %arg1: i64, %arg2: !llvm.ptr, %arg3: !llvm.ptr {llvm.align = 16 : index, llvm.noalias}, %arg4: i64, %arg5: i64, %arg6: i64, %arg7: i64, %arg8: i64, %arg9: !llvm.ptr, %arg10: !llvm.ptr {llvm.align = 16 : index}, %arg11: i64, %arg12: i64, %arg13: i64, %arg14: i64, %arg15: i64, %arg16: !llvm.ptr, %arg17: !llvm.ptr {llvm.align = 16 : index}, %arg18: i64, %arg19: i64, %arg20: i64, %arg21: i64, %arg22: i64) attributes {gpu.kernel} { + // ABI: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64 + // ABI: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64 + %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %1 = llvm.insertvalue %arg2, %0[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %2 = llvm.insertvalue %arg3, %1[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %3 = llvm.insertvalue %arg4, %2[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %4 = llvm.insertvalue %arg5, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %5 = llvm.insertvalue %arg7, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %6 = llvm.insertvalue %arg6, %5[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %7 = llvm.insertvalue %arg8, %6[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP0:.*]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[STR0:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP1:.*]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[STR1:.*]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %8 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %9 = llvm.insertvalue %arg9, %8[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %10 = llvm.insertvalue %arg10, %9[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %11 = llvm.insertvalue %arg11, %10[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %12 = llvm.insertvalue %arg12, %11[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %13 = llvm.insertvalue %arg14, %12[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %14 = llvm.insertvalue %arg13, %13[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %15 = llvm.insertvalue %arg15, %14[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NOT: llvm.insertvalue %[[C1]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP0]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR0]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE: llvm.insertvalue %[[SHP1]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %16 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %17 = llvm.insertvalue %arg16, %16[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %18 = llvm.insertvalue %arg17, %17[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %19 = llvm.insertvalue %arg18, %18[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %20 = llvm.insertvalue %arg19, %19[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %21 = llvm.insertvalue %arg21, %20[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %22 = llvm.insertvalue %arg20, %21[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + %23 = llvm.insertvalue %arg22, %22[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // ABI-NOT: llvm.insertvalue %[[C1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP0]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR0]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE: llvm.insertvalue %[[SHP1]], %{{.*}}[3, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR1]], %{{.*}}[4, 1] : !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> + llvm.return + // CHECK: llvm.return + } + } +} + +// ----- + + +// Test binary op with broadcasting a scalar. + +#map0 = affine_map<(d0)[s0] -> (d0 * s0)> + +// CHECK-LABEL: module attributes {gpu.container_module} +module attributes {gpu.container_module} { + // CHECK-LABEL: func @add_one_scalar + func.func @add_one_scalar(%arg0: !tf_framework.op_kernel_context, %arg1: memref<*xf32>, %arg2: memref<*xf32>, %size: index) + attributes {tf_entry} { + %c0 = arith.constant 0 : index + %c1 = arith.constant 1 : index + %13 = memref.cast %arg1 : memref<*xf32> to memref + %26 = memref.reinterpret_cast %arg2 to offset: [0], sizes: [%size], strides: [%c1]: memref<*xf32> to memref> + %27 = memref.reinterpret_cast %13 to offset: [0], sizes: [%size], strides: [%c0]: memref to memref + %28 = memref.reinterpret_cast %26 to offset: [0], sizes: [%size], strides: [%c1]: memref> to memref + %29 = tf_framework.alloc(%arg0, %size) : memref + gpu.launch_func @AddV2_kernel::@AddV2_kernel blocks in (%c1, %c1, %c1) threads in (%c1, %c1, %c1) args(%size : index, %29 : memref, %27 : memref, %28 : memref) + func.return + } + // CHECK-LABEL: gpu.module @AddV2_kernel + gpu.module @AddV2_kernel { + // CHECK-LABEL: llvm.func @AddV2_kernel + // ABI-SAME: {llvm.align = 16 : index, llvm.noalias} + // ABI-SAME: {llvm.align = 16 : index} + // ABI-SAME: {llvm.align = 16 : index} + llvm.func @AddV2_kernel(%arg0: i64, %arg1: !llvm.ptr, %arg2: !llvm.ptr, %arg3: i64, %arg4: i64, %arg5: i64, %arg6: !llvm.ptr, %arg7: !llvm.ptr, %arg8: i64, %arg9: i64, %arg10: i64, %arg11: !llvm.ptr, %arg12: !llvm.ptr, %arg13: i64, %arg14: i64, %arg15: i64) attributes {gpu.kernel} { + // ABI: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64 + // ABI: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64 + %0 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %1 = llvm.insertvalue %arg1, %0[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %2 = llvm.insertvalue %arg2, %1[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %3 = llvm.insertvalue %arg3, %2[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %4 = llvm.insertvalue %arg4, %3[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %5 = llvm.insertvalue %arg5, %4[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR0]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP:.*]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[STR:.*]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %6 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %7 = llvm.insertvalue %arg6, %6[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %8 = llvm.insertvalue %arg7, %7[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %9 = llvm.insertvalue %arg8, %8[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %10 = llvm.insertvalue %arg9, %9[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %11 = llvm.insertvalue %arg10, %10[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR1:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR1]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %12 = llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %13 = llvm.insertvalue %arg11, %12[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %14 = llvm.insertvalue %arg12, %13[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %15 = llvm.insertvalue %arg13, %14[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %16 = llvm.insertvalue %arg14, %15[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + %17 = llvm.insertvalue %arg15, %16[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR2:.*]], %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[PTR2]], %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C0]], %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // ABI-NEXT: llvm.insertvalue %[[C1]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE: llvm.mlir.undef : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[1] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %{{.*}}, %{{.*}}[2] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NEXT: llvm.insertvalue %[[SHP]], %{{.*}}[3, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + // SHAPE-NOT: llvm.insertvalue %[[STR]], %{{.*}}[4, 0] : !llvm.struct<(ptr, ptr, i64, array<1 x i64>, array<1 x i64>)> + llvm.return + // CHECK: llvm.return + } + } +} + diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_framework_legalize_to_llvm.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_framework_legalize_to_llvm.mlir new file mode 100644 index 0000000000000000000000000000000000000000..7aaeafef590c61c30fb43d051022693d4339670d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_framework_legalize_to_llvm.mlir @@ -0,0 +1,249 @@ +// RUN: kernel-gen-opt %s -tf-kernel-to-llvm -reconcile-unrealized-casts -split-input-file | FileCheck %s + +// CHECK: llvm.func @_mlir_ciface_tf_alloc +// CHECK-SAME: (!llvm.ptr, i64, i64, i32, i32, !llvm.ptr) -> !llvm.ptr + +// CHECK-LABEL: llvm.func @alloc( +// CHECK-SAME: [[TF_CTX:%.*]]: !llvm.ptr, +// CHECK-SAME: [[SIZE_0:%.*]]: i64, +// CHECK-SAME: [[SIZE_2:%.*]]: i64) -> [[DESC_TY:!.*]] { +func.func @alloc(%ctx: !tf_framework.op_kernel_context, + %size_0 : index , %size_2 : index) -> memref { + %buf = tf_framework.alloc(%ctx, %size_0, %size_2) : memref + func.return %buf : memref +} +// Compute number of elements. +// CHECK: [[SIZE_1A:%.*]] = llvm.mlir.constant(10 : index) : i64 +// CHECK: [[SIZE_1B:%.*]] = llvm.mlir.constant(10 : index) : i64 +// CHECK: [[NUM_ELEM_0:%.*]] = llvm.mul [[SIZE_0]], [[SIZE_1B]] : i64 +// CHECK: [[NUM_ELEMS:%.*]] = llvm.mul [[NUM_ELEM_0]], [[SIZE_2]] : i64 + +// Compute the size of an individual element. +// CHECK: [[NULL:%.*]] = llvm.mlir.zero : !llvm.ptr +// CHECK: [[GEP:%.*]] = llvm.getelementptr [[NULL]]{{\[}}1] +// CHECK-SAME: (!llvm.ptr) -> !llvm.ptr, f32 +// CHECK: [[SIZE_OF_FLOAT:%.*]] = llvm.ptrtoint [[GEP]] +// CHECK-SAME: !llvm.ptr to i64 + +// Compute output index (-1) and candidate indices (0, NULL). +// CHECK: [[OUTPUT_INDEX:%.*]] = llvm.mlir.constant(-1 : i32) : i32 +// CHECK-NEXT: [[NUM_CANDIDATES:%.*]] = llvm.mlir.constant(0 : i32) : i32 +// CHECK-NEXT: [[CANDIDATES_PTR:%.*]] = llvm.mlir.zero : !llvm.ptr + +// Allocate memory. +// CHECK: [[BYTES_PTR:%.*]] = llvm.call @{{.*}}([[TF_CTX]], [[NUM_ELEMS]], +// CHECK-SAME: [[SIZE_OF_FLOAT]], [[OUTPUT_INDEX]], [[NUM_CANDIDATES]], +// CHECK-SAME: [[CANDIDATES_PTR]]) + +// Build memref descriptor. +// CHECK: [[DESC_0:%.*]] = llvm.mlir.poison : [[DESC_TY]] + +// Set pointers and offset. +// CHECK: [[DESC_1:%.*]] = llvm.insertvalue [[BYTES_PTR]], [[DESC_0]][0] +// CHECK: [[DESC_2:%.*]] = llvm.insertvalue [[BYTES_PTR]], [[DESC_1]][1] +// CHECK: [[C0:%.*]] = llvm.mlir.constant(0 : index) : i64 +// CHECK: [[DESC_3:%.*]] = llvm.insertvalue [[C0]], [[DESC_2]][2] : [[DESC_TY]] + +// Set sizes and strides. +// CHECK: [[STRIDE_2:%.*]] = llvm.mlir.constant(1 : index) : i64 +// CHECK: [[DESC_4:%.*]] = llvm.insertvalue [[SIZE_2]], [[DESC_3]][3, 2] +// CHECK: [[DESC_5:%.*]] = llvm.insertvalue [[STRIDE_2]], [[DESC_4]][4, 2] +// CHECK: [[STRIDE_1:%.*]] = llvm.mul [[STRIDE_2]], [[SIZE_2]] : i64 +// CHECK: [[DESC_6:%.*]] = llvm.insertvalue [[SIZE_1A]], [[DESC_5]][3, 1] +// CHECK: [[DESC_7:%.*]] = llvm.insertvalue [[STRIDE_1]], [[DESC_6]][4, 1] +// CHECK: [[STRIDE_0:%.*]] = llvm.mul [[STRIDE_1]], [[SIZE_1A]] : i64 +// CHECK: [[DESC_8:%.*]] = llvm.insertvalue [[SIZE_0]], [[DESC_7]][3, 0] +// CHECK: [[DESC_9:%.*]] = llvm.insertvalue [[STRIDE_0]], [[DESC_8]][4, 0] +// CHECK: llvm.return [[DESC_9]] : [[DESC_TY]] + +// ----- + +// CHECK: llvm.func @_mlir_ciface_tf_dealloc(!llvm.ptr, !llvm.ptr) + +// CHECK-LABEL: llvm.func @dealloc( +// CHECK-SAME: [[TF_CTX:%[a-z0-9]*]]: !llvm.ptr +func.func @dealloc(%ctx: !tf_framework.op_kernel_context, + %memref : memref) { + tf_framework.dealloc(%ctx, %memref) : memref + func.return +} +// Extract allocated ptr from the memref descriptor. +// CHECK: %{{.*}} = llvm.mlir.poison : [[DESC_TY:!.*]] +// CHECK: [[FLOAT_PTR:%.*]] = llvm.extractvalue %{{.*}}[0] : [[DESC_TY]] + +// Deallocate. +// CHECK: llvm.call @_mlir_ciface_tf_dealloc( +// CHECK-SAME: [[TF_CTX]], [[FLOAT_PTR]]) : (!llvm.ptr, !llvm.ptr) -> () + +// ----- + +// CHECK-LABEL: llvm.func @_mlir_ciface_tf_report_error(!llvm.ptr, i32, !llvm.ptr) +// CHECK: llvm.mlir.global internal constant [[MSG_CONST:@error_message_[0-9]+]]("Everything is awesome\00") + +func.func @report_error(%ctx: !tf_framework.op_kernel_context) { + tf_framework.report_error %ctx, "INVALID_ARGUMENT", "Everything is awesome" loc(unknown) + func.return +} +// CHECK: llvm.func @report_error([[CTX:%.*]]: !llvm.ptr) +// CHECK-NEXT: [[ADDR:%.*]] = llvm.mlir.addressof [[MSG_CONST]] +// CHECK: [[MSG:%.*]] = llvm.getelementptr [[ADDR]] +// CHECK: [[CODE:%.*]] = llvm.mlir.constant({{.*}}) : i32 +// CHECK: llvm.call @{{.*}}_tf_report_error([[CTX]], [[CODE]], [[MSG]]) + +// ----- + +// CHECK-LABEL: llvm.func @unranked_null_memref() +func.func @unranked_null_memref() { + %null = tf_framework.null_memref : memref<*xf32> + func.return +} +// CHECK: [[C0:%.*]] = llvm.mlir.constant(0 : index) : i64 +// CHECK: [[DESC_0:%.*]] = llvm.mlir.poison : !llvm.struct<(i64, ptr)> +// CHECK: [[DESC_1:%.*]] = llvm.insertvalue [[C0]], [[DESC_0]][0] +// CHECK: [[PTR:%.*]] = llvm.alloca {{.*}} x i8 +// CHECK: [[DESC_2:%.*]] = llvm.insertvalue [[PTR]], [[DESC_1]][1] + +// ----- + +// CHECK-LABEL: llvm.func @ranked_null_memref() +func.func @ranked_null_memref() { + %null = tf_framework.null_memref : memref<2x?xf32> + func.return +} +// CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64 +// CHECK-NEXT: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64 +// CHECK-NEXT: %[[C2:.*]] = llvm.mlir.constant(2 : index) : i64 +// CHECK-NEXT: %[[C1_:.*]] = llvm.mlir.constant(1 : index) : i64 + +// CHECK: llvm.mlir.zero +// CHECK: %[[NULL:.*]] = llvm.mlir.zero : !llvm.ptr +// CHECK-NEXT: %[[DESC_0:.*]] = llvm.mlir.poison : +// CHECK-SAME: !llvm.struct<(ptr, ptr, i64, array<2 x i64>, array<2 x i64>)> +// CHECK-NEXT: %[[DESC_1:.*]] = llvm.insertvalue %[[NULL]], %[[DESC_0]][0] +// CHECK-NEXT: %[[DESC_2:.*]] = llvm.insertvalue %[[NULL]], %[[DESC_1]][1] +// CHECK-NEXT: %[[DESC_3:.*]] = llvm.insertvalue %[[C0]], %[[DESC_2]][2] +// CHECK-NEXT: %[[DESC_4:.*]] = llvm.insertvalue %[[C2]], %[[DESC_3]][3, 0] +// CHECK-NEXT: %[[DESC_5:.*]] = llvm.insertvalue %[[C1]], %[[DESC_4]][4, 0] +// CHECK-NEXT: %[[DESC_6:.*]] = llvm.insertvalue %[[C1]], %[[DESC_5]][3, 1] +// CHECK-NEXT: %[[DESC_7:.*]] = llvm.insertvalue %[[C1_]], %[[DESC_6]][4, 1] + +// ----- + +// CHECK-LABEL: llvm.func @is_valid_memref +func.func @is_valid_memref(%buf: memref) -> i1 { + %pred = tf_framework.is_valid_memref(%buf) : memref -> i1 + func.return %pred : i1 +} +// CHECK: %[[MEMREF:.*]] = llvm.insertvalue %{{.*}}, %{{.*}}[4, 0] + +// CHECK-NEXT: %[[IS_EMPTY:.*]] = llvm.mlir.constant(false) : i1 +// CHECK-NEXT: %[[C0:.*]] = llvm.mlir.constant(0 : index) : i64 +// CHECK-NEXT: %[[SIZE:.*]] = llvm.extractvalue %[[MEMREF]][3, 0] +// CHECK-NEXT: %[[IS_ZERO:.*]] = llvm.icmp "eq" %[[SIZE]], %[[C0]] : i64 +// CHECK-NEXT: %[[IS_EMPTY_:.*]] = llvm.or %[[IS_EMPTY]], %[[IS_ZERO]] : i1 + +// CHECK-NEXT: %[[PTR_F32:.*]] = llvm.extractvalue %[[MEMREF]][0] +// CHECK-NEXT: %[[NULL_PTR:.*]] = llvm.mlir.zero : !llvm.ptr +// CHECK-NEXT: %[[NOT_NULL:.*]] = llvm.icmp "ne" %[[PTR_F32]], %[[NULL_PTR]] + +// CHECK-NEXT: %[[PRED:.*]] = llvm.or %[[NOT_NULL]], %[[IS_EMPTY_]] : i1 +// CHECK-NEXT: llvm.return %[[PRED]] + +// ----- + +// CHECK-LABEL: llvm.func @_mlir_ciface_tf_jit_compile(!llvm.ptr, !llvm.ptr, i64, !llvm.ptr, i64, !llvm.ptr, i1, i1, i1) -> !llvm.ptr +// CHECK: llvm.mlir.global internal constant @[[CODE:jit_module_code_[0-9]+]]("placeholder\00") + +// CHECK: @jit_compile_from_str(%[[CTX:.*]]: !llvm.ptr) +func.func @jit_compile_from_str(%ctx: !tf_framework.op_kernel_context) + -> !tf_framework.jit_callable { + // CHECK: %[[ADDR:.*]] = llvm.mlir.addressof @[[CODE]] + // CHECK: %[[CODE_PTR:.*]] = llvm.getelementptr %[[ADDR]][0, 0] + + // Create stack-allocated array for the tile sizes. + // CHECK: %[[NUM_TILE_SIZES:.*]] = llvm.mlir.constant(3 : i64) + // CHECK: %[[TILE_SIZES:.*]] = llvm.alloca %[[NUM_TILE_SIZES]] x i64 + // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : i64) + // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[TILE_SIZES]][%[[C0]]] + // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : i64) + // CHECK: llvm.store %[[C1]], %[[PTR]] + // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : i64) + // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[TILE_SIZES]][%[[C1]]] + // CHECK: %[[C2:.*]] = llvm.mlir.constant(2 : i64) + // CHECK: llvm.store %[[C2]], %[[PTR]] + // CHECK: %[[C2:.*]] = llvm.mlir.constant(2 : i64) + // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[TILE_SIZES]][%[[C2]]] + // CHECK: %[[C3:.*]] = llvm.mlir.constant(3 : i64) + // CHECK: llvm.store %[[C3]], %[[PTR]] + + // Create stack-allocated array for the unroll factors. + // CHECK: %[[NUM_UNROLL_FACTORS:.*]] = llvm.mlir.constant(1 : i64) : i64 + // CHECK: %[[UNROLL_FACTORS:.*]] = llvm.alloca %[[NUM_UNROLL_FACTORS]] x i64 + // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : i64) + // CHECK: %[[PTR:.*]] = llvm.getelementptr %[[UNROLL_FACTORS]][%[[C0]]] + // CHECK: %[[C4:.*]] = llvm.mlir.constant(4 : i64) + // CHECK: llvm.store %[[C4]], %[[PTR]] + + // CHECK-DAG: %[[ENABLE_FTZ:.*]] = llvm.mlir.constant(false) + // CHECK-DAG: %[[CPU_CODEGEN:.*]] = llvm.mlir.constant(false) + // CHECK: %[[RES:.*]] = llvm.call @_mlir_ciface_tf_jit_compile + // CHECK-SAME: %[[CTX]], %[[CODE_PTR]], + // CHECK-SAME: %[[NUM_TILE_SIZES]], %[[TILE_SIZES]], + // CHECK-SAME: %[[NUM_UNROLL_FACTORS]], %[[UNROLL_FACTORS]], + // CHECK-SAME: %[[ENABLE_FTZ]], %[[CPU_CODEGEN]] + // CHECK: llvm.return %[[RES]] + %0 = tf_framework.jit_compile_from_str %ctx, "placeholder" { + tileSizes = [1, 2, 3], unrollFactors = [4], + enableFtz = false, index64Bit = false, cpuCodegen = false } + func.return %0 : !tf_framework.jit_callable +} + +// ----- + +// CHECK-LABEL: llvm.func @_mlir_ciface_tf_jit_execute(!llvm.ptr, !llvm.ptr, !llvm.ptr, i64, !llvm.ptr) + +// CHECK: @jit_execute +// CHECK-SAME: (%[[CTX:.*]]: !llvm.ptr, %[[CALLABLE:.*]]: !llvm.ptr, %[[RANK:.*]]: i64, %[[ARG_DESCR:.*]]: !llvm.ptr) +func.func @jit_execute(%ctx: !tf_framework.op_kernel_context, + %callable : !tf_framework.jit_callable, %arg : memref<*xf32>) + -> memref<*xf32> { + // CHECK: %[[T0:.*]] = llvm.mlir.poison + // CHECK: %[[T1:.*]] = llvm.insertvalue %[[RANK]], %[[T0]][0] + // CHECK: %[[ARG:.*]] = llvm.insertvalue %[[ARG_DESCR]], %[[T1]][1] + // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : i64) + // CHECK: %[[RESULT_PTR:.*]] = llvm.alloca %[[C1]] x !llvm.struct<(i64, ptr)> + + // Copy argument(s) to stack-allocated buffer. + // CHECK: %[[NUM_ARGS:.*]] = llvm.mlir.constant(1 : i64) + // CHECK: %[[ARGS_PTR:.*]] = llvm.alloca %[[NUM_ARGS]] x !llvm.struct<(i64, ptr)> + // CHECK: %[[C0:.*]] = llvm.mlir.constant(0 : i64) + // CHECK: %[[ARGS0_PTR:.*]] = llvm.getelementptr %[[ARGS_PTR]][%[[C0]]] + // CHECK: llvm.store %[[ARG]], %[[ARGS0_PTR]] + // CHECK: llvm.call @_mlir_ciface_tf_jit_execute(%[[CTX]], %[[CALLABLE]], %[[RESULT_PTR]], %[[NUM_ARGS]], %[[ARGS_PTR]]) + // CHECK: %[[RESULT:.*]] = llvm.load %[[RESULT_PTR]] + + // Copy unranked memref descriptor to stack-allocated memory. + // ... + // CHECK: %[[STACK_RESULT_DESCR:.*]] = llvm.alloca %[[RESULT_DESCR_SIZE:[0-9]*]] x i8 + // CHECK: %[[RESULT_DESCR:.*]] = llvm.extractvalue %[[RESULT]][1] + // CHECK: "llvm.intr.memcpy"(%[[STACK_RESULT_DESCR]], %[[RESULT_DESCR]], %[[RESULT_DESCR_SIZE]]) <{isVolatile = false}> + // CHECK: llvm.call @free(%[[RESULT_DESCR]]) + // CHECK: %[[T0:.*]] = llvm.mlir.poison + // CHECK: %[[RANK:.*]] = llvm.extractvalue %[[RESULT]][0] + // CHECK: %[[T1:.*]] = llvm.insertvalue %[[RANK]], %[[T0]][0] + // CHECK: %[[RESULT:.*]] = llvm.insertvalue %[[STACK_RESULT_DESCR]], %[[T1]][1] + + // Copy unranked memref descriptor to heap-allocated memory for return. + // ... + // CHECK: %[[HEAP_RESULT_DESCR:.*]] = llvm.call @malloc(%[[RESULT_DESCR_SIZE:[0-9]*]]) + // CHECK: %[[STACK_RESULT_DESCR:.*]] = llvm.extractvalue %[[RESULT]][1] + // CHECK: "llvm.intr.memcpy"(%[[HEAP_RESULT_DESCR]], %[[STACK_RESULT_DESCR]], %[[RESULT_DESCR_SIZE]]) <{isVolatile = false}> + // CHECK: %[[T0:.*]] = llvm.mlir.poison + // CHECK: %[[RANK:.*]] = llvm.extractvalue %[[RESULT]][0] + // CHECK: %[[T1:.*]] = llvm.insertvalue %[[RANK]], %[[T0]][0] + // CHECK: %[[RESULT:.*]] = llvm.insertvalue %[[HEAP_RESULT_DESCR]], %[[T1]][1] + // CHECK: llvm.return %[[RESULT]] + %0 = tf_framework.jit_execute ctx(%ctx) %callable(%arg) + : memref<*xf32> -> memref<*xf32> + func.return %0 : memref<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_kernel_gpu_launch_to_llvm.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_kernel_gpu_launch_to_llvm.mlir new file mode 100644 index 0000000000000000000000000000000000000000..a0c851e8059d048ab967c16f4c4c04c1425062a0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tests/tf_kernel_gpu_launch_to_llvm.mlir @@ -0,0 +1,36 @@ +// RUN: kernel-gen-opt %s -tf-kernel-to-llvm -reconcile-unrealized-casts -split-input-file | FileCheck %s --dump-input=always + +// CHECK-LABEL: module @main +module @main attributes {gpu.container_module} { + +// CHECK-NOT: gpu.module @kernel_module +gpu.module @kernel_module attributes {gpu.binary_blob = "BLOB!"} { + llvm.func @the_kernel() attributes {gpu.kernel} { + llvm.return + } +} + +// CHECK: llvm.func @_mlir_ciface_tf_launch_kernel(!llvm.ptr, !llvm.ptr, !llvm.ptr, i64, i64, i64, i64, i64, i64, !llvm.ptr) +// CHECK-DAG: llvm.mlir.global internal constant @kernel_module_the_kernel_kernel_name("the_kernel\00") +// CHECK-DAG: llvm.mlir.global internal constant @kernel_module_blob("BLOB!") + +// CHECK-LABEL: llvm.func @launch +// CHECK-SAME: (%[[CTX:.*]]: !llvm.ptr, %{{.*}}: !llvm.ptr, %{{.*}}: !llvm.ptr, %{{.*}}: i64, %{{.*}}: i64, %{{.*}}: i64, %{{.*}}: i64, %{{.*}}: i64 +func.func @launch(%ctx: !tf_framework.op_kernel_context, %memref: memref) { + // CHECK: %[[C1:.*]] = llvm.mlir.constant(1 : index) : i64 + // CHECK: %[[BLOB:.*]] = llvm.mlir.addressof @kernel_module_blob : !llvm.ptr + // CHECK: %[[BLOB_PTR:.*]] = llvm.getelementptr %[[BLOB]][0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.array<5 x i8> + // CHECK: %[[NAME:.*]] = llvm.mlir.addressof @kernel_module_the_kernel_kernel_name : !llvm.ptr + // CHECK: %[[NAME_PTR:.*]] = llvm.getelementptr %[[NAME]][0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.array<11 x i8> + // CHECK: %[[C7:.*]] = llvm.mlir.constant(7 : i32) : i32 + // CHECK: %[[ARGS:.*]] = llvm.alloca %22 x !llvm.ptr : (i32) -> !llvm.ptr + // CHECK: llvm.call @_mlir_ciface_tf_launch_kernel(%[[CTX]], %[[BLOB_PTR]], %[[NAME_PTR]], %[[C1]], %[[C1]], %[[C1]], %[[C1]], %[[C1]], %[[C1]], %[[ARGS]]) + %c1 = arith.constant 1 : index + gpu.launch_func @kernel_module::@the_kernel + blocks in (%c1, %c1, %c1) + threads in (%c1, %c1, %c1) + args(%memref: memref) + func.return +} + +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.cc new file mode 100644 index 0000000000000000000000000000000000000000..dcebc8902e7d759637382c333b35a4336e009945 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.cc @@ -0,0 +1,371 @@ +/* Copyright 2020 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/mlir/tools/kernel_gen/tf_framework_c_interface.h" + +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ExecutionEngine/JITSymbol.h" +#include "llvm/ExecutionEngine/Orc/Core.h" +#include "llvm/ExecutionEngine/Orc/Mangling.h" +#include "llvm/ExecutionEngine/Orc/Shared/ExecutorAddress.h" +#include "llvm/Support/Error.h" +#include "llvm/Support/TargetSelect.h" +#include "llvm/Support/raw_ostream.h" +#include "mlir/Dialect/MemRef/Transforms/AllocationOpInterfaceImpl.h" // from @llvm-project +#include "mlir/ExecutionEngine/CRunnerUtils.h" // from @llvm-project +#include "mlir/ExecutionEngine/ExecutionEngine.h" // from @llvm-project +#include "mlir/ExecutionEngine/OptUtils.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/Parser/Parser.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/compile_cache_item.pb.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/kernel_creator.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.h" +#include "xla/stream_executor/stream.h" +#include "xla/tsl/framework/allocator.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/path.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/statusor.h" + +#if defined(GOOGLE_CUDA) || defined(TENSORFLOW_USE_ROCM) +#include + +#include "tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h" +#endif + +static constexpr absl::string_view kTFJitCacheDirEnvVar = "TF_JIT_CACHE_DIR"; + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { +namespace { + +using tensorflow::Allocator; +using tensorflow::AllocatorAttributes; + +Allocator* GetAllocator(void* op_kernel_ctx) { + auto* ctx = static_cast(op_kernel_ctx); + // TODO(pifon): Figure out how to set AllocatorAttributes correctly. + AllocatorAttributes attrs; + return ctx->get_allocator(attrs); +} + +} // namespace + +extern "C" void* _mlir_ciface_tf_alloc(void* op_kernel_ctx, size_t num_elements, + size_t element_size, + int32_t output_index, + int32_t num_candidates, + int32_t* candidate_input_indices) { + static constexpr int kAmbiguousOutputIndex = -1; + auto* ctx = static_cast(op_kernel_ctx); + if (output_index != kAmbiguousOutputIndex) { + // Create a 1D shape, because the shapes don't have to match exactly for + // input forwarding. Only the number of elements must be the same. + tensorflow::TensorShape output_shape; + output_shape.AddDim(num_elements); + + // Iterate over indices of all inputs that can potentially be used for + // forwarding. + for (int i = 0; i < num_candidates; ++i) { + auto tensor = ctx->forward_input(candidate_input_indices[i], output_index, + ctx->expected_output_dtype(output_index), + output_shape, + ctx->output_memory_type(output_index), + ctx->output_alloc_attr(output_index)); + if (tensor != nullptr) { + return tensor->data(); + } + } + + CHECK(!ctx->output_expects_forwarding(output_index)); + } + + // If no forwarding happened, allocate a chunk of memory. + return GetAllocator(op_kernel_ctx) + ->AllocateRaw(Allocator::kAllocatorAlignment, + num_elements * element_size); +} + +extern "C" void _mlir_ciface_tf_dealloc(void* op_kernel_ctx, void* ptr) { + GetAllocator(op_kernel_ctx)->DeallocateRaw(ptr); +} + +extern "C" void _mlir_ciface_tf_report_error(void* op_kernel_ctx, + int32_t error_code, char* msg) { + std::optional symbol = symbolizeErrorCode(error_code); + if (!symbol.has_value()) { + LOG(ERROR) << "No valid conversion from integer value = " << error_code + << "to ErrorCode attribute"; + return; + } + auto* ctx = static_cast(op_kernel_ctx); + ctx->CtxFailureWithWarning( + absl::Status{ConvertAttrToEnumValue(symbol.value()), msg}); +} + +static void ReportError(void* op_kernel_ctx, ErrorCode error_code, + const char* msg) { + _mlir_ciface_tf_report_error(op_kernel_ctx, static_cast(error_code), + const_cast(msg)); +} + +namespace { + +std::string GetFileCachePath(const std::string cache_dir, + const std::string& code) { + size_t hash = llvm::hash_value(code); + return tensorflow::io::JoinPath(cache_dir, std::to_string(hash)); +} + +// A callback to register all externally defined symbols needed by the kernel. +llvm::orc::SymbolMap TFFrameworkSymbolMap(llvm::orc::MangleAndInterner mangle) { + llvm::orc::SymbolMap symbol_map; + auto bind = [&](llvm::StringRef name, auto symbol_ptr) { + symbol_map[mangle(name)] = {llvm::orc::ExecutorAddr::fromPtr(symbol_ptr), + llvm::JITSymbolFlags()}; + }; + + // Register TF framework symbols. + bind("_mlir_ciface_tf_alloc", &_mlir_ciface_tf_alloc); + bind("_mlir_ciface_tf_dealloc", &_mlir_ciface_tf_dealloc); + bind("_mlir_ciface_tf_report_error", &_mlir_ciface_tf_report_error); +#if defined(GOOGLE_CUDA) || defined(TENSORFLOW_USE_ROCM) + bind("_mlir_ciface_tf_launch_kernel", &_mlir_ciface_tf_launch_kernel); +#endif + + // Register malloc/free to avoid unexpected implementations from shared libs. + bind("malloc", &malloc); + bind("free", &free); + + return symbol_map; +} + +void InitializeLlvmCompiler() { + static const bool initialized = ([] { + llvm::InitializeNativeTarget(); + llvm::InitializeNativeTargetAsmPrinter(); + return true; + })(); + (void)initialized; +} + +llvm::Expected> Compile( + const std::string code, llvm::SmallVectorImpl& architectures, + llvm::SmallVectorImpl& tile_sizes, + llvm::SmallVectorImpl& unroll_factors, bool enable_ftz, + bool index_64bit) { + std::string cache_dir; + if (const char* dir = getenv(kTFJitCacheDirEnvVar.data())) { + cache_dir = dir; + } + + // Check if we already have a partially compiled module in the filesystem + // based cache. + CompilationCacheItem item; + auto tenv = tensorflow::Env::Default(); + if (!cache_dir.empty() && tenv->RecursivelyCreateDir(cache_dir).ok()) { + std::string data; + if (tensorflow::ReadFileToString(tenv, GetFileCachePath(cache_dir, code), + &data) + .ok()) { + item.ParseFromString(data); + if (item.original_module() != code) { + item.Clear(); + } + } + } + + // Create the kernel. + mlir::DialectRegistry registry; + mlir::memref::registerAllocationOpInterfaceExternalModels(registry); + mlir::MLIRContext context(registry); + + mlir::OwningOpRef module; + + if (item.result_module().empty()) { + // Otherwise, compile the module now. + absl::StatusOr> status_or_module = + tensorflow::kernel_gen::GenerateKernelForHloCode( + context, code, architectures, tile_sizes, unroll_factors, + /*print_ptx=*/false, /*print_llvmir=*/false, enable_ftz, + index_64bit, + /*jit_compile=*/false, + /*jit_i64_indexed_for_large_tensors=*/false, + /*apply_cl_options=*/false); + if (!status_or_module.ok()) { + LOG(ERROR) << status_or_module.status(); + return nullptr; + } + module = std::move(status_or_module.value()); + + if (!cache_dir.empty() && tenv->RecursivelyCreateDir(cache_dir).ok()) { + // Save the compilation result here for future processes to use. + item.set_original_module(code); + llvm::raw_string_ostream stream(*item.mutable_result_module()); + module.get().print(stream); + stream.flush(); + + tensorflow::WriteStringToFile(tenv, GetFileCachePath(cache_dir, code), + item.SerializeAsString()) + .IgnoreError(); + } + } else { + module = tensorflow::kernel_gen::SetupContextAndParseModule( + context, item.result_module()) + .value(); + } + + // Initialize LLVM targets. + InitializeLlvmCompiler(); + + // Create execution engine with an inner optimization pipeline. + auto opt_pipeline = mlir::makeOptimizingTransformer( + /*optLevel=*/2, /*sizeLevel=*/0, /*targetMachine=*/nullptr); + mlir::ExecutionEngineOptions engine_options; + engine_options.transformer = opt_pipeline; + llvm::Expected> engine = + mlir::ExecutionEngine::create(module.get(), engine_options); + if (!engine) { + LOG(ERROR) << "Failed to create ExecutionEngine: " + << toString(engine.takeError()); + return nullptr; + } + + // Finally, register the missing symbols. + engine.get()->registerSymbols(TFFrameworkSymbolMap); + return engine; +} + +template +llvm::SmallVector SmallVectorFromCArray(int64_t num_elements, + U* elements_ptr) { + llvm::SmallVector result; + result.reserve(num_elements); + for (int i = 0; i < num_elements; ++i) result.push_back(elements_ptr[i]); + return result; +} + +} // namespace + +extern "C" void* _mlir_ciface_tf_jit_compile( + void* op_kernel_ctx, char* code, int64_t num_tile_sizes, + int64_t* tile_sizes_ptr, int64_t num_unroll_factors, + int64_t* unroll_factors_ptr, bool enable_ftz, bool index_64bit) { + // Get the resource manager. + auto* ctx = static_cast(op_kernel_ctx); + tensorflow::ResourceMgr* rm = ctx->resource_manager(); + if (!rm) { + ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "No resource manager."); + return nullptr; + } + + // Get the JIT cache. + JITCache* jit_cache = nullptr; + auto status = rm->LookupOrCreate(rm->default_container(), + JITCache::kDefaultResourceName, + &jit_cache, JITCache::Create); + tensorflow::core::ScopedUnref jit_cache_ref(jit_cache); + if (!status.ok()) { + ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, + "Failed to find or create JIT cache."); + return nullptr; + } + + // Determine the unique architecture for the current GPU, if any. + SmallVector architectures; +#if defined(GOOGLE_CUDA) + stream_executor::CudaComputeCapability cc = + ctx->op_device_context()->stream()->GetCudaComputeCapability(); + architectures.push_back(absl::StrCat("sm_", cc.major, cc.minor)); +#elif defined(TENSORFLOW_USE_ROCM) + stream_executor::RocmComputeCapability cc = + ctx->op_device_context()->stream()->GetRocmComputeCapability(); + architectures.push_back(cc.gcn_arch_name()); +#endif + + // Construct `SmallVector`s from arguments. + llvm::SmallVector tile_sizes = + SmallVectorFromCArray(num_tile_sizes, tile_sizes_ptr); + llvm::SmallVector unroll_factors = + SmallVectorFromCArray(num_unroll_factors, unroll_factors_ptr); + + // Lookup or compile the execution module. + ExecutionEngine* engine = jit_cache->LookupOrCompile(code, [&]() { + return Compile(code, architectures, tile_sizes, unroll_factors, enable_ftz, + index_64bit); + }); + if (engine == nullptr) { + ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "JIT compilation failed."); + return nullptr; + } + return engine; +} + +extern "C" void _mlir_ciface_tf_jit_execute(void* op_kernel_ctx, void* callable, + void* result, int64_t num_args, + void* args_ptr) { + // JIT compilation must have failed earlier if there is no callable ptr. + // Return some empty memory descriptor to prevent a crash. + if (callable == nullptr) { + auto* desc = static_cast<::UnrankedMemRefType*>(result); + desc->rank = 0; + auto* inner_desc = static_cast*>( + malloc(sizeof(StridedMemRefType))); + inner_desc->basePtr = nullptr; + inner_desc->data = nullptr; + inner_desc->offset = 0; + desc->descriptor = inner_desc; + return; + } + + // Build the argument array according to `ExecutionEngine`'s calling + // convention. + auto* typed_args_ptr = static_cast<::UnrankedMemRefType*>(args_ptr); + llvm::SmallVector args_array = {&op_kernel_ctx}; + for (int i = 0; i < num_args; i++) { + auto& desc = typed_args_ptr[i]; + args_array.push_back(&desc.rank); + args_array.push_back(&desc.descriptor); + } + args_array.push_back(result); + + llvm::Error invocation_result = + static_cast(callable)->invokePacked("main", args_array); + if (invocation_result) + ReportError(op_kernel_ctx, ErrorCode::UNKNOWN, "JIT invocation failed."); +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.h new file mode 100644 index 0000000000000000000000000000000000000000..2051aab8c8dd7ca7aee2fd476e0b1765b36c21ee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_framework_c_interface.h @@ -0,0 +1,52 @@ +/* Copyright 2020 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_MLIR_TOOLS_KERNEL_GEN_TF_FRAMEWORK_C_INTERFACE_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TF_FRAMEWORK_C_INTERFACE_H_ + +#include +#include + +#include "mlir/ExecutionEngine/RunnerUtils.h" // from @llvm-project + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +extern "C" MLIR_RUNNERUTILS_EXPORT void* _mlir_ciface_tf_alloc( + void* op_kernel_ctx, size_t num_elements, size_t element_size, + int32_t output_index, int32_t num_candidates, + int32_t* candidate_input_indices); + +extern "C" MLIR_RUNNERUTILS_EXPORT void _mlir_ciface_tf_dealloc( + void* op_kernel_ctx, void* ptr); + +extern "C" MLIR_RUNNERUTILS_EXPORT void _mlir_ciface_tf_report_error( + void* op_kernel_ctx, int32_t error_code, char* msg); + +extern "C" MLIR_RUNNERUTILS_EXPORT void* _mlir_ciface_tf_jit_compile( + void* op_kernel_ctx, char* code, int64_t num_tile_sizes, + int64_t* tile_sizes_ptr, int64_t num_unroll_factors, + int64_t* unroll_factors_ptr, bool enable_ftz, bool index_64bit); + +extern "C" MLIR_RUNNERUTILS_EXPORT void _mlir_ciface_tf_jit_execute( + void* op_kernel_ctx, void* callable, void* result, int64_t num_args, + void* args_ptr); + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TF_FRAMEWORK_C_INTERFACE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.cc new file mode 100644 index 0000000000000000000000000000000000000000..5bc4e479332f8c6adafbf9f70172c23b803c0996 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.cc @@ -0,0 +1,187 @@ +/* Copyright 2020 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/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h" + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "xla/stream_executor/stream.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" + +#if GOOGLE_CUDA +#include "third_party/gpus/cuda/include/cuda.h" +#endif + +static void ReportInternalError(tensorflow::OpKernelContext *ctx, + const std::string msg) { + if (ctx == nullptr) { + LOG(WARNING) << msg << "\n"; + return; + } + ctx->CtxFailureWithWarning(absl::Status{absl::StatusCode::kInternal, msg}); +} + +#if GOOGLE_CUDA +using GPUResult = CUresult; +#endif +#if TENSORFLOW_USE_ROCM +using GPUResult = hipError_t; +#endif + +void GPUReportIfError(GPUResult result, tensorflow::OpKernelContext *ctx, + const char *expr_str) { + if (!result) return; + const char *name = nullptr; + +#if GOOGLE_CUDA + cuGetErrorName(result, &name); +#endif +#if TENSORFLOW_USE_ROCM + name = hipGetErrorName(result); +#endif + + if (!name) name = ""; + std::string msg = absl::StrCat("'", expr_str, "' failed with '", name, "'"); + ReportInternalError(ctx, msg); +} + +#define GPU_REPORT_IF_ERROR_WITH_CTX(expr, ctx) \ + GPUReportIfError(expr, ctx, #expr) +#define GPU_REPORT_IF_ERROR(expr) GPU_REPORT_IF_ERROR_WITH_CTX(expr, nullptr) + +// Implement the GPU module cache and share what can be shared. + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +GPURuntimeCache::~GPURuntimeCache() { + tensorflow::mutex_lock lock(mu_); + for (auto it : gpu_module_by_data_ptr_) { +#if GOOGLE_CUDA + GPU_REPORT_IF_ERROR(cuModuleUnload(it.second)); +#endif +#if TENSORFLOW_USE_ROCM + GPU_REPORT_IF_ERROR(hipModuleUnload(it.second)); +#endif + } +} + +absl::Status GPURuntimeCache::Create(GPURuntimeCache **dst) { + *dst = new GPURuntimeCache; + return absl::OkStatus(); +} + +std::string GPURuntimeCache::DebugString() const { return "GPU runtime cache"; } + +GPURuntimeCache::GPUModule GPURuntimeCache::LookupOrLoadModule(void *data) { + tensorflow::mutex_lock lock(mu_); + GPUModule &module = gpu_module_by_data_ptr_[data]; + +#if GOOGLE_CUDA + if (!module) GPU_REPORT_IF_ERROR(cuModuleLoadData(&module, data)); +#endif +#if TENSORFLOW_USE_ROCM + if (!module) GPU_REPORT_IF_ERROR(hipModuleLoadData(&module, data)); +#endif + + return module; +} + +GPURuntimeCache::GPUFunction GPURuntimeCache::LookupOrGetFunction( + GPUModule module, const char *kernel_name) { + tensorflow::mutex_lock lock(mu_); + GPUFunction &function = + gpu_function_by_module_and_name_[{module, kernel_name}]; + + if (!function) { +#if GOOGLE_CUDA + GPU_REPORT_IF_ERROR(cuModuleGetFunction(&function, module, kernel_name)); +#endif +#if TENSORFLOW_USE_ROCM + GPU_REPORT_IF_ERROR(hipModuleGetFunction(&function, module, kernel_name)); +#endif + } + + return function; +} + +// Implements a C wrapper around the TensorFlow runtime and CUDA (or ROCm) +// library that allows launching a kernel on the current device and stream from +// a binary blob for the module and function name. +// The wrapper uses intptr_t instead of CUDA's unsigned int (or ROCm's unsigned +// int) to match the type of MLIR's index type. This avoids the need for casts +// in the generated MLIR code. +extern "C" void _mlir_ciface_tf_launch_kernel(void *ctx, void *module_blob, + char *kernel_name, intptr_t gridX, + intptr_t gridY, intptr_t gridZ, + intptr_t blockX, intptr_t blockY, + intptr_t blockZ, void **params) { + // For empty grids, we don't need to do anything. + if (!gridX || !gridY || !gridZ) return; + + // Get the GPU module cache. + auto *op_kernel_ctx = static_cast(ctx); + auto *rm = op_kernel_ctx->resource_manager(); + if (rm == nullptr) { + ReportInternalError(op_kernel_ctx, "expected resource_manager"); + return; + } + GPURuntimeCache *cache = nullptr; + OP_REQUIRES_OK(op_kernel_ctx, rm->LookupOrCreate( + rm->default_container(), + GPURuntimeCache::kDefaultResourceName, + &cache, GPURuntimeCache::Create)); + assert(cache != nullptr && "cache creation must not fail"); + tensorflow::core::ScopedUnref ref(cache); + + // Get the GPU module. + stream_executor::Stream *se_stream = + op_kernel_ctx->op_device_context()->stream(); + void *stream = se_stream->platform_specific_handle().stream; + GPURuntimeCache::GPUModule module = cache->LookupOrLoadModule(module_blob); + GPURuntimeCache::GPUFunction function = + cache->LookupOrGetFunction(module, kernel_name); + +#if GOOGLE_CUDA + GPU_REPORT_IF_ERROR_WITH_CTX( + cuLaunchKernel(function, gridX, gridY, gridZ, blockX, blockY, blockZ, + /*sharedMemBytes=*/0, reinterpret_cast(stream), + params, nullptr), + op_kernel_ctx); +#endif +#if TENSORFLOW_USE_ROCM + GPU_REPORT_IF_ERROR_WITH_CTX( + hipModuleLaunchKernel( + function, gridX, gridY, gridZ, blockX, blockY, blockZ, + /*sharedMemBytes=*/0, reinterpret_cast(stream), params, + nullptr), + op_kernel_ctx); +#endif +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h new file mode 100644 index 0000000000000000000000000000000000000000..c910083258450623fe807aaa43b9e66f1272de29 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_gpu_runtime_wrappers.h @@ -0,0 +1,98 @@ +/* Copyright 2021 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_MLIR_TOOLS_KERNEL_GEN_TF_GPU_RUNTIME_WRAPPERS_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TF_GPU_RUNTIME_WRAPPERS_H_ + +#include "absl/container/flat_hash_map.h" +#include "mlir/ExecutionEngine/RunnerUtils.h" // from @llvm-project +#include "tensorflow/core/framework/resource_base.h" +#include "tensorflow/core/framework/resource_op_kernel.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/status.h" +#include "tsl/platform/hash.h" +#include "tsl/platform/thread_annotations.h" + +#if GOOGLE_CUDA +#include "third_party/gpus/cuda/include/cuda.h" +#endif +#if TENSORFLOW_USE_ROCM +#include "rocm/include/hip/hip_runtime.h" +#endif + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +class GPURuntimeCache : public tensorflow::ResourceBase { + public: +#if GOOGLE_CUDA + using GPUModule = CUmodule; + using GPUFunction = CUfunction; +#endif +#if TENSORFLOW_USE_ROCM + using GPUModule = hipModule_t; + using GPUFunction = hipFunction_t; +#endif + + ~GPURuntimeCache() override; + static constexpr const char* kDefaultResourceName = "mlir-gpu-runtime-cache"; + static absl::Status Create(GPURuntimeCache** dst); + std::string DebugString() const override; + + // Assumes that no two modules are loaded from the same memory location over + // the lifetime of this cache. This allows to use the pointer as a key. All + // modules are unloaded on destruction of this cache. + GPUModule LookupOrLoadModule(void* data); + + GPUFunction LookupOrGetFunction(GPUModule module, const char* kernel_name); + + private: + struct FunctionKey { + GPUModule module; + const char* kernel_name; + + friend bool operator==(const FunctionKey& lhs, const FunctionKey& rhs) { + return lhs.module == rhs.module && lhs.kernel_name == rhs.kernel_name; + } + + struct Hash { + size_t operator()(const FunctionKey& key) const { + return tsl::Hash64Combine(tsl::hash()(key.module), + tsl::Hash64(key.kernel_name)); + } + }; + }; + + tensorflow::mutex mu_; + absl::flat_hash_map gpu_module_by_data_ptr_ + TF_GUARDED_BY(mu_); + absl::flat_hash_map + gpu_function_by_module_and_name_ TF_GUARDED_BY(mu_); +}; + +// Implements a C wrapper around the TensorFlow runtime and CUDA (or ROCm) +// library that allows launching a kernel on the current device and stream from +// a binary blob for the module and function name. +extern "C" MLIR_RUNNERUTILS_EXPORT void _mlir_ciface_tf_launch_kernel( + void* ctx, void* module_blob, char* kernel_name, intptr_t gridX, + intptr_t gridY, intptr_t gridZ, intptr_t blockX, intptr_t blockY, + intptr_t blockZ, void** params); + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TF_GPU_RUNTIME_WRAPPERS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.cc new file mode 100644 index 0000000000000000000000000000000000000000..1651c356622f61a899feebeb0279d956d836bb17 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.cc @@ -0,0 +1,73 @@ +/* Copyright 2021 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/mlir/tools/kernel_gen/tf_jit_cache.h" + +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "llvm/Support/Error.h" +#include "mlir/ExecutionEngine/ExecutionEngine.h" // from @llvm-project +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/status.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +absl::Status JITCache::Create(JITCache** dst) { + *dst = new JITCache; + return absl::OkStatus(); +} + +std::string JITCache::DebugString() const { return "JIT cache"; } + +ExecutionEngine* JITCache::LookupOrCompile( + const std::string code, + std::function>()> + compile_callback) { + // Check if we already have a compiled module in the cache. + { + tensorflow::mutex_lock lock(mu_); + if (execution_engine_by_key_.contains(code)) + return execution_engine_by_key_[code].get(); + } + + // Otherwise, compile the module now. + llvm::Expected> engine = compile_callback(); + if (!engine) return nullptr; + + // Insert the compiled module into our cache and return a raw pointer. + { + tensorflow::mutex_lock lock(mu_); + // Check again whether we already have a compiled module in the cache. It + // may have been added during the time we ran compile_callback(). + return execution_engine_by_key_.try_emplace(code, std::move(engine.get())) + .first->second.get(); + } +} + +size_t JITCache::Size() { + tensorflow::mutex_lock lock(mu_); + return execution_engine_by_key_.size(); +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..e5b60025365bce814916dd21504ea6fe30fe1987 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tf_jit_cache.h @@ -0,0 +1,59 @@ +/* Copyright 2021 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_MLIR_TOOLS_KERNEL_GEN_TF_JIT_CACHE_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TF_JIT_CACHE_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/status/status.h" +#include "mlir/ExecutionEngine/ExecutionEngine.h" // from @llvm-project +#include "tensorflow/core/framework/resource_base.h" +#include "tensorflow/core/framework/resource_op_kernel.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/status.h" +#include "tsl/platform/thread_annotations.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +class JITCache : public tensorflow::ResourceBase { + public: + static constexpr const char* kDefaultResourceName = "mlir-jit-cache"; + static absl::Status Create(JITCache** dst); + + std::string DebugString() const override; + ExecutionEngine* LookupOrCompile( + std::string code, + std::function>()> + compile_callback); + size_t Size(); + + private: + tensorflow::mutex mu_; + absl::flat_hash_map> + execution_engine_by_key_ TF_GUARDED_BY(mu_); +}; + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TF_JIT_CACHE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tools/kernel-gen-opt/kernel-gen-opt.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tools/kernel-gen-opt/kernel-gen-opt.cc new file mode 100644 index 0000000000000000000000000000000000000000..6149ddc10e95ccb1740b0e4523c858d911026e4e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/tools/kernel-gen-opt/kernel-gen-opt.cc @@ -0,0 +1,44 @@ +/* Copyright 2020 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 "llvm/Support/LogicalResult.h" +#include "mlir/InitAllDialects.h" // from @llvm-project +#include "mlir/InitAllPasses.h" // from @llvm-project +#include "mlir/Tools/mlir-opt/MlirOptMain.h" // from @llvm-project +#include "stablehlo/dialect/Register.h" // from @stablehlo +#include "tensorflow/compiler/mlir/tensorflow/dialect_registration.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "xla/mlir_hlo/deallocation/transforms/passes.h" +#include "xla/mlir_hlo/mhlo/IR/register.h" +#include "xla/mlir_hlo/mhlo/transforms/passes.h" + +int main(int argc, char **argv) { + mlir::registerAllPasses(); + mlir::mhlo::registerAllMhloPasses(); + mlir::kernel_gen::registerKernelGenPasses(); + mlir::deallocation::registerDeallocationPasses(); + + mlir::DialectRegistry registry; + mlir::registerAllDialects(registry); + mlir::mhlo::registerAllMhloDialects(registry); + mlir::stablehlo::registerAllDialects(registry); + mlir::RegisterAllTensorFlowDialects(registry); + + registry.insert(); + + return failed( + mlir::MlirOptMain(argc, argv, "MLIR HLO pass driver\n", registry)); +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..a28a57e52791c6f95f0afff5f4d193e624d39a1b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/BUILD @@ -0,0 +1,235 @@ +load("@llvm-project//mlir:tblgen.bzl", "gentbl_cc_library") +load( + "@local_config_rocm//rocm:build_defs.bzl", + "if_rocm_is_configured", +) +load("@rules_cc//cc:cc_library.bzl", "cc_library") +load( + "@xla//xla/tsl/platform/default:cuda_build_defs.bzl", + "if_cuda_is_configured", +) +load("//tensorflow:tensorflow.default.bzl", "get_compatible_with_portable") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//tensorflow/compiler/mlir/tools/kernel_gen:friends"], + licenses = ["notice"], +) + +cc_library( + name = "utils", + srcs = ["utils.cc"], + hdrs = ["utils.h"], + compatible_with = get_compatible_with_portable(), + deps = [ + "@llvm-project//llvm:Support", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:LLVMDialect", + ], +) + +cc_library( + name = "tf_framework_legalize_to_llvm", + srcs = ["tf_framework_legalize_to_llvm.cc"], + hdrs = ["rewriters.h"], + compatible_with = get_compatible_with_portable(), + deps = [ + ":utils", + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:LLVMCommonConversion", + "@llvm-project//mlir:LLVMDialect", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + ], +) + +cc_library( + name = "bufferize", + srcs = ["bufferize.cc"], + hdrs = ["rewriters.h"], + compatible_with = get_compatible_with_portable(), + deps = [ + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:BufferizationTransforms", + "@llvm-project//mlir:ComplexDialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:SCFDialect", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + "@stablehlo//:chlo_ops", + ], +) + +cc_library( + name = "embed_tf_framework", + srcs = ["embed_tf_framework.cc"], + hdrs = ["rewriters.h"], + compatible_with = get_compatible_with_portable(), + deps = [ + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "@llvm-project//mlir:ControlFlowDialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + ], +) + +gentbl_cc_library( + name = "kernel_gen_passes_inc_gen", + compatible_with = get_compatible_with_portable(), + tbl_outs = {"kernel_gen_passes.h.inc": [ + "-gen-pass-decls", + "-name=KernelGen", + ]}, + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "passes.td", + deps = ["@llvm-project//mlir:PassBaseTdFiles"], +) + +cc_library( + name = "gpu_passes", + srcs = [ + "gpu_kernel_to_blob_pass.cc", + "tf_kernel_to_llvm_pass.cc", + ], + hdrs = ["passes.h"], + copts = if_cuda_is_configured(["-DGOOGLE_CUDA=1"]) + if_rocm_is_configured(["-DTENSORFLOW_USE_ROCM=1"]), + deps = [ + ":embed_tf_framework", + ":kernel_gen_passes_inc_gen", + "//tensorflow/compiler/mlir/tensorflow", + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "//tensorflow/core:lib", + "//tensorflow/core/platform:errors", + "@llvm-project//llvm:Support", + "@llvm-project//llvm:TargetParser", + "@llvm-project//llvm:TransformUtils", + "@llvm-project//mlir:AffineDialect", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:ArithToLLVM", + "@llvm-project//mlir:ArithTransforms", + "@llvm-project//mlir:ComplexDialect", + "@llvm-project//mlir:ComplexToLLVM", + "@llvm-project//mlir:ControlFlowDialect", + "@llvm-project//mlir:ControlFlowToLLVM", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:FuncToLLVM", + "@llvm-project//mlir:FuncTransforms", + "@llvm-project//mlir:GPUDialect", + "@llvm-project//mlir:GPUToGPURuntimeTransforms", + "@llvm-project//mlir:GPUTransforms", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:LLVMCommonConversion", + "@llvm-project//mlir:LLVMDialect", + "@llvm-project//mlir:LinalgDialect", + "@llvm-project//mlir:LinalgTransforms", + "@llvm-project//mlir:MathDialect", + "@llvm-project//mlir:MathToLLVM", + "@llvm-project//mlir:MathToLibm", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:MemRefToLLVM", + "@llvm-project//mlir:MemRefTransforms", + "@llvm-project//mlir:NVVMToLLVMIRTranslation", # buildcleaner: keep + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:ROCDLToLLVMIRTranslation", # buildcleaner: keep + "@llvm-project//mlir:ReconcileUnrealizedCasts", + "@llvm-project//mlir:SCFDialect", + "@llvm-project//mlir:SCFToControlFlow", + "@llvm-project//mlir:SCFTransforms", + "@llvm-project//mlir:ShapeDialect", + "@llvm-project//mlir:ShapeToStandard", + "@llvm-project//mlir:ShapeTransforms", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TensorDialect", + "@llvm-project//mlir:TensorTransforms", + "@llvm-project//mlir:ToLLVMIRTranslation", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + "@llvm-project//mlir:VectorDialect", + "@llvm-project//mlir:VectorToLLVM", + "@llvm-project//mlir:VectorTransforms", + "@xla//xla:debug_options_flags", + "@xla//xla:xla_proto_cc", + "@xla//xla/mlir_hlo", + "@xla//xla/mlir_hlo:mhlo_passes", + "@xla//xla/mlir_hlo:type_conversion", + "@xla//xla/service/gpu:gpu_asm_opts_util", + "@xla//xla/service/gpu:target_constants", + "@xla//xla/stream_executor:device_description", + ] + if_cuda_is_configured([ + "@tsl//tsl/platform:cuda_root_path", + "@xla//xla/stream_executor/cuda:cuda_asm_compiler", + "@xla//xla/service/gpu/llvm_gpu_backend:nvptx_backend", + ]) + if_rocm_is_configured([ + "@xla//xla/stream_executor/gpu:asm_compiler", + "@xla//xla/service/gpu/llvm_gpu_backend:amdgpu_backend", + "//tensorflow/core/platform:rocm_rocdl_path", + ]), +) + +cc_library( + name = "passes", + srcs = [ + "broadcast_propagation_pass.cc", + "buffer_reuse_pass.cc", + "bufferize_pass.cc", + "copy_cleanup_pass.cc", + "embed_tf_framework_pass.cc", + "func_to_jit_invocations.cc", + "fuse_inner_parallel_loops_pass.cc", + "legalize_tensor_reshape_pass.cc", + "merge_assuming_ops_pass.cc", + "parallel_loops_to_sequential.cc", + "rewrite_tf_framework_assert.cc", + "same_shape_propagation.cc", + "shape_simplification_pass.cc", + "shape_to_descriptors_pass.cc", + "tensorflow_abi_knowledge_propagation.cc", + ], + hdrs = ["passes.h"], + compatible_with = get_compatible_with_portable(), + deps = [ + ":bufferize", # buildcleaner: keep + ":embed_tf_framework", # buildcleaner: keep + ":kernel_gen_passes_inc_gen", + ":tf_framework_legalize_to_llvm", # buildcleaner: keep + "//tensorflow/compiler/mlir/tools/kernel_gen/ir:tf_framework_ops", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:Analysis", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:BufferizationTransforms", + "@llvm-project//mlir:ControlFlowDialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:GPUDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:InferTypeOpInterface", + "@llvm-project//mlir:LLVMDialect", + "@llvm-project//mlir:LinalgDialect", + "@llvm-project//mlir:MathDialect", + "@llvm-project//mlir:MemRefDialect", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:SCFDialect", + "@llvm-project//mlir:SCFToControlFlow", + "@llvm-project//mlir:SCFTransforms", + "@llvm-project//mlir:ShapeDialect", + "@llvm-project//mlir:ShapeToStandard", + "@llvm-project//mlir:ShapeTransforms", + "@llvm-project//mlir:SideEffectInterfaces", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TensorDialect", + "@llvm-project//mlir:TransformUtils", + "@stablehlo//:base", + "@xla//xla/mlir_hlo", + "@xla//xla/mlir_hlo:mhlo_passes", + "@xla//xla/mlir_hlo:transforms_passes", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/broadcast_propagation_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/broadcast_propagation_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..71739e593fcbfaf294ade5864a5786b400bdaf38 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/broadcast_propagation_pass.cc @@ -0,0 +1,449 @@ +/* Copyright 2021 The OpenXLA Authors. + +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 +#include +#include +#include + +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OpDefinition.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/OperationSupport.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "stablehlo/dialect/Base.h" // from @stablehlo +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" + +namespace mlir { +namespace kernel_gen { + +using mhlo::DynamicBroadcastInDimOp; + +#define GEN_PASS_DEF_BROADCASTPROPAGATIONPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +namespace { + +// To avoid duplicate broadcasts, we collect all the intended broadcasts ahead +// of realizing any broadcasts in the IR. These are broadcasted versions of +// values that we are interested in, and they are uniquely characterized by a +// `BroadcastIntent` value. +struct BroadcastIntent { + RankedTensorType resultType; + Value targetValue; + Value outputDimensions; + Attribute broadcastDimensions; + bool operator==(BroadcastIntent rhs) const { + return resultType == rhs.resultType && targetValue == rhs.targetValue && + outputDimensions == rhs.outputDimensions && + broadcastDimensions == rhs.broadcastDimensions; + } + bool operator!=(BroadcastIntent rhs) const { return !(*this == rhs); } +}; + +} // namespace +} // namespace kernel_gen +} // namespace mlir + +namespace llvm { + +using mlir::kernel_gen::BroadcastIntent; + +template <> +struct DenseMapInfo { + static unsigned getHashValue(const BroadcastIntent &intent) { + return hash_combine( + DenseMapInfo::getHashValue(intent.resultType), + DenseMapInfo::getHashValue(intent.targetValue), + DenseMapInfo::getHashValue(intent.outputDimensions), + DenseMapInfo::getHashValue( + intent.broadcastDimensions)); + } + static bool isEqual(const BroadcastIntent &lhs, const BroadcastIntent &rhs) { + return lhs == rhs; + } +}; + +} // namespace llvm + +namespace mlir { +namespace kernel_gen { +namespace { + +bool allowsForElementwiseBroadcastPropagation(Operation *op) { + if (op && op->hasTrait() && + op->hasTrait() && op->getNumResults() == 1) { + return true; + } + if (op && op->hasTrait() && + op->getNumResults() == 1) { + return true; + } + return false; +} + +bool allowsForBroadcastPropagation(Operation *op) { + return llvm::isa_and_nonnull(op) || + allowsForElementwiseBroadcastPropagation(op); +} + +DenseIntElementsAttr composeBroadcastDimensionsAttr(OpBuilder &builder, + DenseIntElementsAttr a, + DenseIntElementsAttr b) { + SmallVector bVec = + llvm::to_vector(llvm::map_range(b, [](const APInt &it) { + return static_cast(it.getLimitedValue()); + })); + SmallVector composedVec = llvm::to_vector(llvm::map_range( + a, [bVec](const APInt &it) { return bVec[it.getLimitedValue()]; })); + return builder.getI64TensorAttr(composedVec); +} + +// Find all the broadcast intents and their dependencies. Start analyzing from +// the root an collect all broadcast intents that can help broadcast propagation +// from there. +void findBroadcastIntents( + DynamicBroadcastInDimOp root, Block *parentBlock, + BroadcastIntent &rootBcastIntent, + SmallVector &bcastIntents, + DenseMap> + &bcastIntentDependencies) { + OpBuilder builder(root.getContext()); + + // Use the result vector of broadcast intents as a worklist. The set of + // broadcast intents helps to ensure their uniqueness. + DenseSet bcastIntentsSet; + auto addToWorklistIfNew = [&](BroadcastIntent bcastIntent) { + if (!bcastIntentsSet.count(bcastIntent)) { + bcastIntentsSet.insert(bcastIntent); + bcastIntents.push_back(bcastIntent); + } + }; + + // Derive the broadcast intent associated with the root broadcast operation. + // Add it to the worklist to seed the analysis. + rootBcastIntent = {mlir::cast(root.getResult().getType()), + root.getOperand(), root.getOutputDimensions(), + root.getBroadcastDimensions()}; + addToWorklistIfNew(rootBcastIntent); + + // We use result vector of broadcast intents as a worklist, the first `i` + // intents of which have been processed. + for (int64_t i = 0; i < static_cast(bcastIntents.size()); ++i) { + BroadcastIntent it = bcastIntents[i]; + Operation *producerOp = it.targetValue.getDefiningOp(); + + // We can propagate broadcasts over (broadcasting) element-wise operations + // and dynamic_broadcast_in_dim ops with the restriction that they must be + // in the same block as they may depend on assuming regions. + if (!producerOp || producerOp->getBlock() != parentBlock || + !allowsForBroadcastPropagation(producerOp)) { + continue; + } + + // We can skip broadcasting producers (dynamic_broadcast_in_dim ops) if we + // compose their broadcasting dimensions. + if (auto producerBcastOp = + llvm::dyn_cast(producerOp)) { + DenseIntElementsAttr composedBcastDims = composeBroadcastDimensionsAttr( + builder, producerBcastOp.getBroadcastDimensions(), + mlir::cast(it.broadcastDimensions)); + BroadcastIntent bcastedOperandIntent = { + it.resultType, producerBcastOp.getOperand(), it.outputDimensions, + composedBcastDims}; + + // Record dependency and "recur". + bcastIntentDependencies[it] = {bcastedOperandIntent}; + addToWorklistIfNew(bcastedOperandIntent); + continue; + } + + // We can propagate broadcasts over (broadcasting) element-wise operations. + // Instead of broadcasting the result of such an op, we can broadcast the + // operands and apply the element-wise operation to them. + assert(allowsForElementwiseBroadcastPropagation(producerOp)); + bcastIntentDependencies[it] = {}; + for (auto operand : producerOp->getOperands()) { + auto operandTy = mlir::cast(operand.getType()); + auto operandBcastDims = operandTy.getRank() == 0 + ? builder.getI64TensorAttr({}) + : it.broadcastDimensions; + auto bcastedOperandTy = RankedTensorType::get(it.resultType.getShape(), + operandTy.getElementType()); + BroadcastIntent bcastedOperandIntent = { + bcastedOperandTy, operand, it.outputDimensions, operandBcastDims}; + + // Record dependency and "recur". + bcastIntentDependencies[it].push_back(bcastedOperandIntent); + addToWorklistIfNew(bcastedOperandIntent); + } + } +} + +void sortBroadcastIntentsInReverseTopologicalOrder( + SmallVector &bcastIntentsVec, Block *parentBlock) { + // Sort broadcast intents in reverse topological order of the producer ops. We + // can use the positions in the block for this. All broadcast intents outside + // the block (e.g. arguments) will be sorted towards the front. + // This ordering is independent of the output dimensions as dependencies can + // only occur between broadcast intents of the same output dimension. + std::sort(bcastIntentsVec.begin(), bcastIntentsVec.end(), + [parentBlock](const BroadcastIntent &a, const BroadcastIntent &b) { + Operation *producerOpA = a.targetValue.getDefiningOp(); + Operation *producerOpB = b.targetValue.getDefiningOp(); + bool aInBlock = producerOpA != nullptr && + producerOpA->getBlock() == parentBlock; + bool bInBlock = producerOpB != nullptr && + producerOpB->getBlock() == parentBlock; + if (aInBlock && bInBlock) { + return producerOpA->isBeforeInBlock(producerOpB); + } + return !aInBlock && bInBlock; + }); +} + +void setInsertionPointToEarliestPointWithAllValuesAvailable( + PatternRewriter &rewriter, Block *block, ValueRange values) { + Operation *lastDef = nullptr; + for (Value v : values) { + Operation *def = v.getDefiningOp(); + if (def && def->getBlock() == block) { + if (!lastDef || lastDef->isBeforeInBlock(def)) lastDef = def; + } + } + if (lastDef) { + rewriter.setInsertionPointAfter(lastDef); + } else { + rewriter.setInsertionPointToStart(block); + } +} + +DenseMap realizeBroadcastIntents( + SmallVector &sortedBcastIntents, + DenseMap> + &bcastIntentDependencies, + Block *parentBlock, PatternRewriter &rewriter) { + // Realize broadcast intents in order. They must be sorted so that their + // dependencies are realized before them. + DenseMap realizations; + for (auto it : sortedBcastIntents) { + Operation *producerOp = it.targetValue.getDefiningOp(); + assert(!realizations.count(it) && "expect unrealized broadcast intent"); + auto deps = bcastIntentDependencies.find(it); + + // If we cannot propagate broadcasts further, materialize them as a + // dynamic_broadcast_in_dim op. + if (!producerOp || producerOp->getBlock() != parentBlock || + !allowsForBroadcastPropagation(producerOp)) { + assert(deps == bcastIntentDependencies.end() && "expect no dependencies"); + setInsertionPointToEarliestPointWithAllValuesAvailable( + rewriter, parentBlock, + ValueRange{it.targetValue, it.outputDimensions}); + realizations[it] = DynamicBroadcastInDimOp::create( + rewriter, it.targetValue.getLoc(), it.resultType, it.targetValue, + it.outputDimensions, + mlir::cast(it.broadcastDimensions)); + continue; + } + + // For broadcast propagation across dynamic_broadcast_in_dim ops, the + // broadcasted value is already materialized. Forward it. + if (auto producerBcastOp = + llvm::dyn_cast_or_null(producerOp)) { + assert(deps != bcastIntentDependencies.end() && + deps->second.size() == 1 && "expect one dependency"); + auto bcastedOperand = realizations.find(deps->second.front()); + assert(bcastedOperand != realizations.end()); + realizations[it] = Value(bcastedOperand->second); + continue; + } + + // Othwerwise, realize broadcast intent for a (broadcasting) element-wise + // operation based on the broadcasted operands. + assert(allowsForElementwiseBroadcastPropagation(producerOp) && + "expect broadcast propagation over an (broadcasting) element-wise " + "operation"); + assert(deps != bcastIntentDependencies.end() && + deps->second.size() == producerOp->getNumOperands() && + "expect one dependency per operand"); + auto bcastedOperands = llvm::to_vector( + llvm::map_range(deps->second, [&](BroadcastIntent operandIntent) { + auto bcastedOperand = realizations.find(operandIntent); + assert(bcastedOperand != realizations.end() && + "expect dependencies to be realized earlier"); + return bcastedOperand->second; + })); + setInsertionPointToEarliestPointWithAllValuesAvailable( + rewriter, parentBlock, bcastedOperands); + OperationState newProducerOpState( + producerOp->getLoc(), producerOp->getName().getStringRef(), + bcastedOperands, it.resultType, producerOp->getAttrs()); + Operation *newProducerOp = rewriter.create(newProducerOpState); + assert(newProducerOp->getNumResults() == 1 && "expect exactly one result"); + realizations[it] = newProducerOp->getResults().front(); + } + + return realizations; +} + +void transitivelyEraseUnusedSideEffectFreeOps(Operation *root, + PatternRewriter &rewriter) { + // Find ops to erase. + SmallPtrSet opsToEraseSet; + SmallVector opsToErase; + SmallVector worklist = {root}; + while (!worklist.empty()) { + Operation *op = worklist.pop_back_val(); + + // Erase ops only once. + if (opsToEraseSet.count(op)) continue; + + // Erase only operations that are unused and free of side effects. + if (!isMemoryEffectFree(op) || + !llvm::all_of(op->getUsers(), [opsToEraseSet](Operation *user) { + return opsToEraseSet.count(user); + })) { + continue; + } + + // Erase and "recur". + opsToEraseSet.insert(op); + opsToErase.push_back(op); + for (Value operand : op->getOperands()) { + if (Operation *def = operand.getDefiningOp()) worklist.push_back(def); + } + } + + // Finally, erase the ops in the order of their uses. + for (Operation *op : opsToErase) rewriter.eraseOp(op); +} + +LogicalResult propagateBroadcast(DynamicBroadcastInDimOp root, + Block *parentBlock, + PatternRewriter &rewriter) { + // We can move broadcasts up over (i) (broadcasting) element-wise operations + // and (i) dynamic_broadcast_in_dim ops. This way, we propagate them through + // the IR to perform them early. Instead of broadcasting the result of such an + // op, we can broadcast the operands and apply the element-wise operation to + // them. + // + // To avoid exponential growth of the IR, we will do this in two phases: + // 1) First, we collect all the unique broadcast intents. These are + // broadcasted versions of values that we are interested in. They may + // later be materialized as an explicit broadcast or they can be the + // direct result of an operation over which a broadcast was propagated. + // 2) Then, we fulfill every broadcast intent in reverse topological order + // to ensure that their dependencies (the broadcasted operands) are + // available. + + // Find the unique broadcast intents. + BroadcastIntent rootBcastIntent; + SmallVector bcastIntents; + DenseMap> + bcastIntentDependencies; + findBroadcastIntents(root, parentBlock, rootBcastIntent, bcastIntents, + bcastIntentDependencies); + + // Fail if there is nothing but the root intent, i.e. if there is nothing to + // rewrite here. + if (bcastIntents.size() <= 1) { + assert(bcastIntents.front() == rootBcastIntent && "expect root intent"); + return failure(); + } + + // Sort the broadcast intents in reverse topological order so that they can be + // materialized and every depency is available when needed. + sortBroadcastIntentsInReverseTopologicalOrder(bcastIntents, parentBlock); + + // Realize broadcast intents. + DenseMap realizations = realizeBroadcastIntents( + bcastIntents, bcastIntentDependencies, parentBlock, rewriter); + + // Find the operations that may become redundant after replacing the root + // operation. This allows us to transitively erase unused side effect-free + // operations that result from this rewrite (after the root operation is no + // longer accessible). + SmallVector possiblyUnused; + for (auto operand : root->getOperands()) { + if (Operation *def = operand.getDefiningOp()) possiblyUnused.push_back(def); + } + + // Replace the root operation with its broadcast intent's realization. + rewriter.replaceOp(root, realizations[rootBcastIntent]); + + // Erase all the operations that have become redundant as a result of this + // rewrite. + for (Operation *op : possiblyUnused) { + transitivelyEraseUnusedSideEffectFreeOps(op, rewriter); + } + + return success(); +} + +struct BroadcastPropagationPattern + : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(DynamicBroadcastInDimOp op, + PatternRewriter &rewriter) const override { + return propagateBroadcast(op, op->getBlock(), rewriter); + } +}; + +struct BroadcastPropagationPass + : public impl::BroadcastPropagationPassBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + } + + void runOnOperation() override { + MLIRContext *ctx = &getContext(); + + // Collect patterns. + RewritePatternSet patterns(ctx); + patterns.add(ctx); + + // Apply broadcast propagation in reverse order to start propagation at + // the root of broadcast chains. This avoids duplicate work. + GreedyRewriteConfig config; + config.setUseTopDownTraversal(false); + + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns), + config))) { + return signalPassFailure(); + } + } +}; + +} // namespace + +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/buffer_reuse_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/buffer_reuse_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..f15162f6436a5b527a329e09017ea347d6d03731 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/buffer_reuse_pass.cc @@ -0,0 +1,275 @@ +/* Copyright 2020 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 +#include +#include +#include +#include + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "mlir/Analysis/Liveness.h" // from @llvm-project +#include "mlir/Dialect/Bufferization/Transforms/BufferViewFlowAnalysis.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Linalg/IR/Linalg.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/AffineMap.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" + +constexpr llvm::StringRef + mlir::kernel_gen::tf_framework::TFAllocOp::kReuseOutputAttrName; +constexpr llvm::StringRef + mlir::kernel_gen::tf_framework::TFAllocOp::kReuseInputCandidatesAttrName; +constexpr llvm::StringRef + mlir::kernel_gen::tf_framework::TFFrameworkDialect::kTFEntryAttrName; + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +class BufferReuseAnalysis { + public: + explicit BufferReuseAnalysis(func::FuncOp f) { build(f); } + + static constexpr int32_t kIndexAmbiguous = -1; + + std::optional> get_reuse_candiates( + memref::AllocOp op) { + auto it = reuse_candidates_.find(op); + if (it == reuse_candidates_.end()) return std::nullopt; + return it->second; + } + + std::optional get_output_index(memref::AllocOp op) { + auto it = output_indices_.find(op); + if (it == output_indices_.end()) return std::nullopt; + return it->second; + } + + private: + void build(func::FuncOp &f) { + BufferViewFlowAnalysis aliases(f); + find_output_indices(f, aliases); + find_reuse_candiates(f, aliases); + } + + void find_output_indices(func::FuncOp &f, BufferViewFlowAnalysis &aliases) { + f.walk([&](memref::AllocOp alloc_op) { + int32_t output_index = kIndexAmbiguous; + int count_return_uses = 0; + auto buffer_aliases = aliases.resolve(alloc_op.getResult()); + for (Value alias : buffer_aliases) { + for (auto &use : alias.getUses()) { + if (isa(use.getOwner())) { + int32_t index = use.getOperandNumber(); + if (count_return_uses++ == 0) + output_index = index; + else if (output_index != index) + output_index = kIndexAmbiguous; + } + } + } + output_indices_[alloc_op] = output_index; + }); + } + + void find_reuse_candiates(func::FuncOp &f, BufferViewFlowAnalysis &aliases) { + Liveness liveness(f); + f.walk([&](Block *block) { + find_reuse_candiates(block, aliases, liveness.getLiveness(block), + f.getArguments()); + }); + } + + void find_reuse_candiates(Block *block, BufferViewFlowAnalysis &aliases, + const LivenessBlockInfo *liveness, + ArrayRef arguments) { + for (Operation &op : *block) { + auto alloc_op = dyn_cast(op); + if (!alloc_op) continue; + + // Find first use of the newly allocated buffer within this block. + Value new_buffer = alloc_op.getResult(); + Operation *first_reuse = find_first_use_in_block(new_buffer, block); + assert((first_reuse == nullptr || first_reuse->getBlock() == block) && + "Expected first use in same block if found."); + + // Find reuse candidates for the regarded allocation. + SmallVector local_reuse_candidates; + for (BlockArgument old_buffer : arguments) { + if (!mlir::isa(old_buffer.getType())) continue; + + // Lifetime criterion: Only reuse buffers that are no longer used on + // first reuse, i.e. they are no longer alive. + bool lifetimes_compatible = true; + for (Value old_buffer_alias : aliases.resolve(old_buffer)) { + if (first_reuse == nullptr) { + // If the first use is beyond the end of this block we look at the + // block end. An argument buffer that is already reusable there is + // certainly reusable at any later actual use. Otherwise, lifetimes + // are incompatible. + if (liveness->isLiveOut(old_buffer_alias)) { + lifetimes_compatible = false; + break; + } + } else { + // A buffer is reusable if + // i) its last use is before the point of reuse, or + // ii) its last use is also its first reuse and the operation + // allows for local reuse. + // Otherwise, lifetimes are incompatible. + Operation *last_use = + liveness->getEndOperation(old_buffer_alias, &block->front()); + assert(last_use != nullptr && last_use->getBlock() == block && + "Expected last use in same block."); + if (first_reuse->isBeforeInBlock(last_use)) { + lifetimes_compatible = false; + break; + } + if (first_reuse == last_use && + !can_reuse_locally(first_reuse, old_buffer_alias, new_buffer)) { + lifetimes_compatible = false; + break; + } + } + } + + if (lifetimes_compatible) { + // All criteria are fulfilled 🙂. + int32_t old_buffer_index = old_buffer.getArgNumber(); + local_reuse_candidates.push_back(old_buffer_index); + } + } + + reuse_candidates_[&op] = local_reuse_candidates; + } + } + + Operation *find_first_use_in_block(Value value, Block *block) { + Operation *first_use = nullptr; + for (Operation *op : value.getUsers()) { + Operation *ancestor_op = block->findAncestorOpInBlock(*op); + if (ancestor_op == nullptr) continue; + if (first_use == nullptr || ancestor_op->isBeforeInBlock(first_use)) + first_use = ancestor_op; + } + return first_use; + } + + std::vector get_buffer_arguments(func::FuncOp &f) { + std::vector buffer_arguments; + for (BlockArgument arg : f.getArguments()) { + if (mlir::isa(arg.getType())) + buffer_arguments.push_back(arg); + } + return buffer_arguments; + } + + bool can_reuse_locally(Operation *op, Value old_buffer, Value new_buffer) { + // For now, we support only memrefs with the same memory layout. + auto old_buffer_ty = mlir::dyn_cast(old_buffer.getType()); + auto new_buffer_ty = mlir::dyn_cast(old_buffer.getType()); + if (!old_buffer_ty || !new_buffer_ty || + old_buffer_ty.getLayout() != new_buffer_ty.getLayout()) + return false; + + if (auto generic_op = dyn_cast(op)) { + auto op_operands = op->getOpOperands(); + auto old_it = llvm::find_if(op_operands, [&](OpOperand &op_operand) { + return op_operand.get() == old_buffer; + }); + auto new_it = llvm::find_if(op_operands, [&](OpOperand &op_operand) { + return op_operand.get() == new_buffer; + }); + assert(old_it != op_operands.end() && new_it != op_operands.end() && + "Expect `old/new_buffer` to be operand of `op`."); + + auto is_projection = [](AffineMap map) { + // Allow dropping dimensions but no permutations. + int64_t i = -1; + for (AffineExpr expr : map.getResults()) { + auto dim_expr = mlir::dyn_cast(expr); + if (!dim_expr || dim_expr.getPosition() <= i) return false; + i = dim_expr.getPosition(); + } + return true; + }; + + // If `linalg.generic` indexing maps are the same for input and output + // buffer then the last use of the input buffer happens before its first + // reuse (per memory location). Since we know that the inputs and outputs + // have the same size we also know that when one side has an identity map + // and the other side only drops dimensions, these dimensions have to be + // of size 1. + AffineMap old_indexing_map = generic_op.getMatchingIndexingMap(old_it); + AffineMap new_indexing_map = generic_op.getMatchingIndexingMap(new_it); + return (old_indexing_map == new_indexing_map && + old_indexing_map.isProjectedPermutation()) || + (old_indexing_map.isIdentity() && + is_projection(new_indexing_map)) || + (is_projection(old_indexing_map) && new_indexing_map.isIdentity()); + } + return false; + } + + DenseMap> reuse_candidates_; + DenseMap output_indices_; +}; + +#define GEN_PASS_DEF_BUFFERREUSEPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct BufferReusePass : public impl::BufferReusePassBase { + void runOnOperation() override { + if (!getOperation()->getAttrOfType( + tf_framework::TFFrameworkDialect::kTFEntryAttrName)) + return; + + BufferReuseAnalysis analysis(getOperation()); + + // Annotate IR with reuse candidates and output indices per allocation. + Builder builder(&getContext()); + getOperation().walk([&](memref::AllocOp op) { + if (auto output_index = analysis.get_output_index(op)) { + auto attr = builder.getI32IntegerAttr(*output_index); + op.getOperation()->setAttr( + tf_framework::TFAllocOp::kReuseOutputAttrName, attr); + } + if (auto reuse_candiates = analysis.get_reuse_candiates(op)) { + auto attr = builder.getI32ArrayAttr(*reuse_candiates); + op.getOperation()->setAttr( + tf_framework::TFAllocOp::kReuseInputCandidatesAttrName, attr); + } + }); + } +}; + +} // namespace + +std::unique_ptr> CreateBufferReusePass() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/bufferize.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/bufferize.cc new file mode 100644 index 0000000000000000000000000000000000000000..581f02aed28525d032b9d093754fba867dda587a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/bufferize.cc @@ -0,0 +1,78 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file implements logic for translating mixed IR to buffer form. + +#include "mlir/Dialect/Bufferization/Transforms/Bufferize.h" // from @llvm-project + +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Complex/IR/Complex.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/Dialect/SCF/IR/SCF.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/IRMapping.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "stablehlo/dialect/ChloOps.h" // from @stablehlo +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +struct BufferizeJITExecuteOp + : public OpConversionPattern { + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + tf_framework::JITExecuteOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + Type result_ty = getTypeConverter()->convertType(op.getType()); + rewriter.replaceOpWithNewOp( + op, result_ty, adaptor.getOperands(), op->getAttrs()); + return success(); + } +}; + +} // namespace + +void populateExtraBufferizePatterns(ConversionTarget &target, + MLIRContext *context, + TypeConverter *converter, + RewritePatternSet *patterns) { + target.addLegalDialect(); + auto typesAreLegal = [converter](Operation *op) { + return converter->isLegal(op->getOperandTypes()) && + converter->isLegal(op->getResultTypes()); + }; + target.addDynamicallyLegalOp(typesAreLegal); + // clang-format off + patterns->add< + BufferizeJITExecuteOp + >(*converter, context); + // clang-format on +} + +void populateExtraBufferizeDialects(DialectRegistry ®istry) { + registry.insert(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/bufferize_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/bufferize_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..e232c2c3de972b8443faea4f6f3aa71f4fec67f3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/bufferize_pass.cc @@ -0,0 +1,58 @@ +/* Copyright 2022 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. +==============================================================================*/ + +// This file implements logic for translating mixed IR to buffer form. + +#include + +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Bufferization/Transforms/Bufferize.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" +#include "xla/mlir_hlo/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +#define GEN_PASS_DEF_KERNELGENFINALBUFFERIZEPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct KernelgenFinalBufferizePass + : public impl::KernelgenFinalBufferizePassBase< + KernelgenFinalBufferizePass> { + // Default alignment_ specified in passes.td + KernelgenFinalBufferizePass() = default; + + void runOnOperation() override { + mlir::PassManager pm(&getContext()); + pm.addPass(mlir::createFinalBufferizePass(/*alignment=*/64, + populateExtraBufferizeDialects, + populateExtraBufferizePatterns)); + (void)runPipeline(pm, getOperation()); + } +}; + +} // namespace + +std::unique_ptr> CreateKernelgenFinalBufferizePass() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/copy_cleanup_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/copy_cleanup_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..5a7320659be6f1073911d75bf7733d3cc8c14506 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/copy_cleanup_pass.cc @@ -0,0 +1,177 @@ +/* Copyright 2021 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 + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallPtrSet.h" +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { +#define GEN_PASS_DEF_COPYCLEANUPPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +// A pass to remove memref::AllocOps and memref::CopyOps ops. +// +// The idea behind this pass is to collect all patterns we are interested in in +// a single place. Eventually, this should be replaced by a generalized copy +// removal pass. + +// Handles the pattern where an input operand of a linalg generic is copied +// even though the producer is not mutated. +void RemoveCopyIfTargetOnlyRead(func::FuncOp func) { + llvm::SmallVector allocs_to_remove; + llvm::SmallVector copies_to_remove; + + // Gather all allocs and copies which are only read and have an immutable + // source. + func->walk([&](memref::AllocOp op) { + memref::CopyOp copy; + MemoryEffectOpInterface reader; + bool at_most_one_copy = true; + bool at_most_one_read = true; + for (auto user : op->getUsers()) { + if (auto copy_user = dyn_cast(user)) { + if (copy) { + at_most_one_copy = false; + } else { + copy = copy_user; + } + continue; + } + if (auto effect_interface = dyn_cast(user)) { + if (reader) { + at_most_one_read = false; + } else { + reader = effect_interface; + } + SmallVector effects; + effect_interface.getEffectsOnValue(op.getResult(), effects); + if (llvm::any_of(effects, [](MemoryEffects::EffectInstance it) { + return !isa(it.getEffect()); + })) { + at_most_one_read = false; + } + continue; + } + // We don't understand this use, be conservative. + at_most_one_read = false; + } + if (!copy || !at_most_one_copy) return; + if (!reader || !at_most_one_read) return; + // The copy should have the alloc op as target. + if (copy.getTarget() != op.getResult()) return; + + // The copy should be before the reading use. + if (copy->getBlock() != reader->getBlock() || + !copy->isBeforeInBlock(reader)) { + return; + } + + // No write effects between copy and use. With aliasing information, this + // could be made more precise but for now we have to be conservative. The + // only thing we allow are writes to values that are allocated after the + // copy, as the aliasing is clear in those cases. + bool source_is_mutated = false; + for (Operation *pos = copy->getNextNode(), *end = reader; pos != end; + pos = pos->getNextNode()) { + auto effect_interface = dyn_cast(pos); + if (!effect_interface) { + continue; + } + SmallVector effects; + effect_interface.getEffects(effects); + for (auto effect : effects) { + if (effect.getValue() != nullptr) { + if (auto alloc = effect.getValue().getDefiningOp()) { + if (alloc->getBlock() == copy->getBlock() && + copy->isBeforeInBlock(alloc)) { + continue; + } + } + } + source_is_mutated = true; + break; + } + } + if (source_is_mutated) return; + + op->replaceAllUsesWith(ValueRange{copy.getSource()}); + allocs_to_remove.push_back(op); + copies_to_remove.push_back(copy); + }); + llvm::for_each(allocs_to_remove, [](Operation *op) { op->erase(); }); + llvm::for_each(copies_to_remove, [](Operation *op) { op->erase(); }); +} + +// Handles the case where the last instructions of a function implements a copy +// back to a function argument. +void RemoveCopyIfTargetIsFunctionArg(func::FuncOp func) { + // For now only support this on functions with a single block. + if (!func.getBody().hasOneBlock()) return; + + llvm::SmallVector allocs_to_remove; + llvm::SmallVector copies_to_remove; + + Block &body = func.getBody().front(); + for (auto &op : llvm::reverse(body.without_terminator())) { + if (auto copy = dyn_cast(op)) { + auto block_arg = mlir::dyn_cast(copy.getTarget()); + if (!block_arg) break; + if (!isa(block_arg.getOwner()->getParentOp()) || + !block_arg.hasOneUse()) + break; + auto alloc = copy.getSource().getDefiningOp(); + if (!alloc) break; + alloc->replaceAllUsesWith(ValueRange{block_arg}); + allocs_to_remove.push_back(alloc); + copies_to_remove.push_back(copy); + continue; + } + break; + } + llvm::for_each(allocs_to_remove, [](Operation *op) { op->erase(); }); + llvm::for_each(copies_to_remove, [](Operation *op) { op->erase(); }); +} + +} // namespace + +struct CopyCleanupPass : public impl::CopyCleanupPassBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + } + + void runOnOperation() override { + RemoveCopyIfTargetOnlyRead(getOperation()); + RemoveCopyIfTargetIsFunctionArg(getOperation()); + } +}; + +std::unique_ptr> CreateCopyCleanupPass() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/embed_tf_framework.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/embed_tf_framework.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5beb54fe2c9c2b08bc8b6f4140fbe92b686f603 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/embed_tf_framework.cc @@ -0,0 +1,199 @@ +/* Copyright 2020 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 + +#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/TypeRange.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { +namespace { + +// Prepends argument type list of the function with an OpKernelContextType arg. +class FuncOpConverter : public OpConversionPattern { + public: + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + func::FuncOp func, OpAdaptor /*adaptor*/, + ConversionPatternRewriter &rewriter) const override { + // Convert function arguments using the provided TypeConverter. + auto func_type = func.getFunctionType(); + TypeConverter::SignatureConversion conversion(func_type.getNumInputs()); + + conversion.addInputs(OpKernelContextType::get(rewriter.getContext())); + for (auto arg_type : llvm::enumerate(func_type.getInputs())) { + conversion.addInputs(arg_type.index(), arg_type.value()); + } + + rewriter.applySignatureConversion(&func.getBody().front(), conversion); + + // Update the signature of the function. + rewriter.modifyOpInPlace(func, [&] { + func.setType(rewriter.getFunctionType(conversion.getConvertedTypes(), + func_type.getResults())); + }); + return success(); + } +}; + +std::optional FindOpKernelContext(Operation *op) { + auto func = op->getParentOfType(); + if (func.getNumArguments() == 0) { + return std::nullopt; + } + Value ctx = func.getArgument(0); + if (!mlir::isa(ctx.getType())) { + return std::nullopt; + } + return ctx; +} + +// Converts std.alloc to tf_framework.alloc_raw using OpKernelContextType arg of +// the parent function. +struct AllocOpConverter : public OpConversionPattern { + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + memref::AllocOp alloc, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + std::optional ctx = FindOpKernelContext(alloc); + if (!ctx) return failure(); + + // Symbolic operands that bind to the symbols of the memref's layout map are + // not supported by TFAllocOp. + if (!alloc.getSymbolOperands().empty()) { + return failure(); + } + auto reuse_input_candidates = alloc->getAttrOfType( + TFAllocOp::kReuseInputCandidatesAttrName); + auto reuse_output_index = + alloc->getAttrOfType(TFAllocOp::kReuseOutputAttrName); + Value buffer = rewriter.replaceOpWithNewOp( + alloc, alloc.getType(), *ctx, adaptor.getOperands(), + reuse_input_candidates, reuse_output_index); + Location loc = buffer.getLoc(); + Value cond = IsValidMemRefOp::create(rewriter, loc, + rewriter.getIntegerType(1), buffer); + TFAssertOp::create(rewriter, loc, *ctx, cond, ErrorCode::RESOURCE_EXHAUSTED, + "failed to allocate memory"); + return success(); + } +}; + +// Converts std.dealloc to tf_framework.dealloc_raw using OpKernelContextType +// arg of the parent function. +struct DeallocOpConverter : public OpConversionPattern { + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + memref::DeallocOp dealloc, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + std::optional ctx = FindOpKernelContext(dealloc); + if (!ctx) return failure(); + + // Operand with no layout is expected. + auto operand_memref_type = + mlir::cast(dealloc.getMemref().getType()); + if (!operand_memref_type.getLayout().isIdentity()) { + return failure(); + } + rewriter.replaceOpWithNewOp(dealloc, *ctx, + adaptor.getMemref()); + return success(); + } +}; + +// Converts std.assert to tf_framework.assert with using OpKernelContextType +// arg of the parent function. +struct AssertOpConverter : public OpConversionPattern { + public: + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + cf::AssertOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + std::optional ctx = FindOpKernelContext(op); + if (!ctx) return failure(); + rewriter.replaceOpWithNewOp(op, *ctx, adaptor.getArg(), + ErrorCode::INVALID_ARGUMENT, + adaptor.getMsg()); + return success(); + } +}; + +// Amends `tf_framework.jit_execute` with the newly introduced OpKernelContext. +struct JITExecuteOpConverter : public OpConversionPattern { + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + JITExecuteOp op, OpAdaptor /*adaptor*/, + ConversionPatternRewriter &rewriter) const override { + std::optional ctx = FindOpKernelContext(op); + if (!ctx) return failure(); + rewriter.replaceOpWithNewOp( + op, op.getResult().getType(), *ctx, op.getCallable(), op.getInputs()); + return success(); + } +}; + +// Amends `tf_framework.jit_compile_from_str` with the newly introduced +// OpKernelContext. +struct JITCompileFromStrOpConverter + : public OpConversionPattern { + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + JITCompileFromStrOp op, OpAdaptor /*adaptor*/, + ConversionPatternRewriter &rewriter) const override { + std::optional ctx = FindOpKernelContext(op); + if (!ctx) return failure(); + rewriter.replaceOpWithNewOp( + op, rewriter.getType(), *ctx, op->getAttrs()); + return success(); + } +}; + +} // namespace + +void PopulateEmbedTFFrameworkAssertPattern(RewritePatternSet *patterns) { + patterns->add(patterns->getContext()); +} + +void PopulateEmbedTFFrameworkPatterns(RewritePatternSet *patterns) { + // clang-format off + patterns->add< + AllocOpConverter, + AssertOpConverter, + DeallocOpConverter, + FuncOpConverter, + JITCompileFromStrOpConverter, + JITExecuteOpConverter>(patterns->getContext()); + // clang-format on +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/embed_tf_framework_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/embed_tf_framework_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..4c1975d683d63a51b8e4130f5b2ab8399c798d41 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/embed_tf_framework_pass.cc @@ -0,0 +1,98 @@ +/* Copyright 2020 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 +#include + +#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { +namespace { + +#define GEN_PASS_DEF_EMBEDTFFRAMEWORKPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +bool IsNotInsideTfEntryFunction(Operation* op) { + auto func = op->getParentOfType(); + return !func->hasAttrOfType(TFFrameworkDialect::kTFEntryAttrName); +} + +template +bool HasInitializedOpKernelContextOperand(OpTy op) { + return op.getCtx() != nullptr; +} + +// The pass rewrites the function marked with `tf_entry` attribute. +// * adds tf_framework::OpKernelContextType argument to the function, +// * std.alloc becomes tf_framework.alloc_raw, +// * std.dealloc becomes tf_framework.dealloc_raw. +class EmbedTFFrameworkPass + : public impl::EmbedTFFrameworkPassBase { + void getDependentDialects(DialectRegistry& registry) const override { + registry.insert(); + } + + public: + void runOnOperation() override { + ModuleOp m = getOperation(); + + // Populate patterns. + RewritePatternSet patterns(&getContext()); + PopulateEmbedTFFrameworkPatterns(&patterns); + + // Set target. + ConversionTarget target(getContext()); + target.addLegalDialect(); + + target.addDynamicallyLegalOp([&](func::FuncOp op) { + if (!op->hasAttrOfType(TFFrameworkDialect::kTFEntryAttrName)) { + return true; + } + FunctionType func_type = op.getFunctionType(); + return func_type.getNumInputs() > 0 && + mlir::isa(func_type.getInput(0)); + }); + target.addDynamicallyLegalOp(IsNotInsideTfEntryFunction); + target.addDynamicallyLegalOp( + &HasInitializedOpKernelContextOperand); + target.addDynamicallyLegalOp( + &HasInitializedOpKernelContextOperand); + + if (failed(applyPartialConversion(m, target, std::move(patterns)))) { + signalPassFailure(); + } + } +}; + +} // namespace + +std::unique_ptr > CreateEmbedTFFrameworkPass() { + return std::make_unique(); +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/func_to_jit_invocations.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/func_to_jit_invocations.cc new file mode 100644 index 0000000000000000000000000000000000000000..17008d96138c10ba7b2d333d7424749212411383 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/func_to_jit_invocations.cc @@ -0,0 +1,275 @@ +/* Copyright 2021 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 +#include +#include +#include + +#include "mlir/Dialect/SCF/IR/SCF.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project +#include "mlir/IR/Block.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/IRMapping.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OperationSupport.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/IR/TypeRange.h" // from @llvm-project +#include "mlir/IR/Visitors.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +constexpr llvm::StringRef + mlir::kernel_gen::tf_framework ::JITCompileFromStrOp::kJITEntryFunctionName; + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +constexpr int64_t i32Limit = 2147483647; +using func::FuncOp; +using shape::ShapeOfOp; + +LogicalResult RewriteToFullJit(func::FuncOp op) { + // Rewrite all functions that have a single result. + if (op.getResultTypes().size() != 1) return failure(); + + IRRewriter rewriter(op.getContext()); + + // Insert a new block at the front of the function. + Block *old_body = &op.getFunctionBody().front(); + Location loc = op.getLoc(); + llvm::SmallVector locs(old_body->getNumArguments(), loc); + Block *new_body = rewriter.createBlock(&op.getBody(), op.getBody().begin(), + old_body->getArgumentTypes(), locs); + + // Create the JIT compile op. + auto jit_compile_op = tf_framework::JITCompileOp::create( + rewriter, loc, rewriter.getType(), + /*ctx=*/mlir::Value()); + + // Move the original functions operations into the body. + { + OpBuilder::InsertionGuard guard(rewriter); + Block *jit_block = rewriter.createBlock(&jit_compile_op.getBody(), {}, + old_body->getArgumentTypes(), locs); + + rewriter.inlineBlockBefore(old_body, jit_block, jit_block->begin(), + jit_block->getArguments()); + + Operation *terminator = jit_block->getTerminator(); + rewriter.setInsertionPointAfter(terminator); + tf_framework::JITCompileYieldOp::create(rewriter, loc, + terminator->getOperands().front()); + terminator->erase(); + } + + // Create JIT execute op. + auto execute = tf_framework::JITExecuteOp::create( + rewriter, loc, op.getResultTypes().front(), /*ctx=*/Value(), + jit_compile_op.getResult(), new_body->getArguments()); + + // Create a return. + func::ReturnOp::create(rewriter, loc, execute.getResult()); + return success(); +} + +LogicalResult RewriteToLargeSizeJit(FuncOp op) { + // Rewrite all functions that have at most two arguments and a single result. + if (op.getArgumentTypes().size() > 2 || op.getResultTypes().size() != 1) + return failure(); + + IRRewriter rewriter(op.getContext()); + Location loc = op.getLoc(); + + // Insert a new block at the front of the function. + Block *old_body = &op.getFunctionBody().front(); + llvm::SmallVector locs(old_body->getNumArguments(), loc); + Block *new_body = rewriter.createBlock(&op.getBody(), op.getBody().begin(), + old_body->getArgumentTypes(), locs); + + // Create large argument condition. + auto arg_1 = new_body->getArgument(0); + auto shape_1 = shape::ShapeOfOp::create(rewriter, loc, arg_1); + auto num_elems_1 = shape::NumElementsOp::create(rewriter, loc, shape_1); + Value cst_i32_limit = arith::ConstantIndexOp::create(rewriter, loc, i32Limit); + Value large_tensor_predicate = arith::CmpIOp::create( + rewriter, loc, arith::CmpIPredicate::sgt, num_elems_1, cst_i32_limit); + if (new_body->getNumArguments() > 1) { + auto arg_2 = new_body->getArgument(1); + auto shape_2 = shape::ShapeOfOp::create(rewriter, loc, arg_2); + auto num_elems_2 = shape::NumElementsOp::create(rewriter, loc, shape_2); + large_tensor_predicate = arith::OrIOp::create( + rewriter, loc, large_tensor_predicate, + // Compare op to check size of the second op + arith::CmpIOp::create(rewriter, loc, arith::CmpIPredicate::sgt, + num_elems_2, cst_i32_limit)); + } + + // Create dispatch code. + auto jit_body_builder_fn = [&](OpBuilder &b, Location loc) { + // Create JIT compile op. + auto callable_ty = b.getType(); + auto jit_compile_op = tf_framework::JITCompileOp::create( + b, loc, callable_ty, /*ctx=*/Value()); + { + OpBuilder::InsertionGuard g(b); + Block *block = b.createBlock( + &jit_compile_op.getBody(), {}, new_body->getArgumentTypes(), + SmallVector(new_body->getNumArguments(), loc)); + b.setInsertionPointToStart(block); + IRMapping bvm; + bvm.map(old_body->getArguments(), block->getArguments()); + for (auto &op : old_body->without_terminator()) { + b.clone(op, bvm); + } + tf_framework::JITCompileYieldOp::create( + b, loc, block->back().getResults().front()); + } + + // Create JIT execute op. + auto jit_execute_op = tf_framework::JITExecuteOp::create( + b, loc, op.getResultTypes().front(), /*ctx=*/Value(), + jit_compile_op.getResult(), new_body->getArguments()); + scf::YieldOp::create(b, loc, jit_execute_op.getResult()); + }; + auto aot_body_builder_fn = [&](OpBuilder &b, Location loc) { + IRMapping bvm; + bvm.map(old_body->getArguments(), new_body->getArguments()); + Operation *last_clone; + for (auto &op : old_body->without_terminator()) { + last_clone = b.clone(op, bvm); + } + scf::YieldOp::create(b, loc, last_clone->getResults().front()); + }; + + // Create the conditional and return operation. + auto ifOp = scf::IfOp::create(rewriter, loc, large_tensor_predicate, + jit_body_builder_fn, aot_body_builder_fn); + func::ReturnOp::create(rewriter, loc, ifOp.getResults().front()); + + // Remove the old body. + rewriter.eraseBlock(old_body); + return success(); +} + +void PackJITCompileOp(tf_framework::JITCompileOp op, + llvm::ArrayRef tile_sizes, + llvm::ArrayRef unroll_factors, bool enable_ftz, + bool index_64bit, bool cpu_codegen) { + IRRewriter rewriter(op.getContext()); + Block *body = op.SingleBlock::getBody(); + auto yield_op = + llvm::cast(body->getTerminator()); + + // Temporarily, build the module that would be JIT-compiled. This is only to + // obtain the serialized code attribute. + auto loc = op->getLoc(); + auto jit_module = ModuleOp::create(rewriter, loc); + { + OpBuilder::InsertionGuard g(rewriter); + rewriter.setInsertionPointToStart(jit_module.SingleBlock::getBody()); + auto jit_function = func::FuncOp::create( + rewriter, loc, tf_framework::JITCompileFromStrOp::kJITEntryFunctionName, + rewriter.getFunctionType(body->getArgumentTypes(), + yield_op->getOperandTypes())); + jit_function->setAttr(tf_framework::TFFrameworkDialect::kTFEntryAttrName, + rewriter.getUnitAttr()); + jit_function.getBody().takeBody(op.getBodyRegion()); + rewriter.setInsertionPointToEnd(&jit_function.getBody().front()); + func::ReturnOp::create(rewriter, loc, yield_op.getResult()); + rewriter.eraseOp(yield_op); + } + + // Serialize JIT module. + std::string code; + llvm::raw_string_ostream ss(code); + assert(succeeded(jit_module.verify())); + mlir::OpPrintingFlags flags; + jit_module.print(ss, flags.assumeVerified()); + + // Remove temporary module. + rewriter.eraseOp(jit_module); + + // Finally, create the new JIT compile op. + rewriter.setInsertionPointAfter(op); + rewriter.replaceOpWithNewOp( + op, op->getResultTypes(), op.getCtx(), rewriter.getStringAttr(code), + rewriter.getI64ArrayAttr(tile_sizes), + rewriter.getI64ArrayAttr(unroll_factors), + rewriter.getBoolAttr(enable_ftz), rewriter.getBoolAttr(index_64bit), + rewriter.getBoolAttr(cpu_codegen)); +} + +#define GEN_PASS_DEF_FUNCTOJITINVOCATIONPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct FuncToJITInvocationPass + : public impl::FuncToJITInvocationPassBase { + explicit FuncToJITInvocationPass(llvm::ArrayRef tile_sizes, + llvm::ArrayRef unroll_factors, + bool enable_ftz, bool index_64bit, + bool cpu_codegen, + bool jit_i64_indexed_for_large_tensors) { + tile_sizes_ = tile_sizes; + unroll_factors_ = unroll_factors; + enable_ftz_ = enable_ftz; + index_64bit_ = index_64bit; + cpu_codegen_ = cpu_codegen; + jit_i64_indexed_for_large_tensors_ = jit_i64_indexed_for_large_tensors; + } + + void runOnOperation() override { + if (jit_i64_indexed_for_large_tensors_) { + if (failed(RewriteToLargeSizeJit(getOperation()))) { + return signalPassFailure(); + } + } else { + if (failed(RewriteToFullJit(getOperation()))) { + return signalPassFailure(); + } + } + + getOperation().walk([&](tf_framework::JITCompileOp op) { + PackJITCompileOp(op, tile_sizes_, unroll_factors_, enable_ftz_, + index_64bit_ || jit_i64_indexed_for_large_tensors_, + cpu_codegen_); + }); + } +}; + +} // namespace + +std::unique_ptr> CreateFuncToJITInvocationPass( + llvm::ArrayRef tile_sizes, llvm::ArrayRef unroll_factors, + bool enable_ftz, bool index_64bit, bool cpu_codegen, + bool jit_i64_indexed_for_large_tensors) { + return std::make_unique( + tile_sizes, unroll_factors, enable_ftz, index_64bit, cpu_codegen, + jit_i64_indexed_for_large_tensors); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/fuse_inner_parallel_loops_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/fuse_inner_parallel_loops_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..b47847700faccfeec9de0ed38dce0c657ba72113 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/fuse_inner_parallel_loops_pass.cc @@ -0,0 +1,54 @@ +/* Copyright 2020 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 + +#include "mlir/Analysis/AliasAnalysis.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/SCF/IR/SCF.h" // from @llvm-project +#include "mlir/Dialect/SCF/Transforms/Transforms.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +#define GEN_PASS_DEF_FUSEINNERPARALLELLOOPSPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct FuseInnerParallelLoopsPass + : impl::FuseInnerParallelLoopsPassBase { + void runOnOperation() override { + auto &alias_analysis = getAnalysis(); + auto may_alias = [&](Value val1, Value val2) -> bool { + return !alias_analysis.alias(val1, val2).isNo(); + }; + getOperation().walk([&](mlir::scf::ParallelOp op) { + mlir::scf::naivelyFuseParallelOps(op.getRegion(), may_alias); + }); + } +}; + +} // namespace + +std::unique_ptr> +CreateFuseInnerParallelLoopsPass() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/gpu_kernel_to_blob_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/gpu_kernel_to_blob_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..4e96dbe8e6070fc42e4ef80831ce3173dcf3fb5c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/gpu_kernel_to_blob_pass.cc @@ -0,0 +1,250 @@ +/* Copyright 2020 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 +#include +#include +#include +#include +#include + +#include "llvm/TargetParser/Triple.h" +#include "llvm/Transforms/Utils/Cloning.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Target/LLVMIR/Export.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "xla/debug_options_flags.h" +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/service/gpu/gpu_asm_opts_util.h" +#include "xla/service/gpu/target_constants.h" +#include "xla/stream_executor/device_description.h" +#include "xla/xla.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/path.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/statusor.h" + +#if GOOGLE_CUDA +#include "xla/service/gpu/llvm_gpu_backend/nvptx_backend.h" +#include "xla/stream_executor/cuda/cuda_asm_compiler.h" +#elif TENSORFLOW_USE_ROCM +#include "xla/service/gpu/llvm_gpu_backend/amdgpu_backend.h" +#include "xla/stream_executor/gpu/asm_compiler.h" +#include "tensorflow/core/platform/rocm_rocdl_path.h" +#endif + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +#define GEN_PASS_DEF_GPUKERNELTOBLOBPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +class GpuKernelToBlobPass + : public impl::GpuKernelToBlobPassBase { + public: + GpuKernelToBlobPass(StringRef blob_annotation, + llvm::ArrayRef architectures, bool print_ptx, + bool print_llvmir, bool enable_ftz) { + if (!blob_annotation.empty()) blob_annotation_ = blob_annotation.str(); + architectures_ = architectures; + print_ptx_ = print_ptx; + print_llvmir_ = print_llvmir; + enable_ftz_ = enable_ftz; + } + + void runOnOperation() override { + gpu::GPUModuleOp gpu_module = getOperation(); + auto blob_or = GetGpuBinaryBlob(gpu_module); + if (blob_or.ok()) { + const auto& blob = blob_or.value(); + std::string blob_string(blob.begin(), blob.end()); + gpu_module->setAttr(blob_annotation_, + StringAttr::get(&getContext(), blob_string)); + return; + } + // Forward the error by attaching the message to the gpu module. + gpu_module.emitError(blob_or.status().message()); + return signalPassFailure(); + } + + absl::StatusOr> GetGpuBinaryBlob( + gpu::GPUModuleOp gpu_module) { + if (architectures_.empty()) { + return absl::InternalError("Expected at least one GPU architecture."); + } + + // Lower to LLVM module. + llvm::LLVMContext llvmContext; + auto llvmModule = translateModuleToLLVMIR(gpu_module, llvmContext); + if (!llvmModule) { + return absl::InternalError("Could not translate MLIR module to LLVM IR"); + } + llvmModule->setModuleIdentifier(gpu_module.getName()); + +#if TENSORFLOW_USE_ROCM + xla::DebugOptions options = xla::GetDebugOptionsFromFlags(); + options.set_xla_gpu_ftz(enable_ftz_); + options.set_xla_gpu_dump_llvmir(print_llvmir_); + + using AmdGpuHsaco = std::vector; + std::vector images; + images.reserve(architectures_.size()); + for (const std::string& arch_str : architectures_) { + // Parse ROCm architecture. + absl::string_view consumable_arch(arch_str); + if (!absl::ConsumePrefix(&consumable_arch, "gfx")) { + return tensorflow::errors::Internal( + "Could not parse ROCm architecture prefix (expected gfx)"); + } + auto llvm_module_copy = llvm::CloneModule(*llvmModule); + auto hsaco_or = xla::gpu::amdgpu::CompileToHsaco( + llvm_module_copy.get(), + tensorflow::se::RocmComputeCapability{arch_str}, options, + options.DebugString()); + if (!hsaco_or.ok()) { + return tensorflow::errors::Internal("Failure when generating HSACO"); + } + auto hsaco = hsaco_or.value(); + images.push_back({arch_str, std::move(hsaco)}); + } + + // TODO(b/169870789): Revisit the use of fatbins. + // Bundle HSACO images into a single fatbin. + if (images.size() == 1) return images.front().bytes; + return tensorflow::se::BundleGpuAsm(images, tensorflow::RocmRoot()); + +#elif GOOGLE_CUDA + xla::DebugOptions options = xla::GetDebugOptionsFromFlags(); + options.set_xla_gpu_ftz(enable_ftz_); + options.set_xla_gpu_dump_llvmir(print_llvmir_); + // Make sure we use full precision division operations. + (*options.mutable_xla_backend_extra_options())["-nvptx-prec-divf32"] = "2"; + // Disable tail sinking as it interferes with load/store vectorization. If + // we have common tails that is intentional. + (*options.mutable_xla_backend_extra_options())["-simplifycfg-sink-common"] = + "false"; + + llvmModule->setDataLayout(xla::gpu::nvptx::DataLayout()); + llvmModule->setTargetTriple(llvm::Triple(xla::gpu::nvptx::TargetTriple())); + + // Compile and collect requested cubin and PTX images. + std::vector images; + auto gpu_asm_opts = xla::gpu::PtxOptsFromDebugOptions(options); + for (const std::string& arch_str : architectures_) { + TF_ASSIGN_OR_RETURN(auto arch_pair, ParseCudaArch(arch_str)); + bool is_compute_profile = arch_pair.first; + int arch = arch_pair.second; + int cc_major = arch / 10; + int cc_minor = arch % 10; + tensorflow::se::CudaComputeCapability cc{cc_major, cc_minor}; + + // Generate PTX code. + // Module may be changed by CompileToPtx. + auto llvm_module_copy = llvm::CloneModule(*llvmModule); + auto enable_fusion = [](llvm::TargetMachine* target) { + target->Options.AllowFPOpFusion = + llvm::FPOpFusion::FPOpFusionMode::Fast; + }; + TF_ASSIGN_OR_RETURN( + std::string ptx, + xla::gpu::nvptx::CompileToPtx( + llvm_module_copy.get(), stream_executor::GpuComputeCapability(cc), + options, enable_fusion)); + if (print_ptx_) { + llvm::dbgs() << "Generated PTX code for module '" + << gpu_module.getName() << "' on architecture sm_" << arch + << ":\n"; + llvm::dbgs() << ptx << "\n"; + } + + // Compile PTX code with ptxas if requested and possible and fall back to + // a compute image, otherwise. + if (!is_compute_profile) { + auto gpu_asm = tensorflow::se::CompileGpuAsm(cc, ptx, gpu_asm_opts); + if (gpu_asm.ok()) { + images.push_back({/*is_ptx=*/false, cc, std::move(gpu_asm.value())}); + } else { +#ifdef PLATFORM_GOOGLE + // Require compilation with ptxas. + return gpu_asm; +#else + // Fall back to compilation by driver in OSS. + LOG(WARNING) << "Failed to compile generated PTX with ptxas. Falling " + "back to compilation by driver."; + is_compute_profile = true; +#endif + } + } + if (is_compute_profile) { + std::vector ptx_bytes; + ptx_bytes.reserve(ptx.size() + 1); + std::copy(ptx.begin(), ptx.end(), std::back_inserter(ptx_bytes)); + ptx_bytes.push_back('\0'); + images.push_back({/*is_ptx=*/true, cc, std::move(ptx_bytes)}); + } + } + + // TODO(b/169870789): Revisit the use of fatbins. + // Bundle cubin and PTX images into a single fatbin if needed. + if (images.size() == 1) return images.front().bytes; + return tensorflow::se::BundleGpuAsm(images, gpu_asm_opts); + +#else + return tensorflow::errors::Internal( + "Neither TENSORFLOW_USE_ROCM nor GOOGLE_CUDA are defined." + " Did you specify either --config=rocm or --config=cuda ?"); +#endif + } + + private: + absl::StatusOr> ParseCudaArch( + const std::string& arch_str) { + absl::string_view consumable_arch(arch_str); + bool is_compute_profile; + if (absl::ConsumePrefix(&consumable_arch, "compute_")) { + is_compute_profile = true; + } else if (absl::ConsumePrefix(&consumable_arch, "sm_")) { + is_compute_profile = false; + } else { + return absl::InternalError( + "Could not parse cuda architecture prefix (expected sm_ or " + "compute_)"); + } + int arch; + if (!absl::SimpleAtoi(consumable_arch, &arch)) { + return absl::InternalError("Could not parse cuda architecture number"); + } + return std::pair(is_compute_profile, arch); + } + + bool enable_ftz_; +}; + +} // namespace + +std::unique_ptr> CreateGpuKernelToBlobPass( + StringRef blob_annotation, ArrayRef architectures, + bool print_ptx, bool print_llvmir, bool enable_ftz) { + return std::make_unique( + blob_annotation, architectures, print_ptx, print_llvmir, enable_ftz); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/legalize_tensor_reshape_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/legalize_tensor_reshape_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..cc7674fb5b58681991dae31febb39fe4f2404eeb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/legalize_tensor_reshape_pass.cc @@ -0,0 +1,73 @@ +/* Copyright 2025 The OpenXLA Authors. + +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 +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OperationSupport.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" + +namespace mlir { +namespace kernel_gen { + +#define GEN_PASS_DEF_LEGALIZETENSORRESHAPEPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +namespace { + +struct LegalizeTensorReshapePattern + : public OpRewritePattern { + explicit LegalizeTensorReshapePattern(MLIRContext* context) + : OpRewritePattern(context) {} + + LogicalResult matchAndRewrite(tensor::ReshapeOp op, + PatternRewriter& rewriter) const override { + rewriter.replaceOpWithNewOp(op, op.getResultType(), + op.getOperands()); + return success(); + } +}; + +} // namespace + +struct LegalizeTensorReshapePass + : public impl::LegalizeTensorReshapePassBase { + void getDependentDialects(DialectRegistry& registry) const override { + registry.insert(); + } + + void runOnOperation() override { + MLIRContext* ctx = &getContext(); + RewritePatternSet patterns(ctx); + patterns.add(ctx); + GreedyRewriteConfig config; + config.setMaxIterations(GreedyRewriteConfig::kNoLimit); + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns), + config))) { + return signalPassFailure(); + } + } +}; + +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/merge_assuming_ops_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/merge_assuming_ops_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6fbe842719c924dc747d6a924619eae77aebe18 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/merge_assuming_ops_pass.cc @@ -0,0 +1,476 @@ +/* Copyright 2021 The OpenXLA Authors. + +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 +#include +#include +#include + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project +#include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project +#include "mlir/IR/Block.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/IRMapping.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OpDefinition.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/OperationSupport.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Interfaces/InferTypeOpInterface.h" // from @llvm-project +#include "mlir/Interfaces/SideEffectInterfaces.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "stablehlo/dialect/Base.h" // from @stablehlo +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" + +namespace mlir { +namespace kernel_gen { + +#define GEN_PASS_DEF_MERGEASSUMINGOPSPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +namespace { + +struct ShapeReificationPattern : public OpRewritePattern { + explicit ShapeReificationPattern(MLIRContext *context) + : OpRewritePattern(context) { + // Recursively reify until we hit an op that doesn't support it. + setHasBoundedRewriteRecursion(); + } + + LogicalResult matchAndRewrite(shape::ShapeOfOp op, + PatternRewriter &rewriter) const override { + // Only reify shape computation if operand allows for it. + auto shapeOrigin = op.getArg().getDefiningOp(); + if (!shapeOrigin) return failure(); + + llvm::SmallVector reifications; + if (failed(shapeOrigin.reifyReturnTypeShapes( + rewriter, shapeOrigin->getOperands(), reifications))) + return failure(); + assert(reifications.size() == 1); + Value reifiedShape = reifications.front(); + + // Insert cast if needed. + if (reifiedShape.getType() != op.getType()) { + reifiedShape = tensor::CastOp::create(rewriter, op.getLoc(), op.getType(), + reifiedShape); + } + + rewriter.replaceOp(op, reifiedShape); + return success(); + } +}; + +template +struct InlineBroadcastedShapeOperandsPattern : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(OpTy op, + PatternRewriter &rewriter) const override { + // Find all the shape operands, direct and indirect. + SmallVector inlinedOperands; + for (Value direct : op->getOperands()) { + if (auto bcastOp = direct.getDefiningOp()) { + for (Value indirect : bcastOp->getOperands()) + inlinedOperands.push_back(indirect); + } else { + inlinedOperands.push_back(direct); + } + } + + // Only rewrite if it makes a difference. + if (inlinedOperands.size() == op.getNumOperands()) return failure(); + + // Inline shape operands. + rewriter.replaceOpWithNewOp(op, op->getResultTypes(), inlinedOperands, + op->getAttrs()); + return success(); + } +}; + +LogicalResult moveUpIntoAssumingOpMatchAndRewrite(Operation *op, + PatternRewriter &rewriter) { + // Only implemented for single-result ops. + if (op->getNumResults() != 1) return failure(); + + // Find a preceding `assuming` op. + auto *theBlock = op->getBlock(); + Operation *prev = op->getPrevNode(); + while (prev != nullptr && !llvm::isa(prev)) + prev = prev->getPrevNode(); + auto assumingOp = llvm::dyn_cast_or_null(prev); + if (!assumingOp) return failure(); + assert(assumingOp->getBlock() == theBlock && op->getBlock() == theBlock && + "expect assuming op and root op to be in the same block"); + + // Make sure that all operands will be available after moving. + auto isAvailable = [&](Value v) { + Operation *def = v.getDefiningOp(); + return def == nullptr || def->getBlock() != theBlock || + !assumingOp->isBeforeInBlock(def); + }; + if (!llvm::all_of(op->getOperands(), isAvailable)) return failure(); + + Block *body = assumingOp.getBody(); + auto yieldOp = llvm::cast(body->getTerminator()); + + // Find the operands to use if the op was within the assuming region. We + // will later use their copies, as we copy the assuming op and its body. + SmallVector newOperandsUnmapped = + llvm::to_vector<8>(llvm::map_range(op->getOperands(), [&](Value v) { + for (const auto &result : llvm::enumerate(assumingOp->getResults())) { + if (result.value() == v) return yieldOp->getOperand(result.index()); + } + return v; + })); + + // Insert the rewritten assuming op right before the old one. + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPoint(assumingOp); + auto newAssumingOp = shape::AssumingOp::create( + rewriter, assumingOp.getLoc(), assumingOp.getWitness(), + [&](OpBuilder& b, Location) { + // Copy body. + IRMapping mapping; + for (auto &nested : body->without_terminator()) + b.clone(nested, mapping); + + // Copy op into the new body and use the mapped operands. + for (auto it : llvm::zip(op->getOperands(), newOperandsUnmapped)) { + Value oldOperand, newOperandUnmapped; + std::tie(oldOperand, newOperandUnmapped) = it; + mapping.map(oldOperand, mapping.lookupOrDefault(newOperandUnmapped)); + } + Operation *newOp = b.clone(*op, mapping); + + // Yield the previous results and also the new ones. + auto mappedResults = llvm::to_vector<8>(llvm::map_range( + yieldOp.getOperands(), + [&](Value v) { return mapping.lookupOrDefault(v); })); + mappedResults.append(newOp->getResults().begin(), + newOp->getResults().end()); + return mappedResults; + }); + + // Replace the assuming op and the root op with the corresponding result + // values. + ValueRange newAssumingOpResults = newAssumingOp->getResults(); + rewriter.replaceOp(assumingOp, newAssumingOpResults.drop_back()); + rewriter.replaceOp(op, newAssumingOpResults.back()); + return success(); +} + +/// Move operation into a preceding assuming op. This allows to process +/// operations that depend on the assuming op's results. It will eventually +/// allow to make assuming regions' constraints independent from each other. +template +struct MoveUpIntoAssumingOpPattern : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(OpTy op, + PatternRewriter &rewriter) const override { + return moveUpIntoAssumingOpMatchAndRewrite(op.getOperation(), rewriter); + } +}; + +// Move elementwise operations into a preceding assuming op. This will +// eventually allow for more fusion opportunities. +struct MoveElementwiseOpsUpIntoAssumingOpPattern : public RewritePattern { + explicit MoveElementwiseOpsUpIntoAssumingOpPattern(MLIRContext *ctx) + : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, ctx) {} + + LogicalResult matchAndRewrite(Operation *op, + PatternRewriter &rewriter) const override { + // Apply to all elementwise and broadcasting elementwise operations with no + // side effects. + if (!op->hasTrait() && + !op->hasTrait()) { + return failure(); + } + if (!isMemoryEffectFree(op)) return failure(); + + return moveUpIntoAssumingOpMatchAndRewrite(op, rewriter); + } +}; + +// Move operation into an assuming region if all uses are within its body. +LogicalResult moveDownIntoAssumingOpMatchAndRewrite(Operation *op, + PatternRewriter &rewriter) { + auto users = op->getUsers(); + auto it = users.begin(); + auto end = users.end(); + if (it == end) return failure(); + + // Find candidate assuming op. + auto assumingOp = (it++)->getParentOfType(); + if (!assumingOp || assumingOp->isProperAncestor(op)) return failure(); + + // Make sure all uses are within the unique assuming op's body. + while (it != end) { + auto hopefullySameAssumingOp = (it++)->getParentOfType(); + if (!hopefullySameAssumingOp || hopefullySameAssumingOp != assumingOp) { + return failure(); + } + } + + // Move op into the assuming region. + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPointToStart(assumingOp.getBody()); + Operation *newOp = rewriter.clone(*op); + rewriter.replaceOp(op, newOp->getResults()); + return success(); +} + +// Move elementwise operations into succeeding assuming regions. This will +// eventually allow for more fusion opportunities. +struct MoveElementwiseOpsDownIntoAssumingOpPattern : public RewritePattern { + explicit MoveElementwiseOpsDownIntoAssumingOpPattern(MLIRContext *ctx) + : RewritePattern(MatchAnyOpTypeTag(), /*benefit=*/1, ctx) {} + + LogicalResult matchAndRewrite(Operation *op, + PatternRewriter &rewriter) const override { + // Apply to all elementwise and broadcasting elementwise operations with no + // side effects. + if (!op->hasTrait() && + !op->hasTrait()) { + return failure(); + } + if (!isMemoryEffectFree(op)) return failure(); + + return moveDownIntoAssumingOpMatchAndRewrite(op, rewriter); + } +}; + +/// Move operation out of assuming op. This is only valid for +/// constraint-independent ops, like `cstr_broadcastable` and `shape_of`. It +/// will eventually allow to make assuming regions' constraints independent from +/// each other. +template +struct MoveUpOutOfAssumingOpPattern : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(OpTy op, + PatternRewriter &rewriter) const override { + // Must be inside of an assuming op. + auto assumingOp = op->template getParentOfType(); + if (!assumingOp) return failure(); + + // Operands must not be defined within the assuming op. + Block *body = assumingOp.getBody(); + auto isAvailable = [&](Value v) { + Operation *def = v.getDefiningOp(); + return def == nullptr || def->getBlock() != body; + }; + if (!llvm::all_of(op->getOperands(), isAvailable)) return failure(); + + // Move op before the assuming region. + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPoint(assumingOp); + Operation *newOp = rewriter.clone(*op); + rewriter.replaceOp(op, newOp->getResults()); + + // If the assuming region yields none of the new op's results, these values + // are exclusively used in the assuming op's body. In these cases there is + // no need for further rewrites. + auto isNewOpResult = [newOp](Value v) { + return llvm::is_contained(newOp->getResults(), v); + }; + auto yieldOp = cast(body->getTerminator()); + if (llvm::none_of(yieldOp.getOperands(), isNewOpResult)) return success(); + + // If the assuming region yields any of the new op's results, these values + // can instead bypass the assuming region. There is no need to yield them + // explicitly as they are assumed to be independent. The assuming op is + // rewritten accordingly. + SmallVector replacementValues; + auto newAssumingOp = shape::AssumingOp::create( + rewriter, assumingOp.getLoc(), assumingOp.getWitness(), + [&](OpBuilder& b, Location) { + // Copy body. + IRMapping mapping; + for (Operation &nested : body->without_terminator()) { + b.clone(nested, mapping); + } + + // Collect new yield operands. + SmallVector newYieldOperands; + for (Value result : yieldOp.getOperands()) { + if (isNewOpResult(result)) { + replacementValues.push_back(result); + } else { + newYieldOperands.push_back(mapping.lookupOrDefault(result)); + replacementValues.push_back(nullptr); + } + } + return newYieldOperands; + }); + + // Use the assuming op's results for the missing replacement values. + auto src = newAssumingOp.getResults().begin(); + for (auto &dst : replacementValues) { + if (dst) continue; + dst = *src++; + } + + rewriter.replaceOp(assumingOp, replacementValues); + return success(); + } +}; + +/// Merge assuming regions if their constraints are independent from each other. +struct MergeAssumingOpsPattern : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(shape::AssumingOp op, + PatternRewriter &rewriter) const override { + // Merge assuming op with directly preceding one if both witnesses are + // available. + auto precedingOp = + llvm::dyn_cast_or_null(op->getPrevNode()); + if (!precedingOp) return failure(); + if (op.getWitness().getDefiningOp() == precedingOp) return failure(); + + // Merge witnesses. + OpBuilder::InsertionGuard guard(rewriter); + rewriter.setInsertionPoint(precedingOp); + Value newWitness = shape::AssumingAllOp::create( + rewriter, op.getWitness().getDefiningOp()->getLoc(), + ValueRange{precedingOp.getWitness(), op.getWitness()}); + + // Merge assuming ops. + Block *body_a = precedingOp.getBody(); + Block *body_b = op.getBody(); + auto newAssumingOp = shape::AssumingOp::create( + rewriter, precedingOp.getLoc(), newWitness, + [&](OpBuilder& b, Location) { + // Copy preceding op's body. + IRMapping mapping; + for (auto &nested : body_a->without_terminator()) { + b.clone(nested, mapping); + } + + // Map result values of preceding assuming op. + auto yieldOpA = + llvm::dyn_cast(body_a->getTerminator()); + for (auto pair : + llvm::zip(precedingOp->getResults(), yieldOpA.getOperands())) { + mapping.map(std::get<0>(pair), + mapping.lookupOrDefault(std::get<1>(pair))); + } + + // Copy op's body. + for (auto &nested : body_b->without_terminator()) { + b.clone(nested, mapping); + } + + // Collect merged assuming op's results. + SmallVector mappedResults; + auto yieldOpB = + llvm::dyn_cast(body_b->getTerminator()); + for (Value v : yieldOpA.getOperands()) { + mappedResults.push_back(mapping.lookupOrDefault(v)); + } + for (Value v : yieldOpB.getOperands()) { + mappedResults.push_back(mapping.lookupOrDefault(v)); + } + return mappedResults; + }); + + // Replace the two assuming ops with the new corresponding results. + ValueRange newResults = newAssumingOp->getResults(); + size_t splitAt = precedingOp->getNumResults(); + rewriter.replaceOp(precedingOp, newResults.take_front(splitAt)); + rewriter.replaceOp(op, newResults.drop_front(splitAt)); + return success(); + } +}; + +struct EliminateDuplicateCstrBroadcastableOps + : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(shape::CstrBroadcastableOp op, + PatternRewriter &rewriter) const override { + // Search for previous occurence of the same constraint. + Operation *it = op->getPrevNode(); + while (it != nullptr) { + if (auto candidate = llvm::dyn_cast(it)) { + if (candidate.getShapes() == op.getShapes()) { + rewriter.replaceOp(op, candidate.getResult()); + return success(); + } + } + it = it->getPrevNode(); + } + + return failure(); + } +}; + +void populateMergeAssumingOpsPatterns(MLIRContext *context, + RewritePatternSet *patterns) { + patterns->add< + EliminateDuplicateCstrBroadcastableOps, + InlineBroadcastedShapeOperandsPattern, + MergeAssumingOpsPattern, MoveElementwiseOpsDownIntoAssumingOpPattern, + MoveElementwiseOpsUpIntoAssumingOpPattern, + MoveUpIntoAssumingOpPattern, + MoveUpIntoAssumingOpPattern, + MoveUpIntoAssumingOpPattern, + MoveUpOutOfAssumingOpPattern, + MoveUpOutOfAssumingOpPattern, + MoveUpOutOfAssumingOpPattern, ShapeReificationPattern>( + context); + mhlo::DynamicBroadcastInDimOp::getCanonicalizationPatterns(*patterns, + context); + mhlo::DynamicReshapeOp::getCanonicalizationPatterns(*patterns, context); + shape::AssumingAllOp::getCanonicalizationPatterns(*patterns, context); + shape::AssumingOp::getCanonicalizationPatterns(*patterns, context); + shape::BroadcastOp::getCanonicalizationPatterns(*patterns, context); + shape::CstrBroadcastableOp::getCanonicalizationPatterns(*patterns, context); + tensor::CastOp::getCanonicalizationPatterns(*patterns, context); +} + +struct MergeAssumingOpsPass + : public impl::MergeAssumingOpsPassBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + } + + void runOnOperation() override { + MLIRContext *ctx = &getContext(); + RewritePatternSet patterns(ctx); + populateMergeAssumingOpsPatterns(ctx, &patterns); + GreedyRewriteConfig config; + config.setMaxIterations(GreedyRewriteConfig::kNoLimit); + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns), + config))) { + return signalPassFailure(); + } + } +}; + +} // namespace + +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/parallel_loops_to_sequential.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/parallel_loops_to_sequential.cc new file mode 100644 index 0000000000000000000000000000000000000000..4fadba8fef5a3b135379c5906e667672a1cd2c8c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/parallel_loops_to_sequential.cc @@ -0,0 +1,59 @@ +/* Copyright 2020 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 +#include + +#include "mlir/Conversion/SCFToControlFlow/SCFToControlFlow.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/SCF/IR/SCF.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +#define GEN_PASS_DEF_PARALLELLOOPSTOSEQUENTIAL +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct ParallelLoopsToSequentialPass + : public impl::ParallelLoopsToSequentialBase< + ParallelLoopsToSequentialPass> { + void runOnOperation() override { + mlir::RewritePatternSet patterns(&getContext()); + mlir::populateSCFToControlFlowConversionPatterns(patterns); + + mlir::ConversionTarget target(getContext()); + target.addIllegalOp(); + target.addLegalOp(); + target.markUnknownOpDynamicallyLegal([](mlir::Operation*) { return true; }); + if (failed(applyPartialConversion(getOperation(), target, + std::move(patterns)))) + signalPassFailure(); + } +}; + +} // namespace + +std::unique_ptr> +CreateParallelLoopsToSequential() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..a01ad38c3d200aea127607aa7ff0195b52b2330a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h @@ -0,0 +1,124 @@ +/* Copyright 2020 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_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_PASSES_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_PASSES_H_ + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/GPU/IR/GPUDialect.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project + +#define GEN_PASS_DECL_TFKERNELTOLLVMPASS +#define GEN_PASS_DECL_EMBEDTFFRAMEWORKPASS +#define GEN_PASS_DECL_REWRITETFFRAMEWORKASSERT +#define GEN_PASS_DECL_FUNCTOJITINVOCATIONPASS +#define GEN_PASS_DECL_BUFFERREUSEPASS +#define GEN_PASS_DECL_SHAPETODESCRIPTORSPASS +#define GEN_PASS_DECL_KERNELGENFINALBUFFERIZEPASS +#define GEN_PASS_DECL_GPUKERNELTOBLOBPASS +#define GEN_PASS_DECL_PARALLELLOOPSTOSEQUENTIAL +#define GEN_PASS_DECL_PROPAGATETFABIKNOWLEDGETOKERNELS +#define GEN_PASS_DECL_PROPAGATESHAPEKNOWLEDGETOKERNELS +#define GEN_PASS_DECL_FUSEINNERPARALLELLOOPSPASS +#define GEN_PASS_DECL_COPYCLEANUPPASS +#define GEN_PASS_DECL_SHAPESIMPLIFICATIONPASS +#define GEN_PASS_DECL_MERGEASSUMINGOPSPASS +#define GEN_PASS_DECL_BROADCASTPROPAGATIONPASS +#define GEN_PASS_DECL_LEGALIZETENSORRESHAPEPASS + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { + +// Pass to replace some of the Standard ops with TF Framework ops. +// * adds tf_framework::OpKernelContextType argument to the function +// * std.alloc becomes tf_framework.alloc_raw +// * std.dealloc becomes tf_framework.dealloc_raw +// * std.assert becomes tf_framework.assert +std::unique_ptr> CreateEmbedTFFrameworkPass(); + +// Pass to convert tf_framework.assert operations to calls to +// tf_framework.report_error and create the required control flow to abort the +// function on failed execution. +std::unique_ptr> CreateRewriteTFFrameworkAssert(); + +} // namespace tf_framework + +namespace transforms { + +// Pass to find and annotate candidates for buffer reuse. +std::unique_ptr> CreateBufferReusePass(); + +// Pass to rewrite all functions to JIT invocations through the TF +// framework. +std::unique_ptr> CreateFuncToJITInvocationPass( + llvm::ArrayRef tile_sizes = {}, + llvm::ArrayRef unroll_factors = {}, bool enable_ftz = false, + bool index_64bit = false, bool cpu_codegen = false, + bool jit_i64_indexed_for_large_tensors = false); + +// Pass for applying LLVM legalization patterns. +std::unique_ptr> CreateTFKernelToLLVMPass( + mlir::StringRef blob_annotation = {}); + +// Pass to tranform shape computations in shape dialect to standard and scf +// using memref descriptors. +std::unique_ptr> CreateShapeToDescriptorsPass(); + +// Pass to convert scf::ParallelOp to scf::ForOp. +std::unique_ptr> CreateParallelLoopsToSequential(); + +// Pass to annotate GPU Module with its PTX. +std::unique_ptr> CreateGpuKernelToBlobPass( + mlir::StringRef blob_annotation = {}, + ArrayRef architectures = {}, bool print_ptx = false, + bool print_llvmir = false, bool enable_ftz = false); + +// Pass to propagate tensorflow runtime ABI knowledge across kernel boundaries. +std::unique_ptr> +CreatePropagateTfAbiKnowledgeToKernels(); + +// Pass to propagate shape equalities across kernel boundaries. +std::unique_ptr> +CreatePropagateShapeKnowledgeToKernels(); + +/// Greedily maps loops to GPU hardware dimensions. +std::unique_ptr> CreateMapParallelLoopsPass(); + +/// We need to direct fusion to the inner loops. This cannot be done with +/// a passmanager alone ATM, as nested pass managers require operations to +/// be closed from above. +std::unique_ptr> +CreateFuseInnerParallelLoopsPass(); + +// Pass to remove copies which are consumed by a GenericOp. +std::unique_ptr> CreateCopyCleanupPass(); + +std::unique_ptr> CreateKernelgenFinalBufferizePass(); + +} // namespace transforms + +#define GEN_PASS_REGISTRATION +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +} // namespace kernel_gen +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_PASSES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.td b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.td new file mode 100644 index 0000000000000000000000000000000000000000..85a4c67236e6ad10beeb6195a721d495806b69c6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.td @@ -0,0 +1,164 @@ +/* Copyright 2020 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 TF_KERNEL_GEN_PASSES +#define TF_KERNEL_GEN_PASSES + +include "mlir/Pass/PassBase.td" + +def TFKernelToLLVMPass : Pass<"tf-kernel-to-llvm", "ModuleOp"> { + let summary = "Pass for applying LLVM legalization patterns."; + let constructor = "transforms::CreateTFKernelToLLVMPass()"; + let options = [ + Option<"blob_annotation_", "blob-annotation", "std::string", + /*default=*/"\"gpu.binary_blob\"", "Blob attribute name">, + ]; +} + +def EmbedTFFrameworkPass + : Pass<"embed-tf-framework", "ModuleOp"> { + let summary = "Pass to embed TF Framework for allocation and assertions,"; + let constructor = "tf_framework::CreateEmbedTFFrameworkPass()"; +} + +def RewriteTFFrameworkAssert : Pass<"rewrite-tf-framework-assert", "ModuleOp"> { + let dependentDialects = ["cf::ControlFlowDialect"]; + let summary = "Pass to rewrite TFAssertOps to CondBranchOp"; + let constructor = "tf_framework::CreateRewriteTFFrameworkAssert()"; +} + +def FuncToJITInvocationPass : Pass<"func-to-jit-invocation", "mlir::func::FuncOp"> { + let dependentDialects = [ + "mlir::kernel_gen::tf_framework::TFFrameworkDialect", + "scf::SCFDialect", + "shape::ShapeDialect" + ]; + let summary = "Pass to rewrite a function to JIT invocations"; + let constructor = "transforms::CreateFuncToJITInvocationPass()"; + let options = [ + ListOption<"tile_sizes_", "tile-sizes", "int64_t", "Tiling sizes", + "llvm::cl::ZeroOrMore">, + ListOption<"unroll_factors_", "unroll-factors", "int64_t", + "Unrolling in each tile dimension", "llvm::cl::ZeroOrMore">, + Option<"enable_ftz_", "enable-ftz", "bool", /*default=*/"", + "Enable the denormal flush to zero mode when generating code">, + Option<"index_64bit_", "index_64bit", "bool", /*default=*/"", + "Enable the 64 bit indexing for GPU kernels">, + Option<"cpu_codegen_", "cpu-codegen", "bool", /*default=*/"", + "CPU codegen (false implies GPU)">, + Option<"jit_i64_indexed_for_large_tensors_", + "jit_i64_indexed_for_large_tensors", "bool", /*default=*/"false", + "Enable JIT compilation of i64-indexed kernels for large input " + "tensors.">, + ]; +} + +def BufferReusePass : Pass<"buffer-reuse", "mlir::func::FuncOp"> { + let summary = "Pass to find and annotate candidates for buffer reuse."; + let constructor = "transforms::CreateBufferReusePass()"; +} + +def ShapeToDescriptorsPass : Pass<"shape-to-descriptors", "ModuleOp"> { + let summary = "Pass to transform shape computations to descriptors"; + let constructor = "transforms::CreateShapeToDescriptorsPass()"; +} + +def KernelgenFinalBufferizePass : Pass<"kernelgen-final-bufferize", "ModuleOp"> { + let summary = "Pass to transform late operations on values to buffer based " + "ones."; + let constructor = "transforms::CreateKernelgenFinalBufferizePass()"; +} + +def GpuKernelToBlobPass : Pass<"gpu-kernel-to-blob", "gpu::GPUModuleOp"> { + let summary = "Pass to annotate GPU Module with its PTX"; + let options = [ + Option<"blob_annotation_", "blob-annotation", "std::string", + /*default=*/"\"gpu.binary_blob\"", "Blob attribute name">, + ListOption<"architectures_", "arch", "std::string", "GPU architectures">, + Option<"generate_fatbin_", "generate-fatbin", "bool", /*default=*/"true", + "Bundle machine code for the different architectures in one " + "fatbin.">, + Option<"print_ptx_", "print-ptx", "bool", /*default=*/"false", + "Print generated PTX code per target architecture.">, + Option<"print_llvmir_", "print-llvmir", "bool", /*default=*/"false", + "Print llvm ir when lowering code per target architecture.">, + ]; + let constructor = "transforms::CreateGpuKernelToBlobPass()"; +} + +def ParallelLoopsToSequential : Pass<"parallel-loops-to-sequential", "mlir::func::FuncOp"> { + let summary = "Pass to convert scf::ParallelOp to scf::ForOp"; + let constructor = "transforms::CreateParallelLoopsToSequential()"; +} + +def PropagateTfAbiKnowledgeToKernels + : Pass<"propagate-tf-abi-knowledge-to-kernels", "mlir::func::FuncOp"> { + let summary = "Pass to propagate tensorflow ABI knowledge to kernels"; + let constructor = "transforms::CreatePropagateTfAbiKnowledgeToKernels()"; +} + +def PropagateShapeKnowledgeToKernels + : Pass<"propagate-shape-knowledge-to-kernels", "mlir::func::FuncOp"> { + let summary = "Pass to propagate shape information into kernels"; + let constructor = "transforms::CreatePropagateShapeKnowledgeToKernels()"; +} + +def FuseInnerParallelLoopsPass + : Pass<"fuse-inner-parallel-loops", "mlir::func::FuncOp"> { + let summary = "Limited pass to forward stores to loads."; + let constructor = "transforms::CreateFuseInnerParallelLoopsPass()"; + let description = [{ + Directs parallel loop fusion to the inner loops. This cannot be done with + a passmanager alone ATM, as nested pass managers require operations to + be closed from above. + }]; +} + +def CopyCleanupPass : Pass<"copy-cleanup", "mlir::func::FuncOp"> { + let summary = "Pass to remove copies which are consumed by a GenericOp."; + let constructor = "transforms::CreateCopyCleanupPass()"; + let description = [{ + We can have GenericOps which have operands that are a copy, but the copy is + not used by any other op. In this case, the GenericOp can just use the + buffer which is the source of the copy, and we can remove the Alloc and the + copy. + }]; +} + +def ShapeSimplificationPass + : Pass<"shape-simplification", "mlir::func::FuncOp"> { + let summary = "Simplify shape ops"; +} + +def MergeAssumingOpsPass : Pass<"mhlo-merge-assuming-ops", "func::FuncOp"> { + let summary = "Prepare moving dynamic broadcasts up over element-wise " + "operations and broadcast the operands rather than the result. This will " + "eventually allow for larger fusions."; +} + +def BroadcastPropagationPass : Pass<"mhlo-broadcast-propagation", "func::FuncOp"> { + let summary = "Move dynamic broadcasts up over element-wise operations and " + "broadcast the operands rather than the result. This will eventually allow " + "for larger fusions."; +} + +def LegalizeTensorReshapePass + : Pass<"legalize-tensor-reshape", "mlir::func::FuncOp"> { + let summary = "Legalize tensor.reshape to mhlo.dynamic_reshape"; +} + + + +#endif // TF_KERNEL_GEN_PASSES diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewrite_tf_framework_assert.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewrite_tf_framework_assert.cc new file mode 100644 index 0000000000000000000000000000000000000000..25849dcc29b0638bed5a106dbb581c269d0d2044 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewrite_tf_framework_assert.cc @@ -0,0 +1,115 @@ +/* Copyright 2021 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 +#include +#include + +#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { +namespace { + +// Converts tf_framework.assert to a conditional branch that reports an error to +// OpKernelContext and creates a fake memref using NullMemRefOp. +class TFAssertOpConverter : public OpConversionPattern { + public: + using OpConversionPattern::OpConversionPattern; + + LogicalResult matchAndRewrite( + TFAssertOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + Location loc = op.getLoc(); + + // Split the block to insert CondBr. + OpBuilder::InsertPoint ip = rewriter.saveInsertionPoint(); + Block *split_block = rewriter.splitBlock( + rewriter.getInsertionBlock(), std::next(rewriter.getInsertionPoint())); + + auto func = op->getParentOfType(); + Block *error_reporting_block = + rewriter.createBlock(&func.getRegion(), {}, {}); + ReportErrorOp::create(rewriter, loc, adaptor.getCtx(), + adaptor.getErrorCode(), adaptor.getMsg()); + + SmallVector null_memrefs; + for (auto type : func.getFunctionType().getResults()) { + null_memrefs.push_back(NullMemRefOp::create(rewriter, loc, type)); + } + func::ReturnOp::create(rewriter, loc, null_memrefs); + + rewriter.restoreInsertionPoint(ip); + rewriter.replaceOpWithNewOp( + op, adaptor.getArg(), split_block, mlir::ValueRange(), + error_reporting_block, mlir::ValueRange()); + return success(); + } +}; + +#define GEN_PASS_DEF_REWRITETFFRAMEWORKASSERT +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +bool IsNotInsideTfEntryFunction(Operation *op) { + auto func = op->getParentOfType(); + return !func->hasAttrOfType(TFFrameworkDialect::kTFEntryAttrName); +} +// All contained `tf_framework.assert` operations are rewritten into calls to +// `tf_framework.report_error` and the required control flow to make +// execution of the function terminate. +class RewriteTFFrameworkAssertPass + : public impl::RewriteTFFrameworkAssertBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + } + + public: + void runOnOperation() override { + ModuleOp m = getOperation(); + + // Populate patterns. + MLIRContext *context = &getContext(); + RewritePatternSet patterns(context); + patterns.add(context); + PopulateEmbedTFFrameworkAssertPattern(&patterns); + + // Set target. + ConversionTarget target(getContext()); + target.addLegalDialect(); + target.addIllegalOp(); + target.addDynamicallyLegalOp(IsNotInsideTfEntryFunction); + + if (failed(applyPartialConversion(m, target, std::move(patterns)))) { + signalPassFailure(); + } + } +}; + +} // namespace + +std::unique_ptr > CreateRewriteTFFrameworkAssert() { + return std::make_unique(); +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h new file mode 100644 index 0000000000000000000000000000000000000000..4037e690284249774ada32a0f4c7802e11d8cc36 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h @@ -0,0 +1,59 @@ +/* Copyright 2020 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_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_REWRITERS_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_REWRITERS_H_ + +#include "mlir/IR/MLIRContext.h" // from @llvm-project + +namespace mlir { +namespace bufferization { +class BufferizeTypeConverter; +} +class ConversionTarget; +class LLVMTypeConverter; +class MLIRContext; +class RewritePatternSet; +class TypeConverter; + +namespace kernel_gen { +namespace tf_framework { + +/// Collects a set of patterns to convert from the TF Framework dialect to LLVM. +void PopulateTFFrameworkToLLVMConversionPatterns(LLVMTypeConverter *converter, + RewritePatternSet *patterns); + +/// Collects a set of patterns to rewrite functions for use with TF framework +/// and also replace `alloc`, `dealloc` and `assert`. +void PopulateEmbedTFFrameworkPatterns(RewritePatternSet *patterns); +void PopulateEmbedTFFrameworkAssertPattern(RewritePatternSet *patterns); + +} // namespace tf_framework + +namespace transforms { + +/// Collects a set of patterns that bufferize operations from the standard and +/// other dialects. +void populateExtraBufferizeDialects(DialectRegistry ®istry); +void populateExtraBufferizePatterns(ConversionTarget &target, + MLIRContext *context, + TypeConverter *converter, + RewritePatternSet *patterns); + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_REWRITERS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/same_shape_propagation.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/same_shape_propagation.cc new file mode 100644 index 0000000000000000000000000000000000000000..2dcd5c8a94d78375bf0e61ef5a29e7046a4fe13a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/same_shape_propagation.cc @@ -0,0 +1,383 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file contains the analysis and transformation to rewrite kernel +// functions such that they use a single set of arguments for the strides and +// sizes of operands with equal shapes. + +#include +#include +#include +#include +#include +#include + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseMapInfo.h" +#include "llvm/ADT/EquivalenceClasses.h" +#include "llvm/ADT/Hashing.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Debug.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/GPU/IR/GPUDialect.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/AsmState.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +#define DEBUG_TYPE "kernel-gen-shapes" + +namespace { + +using mlir::ArrayRef; +using mlir::SmallVector; +using mlir::Value; + +/// Represents a value or constant. Used to unify operands for operations that +/// take both ssa values and attributes. +struct ValueOrConst { + explicit ValueOrConst(Value v) : value_or_constant(v), is_constant(false) {} + explicit ValueOrConst(int64_t c) : value_or_constant(c), is_constant(true) {} + + Value value() const { + assert(!is_constant); + return value_or_constant.value; + } + + int64_t constant() const { + assert(is_constant); + return value_or_constant.constant; + } + + bool isConstant() const { return is_constant; } + + private: + union ValueOrConstStorage { + explicit ValueOrConstStorage(Value v) : value(v) {} + explicit ValueOrConstStorage(size_t c) : constant(c) {} + + Value value; + int64_t constant; + } value_or_constant; + + bool is_constant; +}; + +llvm::hash_code hash_value(ValueOrConst value) { + return value.isConstant() ? static_cast(value.constant()) + : mlir::hash_value(value.value()); +} + +bool operator==(ValueOrConst lhs, ValueOrConst rhs) { + if (lhs.isConstant()) { + return rhs.isConstant() && lhs.constant() == rhs.constant(); + } else { + return !rhs.isConstant() && lhs.value() == rhs.value(); + } +} + +inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, + const ValueOrConst &value) { + if (value.isConstant()) { + os << value.constant(); + } else { + Value val = value.value(); + mlir::AsmState asm_state( + val.getParentRegion()->getParentOfType()); + val.printAsOperand(os, asm_state); + } + return os; +} + +/// Represents a shape, as either a single SSA value that represents the entire +/// shape vector or as a vector of SSA values representing scalars. +struct ShapeValue { + explicit ShapeValue(Value vector) + : shape({ValueOrConst{vector}}), is_vector(true) {} + explicit ShapeValue(ValueOrConst vector) : shape({vector}), is_vector(true) { + assert(!vector.isConstant()); + } + template + explicit ShapeValue(T values) + : shape(values.begin(), values.end()), is_vector(false) {} + + ValueOrConst vector() const { + assert(is_vector); + return shape.front(); + } + + ArrayRef scalars() const { + assert(!is_vector); + return llvm::ArrayRef(shape); + } + + bool isVector() const { return is_vector; } + + private: + SmallVector shape; + bool is_vector; +}; + +llvm::hash_code hash_value(ShapeValue shape) { + return shape.isVector() ? hash_value(shape.vector()) + : hash_value(shape.scalars()); +} + +bool operator==(ShapeValue lhs, ShapeValue rhs) { + if (lhs.isVector()) { + return rhs.isVector() && lhs.vector() == rhs.vector(); + } else { + return !rhs.isVector() && lhs.scalars() == rhs.scalars(); + } +} + +inline llvm::raw_ostream &operator<<(llvm::raw_ostream &os, + const ShapeValue &shape) { + if (shape.isVector()) { + os << shape.vector(); + return os; + } + os << "["; + bool first = true; + for (auto scalar : shape.scalars()) { + if (!first) { + os << ", "; + } + first = false; + os << scalar; + } + os << "]"; + return os; +} + +} // namespace + +namespace llvm { + +template <> +struct DenseMapInfo { + static unsigned getHashValue(ShapeValue shape) { return hash_value(shape); } + static bool isEqual(ShapeValue LHS, ShapeValue RHS) { return LHS == RHS; } +}; + +} // namespace llvm + +namespace mlir { +namespace kernel_gen { +namespace transforms { + +namespace { + +#define GEN_PASS_DEF_PROPAGATESHAPEKNOWLEDGETOKERNELS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +// A basic shape equality inference. This should be superceeded by a proper +// inference once available. Until then, we just build this out to the needs of +// the kernel generator project. +class ShapeEqualityKnowledge { + public: + /// Checks all operations for potential shape equality of their respective + /// results. + void build(func::FuncOp function) { + function.walk([&](Operation *op) { + if (auto reshape = dyn_cast(op)) { + registerAssociation(ShapeValue{(Value)reshape.getShape()}, + reshape.getResult()); + return; + } + if (auto cast = dyn_cast(op)) { + // Only support fully dynamic sizes for now. + // TODO(herhut): Fix once the op has canonicalizers that break this. + for (unsigned int p = 0, e = cast.getResultRank(); p < e; ++p) { + if (!cast.isDynamicSize(p)) { + return; + } + } + registerAssociation(ShapeValue{cast.getSizes()}, cast.getResult()); + return; + } + if (auto alloc = dyn_cast(op)) { + SmallVector shape; + ShapedType type = mlir::cast(alloc.getResult().getType()); + fillShapeFromAllocLike(alloc.getDynamicSizes(), type, shape); + registerAssociation(ShapeValue{shape}, alloc.getResult()); + return; + } + if (auto alloc = dyn_cast(op)) { + // Construct a symbol representing the allocated shape. + SmallVector shape; + ShapedType type = mlir::cast(alloc.getResult().getType()); + fillShapeFromAllocLike(alloc.getDynSizes(), type, shape); + registerAssociation(ShapeValue{shape}, alloc.getResult()); + return; + } + }); + } + + /// Checks whether `one` and `other` are known to have the same shape and + /// strides. + bool haveSameShape(Value one, Value other) { + return equal_shapes_.isEquivalent(one.getAsOpaquePointer(), + other.getAsOpaquePointer()); + } + + private: + static void fillShapeFromAllocLike(mlir::OperandRange operands, + ShapedType type, + SmallVectorImpl &shape) { + assert(type.hasRank()); + auto dynamic_sizes = operands.begin(); + for (auto extent : type.getShape()) { + shape.push_back(ShapedType::isDynamic(extent) + ? ValueOrConst{*(dynamic_sizes++)} + : ValueOrConst{extent}); + } + } + + /// Registers the value `value` to have the shape represented by `shape`. If + /// `shape` has been registered before, place `value` into the same + /// equivalence class. Otherwise register `value` as an equivalence class of + /// its own. + void registerAssociation(ShapeValue shape, Value value) { + LLVM_DEBUG({ llvm::dbgs() << "Processing " << value << "\n"; }); + auto insert_symbolic = symbolic_shapes_.insert({shape, value}); + if (insert_symbolic.second) { + LLVM_DEBUG({ llvm::dbgs() << "New symbolic shape " << shape << "\n"; }); + equal_shapes_.insert(value.getAsOpaquePointer()); + // We have seen this symbolic shape for the first time. Try to match it + // with a vector or shape we already know and alias classes if possible. + // This could be based on shape dialect if we weren't late in the + // lowering. + tryEvaluateShapeToRoot(shape, value); + } else { + auto rep = insert_symbolic.first->second; + LLVM_DEBUG({ llvm::dbgs() << "Aliasing with rep " << rep << "\n"; }); + equal_shapes_.unionSets(rep.getAsOpaquePointer(), + value.getAsOpaquePointer()); + } + } + + /// Follows the definition chains of the ShapeValue `shape` to identify cases + /// where `shape` is derived from some other value's shape. In such case, the + /// equivalence classes of that other value and `value` are unioned. + /// This is based on pattern matching and not complete. + void tryEvaluateShapeToRoot(ShapeValue shape, Value value) { + // Just some pattern matching for common cases here. + if (!shape.isVector()) { + // Patterns that revolve around scalars. + // Check whether the scalars are all dim operations for some other memref. + Value candidate; + bool all_are_dimops = + llvm::all_of(llvm::enumerate(shape.scalars()), [&candidate](auto p) { + ValueOrConst val = p.value(); + if (val.isConstant()) return false; + auto dimOp = val.value().getDefiningOp(); + if (!dimOp) return false; + if (!candidate) candidate = dimOp.getSource(); + auto index = dimOp.getConstantIndex(); + if (!index.has_value()) return false; + return candidate == dimOp.getSource() && p.index() == index.value(); + }); + if (all_are_dimops && candidate) { + equal_shapes_.unionSets(candidate.getAsOpaquePointer(), + value.getAsOpaquePointer()); + } + } + } + + // These are values with identical shapes (or rather their opaque pointers). + llvm::EquivalenceClasses equal_shapes_; + // A map from a value that encodes a shape to a value that has this shape. + llvm::DenseMap symbolic_shapes_; +}; + +/// For arguments to kernels that have the same shape, use the stride and +/// shape information of the left-most argument inside of the kernel function. +/// That way, llvm can CSE index computations on same-shaped inputs. +struct PropagateShapeKnowledgeToKernels + : public impl::PropagateShapeKnowledgeToKernelsBase< + PropagateShapeKnowledgeToKernels> { + void runOnOperation() override { + ShapeEqualityKnowledge knowledge; + + knowledge.build(getOperation()); + + getOperation().walk([&](gpu::LaunchFuncOp launch) { + auto module = launch->getParentOfType(); + auto kernel = module.lookupSymbol(launch.getKernel()); + + if (!kernel || kernel.isExternal()) return; + + llvm::SmallVector, 4> seen_memrefs; + // Position of the kernel argument we are currently at. + int kernel_p = 0; + for (auto operand : launch.getKernelOperands()) { + auto memref = mlir::dyn_cast(operand.getType()); + if (!memref) { + // Scalar argument, advance kernel position by one. + kernel_p++; + continue; + } + for (auto previous : seen_memrefs) { + if (!knowledge.haveSameShape(operand, previous.first)) { + continue; + } + auto previous_type = mlir::cast(previous.first.getType()); + // We use the first equality found and replace uses of corresponding + // size and (potentially) stride information here. + auto args_to_replace = memref.getRank(); + // If both memrefs have identity layouts, we can also reuse the + // strides here, as they are the identity strides and hence fully + // determinded by the shape. + if (previous_type.getLayout().isIdentity() && + memref.getLayout().isIdentity()) { + args_to_replace *= 2; + } + int previous_args_pos = previous.second; + auto previous_args = kernel.getArguments() + .drop_front(previous_args_pos + 3) + .take_front(args_to_replace); + auto current_args = kernel.getArguments() + .drop_front(kernel_p + 3) + .take_front(args_to_replace); + for (auto pair : llvm::zip(previous_args, current_args)) { + mlir::BlockArgument prev, curr; + std::tie(prev, curr) = pair; + curr.replaceAllUsesWith(prev); + } + break; + } + seen_memrefs.push_back({operand, kernel_p}); + // Advance base, aligned, offset, strides and sizes many arguments. + kernel_p += memref.getRank() * 2 + 3; + } + }); + } +}; + +} // namespace + +std::unique_ptr> +CreatePropagateShapeKnowledgeToKernels() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/shape_simplification_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/shape_simplification_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..ab3ff9b90f2e55ef7de00eee3cbf08dd3088f733 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/shape_simplification_pass.cc @@ -0,0 +1,255 @@ +/* Copyright 2021 The OpenXLA Authors. + +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. +==============================================================================*/ + +// This file contains the patterns to simplify shape ops that were deemed not +// suitable for shape op canonicalization in MLIR Core. + +#include +#include +#include +#include + +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project +#include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "xla/mlir_hlo/mhlo/IR/hlo_ops.h" +#include "xla/mlir_hlo/mhlo/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { + +#define GEN_PASS_DEF_SHAPESIMPLIFICATIONPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +namespace { + +using shape::BroadcastOp; +using shape::ConstShapeOp; +using shape::ShapeOfOp; + +// Try to remove operands from broadcasts that don't contribute to the final +// result. +struct BroadcastRemoveSubsumedOperandsPattern + : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(BroadcastOp op, + PatternRewriter &rewriter) const override { + // First collect the static components when joining all shapes. The + // resulting vector contains a static dimension if any operand has a static + // non-1 dimension in that position. The remaining dimensions are set to + // dynamic size. + SmallVector knownExtents; + SmallVector, 4> operandExtents; + for (Value shape : op.getShapes()) { + auto &extents = operandExtents.emplace_back(); + if (failed(shape::getShapeVec(shape, extents))) return failure(); + + // Prepend dynamic dims if sizes don't match. + if (extents.size() > knownExtents.size()) { + knownExtents.insert(knownExtents.begin(), + extents.size() - knownExtents.size(), + ShapedType::kDynamic); + } + + for (size_t i = 0, e = extents.size(); i != e; ++i) { + int64_t extent = extents[e - i - 1]; + if (extent != ShapedType::kDynamic && extent != 1) { + int64_t &knownExtent = knownExtents[knownExtents.size() - i - 1]; + // A dynamic dimension is subsumed by a static one, but bail out for + // known conflicting shapes. + if (knownExtent != extent && knownExtent != ShapedType::kDynamic) + return failure(); + knownExtent = extent; + } + } + } + + // If we've figured out all shapes to be constants we're done. + if (!llvm::is_contained(knownExtents, ShapedType::kDynamic)) { + rewriter.replaceOpWithNewOp( + op, op->getResultTypes(), rewriter.getIndexTensorAttr(knownExtents)); + return success(); + } + + // If only some dimensions are known see if any of the operands can be + // removed without affecting the result. + SmallVector filteredOperands; + for (auto tuple : llvm::zip(op.getShapes(), operandExtents)) { + Value shape = std::get<0>(tuple); + auto &extents = std::get<1>(tuple); + + // An operand can't be dead if it's the only operand of the maximum rank. + // Removing it would reduce the rank of the output. + if (llvm::count_if(operandExtents, [&](ArrayRef op) { + return op.size() >= extents.size(); + }) <= 1) { + filteredOperands.push_back(shape); + continue; + } + + for (size_t i = 0, e = extents.size(); i != e; ++i) { + int64_t extent = extents[e - i - 1]; + // A dimension of an operand can be subsumed if it's + // - a 1 dimension. All other operands will have 1 dims or better. + if (extent == 1) continue; + + // - a dynamic dim but the result is known to be constant. + int64_t knownExtent = knownExtents[knownExtents.size() - i - 1]; + assert(knownExtent != 1); + if (knownExtent != ShapedType::kDynamic && + extent == ShapedType::kDynamic) + continue; + + // - a constant non-1 dimension equal to the "known" dim. + // In this case we also have to check whether this operand is the only + // contributor of that constant. + if (knownExtent != ShapedType::kDynamic && extent == knownExtent && + llvm::count_if(operandExtents, [&](ArrayRef operandShape) { + return i < operandShape.size() && + operandShape[operandShape.size() - i - 1] == knownExtent; + }) > 1) + continue; + + filteredOperands.push_back(shape); + break; + } + } + if (filteredOperands.size() != op.getShapes().size()) { + rewriter.replaceOpWithNewOp(op, op->getResultTypes(), + filteredOperands); + return success(); + } + return failure(); + } +}; + +// Convert cases like: +// ``` +// %1 = shape.shape_of %arg0 : tensor -> tensor<3xindex> +// %2 = shape.shape_of %arg1 : tensor -> tensor<3xindex> +// %3 = shape.broadcast %1, %2 : tensor<3xindex>, tensor<3xindex> +// -> tensor<3xindex> +// %result = tensor.extract %3[%c2] : tensor<3xindex> +// ``` +// to +// +// ``` +// %result = tensor.dim %arg0[%c2] : tensor +// ``` +struct ExtractFromBroadcastedTensorCanonicalizationPattern + : public OpRewritePattern { + using OpRewritePattern::OpRewritePattern; + + LogicalResult matchAndRewrite(tensor::ExtractOp op, + PatternRewriter &rewriter) const override { + auto broadcastOp = op.getTensor().getDefiningOp(); + if (!broadcastOp) return failure(); + + // Confirm that there is a constant index. This is required, so we can + // confirm the DimOp's input will define the resulting broadcasted shape in + // that dimension. + auto index = + op.getIndices().front().getDefiningOp(); + if (!index) return failure(); + auto idx = index.value(); + + // Iterate through the operands with 3 considerations in this order: + // 1. If a static, non-1 dimension is seen, we know this to be the + // broadcasted result + // 2. If a single dynamic dimension is seen, we know this to be the + // broadcasted result (with a possibly 1 or non-1 result) + // 3. If no dynamic dimensions and no non-1 static dimensions are seen, we + // know the result to be 1 + // + // Iterate through all operands, keeping track of dynamic dimensions and + // returning immediately if a non-1 static dimension is seen. + ShapeOfOp dynamicShape; + int64_t numDynamic = 0; + for (auto shape : broadcastOp.getShapes()) { + auto shapeOfOp = shape.getDefiningOp(); + if (!shapeOfOp) return failure(); + auto shapedType = + mlir::cast(shapeOfOp->getOperandTypes().front()); + + // Abort on the existence of unranked shapes as they require more logic. + if (!shapedType.hasRank()) return failure(); + if (shapedType.getRank() <= idx) continue; + + // Only consider dynamic dimensions after the loop because any non-1 + // static dimension takes precedence. + if (shapedType.isDynamicDim(idx)) { + dynamicShape = shapeOfOp; + numDynamic++; + continue; + } + + if (shapedType.getDimSize(idx) == 1) continue; + + // Return as soon as we see a non-1 static dim. + rewriter.replaceOpWithNewOp( + op, shapedType.getDimSize(idx)); + return success(); + } + if (numDynamic > 1) return failure(); + + // Replace with the single dynamic dimension or 1. + if (dynamicShape) { + rewriter.replaceOpWithNewOp(op, dynamicShape.getArg(), + index); + } else { + rewriter.replaceOpWithNewOp(op, 1); + } + return success(); + } +}; + +struct ShapeSimplificationPass + : public impl::ShapeSimplificationPassBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + registry.insert(); + } + + void runOnOperation() override { + MLIRContext *context = &getContext(); + RewritePatternSet patterns(&getContext()); + + for (auto op : context->getRegisteredOperations()) { + if (isa(op.getDialect())) + op.getCanonicalizationPatterns(patterns, context); + } + + patterns.add(context); + + auto func = getOperation(); + if (failed(applyPatternsGreedily(func, std::move(patterns)))) + return signalPassFailure(); + } +}; + +} // namespace + +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/shape_to_descriptors_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/shape_to_descriptors_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..39c5a1738dbabcb5b7872b6ee24d6d4b57f16462 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/shape_to_descriptors_pass.cc @@ -0,0 +1,88 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file combines patterns for lowering shape dialect to standard ops, +// structured control flow and descriptors. + +#include +#include + +#include "mlir/Conversion/ShapeToStandard/ShapeToStandard.h" // from @llvm-project +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Math/IR/Math.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/Dialect/SCF/IR/SCF.h" // from @llvm-project +#include "mlir/Dialect/Shape/IR/Shape.h" // from @llvm-project +#include "mlir/Dialect/Shape/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +#define GEN_PASS_DEF_SHAPETODESCRIPTORSPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct ShapeToDescriptorsPass + : public impl::ShapeToDescriptorsPassBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + } + + public: + void runOnOperation() override { + MLIRContext &ctx = getContext(); + + // Setup target legality. + ConversionTarget target(ctx); + target.addIllegalDialect(); + target.addLegalDialect(); + target.addLegalDialect(); + target.addLegalDialect(); + target.addLegalDialect(); + target.addLegalDialect(); + target.addLegalDialect(); + // Don't mark the primary Cstr/Assuming ops as illegal, so they can be + // lowered at a later time to assertions. + target.addLegalOp(); + + // Setup conversion patterns. + RewritePatternSet patterns(&getContext()); + populateShapeRewritePatterns(patterns); + populateShapeToStandardConversionPatterns(patterns); + + // Apply conversion. + auto module = getOperation(); + if (failed(applyPartialConversion(module, target, std::move(patterns)))) + signalPassFailure(); + } +}; + +} // namespace + +std::unique_ptr > CreateShapeToDescriptorsPass() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tensorflow_abi_knowledge_propagation.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tensorflow_abi_knowledge_propagation.cc new file mode 100644 index 0000000000000000000000000000000000000000..8db8684ede4a46ee9e3c8f8cc801624e2f065f85 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tensorflow_abi_knowledge_propagation.cc @@ -0,0 +1,221 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file contains the analysis and transformation to rewrite kernel +// functions such that information about alignment, aliasing and zero offsets +// steming from the tf_framework uses is propagated. + +#include +#include +#include + +#include "llvm/ADT/Bitfields.h" +#include "llvm/ADT/DenseMap.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/GPU/IR/GPUDialect.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/Dialect/MemRef/IR/MemRef.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +#define GEN_PASS_DEF_PROPAGATETFABIKNOWLEDGETOKERNELS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +struct PropagateTfAbiKnowledgeToKernelsPass + : public impl::PropagateTfAbiKnowledgeToKernelsBase< + PropagateTfAbiKnowledgeToKernelsPass> { + void runOnOperation() override { + func::FuncOp function = getOperation(); + llvm::SmallVector worklist; + // We currently only handle entry functions and do not propagate across + // functions. + if (function->getAttrOfType( + tf_framework::TFFrameworkDialect::kTFEntryAttrName)) { + // For all operands of this function, we know they are aligned. Also, by + // construction of kernel generator, we know that there is no offset and + // the inner stride is one. + // TODO(herhut): Insert asserts in debug mode to check this. + for (auto argument : function.getArguments()) { + if (mlir::isa(argument.getType())) { + worklist.push_back(argument); + allocated_by_tf_runtime.insert(argument); + offset_is_zero.insert(argument); + inner_stride_is_constant.insert({argument, 1}); + } + } + } + + // For locally allocated values, we know they are aligned and have offset + // zero. Further, they also do not alias with other memrefs, except in + // benign ways. This is by construction and ensured by the reuse analysis. + function.walk([&](tf_framework::TFAllocOp op) { + Value allocated = op.getResult(); + worklist.push_back(allocated); + no_alias.insert(allocated); + allocated_by_tf_runtime.insert(allocated); + offset_is_zero.insert(allocated); + inner_stride_is_constant.insert({allocated, 1}); + }); + + // Next, take what we have and propagate it through known operations. + propagateThroughUses(worklist); + + // Now look at launches and make use of the knowledge we have. + function.walk([&](gpu::LaunchFuncOp launch) { + auto module = launch->getParentOfType(); + auto kernel = module.lookupSymbol(launch.getKernel()); + + if (!kernel || kernel.isExternal()) return; + + // Count the position of kernel operands independently, as they do not + // coincide with laucnh operands as memref parameters get expanded when + // lowered to llvm. + int kernel_p = 0; + OpBuilder b = OpBuilder::atBlockBegin(&kernel.getBody().front()); + llvm::SmallDenseMap constants; + auto loc = kernel.getLoc(); + for (auto operand : launch.getKernelOperands()) { + auto memref = mlir::dyn_cast(operand.getType()); + if (!memref) { + // Scalar argument, advance kernel position by one. + kernel_p++; + continue; + } + if (allocated_by_tf_runtime.contains(operand)) { + // This was allocated by the tf runtime, so the two pointers in the + // descriptor coincide. Rewrite the kernel accordingly. + Value alloc_ptr = kernel.getArgument(kernel_p); + Value align_ptr = kernel.getArgument(kernel_p + 1); + alloc_ptr.replaceAllUsesWith(align_ptr); + kernel.setArgAttr( + kernel_p + 1, LLVM::LLVMDialect::getAlignAttrName(), + b.getIndexAttr( + tf_framework::TFFrameworkDialect::kAllocationAlignment)); + } + if (offset_is_zero.contains(operand)) { + Value offset = kernel.getArgument(kernel_p + 2); + Value &zero = constants[0]; + if (!zero) { + zero = LLVM::ConstantOp::create(b, loc, offset.getType(), + b.getIndexAttr(0)); + } + offset.replaceAllUsesWith(zero); + } + auto const_stride = inner_stride_is_constant.find(operand); + if (const_stride != inner_stride_is_constant.end()) { + // The stride is the last argument belonging to this memref. + Value inner_stride = + kernel.getArgument(kernel_p + 2 + memref.getRank() * 2); + Value &stride_val = constants[const_stride->second]; + if (!stride_val) { + stride_val = + LLVM::ConstantOp::create(b, loc, inner_stride.getType(), + b.getIndexAttr(const_stride->second)); + } + inner_stride.replaceAllUsesWith(stride_val); + } + if (no_alias.contains(operand)) { + // TODO(herhut): We also need to check whether any of the other args + // are aliases. This is currently never the case by construction + // but we could use the alias analysis from buffer placement here + // to make sure. + // Add the no_alias attribute to the corresponding pointer. + kernel.setArgAttr(kernel_p + 1, + LLVM::LLVMDialect::getNoAliasAttrName(), + b.getUnitAttr()); + } + // Advance base, aligned, offset, strides and sizes many arguments. + kernel_p += memref.getRank() * 2 + 3; + } + }); + } + + private: + void propagateThroughUses(SmallVectorImpl &worklist) { + while (!worklist.empty()) { + Value candidate = worklist.pop_back_val(); + for (auto user : candidate.getUsers()) { + if (isa(user)) { + // Reshape and Cast propagate alignment, offset and innermost stride. + // TODO(herhut): This should be a trait. + Value result = user->getResult(0); + if (allocated_by_tf_runtime.contains(candidate)) { + allocated_by_tf_runtime.insert(result); + } + auto const_stride = inner_stride_is_constant.find(candidate); + if (const_stride != inner_stride_is_constant.end()) { + inner_stride_is_constant.insert({result, const_stride->second}); + } + if (offset_is_zero.contains(candidate)) { + offset_is_zero.insert(result); + } + worklist.push_back(result); + } + if (auto cast = dyn_cast(user)) { + // Check that we have offset 0. + Value result = cast.getResult(); + if (!cast.isDynamicOffset(0) && cast.getStaticOffset(0) == 0) { + offset_is_zero.insert(result); + } + if (allocated_by_tf_runtime.contains(candidate)) { + allocated_by_tf_runtime.insert(result); + } + size_t last_stride = cast.getResultRank() - 1; + // TODO(herhut): Remove this once canonicalization handles this. + if (cast.isDynamicStride(last_stride)) { + auto dyn_stride = cast.getDynamicStride(last_stride) + .getDefiningOp(); + if (dyn_stride) { + inner_stride_is_constant.insert({result, dyn_stride.value()}); + } + } else { + inner_stride_is_constant.insert( + {result, cast.getStaticStride(last_stride)}); + } + worklist.push_back(result); + } + } + } + } + + // Set of values that were allocated by the tf runtime and hence are aligned. + llvm::SmallPtrSet allocated_by_tf_runtime; + // Set of values that are known to not have an offset of 0. + llvm::SmallPtrSet offset_is_zero; + // Set of values that are known to have a constant stride. + llvm::SmallDenseMap inner_stride_is_constant; + // Set of values we know do not alias other values. + llvm::SmallPtrSet no_alias; +}; + +} // namespace + +std::unique_ptr> +CreatePropagateTfAbiKnowledgeToKernels() { + return std::make_unique(); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_framework_legalize_to_llvm.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_framework_legalize_to_llvm.cc new file mode 100644 index 0000000000000000000000000000000000000000..dd5afcd4dc5da82237e3208bb24ebf2f45e5fd39 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_framework_legalize_to_llvm.cc @@ -0,0 +1,600 @@ +/* Copyright 2020 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 +#include +#include +#include +#include +#include + +#include "mlir/Conversion/LLVMCommon/Pattern.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.h" + +namespace mlir { +namespace kernel_gen { +namespace tf_framework { +namespace { + +using transforms::CreateOrFindGlobalStringConstant; +using transforms::GetGlobalName; +using transforms::GetOrInsertLLVMFunction; + +static constexpr StringRef kCInterfaceAlloc = "_mlir_ciface_tf_alloc"; +static constexpr StringRef kCInterfaceDealloc = "_mlir_ciface_tf_dealloc"; +static constexpr StringRef kCInterfaceReportError = + "_mlir_ciface_tf_report_error"; +static constexpr StringRef kCInterfaceJITCompile = + "_mlir_ciface_tf_jit_compile"; +static constexpr StringRef kCInterfaceJITExecute = + "_mlir_ciface_tf_jit_execute"; +static constexpr StringRef kJITCodeGlobalBaseName = "jit_module_code"; +static constexpr StringRef kErrorMessageGlobalBaseName = "error_message"; + +/// Base class for patterns converting TF Framework ops to function calls. +template +class ConvertToLLVMCallOpPattern : public ConvertOpToLLVMPattern { + public: + using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern; + + protected: + virtual StringRef GetFuncName() const = 0; + virtual Type GetFuncType() const = 0; + + std::pair ConvertArrayAttrToStackAllocatedArray( + Location loc, Type size_ty, Type element_ty, + std::optional attr, ConversionPatternRewriter *rewriter, + std::function create_element) const { + Type ptr_ty = LLVM::LLVMPointerType::get(element_ty.getContext()); + + // If the attribute is missing or empty, set the element count to 0 and + // return NULL. + if (!attr.has_value() || attr.value().empty()) { + Value zero = LLVM::ConstantOp::create( + *rewriter, loc, size_ty, rewriter->getIntegerAttr(size_ty, 0)); + Value null_ptr = LLVM::ZeroOp::create(*rewriter, loc, ptr_ty); + return std::make_pair(zero, null_ptr); + } + + // Allocate array to store the elements. + auto &array_attr = attr.value(); + Value array_size = LLVM::ConstantOp::create( + *rewriter, loc, size_ty, + rewriter->getIntegerAttr(size_ty, array_attr.size())); + Value array_ptr = LLVM::AllocaOp::create(*rewriter, loc, ptr_ty, element_ty, + array_size, /*alignment=*/0); + for (const auto &e : llvm::enumerate(array_attr)) { + Value index = LLVM::ConstantOp::create( + *rewriter, loc, size_ty, + rewriter->getIntegerAttr(size_ty, e.index())); + Value element_ptr = LLVM::GEPOp::create(*rewriter, loc, ptr_ty, + element_ty, array_ptr, index); + Value element = create_element(e.value()); + LLVM::StoreOp::create(*rewriter, loc, element, element_ptr); + } + return std::make_pair(array_size, array_ptr); + } + + std::pair ConvertIntegerArrayAttrToStackAllocatedArray( + Location loc, Type size_ty, Type element_ty, + std::optional attr, + ConversionPatternRewriter *rewriter) const { + assert(mlir::isa(size_ty) && "expect integer size type"); + assert(mlir::isa(element_ty) && "expect integer element type"); + return ConvertArrayAttrToStackAllocatedArray( + loc, size_ty, element_ty, attr, rewriter, [&](Attribute attr) { + return LLVM::ConstantOp::create( + *rewriter, loc, element_ty, + rewriter->getIntegerAttr(element_ty, + mlir::cast(attr).getInt())); + }); + } +}; + +class TFAllocOpConverter : public ConvertToLLVMCallOpPattern { + public: + using ConvertToLLVMCallOpPattern::ConvertToLLVMCallOpPattern; + + LogicalResult matchAndRewrite( + TFAllocOp tf_alloc_op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + mlir::Operation *op = tf_alloc_op.getOperation(); + Location loc = op->getLoc(); + MemRefType memref_type = tf_alloc_op.getType(); + + // Get memref descriptor sizes. + SmallVector sizes; + SmallVector strides; + Value sizeBytes; + getMemRefDescriptorSizes(loc, memref_type, + llvm::to_vector<4>(adaptor.getDynSizes()), + rewriter, sizes, strides, sizeBytes); + // Get number of elements. + Value num_elements = + getNumElements(loc, memref_type, adaptor.getDynSizes(), rewriter); + // Get element size. + Value element_size = + getSizeInBytes(loc, memref_type.getElementType(), rewriter); + + // Convert `output_index` or set it to -1 if the attribute is missing. + Type llvmInt32Type = IntegerType::get(rewriter.getContext(), 32); + Value output_index = LLVM::ConstantOp::create( + rewriter, loc, llvmInt32Type, + rewriter.getI32IntegerAttr(tf_alloc_op.getOutputIndex().has_value() + ? tf_alloc_op.getOutputIndex().value() + : -1)); + + // Convert `candidate_input_indices`. + auto candidates_count_and_ptr = + ConvertIntegerArrayAttrToStackAllocatedArray( + loc, rewriter.getI32Type(), rewriter.getI32Type(), + tf_alloc_op.getInputIndices(), &rewriter); + + // Insert function call. + FlatSymbolRefAttr tf_func_ref = + GetOrInsertLLVMFunction(GetFuncName(), GetFuncType(), op, &rewriter); + Value allocated_byte_ptr = + LLVM::CallOp::create( + rewriter, loc, getVoidPtrType(), tf_func_ref, + llvm::ArrayRef({adaptor.getCtx(), num_elements, element_size, + output_index, candidates_count_and_ptr.first, + candidates_count_and_ptr.second})) + .getResult(); + + MemRefDescriptor memRefDescriptor = CreateMemRefDescriptor( + loc, rewriter, memref_type, allocated_byte_ptr, sizes); + + // Return the final value of the descriptor. + rewriter.replaceOp(op, {memRefDescriptor}); + return success(); + } + + protected: + StringRef GetFuncName() const override { return kCInterfaceAlloc; } + + Type GetFuncType() const override { + Type llvm_i32_type = IntegerType::get(getDialect().getContext(), 32); + Type llvm_ptr_type = LLVM::LLVMPointerType::get(getDialect().getContext()); + return LLVM::LLVMFunctionType::get( + llvm_ptr_type, + llvm::ArrayRef({/*void* op_kernel_ctx*/ llvm_ptr_type, + /*size_t num_elements*/ getIndexType(), + /*size_t element_size*/ getIndexType(), + /*int32_t output_index*/ llvm_i32_type, + /*int32_t num_candidates*/ llvm_i32_type, + /*int32_t* candidate_input_indices*/ llvm_ptr_type})); + } + + private: + // TODO(pifon): Remove strides computation. + MemRefDescriptor CreateMemRefDescriptor(Location loc, + ConversionPatternRewriter &rewriter, + MemRefType memref_type, + Value allocated_byte_ptr, + ArrayRef sizes) const { + auto memref_desc = MemRefDescriptor::poison( + rewriter, loc, typeConverter->convertType(memref_type)); + + // TF AllocateRaw returns aligned pointer => AllocatedPtr == AlignedPtr. + memref_desc.setAllocatedPtr(rewriter, loc, allocated_byte_ptr); + memref_desc.setAlignedPtr(rewriter, loc, allocated_byte_ptr); + memref_desc.setConstantOffset(rewriter, loc, 0); + + if (memref_type.getRank() == 0) { + return memref_desc; + } + + // Compute strides and populate descriptor `size` and `stride` fields. + Value stride_carried = + createIndexAttrConstant(rewriter, loc, getIndexType(), 1); + for (int pos = sizes.size() - 1; pos >= 0; --pos) { + Value size = sizes[pos]; + memref_desc.setSize(rewriter, loc, pos, size); + memref_desc.setStride(rewriter, loc, pos, stride_carried); + // Update stride + if (pos > 0) { + stride_carried = + LLVM::MulOp::create(rewriter, loc, stride_carried, size); + } + } + return memref_desc; + } +}; + +class TFDeallocOpConverter : public ConvertToLLVMCallOpPattern { + public: + using ConvertToLLVMCallOpPattern::ConvertToLLVMCallOpPattern; + + LogicalResult matchAndRewrite( + TFDeallocOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + // TODO(herhut) Support unranked memrefs. + if (!mlir::isa(op.getMemref().getType())) return failure(); + MemRefDescriptor memref(adaptor.getMemref()); + + Value allocated_bytes_ptr = memref.allocatedPtr(rewriter, op.getLoc()); + + // Insert function call. + FlatSymbolRefAttr tf_func_ref = + GetOrInsertLLVMFunction(GetFuncName(), GetFuncType(), op, &rewriter); + rewriter.replaceOpWithNewOp( + op, mlir::TypeRange(), tf_func_ref, + llvm::ArrayRef({adaptor.getCtx(), allocated_bytes_ptr})); + return success(); + } + + protected: + StringRef GetFuncName() const override { return kCInterfaceDealloc; } + Type GetFuncType() const override { + return LLVM::LLVMFunctionType::get(getVoidType(), + {getVoidPtrType(), getVoidPtrType()}); + } +}; + +class JITCompileFromStrOpConverter + : public ConvertToLLVMCallOpPattern { + using ConvertToLLVMCallOpPattern< + JITCompileFromStrOp>::ConvertToLLVMCallOpPattern; + + LogicalResult matchAndRewrite( + JITCompileFromStrOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + if (adaptor.getCtx() == nullptr) return failure(); + auto loc = op.getLoc(); + std::string zero_terminated_code = op.getCode().str() + '\00'; + Value jit_module_code = CreateOrFindGlobalStringConstant( + loc, GetGlobalName(kJITCodeGlobalBaseName, zero_terminated_code), + zero_terminated_code, &rewriter); + std::pair tile_sizes = + ConvertIntegerArrayAttrToStackAllocatedArray( + loc, rewriter.getI64Type(), rewriter.getI64Type(), + op.getTileSizes(), &rewriter); + std::pair unroll_factors = + ConvertIntegerArrayAttrToStackAllocatedArray( + loc, rewriter.getI64Type(), rewriter.getI64Type(), + op.getUnrollFactors(), &rewriter); + Value enable_ftz = LLVM::ConstantOp::create( + rewriter, loc, rewriter.getI1Type(), op.getEnableFtzAttr()); + Value index_64bit = LLVM::ConstantOp::create( + rewriter, loc, rewriter.getI1Type(), op.getIndex64BitAttr()); + Value cpu_codegen = LLVM::ConstantOp::create( + rewriter, loc, rewriter.getI1Type(), op.getCpuCodegenAttr()); + FlatSymbolRefAttr tf_func_ref = + GetOrInsertLLVMFunction(GetFuncName(), GetFuncType(), op, &rewriter); + rewriter.replaceOpWithNewOp( + op, getVoidPtrType(), tf_func_ref, + llvm::ArrayRef({adaptor.getCtx(), jit_module_code, tile_sizes.first, + tile_sizes.second, unroll_factors.first, + unroll_factors.second, enable_ftz, index_64bit, + cpu_codegen})); + return success(); + } + + protected: + StringRef GetFuncName() const override { return kCInterfaceJITCompile; } + + Type GetFuncType() const override { + auto ptr_ty = LLVM::LLVMPointerType::get(getContext()); + auto i64_ty = IntegerType::get(getContext(), 64); + auto i1_ty = IntegerType::get(getContext(), 1); + return LLVM::LLVMFunctionType::get( + getVoidPtrType(), {/*void* op_kernel_ctx*/ getVoidPtrType(), + /*char* code*/ ptr_ty, + /*int64_t num_tile_sizes*/ i64_ty, + /*int64_t* tile_sizes_ptr*/ ptr_ty, + /*int64_t num_unroll_factors*/ i64_ty, + /*int64_t* unroll_factors_ptr*/ ptr_ty, + /*bool enable_ftz*/ i1_ty, + /*bool index_64bit*/ i1_ty, + /*bool cpu_codegen*/ i1_ty}); + } +}; + +class JITExecuteOpConverter : public ConvertToLLVMCallOpPattern { + public: + using ConvertToLLVMCallOpPattern::ConvertToLLVMCallOpPattern; + + LogicalResult matchAndRewrite( + JITExecuteOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + // The TF context must be known for a successful lowering. + if (adaptor.getCtx() == nullptr || op.getInputs().empty()) { + return failure(); + } + + // Allocate result on stack. + auto loc = op.getLoc(); + Type result_ty = + getTypeConverter()->convertType(op->getResultTypes().front()); + Type ptr_ty = LLVM::LLVMPointerType::get(getContext()); + Type i64_ty = rewriter.getI64Type(); + Value one = LLVM::ConstantOp::create(rewriter, loc, i64_ty, + rewriter.getI64IntegerAttr(1)); + auto result_ptr = + LLVM::AllocaOp::create(rewriter, loc, ptr_ty, result_ty, one); + + // Pass the buffer arguments as a stack-allocated array. + Type args_elem_ty = adaptor.getInputs().front().getType(); + Value num_args = LLVM::ConstantOp::create( + rewriter, loc, i64_ty, + rewriter.getI64IntegerAttr( + static_cast(adaptor.getInputs().size()))); + Value args_ptr = + LLVM::AllocaOp::create(rewriter, loc, ptr_ty, args_elem_ty, num_args, + /*alignment=*/0); + for (const auto &it : llvm::enumerate(adaptor.getInputs())) { + Value index = LLVM::ConstantOp::create( + rewriter, loc, i64_ty, rewriter.getI64IntegerAttr(it.index())); + Value element_ptr = LLVM::GEPOp::create(rewriter, loc, ptr_ty, + args_elem_ty, args_ptr, index); + LLVM::StoreOp::create(rewriter, loc, it.value(), element_ptr); + } + + // Materialize runtime call. + FlatSymbolRefAttr tf_func_ref = + GetOrInsertLLVMFunction(GetFuncName(), GetFuncType(), op, &rewriter); + LLVM::CallOp::create(rewriter, loc, mlir::TypeRange(), tf_func_ref, + ValueRange{adaptor.getCtx(), adaptor.getCallable(), + result_ptr, num_args, args_ptr}); + + // Copy result (including the descriptor) to a stack-allocated buffer and + // free the old descriptor. + llvm::SmallVector final_result = { + LLVM::LoadOp::create(rewriter, loc, result_ty, result_ptr)}; + if (failed(copyUnrankedDescriptors(rewriter, loc, op->getResultTypes(), + final_result, + /*toDynamic=*/false))) { + return failure(); + } + + rewriter.replaceOp(op, final_result.front()); + return success(); + } + + protected: + StringRef GetFuncName() const override { return kCInterfaceJITExecute; } + + Type GetFuncType() const override { + auto i64_ty = IntegerType::get(getContext(), 64); + auto ptr_ty = LLVM::LLVMPointerType::get(getContext()); + return LLVM::LLVMFunctionType::get(getVoidType(), + {/*void* op_kernel_ctx*/ ptr_ty, + /*void* callable*/ ptr_ty, + /*void* result*/ ptr_ty, + /*int64_t num_args*/ i64_ty, + /*void* args_ptr*/ ptr_ty}); + } +}; + +class ReportErrorOpConverter + : public ConvertToLLVMCallOpPattern { + public: + using ConvertToLLVMCallOpPattern::ConvertToLLVMCallOpPattern; + + LogicalResult matchAndRewrite( + ReportErrorOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + Location loc = op.getLoc(); + auto module = op->getParentOfType(); + Value message_constant = + GenerateErrorMessageConstant(loc, module, adaptor.getMsg(), rewriter); + + // Insert function call. + FlatSymbolRefAttr tf_func_ref = + GetOrInsertLLVMFunction(GetFuncName(), GetFuncType(), op, &rewriter); + Value error_code = LLVM::ConstantOp::create( + rewriter, loc, typeConverter->convertType(rewriter.getI32Type()), + adaptor.getErrorCodeAttr()); + rewriter.replaceOpWithNewOp( + op, mlir::TypeRange(), tf_func_ref, + llvm::ArrayRef({adaptor.getCtx(), error_code, message_constant})); + return success(); + } + + protected: + StringRef GetFuncName() const override { return kCInterfaceReportError; } + Type GetFuncType() const override { + MLIRContext *ctx = &getTypeConverter()->getContext(); + auto ptr_type = LLVM::LLVMPointerType::get(ctx); + auto i32_type = IntegerType::get(ctx, 32); + return LLVM::LLVMFunctionType::get(getVoidType(), + {getVoidPtrType(), i32_type, ptr_type}); + } + + private: + // Generates an LLVM IR dialect global that contains the name of the given + // kernel function as a C string, and returns a pointer to its beginning. + Value GenerateErrorMessageConstant(Location loc, Operation *module, + StringRef message, + OpBuilder &builder) const { + std::string err_str; + llvm::raw_string_ostream err_stream(err_str); + err_stream << message; + if (!mlir::isa(loc)) { + err_stream << " at "; + loc.print(err_stream); + } + err_stream << '\00'; + StringRef generated_error(err_stream.str()); + return CreateOrFindGlobalStringConstant( + loc, GetGlobalName(kErrorMessageGlobalBaseName, generated_error), + generated_error, &builder); + } +}; + +class NullContextOpConverter : public ConvertOpToLLVMPattern { + public: + using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern; + + LogicalResult matchAndRewrite( + NullContextOp op, OpAdaptor /*adaptor*/, + ConversionPatternRewriter &rewriter) const override { + rewriter.replaceOpWithNewOp(op, getVoidPtrType()); + return success(); + } +}; + +class NullMemRefOpConverter : public ConvertOpToLLVMPattern { + public: + using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern; + + LogicalResult matchAndRewrite( + NullMemRefOp null_memref_op, OpAdaptor /*adaptor*/, + ConversionPatternRewriter &rewriter) const override { + Location loc = null_memref_op->getLoc(); + const LLVMTypeConverter &type_converter = *getTypeConverter(); + MLIRContext *ctx = null_memref_op.getContext(); + mlir::Operation *op = null_memref_op.getOperation(); + + auto shaped_result_type = + mlir::cast(null_memref_op.getType()); + auto mem_space = mlir::dyn_cast_or_null( + shaped_result_type.getMemorySpace()); + unsigned address_space = + static_cast(mem_space ? mem_space.getInt() : 0); + LLVM::LLVMPointerType llvm_ptr_type = + LLVM::LLVMPointerType::get(ctx, address_space); + + Value zero = createIndexAttrConstant(rewriter, loc, getIndexType(), 0); + if (auto result_type = + mlir::dyn_cast(null_memref_op.getType())) { + // Set all dynamic sizes to 1 and compute fake strides. + SmallVector dyn_sizes( + result_type.getNumDynamicDims(), + createIndexAttrConstant(rewriter, loc, getIndexType(), 1)); + SmallVector sizes, strides; + Value sizeBytes; + getMemRefDescriptorSizes(loc, result_type, dyn_sizes, rewriter, sizes, + strides, sizeBytes); + + // Prepare packed args [allocatedPtr, alignedPtr, offset, sizes, strides] + // to create a memref descriptor. + Value null = LLVM::ZeroOp::create(rewriter, loc, llvm_ptr_type); + SmallVector packed_values{null, null, zero}; + packed_values.append(sizes); + packed_values.append(strides); + + rewriter.replaceOp( + op, MemRefDescriptor::pack(rewriter, loc, type_converter, result_type, + packed_values)); + return success(); + } + + auto result_type = mlir::cast(null_memref_op.getType()); + Type llvm_result_type = type_converter.convertType(result_type); + + auto desc = + UnrankedMemRefDescriptor::poison(rewriter, loc, llvm_result_type); + desc.setRank(rewriter, loc, zero); + + // Extract address space and element type. + auto targetType = + mlir::cast(null_memref_op.getResult().getType()); + unsigned addressSpace = + *getTypeConverter()->getMemRefAddressSpace(targetType); + + // Due to the current way of handling unranked memref results escaping, we + // have to actually construct a ranked underlying descriptor instead of just + // setting its pointer to NULL. + Value alloca_size = UnrankedMemRefDescriptor::computeSize( + rewriter, loc, *getTypeConverter(), desc, addressSpace); + Value underlying_desc_ptr = + LLVM::AllocaOp::create(rewriter, loc, getVoidPtrType(), + IntegerType::get(getContext(), 8), alloca_size); + + // Populate underlying ranked descriptor. + Value null = LLVM::ZeroOp::create(rewriter, loc, llvm_ptr_type); + UnrankedMemRefDescriptor::setAllocatedPtr( + rewriter, loc, underlying_desc_ptr, llvm_ptr_type, null); + UnrankedMemRefDescriptor::setAlignedPtr(rewriter, loc, *getTypeConverter(), + underlying_desc_ptr, llvm_ptr_type, + null); + UnrankedMemRefDescriptor::setOffset(rewriter, loc, *getTypeConverter(), + underlying_desc_ptr, llvm_ptr_type, + zero); + + desc.setMemRefDescPtr(rewriter, loc, underlying_desc_ptr); + rewriter.replaceOp(op, {desc}); + return success(); + } +}; + +class IsValidMemRefOpConverter + : public ConvertOpToLLVMPattern { + public: + using ConvertOpToLLVMPattern::ConvertOpToLLVMPattern; + + LogicalResult matchAndRewrite( + IsValidMemRefOp op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override { + Location loc = op.getLoc(); + MemRefDescriptor desc(adaptor.getArg()); + + // Compare every size in the descriptor to 0 to check num_elements == 0. + int64_t rank = mlir::cast(op.getArg().getType()).getRank(); + Value is_empty_shape = LLVM::ConstantOp::create( + rewriter, loc, rewriter.getI1Type(), rewriter.getBoolAttr(false)); + Value zero = createIndexAttrConstant(rewriter, loc, getIndexType(), 0); + for (int i = 0; i < rank; ++i) { + Value size = desc.size(rewriter, loc, i); + Value is_zero_size = + LLVM::ICmpOp::create(rewriter, loc, rewriter.getI1Type(), + LLVM::ICmpPredicate::eq, size, zero); + is_empty_shape = + LLVM::OrOp::create(rewriter, loc, is_empty_shape, is_zero_size); + } + + Value ptr = desc.allocatedPtr(rewriter, loc); + Value null = LLVM::ZeroOp::create(rewriter, loc, getVoidPtrType()); + Value is_not_nullptr = + LLVM::ICmpOp::create(rewriter, loc, rewriter.getI1Type(), + LLVM::ICmpPredicate::ne, ptr, null); + + // Valid memref = ptr != NULL || num_elements == 0; + rewriter.replaceOpWithNewOp(op, is_not_nullptr, is_empty_shape); + return success(); + } +}; + +} // namespace + +void PopulateTFFrameworkToLLVMConversionPatterns(LLVMTypeConverter *converter, + RewritePatternSet *patterns) { + // clang-format off + patterns->add< + IsValidMemRefOpConverter, + JITCompileFromStrOpConverter, + JITExecuteOpConverter, + NullContextOpConverter, + NullMemRefOpConverter, + ReportErrorOpConverter, + TFAllocOpConverter, + TFDeallocOpConverter>(*converter); + // clang-format on +} + +} // namespace tf_framework +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_kernel_to_llvm_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_kernel_to_llvm_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..07faee62cbbd2ade9bec0bc3d356cf72f57226cb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/tf_kernel_to_llvm_pass.cc @@ -0,0 +1,316 @@ +/* Copyright 2020 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 +#include +#include + +#include "llvm/ADT/STLExtras.h" +#include "mlir/Conversion/ArithToLLVM/ArithToLLVM.h" // from @llvm-project +#include "mlir/Conversion/ComplexToLLVM/ComplexToLLVM.h" // from @llvm-project +#include "mlir/Conversion/ControlFlowToLLVM/ControlFlowToLLVM.h" // from @llvm-project +#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVM.h" // from @llvm-project +#include "mlir/Conversion/FuncToLLVM/ConvertFuncToLLVMPass.h" // from @llvm-project +#include "mlir/Conversion/GPUCommon/GPUCommonPass.h" // from @llvm-project +#include "mlir/Conversion/LLVMCommon/Pattern.h" // from @llvm-project +#include "mlir/Conversion/MathToLLVM/MathToLLVM.h" // from @llvm-project +#include "mlir/Conversion/MathToLibm/MathToLibm.h" // from @llvm-project +#include "mlir/Conversion/MemRefToLLVM/MemRefToLLVM.h" // from @llvm-project +#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" // from @llvm-project +#include "mlir/Conversion/VectorToLLVM/ConvertVectorToLLVM.h" // from @llvm-project +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Arith/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Complex/IR/Complex.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/GPU/IR/GPUDialect.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMAttrs.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMTypes.h" // from @llvm-project +#include "mlir/Dialect/Math/IR/Math.h" // from @llvm-project +#include "mlir/Dialect/MemRef/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/MemRef/Transforms/Transforms.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tools/kernel_gen/ir/tf_framework_ops.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/passes.h" +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/rewriters.h" + +namespace mlir { +namespace kernel_gen { +namespace transforms { +namespace { + +constexpr StringRef kTfWrapperLibaryLaunchHelperName = + "_mlir_ciface_tf_launch_kernel"; + +#define GEN_PASS_DEF_TFKERNELTOLLVMPASS +#include "tensorflow/compiler/mlir/tools/kernel_gen/transforms/kernel_gen_passes.h.inc" + +/// A rewrite patter to convert gpu.launch_func operations into a runtime call +/// for the TensorFlow runtime. +class ConvertLaunchFuncOpToTfRuntimeCallPattern + : public ConvertOpToLLVMPattern { + public: + ConvertLaunchFuncOpToTfRuntimeCallPattern(LLVMTypeConverter &type_converter, + StringRef gpu_binary_annotation) + : ConvertOpToLLVMPattern(type_converter), + gpu_binary_annotation_(gpu_binary_annotation) {} + + private: + Value generateParamsArray(gpu::LaunchFuncOp launch_op, OpAdaptor adaptor, + OpBuilder &builder) const; + + LogicalResult matchAndRewrite( + gpu::LaunchFuncOp launch_op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const override; + + MLIRContext *context_ = &this->getTypeConverter()->getContext(); + + Type llvm_void_type_ = LLVM::LLVMVoidType::get(context_); + Type llvm_pointer_type_ = LLVM::LLVMPointerType::get(context_); + Type llvm_int8_type_ = IntegerType::get(context_, 8); + Type llvm_int32_type_ = IntegerType::get(context_, 32); + Type llvm_int64_type_ = IntegerType::get(context_, 64); + Type llvm_intptr_type_ = IntegerType::get( + context_, this->getTypeConverter()->getPointerBitwidth(0)); + + llvm::SmallString<32> gpu_binary_annotation_; +}; + +// Creates a struct containing all kernel parameters on the stack and returns +// an array of type-erased pointers to the fields of the struct. The array can +// then be passed to the CUDA / ROCm (HIP) kernel launch calls. +// The generated code is essentially as follows: +// +// %struct = alloca(sizeof(struct { Parameters... })) +// %array = alloca(NumParameters * sizeof(void *)) +// for (i : [0, NumParameters)) +// %fieldPtr = llvm.getelementptr %struct[0, i] +// llvm.store parameters[i], %fieldPtr +// %elementPtr = llvm.getelementptr %array[i] +// llvm.store %fieldPtr, %elementPtr +// return %array +Value ConvertLaunchFuncOpToTfRuntimeCallPattern::generateParamsArray( + gpu::LaunchFuncOp launch_op, OpAdaptor adaptor, OpBuilder &builder) const { + auto loc = launch_op.getLoc(); + auto num_kernel_operands = launch_op.getNumKernelOperands(); + auto arguments = getTypeConverter()->promoteOperands( + loc, launch_op.getOperands().take_back(num_kernel_operands), + adaptor.getKernelOperands().take_back(num_kernel_operands), builder); + auto num_arguments = arguments.size(); + SmallVector argument_types; + argument_types.reserve(num_arguments); + for (auto argument : arguments) argument_types.push_back(argument.getType()); + auto struct_type = LLVM::LLVMStructType::getNewIdentified( + context_, StringRef(), argument_types); + auto one = LLVM::ConstantOp::create(builder, loc, llvm_int32_type_, + builder.getI32IntegerAttr(1)); + auto struct_ptr = LLVM::AllocaOp::create(builder, loc, llvm_pointer_type_, + struct_type, one, /*alignment=*/0); + auto array_size = LLVM::ConstantOp::create( + builder, loc, llvm_int32_type_, builder.getI32IntegerAttr(num_arguments)); + auto array_ptr = + LLVM::AllocaOp::create(builder, loc, llvm_pointer_type_, + llvm_pointer_type_, array_size, /*alignment=*/0); + auto zero = LLVM::ConstantOp::create(builder, loc, llvm_int32_type_, + builder.getI32IntegerAttr(0)); + for (auto en : llvm::enumerate(arguments)) { + auto index = LLVM::ConstantOp::create( + builder, loc, llvm_int32_type_, builder.getI32IntegerAttr(en.index())); + auto field_ptr = LLVM::GEPOp::create( + builder, loc, llvm_pointer_type_, struct_type, struct_ptr, + ArrayRef{zero, index.getResult()}); + LLVM::StoreOp::create(builder, loc, en.value(), field_ptr); + auto element_ptr = + LLVM::GEPOp::create(builder, loc, llvm_pointer_type_, + llvm_pointer_type_, array_ptr, index.getResult()); + LLVM::StoreOp::create(builder, loc, field_ptr, element_ptr); + } + return array_ptr; +} + +// Emits LLVM IR to launch a kernel function. Expects the module that contains +// the compiled kernel function as a cubin in the 'nvvm.cubin' attribute, or a +// hsaco in the 'rocdl.hsaco' attribute of the kernel function in the IR. +// +// %0 = call %binarygetter +// %1 = +// %2 = +// call %tfLaunchKernel(%ctx, %0, %1, , %2) +LogicalResult ConvertLaunchFuncOpToTfRuntimeCallPattern::matchAndRewrite( + gpu::LaunchFuncOp launch_op, OpAdaptor adaptor, + ConversionPatternRewriter &rewriter) const { + if (!launch_op.getAsyncDependencies().empty() || launch_op.getAsyncToken()) { + return rewriter.notifyMatchFailure( + launch_op, "Cannot convert with async dependency or result."); + } + + Location loc = launch_op.getLoc(); + + // Create an LLVM global with CUBIN extracted from the kernel annotation and + // obtain a pointer to the first byte in it. + auto kernel_module = SymbolTable::lookupNearestSymbolFrom( + launch_op, launch_op.getKernelModuleName()); + assert(kernel_module && "expected a kernel module"); + + auto binary_attr = + kernel_module->getAttrOfType(gpu_binary_annotation_); + if (!binary_attr) { + kernel_module.emitOpError() + << "missing " << gpu_binary_annotation_ << " attribute"; + return failure(); + } + + // Create a global for the module blob. + SmallString<128> name_buffer(kernel_module.getName()); + name_buffer.append("_blob"); + Value module_blob = LLVM::createGlobalString(loc, rewriter, name_buffer.str(), + binary_attr.getValue(), + LLVM::Linkage::Internal); + + // Make sure the trailing zero is included in the constant. + auto kernel_name = launch_op.getKernelName().getValue(); + SmallString<128> kernel_name_buffer(kernel_name); + kernel_name_buffer.push_back('\0'); + + // Create a global for the kernel name. + SmallString<128> kernel_name_global_name_buffer; + auto kernel_name_global_name = + (kernel_module.getName() + "_" + kernel_name + "_kernel_name") + .toStringRef(kernel_name_global_name_buffer); + auto kernel_name_global = LLVM::createGlobalString( + loc, rewriter, kernel_name_global_name, kernel_name_buffer, + LLVM::Linkage::Internal); + + // The TensorFlow OpKernelContext is the first argument of the surrounding + // LLVMFunc. + Value context_arg = + launch_op->getParentOfType().getArgument(0); + auto kernel_params = generateParamsArray(launch_op, adaptor, rewriter); + + auto libraryLaunchNameAttr = + mlir::StringAttr::get(loc.getContext(), kTfWrapperLibaryLaunchHelperName); + auto function = SymbolTable::lookupNearestSymbolFrom( + launch_op, libraryLaunchNameAttr); + if (!function) { + PatternRewriter::InsertionGuard guard(rewriter); + auto function_type = LLVM::LLVMFunctionType::get( + llvm_void_type_, { + llvm_pointer_type_, /* void* context */ + llvm_pointer_type_, /* void* module_blob */ + llvm_pointer_type_, /* void* function_name */ + llvm_intptr_type_, /* intptr_t grid_x_dim */ + llvm_intptr_type_, /* intptr_t grid_y_dim */ + llvm_intptr_type_, /* intptr_t grid_z_dim */ + llvm_intptr_type_, /* intptr_t block_x_dim */ + llvm_intptr_type_, /* intptr_t block_y_dim */ + llvm_intptr_type_, /* intptr_t block_z_dim */ + llvm_pointer_type_, /* void **kernel_params */ + }); + rewriter.setInsertionPointToStart( + launch_op->getParentOfType().getBody()); + function = LLVM::LLVMFuncOp::create( + rewriter, loc, kTfWrapperLibaryLaunchHelperName, function_type); + } + LLVM::CallOp::create( + rewriter, loc, TypeRange(), mlir::SymbolRefAttr::get(function), + + ArrayRef{context_arg, module_blob, kernel_name_global, + adaptor.getGridSizeX(), adaptor.getGridSizeY(), + adaptor.getGridSizeZ(), adaptor.getBlockSizeX(), + adaptor.getBlockSizeY(), adaptor.getBlockSizeZ(), + kernel_params}); + + rewriter.eraseOp(launch_op); + return success(); +} + +class TFKernelToLLVMPass + : public impl::TFKernelToLLVMPassBase { + void getDependentDialects(DialectRegistry ®istry) const override { + registry.insert(); + } + + public: + explicit TFKernelToLLVMPass(StringRef blob_annotation) { + if (!blob_annotation.empty()) { + blob_annotation_ = blob_annotation.str(); + } + } + + void runOnOperation() override { + ModuleOp m = getOperation(); + + // Populate type conversions. + MLIRContext *ctx = m.getContext(); + LowerToLLVMOptions options(&getContext()); + LLVMTypeConverter type_converter(ctx, options); + type_converter.addConversion([&](tf_framework::OpKernelContextType type) { + return LLVM::LLVMPointerType::get(type.getContext()); + }); + type_converter.addConversion([&](tf_framework::JITCallableType type) { + return LLVM::LLVMPointerType::get(type.getContext()); + }); + + // Populate patterns. + RewritePatternSet patterns(&getContext()); + arith::populateArithExpandOpsPatterns(patterns); + memref::populateExpandOpsPatterns(patterns); + arith::populateArithToLLVMConversionPatterns(type_converter, patterns); + populateFinalizeMemRefToLLVMConversionPatterns(type_converter, patterns); + populateMathToLLVMConversionPatterns(type_converter, patterns); + populateFuncToLLVMConversionPatterns(type_converter, patterns); + cf::populateControlFlowToLLVMConversionPatterns(type_converter, patterns); + populateComplexToLLVMConversionPatterns(type_converter, patterns); + populateVectorToLLVMConversionPatterns(type_converter, patterns); + populateMathToLibmConversionPatterns(patterns); + tf_framework::PopulateTFFrameworkToLLVMConversionPatterns(&type_converter, + &patterns); + patterns.add(type_converter, + blob_annotation_); + // Set target. + ConversionTarget target(*ctx); + target.addLegalDialect(); + target.addIllegalDialect< + arith::ArithDialect, func::FuncDialect, complex::ComplexDialect, + gpu::GPUDialect, tf_framework::TFFrameworkDialect, math::MathDialect>(); + // Mark modules as legal. + target.addLegalOp(); + // Do not look into gpu modules, only consider host-side. + target.markOpRecursivelyLegal(); + // Unrealized conversion casts are cleaned up by a separate pass. + target.addLegalOp(); + + if (failed(applyFullConversion(m, target, std::move(patterns)))) { + signalPassFailure(); + } + + // Finally, strip the GPU modules, as they are no longer needed. + for (auto op : llvm::make_early_inc_range(m.getOps())) { + op.erase(); + } + } +}; + +} // namespace + +std::unique_ptr > CreateTFKernelToLLVMPass( + StringRef blob_annotation) { + return std::make_unique(blob_annotation); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..7fce123969f603170db48e5941958b30605ddd46 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.cc @@ -0,0 +1,71 @@ +/* Copyright 2022 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/mlir/tools/kernel_gen/transforms/utils.h" + +#include + +#include "llvm/Support/FormatVariadic.h" +#include "mlir/Dialect/LLVMIR/LLVMAttrs.h" // from @llvm-project +#include "mlir/Dialect/LLVMIR/LLVMDialect.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project + +namespace mlir { +namespace kernel_gen { +namespace transforms { + +using LLVM::LLVMFuncOp; + +FlatSymbolRefAttr GetOrInsertLLVMFunction(StringRef func_name, Type func_type, + Operation* op, OpBuilder* b) { + auto module = op->getParentOfType(); + auto tf_func = module.lookupSymbol(func_name); + if (!tf_func) { + OpBuilder::InsertionGuard guard(*b); + b->setInsertionPointToStart(module.getBody()); + tf_func = LLVMFuncOp::create(*b, b->getUnknownLoc(), func_name, func_type); + } + return SymbolRefAttr::get(b->getContext(), func_name); +} + +std::string GetGlobalName(StringRef base, StringRef content) { + return llvm::formatv("{0}_{1}", base, llvm::hash_value(content)); +} + +Value CreateOrFindGlobalStringConstant(Location loc, StringRef global_name, + StringRef content, OpBuilder* b) { + auto module = + b->getInsertionBlock()->getParentOp()->getParentOfType(); + Operation* global_constant = SymbolTable::lookupNearestSymbolFrom( + module, b->getStringAttr(global_name)); + if (global_constant) { + auto global_op = cast(global_constant); + StringRef symbol_name = global_op.getName(); + Type symbol_type = global_op.getType(); + Type ptr_type = LLVM::LLVMPointerType::get(b->getContext()); + Value global_ptr = + LLVM::AddressOfOp::create(*b, loc, ptr_type, symbol_name); + Value c0 = + LLVM::ConstantOp::create(*b, loc, b->getI64Type(), b->getIndexAttr(0)); + return LLVM::GEPOp::create(*b, loc, ptr_type, symbol_type, global_ptr, + ValueRange{c0, c0}); + } + return LLVM::createGlobalString(loc, *b, global_name, content, + LLVM::Linkage::Internal); +} + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..3cfb1463ec682cdb2d987ac186afb238a00938a2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/kernel_gen/transforms/utils.h @@ -0,0 +1,43 @@ +/* Copyright 2022 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_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_UTILS_H_ + +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project + +namespace mlir { +namespace kernel_gen { +namespace transforms { + +// Attempts to find function symbol in the module, adds it if not found. +FlatSymbolRefAttr GetOrInsertLLVMFunction(StringRef func_name, Type func_type, + Operation* op, OpBuilder* b); + +// Attemts to find a global string constant in the module, adds it if not found. +Value CreateOrFindGlobalStringConstant(Location loc, StringRef global_name, + StringRef content, OpBuilder* builder); + +// Generates a global name with the format "base_hash(content)". +std::string GetGlobalName(StringRef base, StringRef content); + +} // namespace transforms +} // namespace kernel_gen +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_KERNEL_GEN_TRANSFORMS_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..4a73ab5f7a81d1694ce4282bc03e742d212d3450 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/BUILD @@ -0,0 +1,23 @@ +load("@rules_cc//cc:cc_library.bzl", "cc_library") +load("//tensorflow:tensorflow.default.bzl", "get_compatible_with_portable") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [ + "//visibility:public", + ], + licenses = ["notice"], +) + +cc_library( + name = "quantization_utils", + srcs = ["quantization_utils.cc"], + hdrs = ["quantization_utils.h"], + compatible_with = get_compatible_with_portable(), + deps = [ + "//tensorflow/compiler/mlir/tools:safe_cast", + "//tensorflow/core/framework:tensor_shape", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/types:span", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/quantization_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/quantization_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..cc201a3d298718a413c24abce709e31eb5dbd017 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/quantization_utils.cc @@ -0,0 +1,129 @@ +/* Copyright 2024 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/mlir/tools/optimize/quantization_utils.h" + +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/mlir/tools/safe_cast.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace tflite_migration { +namespace optimize { +namespace utils { + +namespace { + +const int8_t kMinQuantizedValue8bit = -127; +const int8_t kMaxQuantizedValue8bit = 127; + +// const int8_t kMinQuantizedValue4bit = -7; +// const int8_t kMaxQuantizedValue4bit = 7; + +// The maximum number of dimensions supported in per-channel quantization. +constexpr int kPerChannelMaxDim = 4; +} // namespace + +template +std::vector SymmetricBiasQuantize(const float* data, + uint64_t num_elements, + const std::vector& scales) { + std::vector buffer(num_elements); + const BiasType kScale = std::numeric_limits::max(); + float scaling_factor_inv_per_layer = (scales[0] == 0) ? 0 : 1.0 / scales[0]; + + for (int32_t idx = 0; idx < num_elements; idx++) { + float scaling_factor_inv = + scales.size() == 1 ? scaling_factor_inv_per_layer + : ((scales[idx] == 0) ? 0 : 1.0 / scales[idx]); + const BiasType quantized_value = + tools::SafeCast(std::round(data[idx] * scaling_factor_inv)); + buffer[idx] = std::min(kScale, std::max(-kScale, quantized_value)); + } + return buffer; +} + +template std::vector SymmetricBiasQuantize( + const float* data, uint64_t num_elements, const std::vector& scales); + +template std::vector SymmetricBiasQuantize( + const float* data, uint64_t num_elements, const std::vector& scales); + +std::vector SymmetricQuantizeFloatsToInt16(const float* data, + uint64_t num_elements, + float scaling_factor) { + // Compute the inverse of scale. + const float scaling_factor_inv = + (scaling_factor == 0) ? 0 : 1.0 / scaling_factor; + std::vector buffer(num_elements); + const int32_t kScale = std::numeric_limits::max(); + + for (size_t i = 0; i < num_elements; i++) { + const int32_t quantized_value = + static_cast(std::round(data[i] * scaling_factor_inv)); + buffer[i] = std::min(kScale, std::max(-kScale, quantized_value)); + } + return buffer; +} + +void SymmetricPerChannelQuantizeValues(const float* const input, + const std::vector& scales_inv, + const std::vector& dimension, + int32_t channel_dim_index, + std::vector* output_value) { + // Quantize the values. + int indices[kPerChannelMaxDim]; + tensorflow::TensorShape unextended_shape; + CHECK_OK(tensorflow::TensorShapeUtils::MakeShape(absl::MakeSpan(dimension), + &unextended_shape)); + tensorflow::TensorShape shape; + for (int i = 0; i < kPerChannelMaxDim - unextended_shape.dims(); ++i) { + CHECK_OK(shape.AddDimWithStatus(1)); + } + CHECK_OK(shape.AppendShapeWithStatus(unextended_shape)); + channel_dim_index += kPerChannelMaxDim - unextended_shape.dims(); + + for (indices[0] = 0; indices[0] < shape.dim_size(0); indices[0]++) { + for (indices[1] = 0; indices[1] < shape.dim_size(1); indices[1]++) { + for (indices[2] = 0; indices[2] < shape.dim_size(2); indices[2]++) { + for (indices[3] = 0; indices[3] < shape.dim_size(3); indices[3]++) { + int channel_idx = indices[channel_dim_index]; + int index = 0; + int current_stride = 1; + for (int i = kPerChannelMaxDim - 1; i >= 0; --i) { + index += indices[i] * current_stride; + current_stride *= shape.dim_size(i); + } + const float val = input[index]; + const int32_t quantized_value = + static_cast(std::round(val * scales_inv[channel_idx])); + output_value->at(index) = std::min( + kMaxQuantizedValue8bit, + std::max(kMinQuantizedValue8bit, quantized_value)); + } + } + } + } +} + +} // namespace utils +} // namespace optimize +} // namespace tflite_migration diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/quantization_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/quantization_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b76ee719281d7eea191f3a83b2ab0d9bf48e0a56 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/optimize/quantization_utils.h @@ -0,0 +1,45 @@ +/* Copyright 2024 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_MLIR_TOOLS_OPTIMIZE_QUANTIZATION_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_OPTIMIZE_QUANTIZATION_UTILS_H_ + +#include +#include + +namespace tflite_migration { +namespace optimize { +namespace utils { + +template +std::vector SymmetricBiasQuantize(const float* data, + uint64_t num_elements, + const std::vector& scales); + +std::vector SymmetricQuantizeFloatsToInt16(const float* data, + uint64_t num_elements, + float scaling_factor); + +// Quantize the values given an array of scales. +void SymmetricPerChannelQuantizeValues(const float* input, + const std::vector& scales_inv, + const std::vector& dimension, + int32_t channel_dim_index, + std::vector* output_value); + +} // namespace utils +} // namespace optimize +} // namespace tflite_migration + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_OPTIMIZE_QUANTIZATION_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/safe_cast.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/safe_cast.h new file mode 100644 index 0000000000000000000000000000000000000000..15a52fdf0d6042a4eadb8dd42a5d4d70c2b9f01b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/safe_cast.h @@ -0,0 +1,89 @@ +/* Copyright 2025 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_MLIR_TOOLS_SAFE_CAST_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_SAFE_CAST_H_ + +#include +#include + +namespace tools { + +// Converts a floating-point number to an integer. For all inputs x where +// static_cast(x) is legal according to the C++ standard, the result +// is identical to that cast (i.e. the result is x with its fractional part +// truncated whenever that is representable as IntOut). +// +// static_cast would cause undefined behavior for the following cases, which +// have well-defined behavior for this function: +// +// 1. If x is NaN, the result is zero. +// +// 2. If the truncated form of x is above the representable range of IntOut, +// the result is std::numeric_limits::max(). +// +// 3. If the truncated form of x is below the representable range of IntOut, +// the result is std::numeric_limits::min(). +// +// Note that cases #2 and #3 cover infinities as well as finite numbers. +// +// The range of FloatIn must include the range of IntOut, otherwise +// the results are undefined. +// TODO(sfeuz): Replace by absl::SafeCast once available. +template +IntOut SafeCast(FloatIn x) { + static_assert(!std::numeric_limits::is_integer, + "FloatIn is integer"); + static_assert(std::numeric_limits::is_integer, + "IntOut is not integer"); + static_assert(std::numeric_limits::radix == 2, "IntOut is base 2"); + + // Special case NaN, for which the logic below doesn't work. + if (std::isnan(x)) { + return 0; + } + + // Negative values all clip to zero for unsigned results. + if (!std::numeric_limits::is_signed && x < 0) { + return 0; + } + + // Handle infinities. + if (std::isinf(x)) { + return x < 0 ? std::numeric_limits::min() + : std::numeric_limits::max(); + } + + // Set exp such that x == f * 2^exp for some f with |f| in [0.5, 1.0), + // unless x is zero in which case exp == 0. Note that this implies that the + // magnitude of x is strictly less than 2^exp. + int exp = 0; + std::frexp(x, &exp); + + // Let N be the number of non-sign bits in the representation of IntOut. If + // the magnitude of x is strictly less than 2^N, the truncated version of x + // is representable as IntOut. The only representable integer for which this + // is not the case is kMin for signed types (i.e. -2^N), but that is covered + // by the fall-through below. + if (exp <= std::numeric_limits::digits) { + return x; + } + + // Handle numbers with magnitude >= 2^N. + return x < 0 ? std::numeric_limits::min() + : std::numeric_limits::max(); +} +} // namespace tools + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_SAFE_CAST_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.cc new file mode 100644 index 0000000000000000000000000000000000000000..7f6a493286c524ed23aabe544c62baaed78b59c7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.cc @@ -0,0 +1,161 @@ +/* Copyright 2019 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/mlir/tools/tf_mlir_translate_cl.h" + +#include + +#include "llvm/Support/CommandLine.h" + +// These command-line options are following LLVM conventions because we also +// need to register the TF Graph(Def) to MLIR conversion with mlir-translate, +// which expects command-line options of such style. + +using llvm::cl::opt; + +// Import options. +// NOLINTNEXTLINE +opt input_arrays( + "tf-input-arrays", llvm::cl::desc("Input tensor names, separated by ','"), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt input_dtypes( + "tf-input-data-types", + llvm::cl::desc("(Optional) Input tensor data types, separated by ','. Use " + "'' if a single data type is skipped. The data type from " + "the import graph is used if it is skipped."), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt input_shapes( + "tf-input-shapes", + llvm::cl::desc( + "Input tensor shapes. Shapes for different tensors are separated by " + "':', and dimension sizes for the same tensor are separated by ','"), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt output_arrays( + "tf-output-arrays", llvm::cl::desc("Output tensor names, separated by ','"), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt control_output_arrays( + "tf-control-output-arrays", + llvm::cl::desc("Control output node names, separated by ','"), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt inference_type( + "tf-inference-type", + llvm::cl::desc( + "Sets the type of real-number arrays in the output file. Only allows " + "float and quantized types"), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt min_values( + "tf-input-min-values", + llvm::cl::desc( + "Sets the lower bound of the input data. Separated by ','; Each entry " + "in the list should match an entry in -tf-input-arrays. This is " + "used when -tf-inference-type is a quantized type."), + llvm::cl::Optional, llvm::cl::init("")); + +// NOLINTNEXTLINE +opt max_values( + "tf-input-max-values", + llvm::cl::desc( + "Sets the upper bound of the input data. Separated by ','; Each entry " + "in the list should match an entry in -tf-input-arrays. This is " + "used when -tf-inference-type is a quantized type."), + llvm::cl::Optional, llvm::cl::init("")); + +// NOLINTNEXTLINE +opt debug_info_file( + "tf-debug-info", + llvm::cl::desc("Path to the debug info file of the input graph def"), + llvm::cl::init("")); + +// NOLINTNEXTLINE +opt xla_compile_device_type( + "tf-xla-compile-device-type", + llvm::cl::desc("Sets the compilation device type of the input graph def"), + llvm::cl::init("")); + +// TODO(b/134792656): If pruning is moved into TF dialect as a pass +// we should remove this. +// NOLINTNEXTLINE +opt prune_unused_nodes( + "tf-prune-unused-nodes", + llvm::cl::desc("Prune unused nodes in the input graphdef"), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt convert_legacy_fed_inputs( + "tf-convert-legacy-fed-inputs", + llvm::cl::desc( + "Eliminate LegacyFedInput nodes by replacing them with Placeholder"), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt graph_as_function("tf-graph-as-function", + llvm::cl::desc("Treat main graph as a function"), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt upgrade_legacy("tf-upgrade-legacy", + llvm::cl::desc("Upgrade legacy TF graph behavior"), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt enable_shape_inference( + "tf-enable-shape-inference-on-import", + llvm::cl::desc("Enable shape inference on import (temporary)"), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt unconditionally_use_set_output_shapes( + "tf-enable-unconditionally-use-set-output-shapes-on-import", + llvm::cl::desc("Enable using the _output_shapes unconditionally on import " + "(temporary)"), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt enable_soft_placement( + "tf-enable-soft-placement-on-import", + llvm::cl::desc("Enable soft device placement on import."), + llvm::cl::init(false)); + +// NOLINTNEXTLINE +opt set_original_tf_func_name( + "tf-set-original-tf-func-name-on-import", + llvm::cl::desc("Set original TF function name on importi."), + llvm::cl::init(false)); + +// Export options. +// NOLINTNEXTLINE +opt export_entry_func_to_flib( + "tf-export-entry-func-to-flib", + llvm::cl::desc( + "Export entry function to function library instead of graph"), + llvm::cl::init(false)); +// NOLINTNEXTLINE +opt export_original_tf_func_name( + "tf-export-original-func-name", + llvm::cl::desc("Export functions using the name set in the attribute " + "'tf._original_func_name' if it exists."), + llvm::cl::init(false)); diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.h new file mode 100644 index 0000000000000000000000000000000000000000..02f7ca62d9ee97969c117f1e52b950808639cefa --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.h @@ -0,0 +1,54 @@ +/* Copyright 2019 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_MLIR_TOOLS_TF_MLIR_TRANSLATE_CL_H_ +#define TENSORFLOW_COMPILER_MLIR_TOOLS_TF_MLIR_TRANSLATE_CL_H_ + +// This file contains command-line options aimed to provide the parameters +// required by the TensorFlow Graph(Def) to MLIR module conversion. It is only +// intended to be included by binaries. + +#include + +#include "llvm/Support/CommandLine.h" + +// Please see the implementation file for documentation of these options. + +// Import options. +extern llvm::cl::opt input_arrays; +extern llvm::cl::opt input_dtypes; +extern llvm::cl::opt input_shapes; +extern llvm::cl::opt output_arrays; +extern llvm::cl::opt control_output_arrays; +extern llvm::cl::opt inference_type; +extern llvm::cl::opt min_values; +extern llvm::cl::opt max_values; +extern llvm::cl::opt debug_info_file; +extern llvm::cl::opt xla_compile_device_type; +extern llvm::cl::opt prune_unused_nodes; +extern llvm::cl::opt convert_legacy_fed_inputs; +extern llvm::cl::opt graph_as_function; +extern llvm::cl::opt upgrade_legacy; +// TODO(jpienaar): Temporary flag, flip default and remove. +extern llvm::cl::opt enable_shape_inference; +extern llvm::cl::opt unconditionally_use_set_output_shapes; +extern llvm::cl::opt enable_soft_placement; +extern llvm::cl::opt set_original_tf_func_name; + +// Export options. +extern llvm::cl::opt export_entry_func_to_flib; +extern llvm::cl::opt export_original_tf_func_name; + +#endif // TENSORFLOW_COMPILER_MLIR_TOOLS_TF_MLIR_TRANSLATE_CL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_registration.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_registration.cc new file mode 100644 index 0000000000000000000000000000000000000000..8edff70d5f8a6392cb92d7caeec622fc8fb17213 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tools/tf_mlir_translate_registration.cc @@ -0,0 +1,51 @@ +/* Copyright 2019 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. +==============================================================================*/ + +// This file wraps TensorFlow Graph(Def) to MLIR module conversion into passes +// to satisfy the API of MLIR pass registration. In order to do this, the +// command-line option header is pulled in. + +#include + +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Tools/mlir-translate/Translation.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tensorflow/translate/tools/file_tf_mlir_translate.h" +#include "tensorflow/compiler/mlir/tools/tf_mlir_translate_cl.h" +#include "tensorflow/core/framework/graph.pb.h" + +namespace mlir { +using tsl::Status; +using tsl::StatusOr; + + +static OwningOpRef GraphdefToSplattedMlirTranslateFunction( + llvm::StringRef input, MLIRContext* context) { + tensorflow::GraphdefToMlirOptions options{ + debug_info_file, xla_compile_device_type, + prune_unused_nodes, convert_legacy_fed_inputs, + graph_as_function, upgrade_legacy, + enable_shape_inference, unconditionally_use_set_output_shapes}; + auto module_or = tensorflow::GraphdefToSplattedMlirTranslateFunction( + input, input_arrays, input_dtypes, input_shapes, output_arrays, + control_output_arrays, options, context); + if (!module_or.status().ok()) return nullptr; + return std::move(module_or).value(); +} + +static TranslateToMLIRRegistration GraphdefToSplattedMlirTranslate( + "graphdef-to-splatted-mlir", "graphdef-to-splatted-mlir", + GraphdefToSplattedMlirTranslateFunction); + +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..9efe09dfe80f517023ef1643aa0ad60530df47a3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/BUILD @@ -0,0 +1,298 @@ +# TensorFlow -> TOSA Compiler Bridge. +# See: +# https://developer.mlplatform.org/w/tosa/ +# https://github.com/llvm/llvm-project/blob/main/mlir/docs/Dialects/TOSA.md + +load("@llvm-project//mlir:tblgen.bzl", "gentbl_cc_library") +load("//tensorflow:tensorflow.bzl", "tf_cc_binary") +load("//tensorflow:tensorflow.default.bzl", "get_compatible_with_portable") + +# TODO: Tighten visibility once targets are at the right granularity. +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [":internal"], + licenses = ["notice"], +) + +package_group( + name = "internal", + packages = [ + "//tensorflow/compiler/mlir/tosa/...", + ], +) + +filegroup( + name = "tosa_ops_td_files", + srcs = [ + "@llvm-project//mlir:TosaDialectTdFiles", + ], + compatible_with = get_compatible_with_portable(), +) + +gentbl_cc_library( + name = "tosa_passes_inc_gen", + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + tbl_outs = [ + ( + [ + "-gen-pass-decls", + "-name=LegalizeTosa", + ], + "transforms/passes.h.inc", + ), + ], + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "transforms/passes.td", + deps = [ + "@llvm-project//mlir:PassBaseTdFiles", + ], +) + +cc_library( + name = "passes_header", + hdrs = [ + "transforms/passes.h", + "transforms/passes.h.inc", + ], + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + deps = [ + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Pass", + ], +) + +cc_library( + name = "legalize_common", + srcs = [ + "transforms/legalize_common.cc", + "transforms/legalize_utils.cc", + ], + hdrs = [ + "transforms/legalize_common.h", + "transforms/legalize_utils.h", + ], + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + deps = [ + "//tensorflow/compiler/mlir/lite:tensorflow_lite", + "//tensorflow/compiler/mlir/lite/kernels/internal:common", + "//tensorflow/compiler/mlir/lite/kernels/internal:quantization_util", + "//tensorflow/compiler/mlir/lite/quantization/ir:QuantOps", + "//tensorflow/compiler/mlir/tensorflow:dynamic_shape_utils", + "//tensorflow/core:framework", + "//tensorflow/core/kernels:conv_grad_shape_utils", + "//tensorflow/lite/kernels/internal:reference_base", + "@com_google_absl//absl/status", + "@gemmlowp", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:ArithDialect", + "@llvm-project//mlir:ArithUtils", + "@llvm-project//mlir:DialectUtils", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:InferTypeOpInterface", + "@llvm-project//mlir:QuantOps", + "@llvm-project//mlir:Rewrite", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TensorDialect", + "@llvm-project//mlir:TosaDialect", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + "@xla//xla/tsl/framework/fixedpoint", + ], +) + +gentbl_cc_library( + name = "tosa_legalize_tf_inc_gen", + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + tbl_outs = [ + ( + ["-gen-rewriters"], + "transforms/tf_legalize_patterns.inc", + ), + ], + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "transforms/tf_legalize_patterns.td", + deps = [ + ":tosa_ops_td_files", + "//tensorflow/compiler/mlir/lite/quantization/ir:QuantizationOpsTdFiles", + "//tensorflow/compiler/mlir/tensorflow:tensorflow_ops_td_files", + "@llvm-project//mlir:FuncTdFiles", + ], +) + +cc_library( + name = "tf_passes", + srcs = [ + "tf_passes.cc", + "transforms/fuse_bias_tf.cc", + "transforms/legalize_tf.cc", + "transforms/tf_legalize_patterns.inc", + ], + hdrs = [ + "tf_passes.h", + "transforms/passes.h", + ], + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + deps = [ + ":legalize_common", + ":passes_header", + ":tosa_legalize_tf_inc_gen", + "//tensorflow/compiler/mlir/lite:tensorflow_lite", + "//tensorflow/compiler/mlir/lite/quantization/ir:QuantOps", + "//tensorflow/compiler/mlir/tensorflow", + "//tensorflow/compiler/mlir/tensorflow:dynamic_shape_utils", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:AffineTransforms", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:QuantOps", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TosaDialect", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + ], +) + +gentbl_cc_library( + name = "tosa_legalize_tfl_inc_gen", + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + tbl_outs = [ + ( + ["-gen-rewriters"], + "transforms/tfl_legalize_patterns.inc", + ), + ], + tblgen = "@llvm-project//mlir:mlir-tblgen", + td_file = "transforms/tfl_legalize_patterns.td", + deps = [ + ":tosa_ops_td_files", + "//tensorflow/compiler/mlir/lite:tensorflow_lite_ops_td_files", + "//tensorflow/compiler/mlir/lite/quantization/ir:QuantizationOpsTdFiles", + "@llvm-project//mlir:FuncTdFiles", + ], +) + +cc_library( + name = "tfl_passes", + srcs = [ + "tfl_passes.cc", + "transforms/convert_metadata.cc", + "transforms/convert_tfl_uint.cc", + "transforms/dequantize_tfl_softmax.cc", + "transforms/legalize_tfl.cc", + "transforms/legalize_tfl_stateful.cc", + "transforms/lower_complex_types.cc", + "transforms/retain_call_once_funcs.cc", + "transforms/strip_metadata.cc", + "transforms/strip_quant_types.cc", + "transforms/tfl_legalize_patterns.inc", + "transforms/verify_fully_converted.cc", + ], + hdrs = [ + "tfl_passes.h", + "transforms/passes.h", + ], + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + deps = [ + ":legalize_common", + ":passes_header", + ":tosa_legalize_tfl_inc_gen", + "//tensorflow/compiler/mlir/lite:tensorflow_lite", + "//tensorflow/compiler/mlir/lite:tensorflow_lite_quantize", + "//tensorflow/compiler/mlir/lite/quantization/ir:QuantOps", + "//tensorflow/compiler/mlir/tensorflow:dynamic_shape_utils", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:AffineTransforms", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:FunctionInterfaces", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:QuantOps", + "@llvm-project//mlir:ReconcileUnrealizedCasts", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TosaDialect", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + ], +) + +cc_library( + name = "tf_tfl_passes", + srcs = [ + "tf_tfl_passes.cc", + "transforms/legalize_tf_tfl.cc", + ], + hdrs = [ + "tf_tfl_passes.h", + "transforms/passes.h", + ], + compatible_with = get_compatible_with_portable(), + tags = ["tf_tosa"], + deps = [ + ":legalize_common", + ":passes_header", + ":tf_passes", + ":tfl_passes", + "//tensorflow/compiler/mlir/lite:lift_tflite_flex_ops", + "//tensorflow/compiler/mlir/lite:tensorflow_lite", + "@llvm-project//mlir:AffineTransforms", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:TosaDialect", + "@llvm-project//mlir:TransformUtils", + "@llvm-project//mlir:Transforms", + ], +) + +tf_cc_binary( + name = "tf-tosa-opt", + testonly = True, + srcs = ["tf_tosa_opt.cc"], + tags = ["tf_tosa"], + deps = [ + "//tensorflow/compiler/mlir:init_mlir", + "//tensorflow/compiler/mlir:passes", + "//tensorflow/compiler/mlir:register_common_dialects", + "//tensorflow/compiler/mlir/lite:tensorflow_lite", + "//tensorflow/compiler/mlir/lite:tf_tfl_passes", # buildcleaner:keep + "//tensorflow/compiler/mlir/quantization/stablehlo:bridge_passes", + "//tensorflow/compiler/mlir/tensorflow:mlprogram_util", + "//tensorflow/compiler/mlir/tensorflow/transforms:tensorflow_passes", + "//tensorflow/compiler/mlir/tensorflow/transforms:tensorflow_test_passes", + "//tensorflow/compiler/mlir/tensorflow/transforms:tf_graph_optimization_pass", + "//tensorflow/compiler/mlir/tensorflow/transforms:tf_saved_model_passes", # buildcleaner:keep + "//tensorflow/compiler/mlir/tensorflow/transforms/host_runtime:lower_cluster_to_runtime_ops", + "//tensorflow/compiler/mlir/tensorflow/transforms/host_runtime:runtime_passes", + "//tensorflow/compiler/mlir/tensorflow/transforms/sparsecore:sparsecore_passes", + "//tensorflow/compiler/mlir/tf2xla:compile_mlir_util", + "//tensorflow/compiler/mlir/tf2xla/internal/passes:clustering_passes", + "//tensorflow/compiler/mlir/tf2xla/internal/passes:mlir_to_graph_passes", + "//tensorflow/compiler/mlir/tf2xla/transforms:tf_xla_passes", + "//tensorflow/compiler/mlir/tf2xla/transforms:xla_legalize_tf", + "//tensorflow/compiler/mlir/tosa:tf_passes", + "//tensorflow/compiler/mlir/tosa:tf_tfl_passes", + "//tensorflow/compiler/mlir/tosa:tfl_passes", + "@llvm-project//mlir:AllPassesAndDialects", + "@llvm-project//mlir:MlirOptLib", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:Transforms", + "@xla//xla/mlir_hlo:all_passes", + ], +) + +filegroup( + name = "litfiles", + srcs = glob(["runlit*py"]), + visibility = ["//tensorflow:__subpackages__"], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/README.md b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c5c6ae320b4b18d2c07f400403ea2a402308789c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/README.md @@ -0,0 +1,13 @@ +# TOSA legalizations for TensorFlow and TensorFlow Lite (Deprecated) + +## Deprecation notice + +This directory contains an archive of the Tensor Operator Set Architecture (TOSA) MLIR legalizations for the TensorFlow and TF Lite MLIR Dialects. For more information see the resources below. + +Support for these legalization paths has been **moved** to the [TOSA Converter for TFLite](https://gitlab.arm.com/tosa/tosa-converter-for-tflite) repository and is **not currently maintained nor kept up to date within this repository**. + +## Resources + +* [Tensor Operator Set Architecture (TOSA) Specification](https://www.mlplatform.org/tosa/tosa_spec.html) +* [TOSA MLIR Dialect](https://mlir.llvm.org/docs/Dialects/TOSA/) +* [TOSA Converter for TFLite](https://gitlab.arm.com/tosa/tosa-converter-for-tflite) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/g3doc/legalization.md b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/g3doc/legalization.md new file mode 100644 index 0000000000000000000000000000000000000000..59c057fd6408e0a6dc9b7d12a27a370c2a1ff3b9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/g3doc/legalization.md @@ -0,0 +1,5244 @@ +# TOSA Lowerings + +## Introduction + +### Overview + +This document provides pseudo-code lowerings from TensorFlow and TensorFlow Lite +MLIR Dialects (https://www.tensorflow.org/mlir/dialects) to the TOSA Dialect +(https://mlir.llvm.org/docs/Dialects/TOSA/). + +The documentation is a work-in-progress: sections with missing legalizations are +in the process of being written. + +## Syntax + +The pseudo-code syntax used in this document is described below. + +### Primitive Datatypes + +int8: signed 8-bit integer uint8: unsigned 8-bit integer int16: signed 16-bit +integer int32: signed 32-bit integer int64: signed 32-bit integer uint32: +unsigned 32-bit integer float32: IEEE-754 32-bit floating point format float64: +IEEE-754 64-bit floating point format bool: boolean + +### Value + +In pseudo-code, symbol starting with "%" indicates it’s a value. A value is +evaluated by an operator at run time, and operator can consume and can only +consume a list of values as operands. Note value’s tensor type is determined at +compile time. Only the evaluation happens at run time One can easily construct a +data flow subgraph by looking at the producer/consumer. + +### Tensor Type + +Tensor type is an attribute determined by legalization at compile time, +describing the shape and element data type. It’s noted as tensor<shape, +dtype>, or shorthanded as tensor<%t.type> + +### Operator Prototype + +In pseudocode an TOSA operator is prototyped as following format. + +%<output\_value> = tosa.<OPERATOR>(%<input\_value>) +{<attribute = …​} + +### Value Attributes + +For the purposes of brevity and clarity in this document, the pseudocode allows +the following notation on value attribute. + +Shorthand | Description +----------------- | --------------------------------------------------- +`%t.shape` | Shape vector for the tensor +`%t.shape[i]` | Size of dimension i for the tensor +`%t.rank` | Rank of the tensor +`%t.dtype` | Datatype of the tensor +`%t.scale` | Quantized scaling parameter (float64) +`%t.zp` | Quantized zero-point (int64) +`%t.signed` | Boolean indicating the type is signed +`%t.num_bits` | Number of bits in the datatype +`%t.num_elements` | Number of elements in the tensor +`%t.type` | Tuple of `tensor<%t.shape, %t.dtype>` +`%t.size` | For tensor lists: the number of tensors in the list + +### Tensor Dimension Shorthand + +Where the TOSA Specification allows the use of named dimensions, the following +names may be used. + +Name | Description +---- | -------------------- +`N` | Batch dimension +`H` | Height dimension +`W` | Width dimension +`C` | Channel dimension +`M` | Depthwise multiplier + +Each of these may be prefixed with `I` for the input dimension or `O` for the +output dimension or `K` for kernel dimensions. + +## Common Legalization Functions + +The following pseudocode helper functions are used to cannonicalize arguments +from different frameworks to the TOSA dialect. + +### .as_constant(): Matched as Constant + +Wherever %tensor.as_constant() is specified, a constant vector will be created +to hold the value in the %tensor at compile time. This only succeeds if %tensor +is fed by a constant type operator. If constant matching fails, the lowering +will fail and be terminated. + +## Common Legalization Functions + +The following pseudo-code helper functions are used to cannonicalize arguments +from different frameworks to the TOSA dialect. + +### get_padding_values_from_explicit_pad_attr() + +``` +vector get_padding_values_from_explicit_pad_attr(vector explicit_pad, + tensorflow::TensorFormat data_format_tf) +{ + int64 pad_before, pad_after + vector computed_paddings + + for (int32 i = 0; i < 2; i++) { + int64 dim = GetTensorSpatialDimIndex(4, data_format_tf, i) + pad_before = explicit_pad[dim * 2] + pad_after = explicit_pad[dim * 2 + 1] + computed_paddings.push_back(pad_before) + computed_paddings.push_back(pad_after) + } + + return computed_paddings +} +``` + +### get_padding_values_from_pad_type() + +Calculate explicit padding array based on pad type + +``` +vector get_padding_values_from_pad_type(tensorflow::Padding padding, tensorflow::TensorFormat data_format, + uint32 first_filter_spatial_dim, type input_type, type filter_type + vector strides, vector dilations) +{ + assert(padding != tensorflow::Padding::EXPLICIT); + + vector computed_padding; + + // Padding over H and W dimensions + for (int32 i = 0; i < 2; i++) { + int32 ifm_dim = get_tensor_spatial_dim_index(4, data_format, i); + + int32 filter_dim = first_filter_spatial_dim + i; + + int32 dim_dilation = dilations[ifm_dim]; + int32 dim_stride = strides[ifm_dim]; + + int64 op_size, pad_before_tf, pad_after_tf; + + tensorflow::GetWindowedOutputSizeVerbose(input_type.shape[ifm_dim], filter_type.shape[filter_dim], + dim_dilation, dim_stride, padding, + // Outputs + &op_size, &pad_before_tf, &pad_after_tf); + computed_paddings.push_back(pad_before_tf); + computed_paddings.push_back(pad_after_tf); + } + + return computed_paddings; +} +``` + +### positive_axis() + +``` +// Cannonicalize scalar axis attributes to a scalar positive axis attribute +int32 positive_axis(int32 axis, int32 rank) +{ + if (axis < 0) + axis += rank; + + return axis; +} +``` + +### compute_scale_32() + +``` +void compute_scale_32(float64 scale, int32& multiplier, int32& shift) +{ + /* Generates mantissa and shift values where mantissa is in [-1.0,-0.5] or + [0.5, 1.0] such that + multiplier = mantissa*2^shift */ + + const float64 mantissa = std::frexp(scale, &shift); + auto shifted_m = std::round(mantissa * (int64(1) << 31)); + + assert(shifted_m <= (int64(1) << 31)); // can't be greater that 1.0 + if (shifted_m == (int64(1) << 31)) { + shifted_m /= 2; + shift++; + } + // TOSA expect right shift to be positive, and embed (1 << 31) into right + // shift bits + shift = (-shift) + 31; + + assert(shifted_m <= std::numeric_limits::max()); + + multiplier = static_cast(shifted_m); + +} +``` + +### lower_batch_to_space_nd_op() + +``` +Value lower_batch_to_space_nd_op(Value %input, Value %block_shape, Value %crops, shape_t output_shape) +{ + + vector block_shape(%block_shape.rank) + vector std::pair crops_arr + + size_t remaining_shape_rank = %input.rank - %block.rank - 1 + size_t crops_dim = %crops.shape[0] + + for (int32 i = 0; i < crops_dim; i++) { + crops[i] = std::make_pair(%crops.as_constant()[i * crops_dim + 0], + %crops.as_constant()[i * crops_dim + 1]) + } + + // Step 1: Reshape input to + // [block_shape[0], + // ... + // [block_shape[M-1], + // [batch / prod(block_shape)] + // [input_shape[1], + // ... + // [input_shape[N-1] + + vector a1_shape(%block.rank + %input.rank) + + for (int32 i = 0; i < %block.rank; i++) { + a1_shape[i] = %block.shape[i] + } + + a1_shape[%block.rank] = %input.shape.[0] / %block.num_elements + + for (int32 i = 1; i < %input.rank; i++) { + a1_shape[i + %block.rank] = %input.shape[i] + } + + // Step 2. Permute to shape: + // [ batch / prod(block_shape) ], + // [ input_shape[1] ], [ block_shape[0] ] + // ... + // [ input_shape[M] ], [ block_shape[M-1] + // + remaining_input_shapes input_shape[M+1 .. N-1] + vector a2_perm(%block.rank + %input.rank) + + a2_perm[0] = %block.rank + for (int32 i = 0; i < %block.rank; i++) { + a2_perm[1 + i * 2 + 0] = %block.rank + 1 + i + a2_perm[1 + i * 2 + 1] = i + } + + // Step 3. Reshape to + // [ batch / prod(block_shape) ], + // [input_shape[1] * block_shape[0] ], + // .. + // [input_shape[M * block_shape[M-1], + // + remaining input shapes [input_shape[M+1.. N-1]] + vector a3_shape(%input.rank) + + %a3_shape[0] = %input.shape[0] / %block.num_elements + for (int32 i = 0; i < %block.rank; i++) { + a3_shape[i + 1] = %input.shape[i + 1] * %block.shape[i] + } + + for (int32 i = 0; remaining_block_shape; i++) { + a3_shape[1 + %block.rank + 1] = %input.shape[%block.rank + 1 + i] + } + + // Step 4 Crop the start/end dimensions using slice + vector a4_begin(%input.rank), a4_size(%input.rank) + + for (int32 i = 0; i < %input.rank; i++) { + if (i == 0 || i > crop_dims) { + a4_begin[i] = 0 + a4_size[i] = output_shape[i] + } else { + a4_begin[i] = %crops[i-1].first + a4_size[i] = crops[i - 1].first - crops[i - 1].second + } + } + + %a1_reshape = tosa.RESHAPE(%input) {new_shape=a1_shape} + %a2_transpose = tosa.TRANSPOSE(%a1_reshape) {perms=a2_perm} + %a3_reshape = tosa.RESHAPE(%a2_transpose) {new_shape=a3_shape} + %output = tosa.SLICE(%a3_reshape) {begin=a4_begin, size=a4_size} + + return %output +} +``` + +### lower_concatv2_op() + +``` +Value lower_concatv2_op(Type output_type, Value %values, int32 axis) +{ + int32 tosa_axis = positive_axis(axis) + + assert(%values.size >= 2) + + // Convert scalar inputs to a tensor + if (%values:0.size == 0) { + for (int32 i = 0; i < %values.size; i++) { + %values:i = tosa.RESHAPE(%values:i) {new_shape=1} + } + } + + for (int32 i=0; i < %values.size(); i++) { + %val = %values:i + if (%val.zp != output_type.zp || %val.scale != output_type.scale) { + float64 rescale_scale = %val.scale / output_type.scale + %values:i = tosa.RESCALE(%val) {scale=rescale_scale, input_zp=%values:0.zp, output_zp=output_type.zp} + } + } + + %concat_op = tosa.CONCAT(%values:0, %values:1) {axis=tosa_axis} + + for (int32 i = 2; i < %values.size; i++) { + %concat_op = tosa.CONCAT(%concat_op, %values:i) {axis=tosa_axis} + } + + return %concat_op +} +``` + +### lower_depth_to_space_op() + +``` +Value lower_depth_to_space_op(Value %input, size_t block_size[], Format_t data_format) +{ + assert(data_format == 'NHWC') + + vector a2_shape = {%input.shape[0], + %input.shape[1], + %input.shape[2], + block_size[0], + block_size[1], + %input.shape[3] / (block_size[0] * block_size[1])} + + vector a4_shape = {%input.shape[0], + %input.shape[1] * block_size[0], + %input.shape[2] * block_size[1], + %input.shape[3] / (block_size[0] * block_size[1])} + + %a2_reshape = tosa.RESHAPE(%input) {new_shape=a2_shape} + %a3_transpose = tosa.TRANSPOSE(%a2_reshape) {perms={0, 1, 3, 2, 4, 5}} + %output = tosa.RESHAPE(%a3_transpose) {new_shape=a4_shape} + + return %output +} +``` + +### lower_elu_op() + +``` +Value lower_elu_op(Value %value) +{ + // elu(x) = x < 0 ? (exp(x) - 1) : x + // Create constants for 0/1 and reshape to match the rank + // of %value + %one_const = tosa.CONST() {value={1}} + %zero_const = tosa.CONST() {value={0}} + + vector bcast_shape + for (int32 i = 0; i < %value.rank; i++) { + bcast_shape.push_back(1) + } + + %one_reshape = tosa.RESHAPE(%one_const) {new_shape=bcast_shape} + %zero_reshape = tosa.RESHAPE(%zero_const) {new_shape=bcast_shape} + + %exp_in = tosa.EXP(%value) + %sub = tosa.SUB(%exp_in, %one_reshape) + %ge = tosa.GREATER_EQUAL(%value, %zero_reshape) + %output = tosa.SELECT(%ge, %value, %sub) + return %output +} +``` + +### lower_expand_dims() + +``` +Value lower_expand_dims(Value %input, int32 axis) +{ + vector reshape_dims + + if (axis < 0 || axis >= %input.rank) { + // Insert at the end of the tensor + axis += %input.rank + for (int32 i = 0; i < input.rank; i++) { + reshape_dims.push_back(%input.shape[i]) + } + } else { + for (int32 i= 0 ; i < %input.rank; i++) { + if (i == axis) { + reshape_dims.push_back(1) + } + reshape_dims.push_back(%input.shape[i]) + } + } + + %output = tosa.RESHAPE(%input) {new_shape=reshape_dims} + return %output +} +``` + +### lower_fake_quant_op() + +``` +Value lower_fake_quant_op(Value %inputs, type output_type, float64 min, float64 max, + int64 num_bits, bool narrow_range) +{ + assert(num_bits == 8 || num_bits == 16) + + int64 qmax = (1L << (num_bits - 1)) - 1; + int64 qmin = -(1L << (num_bits - 1)) + + if (narrow_range) { + qmin = qmin + 1 + } + + float64 scale = (max - min) / float64(qmax - qmin) + + int64 zeropoint = (int64)std::round((-min) / scale + float64(qmin)) + + %quantized = lower_quantize_op(%inputs.type, %inputs, 1.0 / scale, zeropoint) + + %dequantized = lower_dequantize_op(output_type, %quantized_op, scale, zeropoint) + + return %dequantized +} +``` + +### lower_floor_div() + +``` +Value lower_floor_div(Value %lhs, Value %rhs) +{ + %recip = tosa.RECIPROCAL(%rhs) + %mul = tosa.MUL(%lhs, %recip) + %output = tosa.FLOOR(%mul) + + return %output +} +``` + +### lower_floor_mod() + +``` +Value lower_floor_mod(Value %lhs, Value %rhs) +{ + %recip = tosa.RECIPROCAL(%rhs) + %mul = tosa.MUL(%lhs, %recip) + %floor = tosa.FLOOR(%mul) + %output = tosa.SUB(%mul, %floor) + return %output +} +``` + +### lower_quantize_op() + +``` +Value lower_quantize_op(Type output_type, Value %input, float64 scale, int64 zeropoint) +{ + %const_scale = tosa.CONST() {value={scale}} + %const_zp = tosa.CONST() {value={zeropoint}} + %op1_mul_in_scale = tosa.MUL(%input, %const_scale) + %op2_add_op1_zp = tosa.ADD(%op1_mul_in_scale, %const_zp) + %op3_cast_op2 = tosa.CAST(%op2_add_op1_zp) // f32->%output.dtype +} +``` + +### lower_dequantize_op() + +``` +Value lower_dequantize_op(Value %input, float64 scale, int64 zeropoint) +{ + %const_scale = tosa.CONST() {value={scale}} + %const_zp = tosa.CONST() {value={(float64)zeropoint}} + %op1_cast_in = tosa.CAST(%input) // %input.dtype->f32 + %op2_sub_op1_zp = tosa.SUB(%op1_cast_in, %const_zp) + %op3_mul_op2_scale = tosa.MUL(%op2_sub_op1_zp, %const_scale) +} +``` + +### lower_log_softmax_op() + +``` +Value lower_log_softmax_op(Value %logits) +{ + %op1 = tosa.EXP(%logits) + %op2 = tosa.REDUCE_SUM(%op1) {axis=(%logits.rank-1)} + %op3 = tosa.RECIPROCAL(%op2) + %op4 = tosa.MUL(%op1, %op3) + %op5 = tosa.LOG(%op4) + + return %op5 +} +``` + +### lower_pack_op() + +``` +Value lower_pack_op(Value %input[], size_t axis) +{ + size_t concat_axis = positive_axis(axis) + + size_t input_tensor_rank = %input[0].rank + + // Convert any rank 0 to rank 1 with reshape + if (input_tensor_rank == 0) { + for (int32 i = 0; i < %input.size; i++) { + %input[i] = tosa.RESHAPE(%input[i], {1}) + } + } + + vector output_shape + for (int32 i = 0; i < input_tensor_rank; i++) { + output_shape.push_back(%input[0].shape[i] + } + + output_shape[concat_axis] = output_shape[concat_axis] * %input.size + + // First pair of tensors + %concat = tosa.CONCAT(%input[0], %input[1]) {axis=concat_axis} + + // Remaining tensors + for (int32 i = 2; i < %input.size; i++) { + %concat = tosa.CONCAT(%concat, %input[i]) {axis=concat_axis} + } + + if (input_tensor_rank == 0) { + // No reshape needed for rank 0, already done + %output = %concat + } else + + %reshape = tosa.RESHAPE(%concat) {new_shape=output_shape} + + if (concat_axis == input_tensor_rank) { + // Output shape is [A, B, C, .. n] in this case, + // need to reshape to [N, A, B, C, ..] with perm [1, 2, 3, .. 0] + concat_axis = 0 + + vector perms + for (int32 i = 0; i < %input[0].rank; i++) + perms.push_back(i + 1) + perms.push_back(0) + + %output = tosa.TRANSPOSE(%reshape) {perms=perms} + } else { + %output = %reshape + } + + return %output +} +``` + +### lower_reduce_op() + +``` +Value lower_reduce_op(Value %input, shape_t output_shape, Value %axes, bool keep_dims, float64 input_scale=1.0f, int32 input_zp=0, float64 output_scale=1.0f, int32 output_zp=0) +{ + + vector axes_vec = %axes.as_constant(); + + // Special case of no axes means no transformation + if (axes_vec.size() == 0) { + return tosa.IDENTITY(%input) + } + + bool is_quantized = isa(%input.dtype) ? true : false + + shape_t shape = %input.shape; + %output = %input; + + if (is_quantized) { + %output = tosa.RESCALE(%output) {scale=input_scale, input_zp=input_zp, output_zp=0} + } + + for (int32 i = 0; i < axes_vec.size(); i++) { + int32 axis = positive_axis(axes_vec[i], %input.rank); + + shape[axis] = 1; + %output = tosa.OP(%output) {axis=axis} + } + + if (!keep_dims) { + %output = tosa.RESHAPE(%output) {new_shape=output_shape} + } + + if (is_quantized) { + %output = tosa.RESCALE(%output) {scale=output_scale, input_zp=0, output_zp=output_zp} + } + + return %output; +} +``` + +### lower_resize_op() + +``` +Value lower_resize_op(Value %images, Value %size, shape output_shape, dtype output_dtype, mode_t mode) +{ + int32 input_height = %input.shape[1] + int32 input_width = %input.shape[2] + int32 output_height = %output.shape[1] + int32 output_width = %output.shape[2] + + float64 in_center_h = static_cast(input_height - 1) / 2.0 + float64 in_center_w = static_cast(input_width - 1) / 2.0 + float64 out_center_h = static_cast(output_height - 1) / 2.0 + float64 out_center_w = static_cast(output_width - 1) / 2.0 + + float64 fp_stride_y, fp_stride_x + if (align_corner && output_height > 1) + fp_stride_y = static_cast(input_height - 1) / static_cast(output_height - 1) + else + fp_stride_y = static_cast(input_height) / static_cast(output_height) + if (align_corner && output_width > 1) + fp_stride_x = static_cast(input_width - 1) / static_cast(output_width - 1) + else + fp_stride_x = static_cast(input_width) / static_cast(output_width) + + float64 fp_offset_y = fp_offset_y = 0.0f + if (half_pixel_centers) { + fp_offset_y = fp_stride_y * 0.5f - 0.5f + fp_offset_x = fp_stride_x * 0.5f - 0.5f + } + + if (dtype == float) + %op1_resize_in = tosa.RESIZE(%input) {stride={fp_stride_y, fp_stride_x}, offset={fp_offset_y, fp_offset_x}, shift=0, resize_mode=mode} + else { + int32 shift = 10 + float64 unit = static_cast(1 << shift) + int32 stride_y = fp_stride_y * unit + int32 stride_x = fp_stride_x * unit + int32 offset_y = fp_offset_y * unit + int32 offset_x = fp_offset_x * unit + + %op1_resize_in = tosa.RESIZE(%input) {stride={stride_y, stride_x}, offset={offset_y, offset_x}, shift=shift, resize_mode=mode} + + if (mode == "BILINEAR") { + %const_zero = tosa.CONST() {value={0}} + %const_twenty = tosa.CONST() {value={20}} + %op2_ge_op1 = tosa.GREATER_EQUAL(%op1_resize_in, %const_zero) + %op3_abs_op1 = tosa.ABS(%op1_resize_in) + %op4_rshift_op3 = tosa.ARITHMETIC_RIGHT_SHIFT(%op3_abs_op1, %const_twenty) + %op5_negate_op4 = tosa.NEGATE(%op4_rshift_op3) + %op6_select_op2_op4_op5 = tosa.SELECT(%op2_ge_op1, %op4_rshift_op3, %op5_negate_op4) + %op7_cast_op6 = tosa.CAST(%op6_select_op2_op4_op5) // i32/i48->%output.dtype + } + } +} +``` + +### lower_reversev2_op() + +``` +Value lower_reverse_v2_op(Value %tensor, Value %axis) +{ + Value %output = %tensor + + if (%axis.num_elements == 0) { + %output = tosa.IDENTITY(%tensor) + } else { + for (int32 i = 0; i < %axis.shape[0]; i++) { + size_t axis_val = positive_axis(%axis.as_constant()[i]) + %output = tosa.REVERSE(%output) {axis=%axis_val} + } + } + + return %output +} +``` + +### lower_round_op() + +``` +Value lower_round_op(Value %x) +{ + %half = tosa.CONST() {value={0.5}} + %add = tosa.ADD(%x, %half) + %output = tosa.FLOOR(%add) + + return %output +} +``` + +### lower_selectv2_op() + +``` +Value lower_selectv2_op(Value %condition, Value %t, Value %e, shape output_shape) +{ + // Reshape condition so that ranks match to support + // broadcasting (if necessary) + + if (%condition.rank != output_shape.size) { + vector cond_shape = %condition.shape + for (int32 i = 0; i < (output_shape.size - %condition.rank); i++) { + cond_shape.push_front(1) + } + + %condition = tosa.RESHAPE(%condition) {new_shape=cond_shape} + } + + %output = tosa.SELECT(%condition, %t, %e) + + return %output +} +``` + +### lower_shape_op() + +``` +Value lower_shape_op(Value %input) +{ + vector input_shape = %input.shape + + %shape = tosa.CONST() {value={input_shape}} + return %shape +} +``` + +### lower_space_to_batch_nd_op() + +``` +Value lower_space_to_batch_nd_op(Value %input, Value %block_shape, Value %padding) +{ + + size_t block_rank = %block.shape[0] + size_t remaining_shape_rank = %input.rank - block_rank - 1; + + // Step 1. Pad based on paddings operand (flattened representation of [input.rank][2]-shaped array) + vector a1_padding + a1_padding[0] = 0 + a1_padding[1] = 0 + + for (int32 i = 0; i < %padding.shape[0]; i++) { + a1_padding[i + 2] = %padding.as_constant()[i] + } + + %a1_pad = tosa.PAD(%input) {padding=a1_padding} + + // Step 2. Reshape to + // [batch + padded_shape[1] / block_shape[0], block_shape[0], ... + // padded_shape[M] / block_shape[M-1], block_shape[M-1]] + + // remaining_shape + + vector a2_shape(1 + block_rank * 2 + remaining_shape_rank) + a2_shape[0] = %input.shape[0] + for (int32 i = 0; i < block_rank; i++) { + a2_shape[1 + i * 2 + 0] = %a1_pad.shape[1 + i] / block_shape.as_constant()[i] + a2_shape[1 + i * 2 + 1] = block_shape.as_constant()[i] + } + + for (int32 i = 0; i < remaining_shape_rank; i++) { + a2_shape[1 + block_rank * 2 + i] = %input.shape[1 + block_rank + i] + } + + %a2_reshape = tosa.RESHAPE(%a1_pad) {new_shape=a2_shape} + + // Step 3 transpose to + // block-shape + + // [batch] + + // [padded_shape[1] / block_shape[0], + // ... + // [padded_shape[M] / block_shape[M-1]] + + // remaining_shape + vector a3_perm(%a2_reshape.rank) + size_t block_num_elems = 1 + + for (int32 i = 0; i < block_rank; i++) { + a3_perm[i] = 1 + 2 * i + 1 + a3_perm[block_rank + 1 + i] = 2 * i + 1 + block_num_elems *= %block.as_constant()[i] + } + + a3_perm[block_rank] = 0 + for (int32 i = (1 + block_rank * 2); i < %a2_reshape.rank; i++) { + a3_perm[i] = i + } + + %a3_reshape = tosa.RESHAPE(%a2_reshape) {perm=a3_perm} + + // Step 4. Reshape transposed tensor to + // [ batch * prod(block_shape)] + + // [ padded_shape[1] / block_shape[0], + // ..., + // padded_shape[M] / block_shape[M-1]] + + // remaining_shape + + vector a4_shape(%input.rank) + a4_shape[0] = batch_size * block_num_elements + + for (int32 i = 0; i < block_rank; i++) { + a4_shape[i + 1] = %a1_pad.shape[i + 1] / %block.as_constant()[i] + } + + for (int32 i = 0; i < remaining_block_shape; i++) { + a4_shape[1 + block_rank + i] = %input.shape[1 + block_rank + i] + } + + %output = tosa.RESHAPE(%a3_reshape) {new_shape=a4_shape} + + return %output +} +``` + +### lower_space_to_depth_op() + +``` +Value lower_space_to_depth_op(Value %input, size_t block_size[], Format_t data_format) +{ + assert(data_format == 'NHWC') + + vector a2_shape = {%input.shape[0], + %input.shape[1] / block_size[0], + %block_size[0], + %input_shape[2] / block_size[1], + %block_size[1], + %input_shape[3]} + %a2_reshape = tosa.RESHAPE(%input) {new_shape=a2_shape} + %a3_transpose = tosa.TRANSPOSE(%a2_reshape) {perm={0, 1, 3, 2, 4, 5}} + + vector a4_shape = {%input.shape[0], + %input_shape[1] / block_size[0], + %input_shape[2] / block_size[1], + %input_shape[3] * block_size[0] * block_size[1]} + %output = tosa.RESHAPE(%a3_transpose) {new_shape=%a4_shape} + return %output +} +``` + +### lower_split_op() + +``` +Value lower_split_op(Value %value, size_t axis, size_t num_split) +{ + Value %output[] + + size_t slice_size = %value.shape[axis] / num_split + + for (int32 i = 0; i < num_split; i++) { + vector begin_vals, size_vals + + for (int32 j = 0; j < %value.rank; j++) { + if (j == axis) { + begin_vals.push_back(slice_size * i) + size_vals.push_back(slice_size) + } else { + begin_vals.push_back(0) + size_vals.push_bac(%value.shape[j]) + } + + %output[i] = tosa.SLICE(%value) {start=begin_vals, size=size_vals} + } + + } + + %output_list = tosa.IDENTITYN(%output) + return %output_list +} +``` + +### lower_splitv_op() + +``` +Value lower_splitv_op(Value %value, vector size_split, size_t axis) +{ + Value %output[] + + size_t curr_split_start = 0 + + for (int32 i = 0; i < size_split.size(); i++) { + vector begin_vals, size_vals + + for (int32 j = 0; j < %value.rank; j++) { + if (j == axis) { + begin_vals.push_back(curr_split_start) + size_vals.push_back(size_split[i]) + } else { + begin_vals.push_back(0) + size_vals.push_back(input.shape[j]) + } + } + + %output[i] = tosa.SLICE(%value) {start=begin_vals, size=size_vals} + + curr_split_start += size_split[i] + } + + %output_list = tosa.IDENTITYN(%output) + return %output_list +} +``` + +### lower_squeeze_op() + +``` +Value lower_squeeze_op(Value %input, vector squeeze_dims) +{ + vector reshape_dims + + if (squeeze_dims.size() == 0) { + // Remove all 1-dims + for (int32 i = 0; i < %input.rank; i++) { + if (%input.shape[i] != 1) { + reshape_dims.push_back(%input_shape[i]) + } + } + } else { + // Remove the specified dimensions + for (int32 i = 0; i < %input.rank; i++) { + if (!squeeze_dims.find(i) || %input.shape[i] != -1) { + reshape_dims.push_back(%input_shape[i]) + } + } + } + + %output = tosa.RESHAPE(%input) {new_shape=reshape_dims} + + return %output +} +``` + +### lower_strided_slice_op() + +``` +Value lower_strided_slice_op(Value %input, Value %begin_val, Value %end_val, Value %strides_val, + size_t begin_mask, size_t end_mask, size_t ellipsis_mask, + size_t new_axis_mask, size_t shrink_axis_mask) +{ + // Note: does not implement ellipsis_mask or reverse stride at this time + assert(ellipsis_mask == 0) + + vector begin(%begin_val.as_constant()), end(%end_val.as_constant()), strides(%strides_val.as_constant()) + vector a1_start, a1_size, a2_shape, a3_start, a3_size, a4_shape + + for (int32 i = 0; i < %input.rank; i++) { + if (begin_mask & (1 << i)) { + begin[i] = 0 + } + + if (end_mask & (1 << i)) { + end[i] = %input.shape[i] + } + + // Wrap around index if begin and end are negative + if (begin[i] < 0) { + begin[i] += %input.shape[i] + } + + if (end[i] < 0) { + end[i] += %input.shape[i] + } + + a1_start[i] = begin[i] + a1_size[i] = end[i] - begin[i] + + a2_shape[i*2 + 0] = a1_size[i] / strides[i] + a2_shape[i*2 + 1] = strides[i] + + a3_start[i*2 + 0] = 0 + a3_start[i*2 + 1] = 0 + + if (shrink_axis_mask & (1 << i)) { + a3_size[i*2 + 0] = 1 + } else { + a3_size[i*2 + 0] = a1_size[i] / strides[i] + } + a3_size[i*2 + 1] = 1 + + if (!(shrink_axis_mask & (1 << i))) { + if (new_axis_mask & (1 << i)) { + a4_shape.push_back(1) + a4_shape.push_back((a1_size[i] / strides[i])) + } + } + + // Step 1: Slice the input array + %a1_slice = tosa.SLICE(%input) {start=a1_start, size=a1_size} + + // Step 2: Reshape the sliced array: 2x as many dimensions as %input + %a2_reshape = tosa.RESHAPE(%a1_slice) {new_shape=a2_shape} + + // Step 3: Take a slice of the [0] index along each of the strided dimensions (even dimensions) + %a3_slice = tosa.SLICE(%a2_reshape) {start=a3_start, size=a3_size} + + // Step 4: Reshape the now-strided tensor back down to the desired number of dimensions + %output = tosa.RESHAPE(%a3_slice) {new_shape=a4_shape} + + return %output +} +``` + +### lower_unpack_op() + +``` +Value lower_unpack_op(Value %value, size_t axis, uint64_t num) +{ + axis = positive_axis(axis) + + Value %output_arr[] + + // Step 1: transpose 'axis' to left-most dimension, if necessary + Value %transposed_value + + if (axis != 0) { + vector perms + + perms.push_back(axis) + for (int32 i = 0; i < %input.rank; i++) { + if (i != axis) + perms.push_back(i) + } + + %transposed_value = tosa.TRANSPOSE(%value) {perms=perms} + + } else { + %transposed_value = %value + } + + // Step 2: Slice [N, A, B, C] into [N] [A, B, C] + for (int32 i = 0; i < %transposed_value.rank; i++) { + vector begin_vals, size_vals, shape_vals + + begin_vals.push_back(i) + size_vals.push_back(1) + + for (int32 j = 1; j < %transposed_value.rank; j++) { + begin_vals.push_back(0) + size_vals.push_back(transposed_value.shape[j]) + shape_vals.push_back(transposed_value.shape[j]) + } + + %slice = %tosa.SLICE(%transposed_value) {begin=begin_vals, size=size_vals} + %output_arr[i] = %tosa.RESHAPE(%slice) {new_shape=shape_vals} {begin=begin_vals, size=size_vals} + } + + // Combine array of sliced tensors into a list of tensors + %output = tosa.IDENTITYN(%output_arr) + return %output +} +``` + +### get_transpose_conv2d_padding_values_from_pad_type() + +``` +vector get_transpose_conv2d_padding_values_from_pad_type(tensorflow::Padding padding, tensorflow::TensorFormat data_format, + uint32 first_filter_spatial_dim, type input_type, type filter_type + vector strides, vector dilations) +{ + int64 pad_before, pad_after; + vector computed_padding + + for (int32 i = 0; i < 2; i++) { + int64 ifm_dim = GetTensorSpatialDimIndex(4, data_format, i); + int64 ofm_dim = GetTensorSpatialDimIndex(4, data_format, i); + int64 filter_dim = first_filter_spatial_dim + 1 + + int64 ifm_size = input_shape[ifm_dim] + int64 ofm_size = output_dims[ofm_dim] + int64 filter_size = filter.shape[filter_dim] + int64 dim_dilation = dilations[i] + int64 dim_stride = strides[i] + int32 effective_filter_size = (filter_size - 1) * dim_dilation + 1 + int32 total_padding = ((ifm_size - 1) * dim_stride + effective_filter_size - ofm_size) + total_padding = total_padding > 0 ? total_padding : 0 + + pad_before = total_padding / 2 + pad_after = total_padding - pad_before + + computed_padding.push_back(pad_before) + } + + return computed_padding +} +``` + +### lower_fused_activation() + +``` +Value lower_fused_activation(Value %input, string activation) +{ + bool is_quantized = isa(%input.dtype) ? true : false + + if (is_quantized) { + if (activation == "NONE") { + return %input + } + else if (activation == "RELU") { + int32 quantized_0 = %input.zp + int32 quantized_max = %input.storage_max + return tosa.CLAMP(%input) {min_int=quantized_0, max_int=quantized_max} + } + else if (activation == "RELU6") { + int32 quantized_0 = %input.zp + int32 quantized_6 = %input.zp + (6.0 / %input.scale) + return tosa.CLAMP(%input) {min_int=quantized_0, max_int=quantized_6} + } + else if (activation == "RELU_N1_TO_1") { + int32 quantized_n1 = %input.zp + (-1.0 / %input.scale) + int32 quantized_1 = %input.zp + (1.0 / %input.scale) + return tosa.CLAMP(%input) {min_int=quantized_n1, max_int=quantized_1} + } + } + else { + if (activation == "NONE") { + return %input + } + else if (activation == "RELU") { + return tosa.RELUN(%input) {max_fp=numeric_limit::max()} + } + else if (activation == "RELU6") { + return tosa.RELUN(%input) {max_fp=6.0} + } + else if (activation == "RELU_N1_TO_1") { + return tosa.CLAMP(%input) {min_fp=-1.0, max_fp=1.0} + } + else if (activation == "TANH") { + return tosa.TANH(%input) + } + } +} +``` + +### get_table_const_tensor() + +``` +Value get_table_const_tensor(function func) +{ + array table_array + for (int32 i = -256; i <= 256; i++) { + table_array[i] = func(i) + } + + return tosa.CONST() {value=table_array} +} +``` + +### lower_gather_op() + +``` +Value lower_gather_op(Value %params, Value %indices, int32 batch_dims, int32 axis) +{ + assert batch_dims <= %indices.rank + assert axis >= batch_dims + + int32 N = W = K = C = 1 + + for (int32 i = 0; i < batch_dims; i++) N *= %params.shape[i] + for (int32 i = batch_dims; i < %indices.rank; i++) W *= %indices.shape[i] + K = %params.shape[axis] + for (int32 i = batch_dims; i < axis; i++) C *= %params.shape[i] + for (int32 i = (axis + 1); i < %params.rank; i++) C *= %params.shape[i] + + vector params_idx_batch, params_idx_left, params_idx_indices, params_idx_right + for (int32 i = 0; i < %params.rank; i++) { + if (i < batch_dims && i < axis) + params_idx_batch.push_back(i) + else if (i < axis) + params_idx_left.push_back(i) + else if (i < (axis + 1)) + params_idx_indices.push_back(i) + else + params_idx_right.push_back(i) + } + + vector params_perm = {params_idx_batch, params_idx_left, params_idx_indices, params_idx_right} + vector result_perm + for (int32 i = 0; i < batch_dims; i++) + result_perm.push_back(i) + for (int32 i = 0; i < params_idx_left.size(); i++) + result_perm.push_back(params_idx_left[i]) + for (int32 i = batch_dims; i < %indices.rank; i++) + result_perm.push_back(i) + for (int32 i = 0; i < params_idx_right.size(); i++) + result_perm.push_back(params_idx_right[i]) + + %const_params_perm = tosa.CONST() {value=params_perm} + %const_result_perm = tosa.CONST() {value=result_perm} + + %op1_transpose_params = tosa.TRANSPOSE(%params, %const_params_perm) + %op2_reshape_op1 = tosa.RESHAPE(%op1_transpose_params) {shape={N,K,C}} + %op3_reshape_indices = tosa.RESHAPE(%indices) {shape={N,W}} + %op4_gather_op2_op3 = tosa.GATHER(%op2_reshape_op1, %op3_reshape_indices) + %op5_reshape_op4 = tosa.RESHAPE(%op4_gather_op2_op3) {shape={N,W,C}} + %op6_transpose_op5 = tosa.TRANSPOSE(%op5_reshape_op4, %const_result_perm) +} +``` + +### lower_gather_nd_op() + +``` +Value lower_gather_nd_op(Value %params, Value %indices) +{ + int32 N = W = K = C = ND = 1 + + ND = %indices.shape[%indices.rank - 1] + + assert ND < %params.rank + + for (int32 i = 0; i < (%indices.rank - 1); i++) W *= %indices.shape[i] + for (int32 i = 0; i < ND; i++) K = %params.shape[i] + for (int32 i = ND; i < %params.rank; i++) C *= %params.shape[i] + + vector flatten_coeff_vec + for (int32 i = 0; i < ND; i++) flatten_coeff_vec.push_back(i) + flatten_coeff_vec.push_back(1) + + %const_flatten_coeff = tosa.CONST() {value=flatten_coeff_vec} + %op1_reshape_params = tosa.RESHAPE(%params) {shape={N,K,C}} + %op2_reshape_indices = tosa.RESHAPE(%indices) {shape={W,ND}} + %op3_mul_op2_flatten_coeff = tosa.MUL(%op2_reshape_indices, %const_flatten_coeff) + %op4_rsum_op3 = tosa.REDUCE_SUM(%op3_mul_op2_flatten_coeff) {axis=1} + %op5_reshape_op4 = tosa.RESHAPE(%op4_rsum_op3) {shape={N,W}} + %op6_gather_op1_op5 = tosa.GATHER(%op1_reshape_params, %op5_reshape_op4) + %op7_reshape_op6 = tosa.RESHAPE(%op6_gather_op1_op5) {shape={N,W,C}} +} +``` + +### lower_one_hot_op() + +``` +Value lower_one_hot_op(Value %indices, Value %depth, Value %on_value, Value %off_value, int32 axis) +{ + int32 N = W = C = 1 + int32 K = %depth.as_constant() + int32 left_dim = right_dim = 1 + for(int32 i : %indices.rank) { + int32 dim = %indices.shape[i] + N *= dim + if (i >= axis) + right_dim *= dim + else + left_dim *= dim + } + + %perm_const = tosa.CONST() {value={0, 2, 1}} + %op1_reshape_on_value = tosa.RESHAPE(%on_value) {shape={1, 1, 1}} + %op2_tile_op1 = tosa.TILE(%op1_reshape_on_value) {multiples={N, W, C}} + %op3_reshape_off_value = tosa.RESHAPE(%off_value) {shape={1, 1, 1}} + %op4_tile_op1 = tosa.TILE(%op3_reshape_off_value) {multiples={N, K, C}} + %op5_reshape_indices = tosa.RESHAPE(%indices) {shape={N, W}} + %op6_scatter_op4_op5_op2 = tosa.SCATTER(%op4_tile_op1, %op5_reshape_indices, %op2_tile_op1) + %op7_reshape_op6 = tosa.RESHAPE(%op6_scatter_op4_op5_op2) {shape={left_dim, right_dim, K}} + %op8_transpose_op7 = tosa.TRANSPOSE(%op7_reshape_op6, %perm_const) + %op9_reshape_op8 = tosa.RESHAPE(%op8_transpose_op7) {shape=%output.shape} +} + + +## MLIR Passes Management + +Legalization is built on multiple MLIR passes. + +| MLIR Pass Name | Input Dialect | Output Dialect | Description | +| ------------------------- | ------------- | -------------- | --------------- | +| legalize_tf | TensorFlow | TOSA | Legalize | +: : : : TensorFlow : +: : : : dialect to TOSA : +: : : : dialect : +| fuse_tf_bias | TensorFlow | TOSA | Mapping | +: : : : tf.BiasAdd + : +: : : : tf.Conv2D to : +: : : : tosa.CONV2D : +| legalize_tfl | TensorFlow | TOSA | Legalize | +: : Lite : : TensorFlow Lite : +: : : : dialect to TOSA : +: : : : dialect : +| convert_tfl_uint8 | TensorFlow | TensorFlow | Convert | +: : Lite : Lite : quantized uint8 : +: : : : graph to int8 : +: : : : graph : + +TF to TOSA legalization could be summarized by following pseudocode: + +``` + +void legalize_tf_to_tosa(mlir::Module module) { mlir::PassManager pm + +``` +// other MLIR passes to optimize TF + +pm.addPass(fuse_tf_bias) +pm.addPass(legalize_tf) + +// other MLIR passes to optimize TOSA +``` + +} ``` + +TFLite to TOSA legalization could be summarized by following pseudocode: + +``` +void legalize_tfl_to_tosa(mlir::Module module) +{ + mlir::PassManager pm + + // other MLIR passes to optimize TFLite + + pm.addPass(convert_tfl_uint8) + pm.addPass(legalize_tfl) + + // other MLIR passes to optimize TOSA +} +``` + +Each of the passes is described in more detail in the subsequent chapters. + +## TensorFlow MLIR Dialect Legalization (legalize_tf) + +### tf.Abs + +This operator is trivially lowered to tosa.ABS + +### tf.AddN + +**TensorFlow Dialect** + +``` +%output = tf.AddN(%inputs) +``` + +**TOSA Lowering** + +``` +%output = tosa.ADD(%inputs:0, %inputs:1) +for (int32 i = 2; i < %inputs.size; i++) { + %output = tosa.ADD(%inputs:i, %output) +} +``` + +### tf.Add + +Element-wise addition. + +**TensorFlow Dialect** + +``` +%output = tf.Add(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.ADD. + +### tf.Addv2 + +Element-wise addition. + +**TensorFlow Dialect** + +``` +%output = tf.Addv2(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.ADD. + +### tf.All + +Computes the "logical and" of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.all(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tf.Any + +Computes the "logical or" of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.any(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tf.ArgMax + +Returns the index with the largest value across the given axis of the input +tensor. + +**TensorFlow Dialect** + +``` +%output = tf.ArgMax(%input, %dimension) +``` + +**TOSA Lowering** + +``` +int64 axis = positive_axis(%dimension) +%output = tosa.ARGMAX(%input) {axis=axis} +``` + +### tf.ArgMin + +Returns the index with the smallest value across the given axis of the input +tensor. + +**TensorFlow Dialect** + +``` +%output = tf.ArgMin(%input, %dimension) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.Assert + +Asserts that the given condition is true. + +**TensorFlow Dialect** + +``` +%output = tf.Assert(%condition, %summarize) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.AssignAddVariableOp + +Adds a value to the current value of a variable. + +**TensorFlow Dialect** + +``` +%output = tf.AssignAddVariableOp(%resource, %value, %dtype) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.AssignSubVariableOp + +Subtracts a value to the current value of a variable. + +**TensorFlow Dialect** + +``` +%output = tf.AssignSubVariableOp(%resource, %value, %dtype) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.AssignVariableOp + +Assigns a new value to a variable. + +**TensorFlow Dialect** + +``` +%output = tf.AssignVariableOp(%resource, %value, %dtype) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.AvgPool + +Performs average pooling on the input. + +**TensorFlow Dialect** + +``` +%output = tf.AvgPool(%value) {ksize, strides, padding, data_format} +``` + +**TOSA Lowering** + +``` +assert(data_format == "NHWC") + +tosa_padding = + get_padding_values_from_pad_type(%input, ksize, padding, data_format, + FORMAT_OHWI, strides, {1, 1, 1, 1}) +%output = tosa.AVG_POOL2D(%value) {ksize=ksize, strides=strides, padding=tosa_padding} +``` + +### tf.BatchMatMul + +Multiplies slices of two tensors in batches. + +**TensorFlow Dialect** + +``` +%output = tf.BatchMatMul(%x, %y, %adj_x, %adj_y) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.BatchMatMulV2 + +Multiplies slices of two tensors in batches. + +**TensorFlow Dialect** + +``` +%output = tf.BatchMatMulV2(%x, %y, %adj_x, %adj_y) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.BatchNormWithGlobalNormalization + +✗ Deprecated operator. + +### tf.BatchToSpaceND + +BatchToSpaceND for N-D tensors of type T. + +**TensorFlow Dialect** + +``` +%output = tf.BatchToSpaceND(%input, %block_shape, %crops) +``` + +**TOSA Lowering** + +``` +%output = lower_batch_to_space_nd_op(%input, %block_shape, %crops, output.shape) +``` + +### tf.BiasAddGrad + +Training profile: TOSA lowering not yet defined. + +### tf.BiasAdd + +Add bias to value. + +**TensorFlow Dialect** + +``` +%output = tf.BiasAdd(%bias, %value) {data_format} +``` + +**TOSA Lowering** + +``` +assert(data_format == 'NHWC') +%output = tosa.ADD(%value, %bias) +``` + +### tf.BitCast + +Bitcasts a tensor from one type to another without copying data. + +**TensorFlow Dialect** + +``` +%output = tf.BitCast(%input, %dtype) +``` + +**TOSA Lowering** + +No TOSA lowering defined. + +### tf.BitwiseAnd + +This operator is trivially lowered to tosa.BITWISE_AND. + +### tf.BitwiseOr + +This operator is trivially lowered to tosa.BITWISE_OR. + +### tf.BroadcastGradientArgs + +Training profile: TOSA lowering not yet defined. + +### tf.BroadcastTo + +No TOSA lowering defined. + +### tf.Cast + +This operator is trivially lowered to tosa.CAST. + +### tf.Ceil + +This operator is trivially lowered to tosa.CEIL. + +### tf.CheckNumerics + +No TOSA lowering defined. + +### tf.ComplexAbs + +No TOSA lowering defined. + +### tf.Complex + +No TOSA lowering defined. + +### tf.ConcatOffset + +No TOSA lowering defined. Training profile: TOSA lowering not yet defined. + +### tf.Concat + +No TOSA lowering defined. + +### tf.ConcatV2 + +Concatenates tensors along one dimension. + +**TensorFlow Dialect** + +``` +%output = tf.ConcatV2(%values, %axis) +``` + +**TOSA Lowering** + +``` +%output = lower_concatv2_op(%values, %axis) +``` + +### tf.Conj + +No TOSA lowering defined. + +### tf.Const + +This operator is trivially lowered to tosa.CONST. + +### tf.Conv2DBackpropFilter + +No TOSA lowering defined. + +### tf.Conv2DBackpropInput + +Computes the gradients of convolution with respect to the input. + +**TensorFlow Dialect** + +``` +%output = tf.Conv2DBackpropInput(%input_sizes, %filter, %out_backprop) {strides, use_cudnn_on_gpu, padding, explicit_paddings, data_format, dilations} +``` + +**TOSA Lowering** + +``` +// Transpose filter from HWIO to OHWI +%tosa_filter = tosa.TRANSPOSE(%filter) {perms={2, 0, 1, 3}} + +vector output_shape + +for (int32 i = 0; i < input_sizes.size(); i++) { + output_shape.push_back(input_size[i]) +} + +if (%padding == "EXPLICIT") { + tosa_padding = + get_padding_values_from_explicit_pad_attr(explicit_padding, data_format) +} else { + tosa_padding = + get_transpose_conv2d_padding_values_from_pad_type(%input_sizes, %filter, output_shape, padding, data_format, FORMAT_HWIO, strides, dilations) +} + +// Create a zero bias tensor +%zero_bias = tosa.CONST() {value={0}} +%output = tosa.TRANSPOSE_CONV2D(%out_backprop) {weight=%tosa_filter, bias=%zero_bias, outpad=tosa_pading, stride=strides, dilation==dilations, out_shape=out_shape} +``` + +### tf.Conv2D + +Computes a 2-D convolution given 4-D input and filter tensors. + +**TensorFlow Dialect** + +``` +%output = tf.Conv2D(%input, %filter) {strides, padding, explicit_paddings, data_format, dilations} +``` + +**TOSA Lowering** + +``` +assert(data_format == "NHWC") + +// Transpose filter from HWIO to OHWI +%filter_tranpose = tosa.TRANSPOSE(%filter {perms={3, 0, 1, 2}} + +if (padding == "EXPLICIT") { + tosa_padding = + get_padding_values_from_explicit_pad_attr(explicit_padding, data_format) +} else { + %tosa_padding = + get_padding_values_from_pad_type(%input, %filter.shape, padding, data_format, + FORMAT_HWIO, strides, dilations) +} + +// Create a zero bias tensor +%zero_bias = tosa.CONST() {value={0}} + +%output = tosa.CONV2D(%input, %filter_transpose, %zero_bias) {padding=tosa_padding, stride=strides, dilation=dilations} +``` + +### tf.Conv3D + +TOSA lowering to tosa.CONV3D to be defined. + +### tf.Cos + +No TOSA lowering defined. + +### tf.CrossReplicaSum + +No TOSA lowering defined. + +### tf.DepthToSpace + +DepthToSpace for tensors of type T. + +**TensorFlow Dialect** + +``` +%output = tf.DepthToSpace(%input) {block_size, data_format} +``` + +**TOSA Lowering** + +``` +%output = lower_depth_to_space_op(%input, block_size, data_format) +``` + +### tf.DepthwiseConv2dNative + +Computes a 2-D depthwise convolution given 4-D input and filter tensors. + +**TensorFlow Dialect** + +``` +%output = tf.DepthwiseConv2dNative(%input, %filter) {strides, padding, data_format, dilations} +``` + +**TOSA Lowering** + +``` +if (padding == "EXPLICIT") { + tosa_padding = + get_padding_values_from_explicit_pad_attr(explicit_padding, data_format) +} else { + tosa_padding = + get_padding_values_from_pad_type(%input, %filter.shape, padding, data_format, + FORMAT_HWIO, strides, dilations) +} + +bias_dim = %filter.shape[2] * %filter.shape[3] + +// Create a zero-bias tensor +%zero_bias = tosa.CONST() {value={0} * bias_dim} + +%output = tosa.DEPTHWISE_CONV2D(%input, %filter, %zero_bias) {stride=strides, dilation=dilations, padding=padding} +``` + +### tf.DivNoNan + +No TOSA lowering defined. + +### tf.Div + +No TOSA lowering defined. + +### tf.DynamicStitch + +No TOSA lowering defined. + +### tf.Einsum + +No TOSA lowering defined. + +### tf.Elu + +Computes exponential linear: exp(features) - 1 if <0, features otherwise + +**TensorFlow Dialect** + +``` +%output = tf.Elu(%features) +``` + +**TOSA Lowering** + +``` +%output = lower_elu_op(%features) +``` + +### tf.EmptyTensorList + +No TOSA lowering defined. + +### tf.Equal + +Returns the truth value of (x == y) element-wise with broadcasting. + +**TensorFlow Dialect** + +``` +%output = tf.Equal(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.EQUAL. + +### tf.Exp + +This operator is trivially lowered to tosa.EXP. + +### tf.ExpandDims + +Inserts a dimension of 1 into a tensor’s shape + +**TensorFlow Dialect** + +``` +%output = tf.ExpandDims(%input, %axis) +``` + +**TOSA Lowering** + +``` +%output = lower_expand_dims(%input, %axis.to_constant()) +``` + +### tf.FakeQuantWithMinMaxArgs + +Fake-quantize the 'inputs' tensor, type float to 'outputs' tensor of same type. + +**TensorFlow Dialect** + +``` +%output = tf.FakeQuantWithMinMaxArgs(%inputs) {min, max, num_bits, narrow_range} +``` + +**TOSA Lowering** + +``` +%output = lower_fake_quant_op(%inputs, %min, %max, %num_bits, %narrow_range) +``` + +### tf.FakeQuantWithMinMaxVars + +Fake-quantize the 'inputs' tensor of type float via global flats scalars min. + +**TensorFlow Dialect** + +``` +%output = tf.FakeQuantWithMinMaxVars(%inputs, %min, %max) {num_bits, narrow_range} +``` + +**TOSA Lowering** + +``` +%output = lower_fake_quant_op(%inputs, %output.type, %min.to_constant(), %max.to_constant(), num_bits, narrow_range) +``` + +### tf.FakeQuantWithMinMaxVarsPerChannel + +Fake-quantize the 'inputs' tensor of type float and one of the shapes \[d\]. + +**TensorFlow Dialect** + +``` +%output = tf.FakeQuantWithMinMaxVarsPerChannel(%inputs, %min, %max) {num_bits, narrow_range} +``` + +No TOSA lowering defined. + +### tf.Fill + +Creates a tensor filled with a scalar value + +**TensorFlow Dialect** + +``` +%output = tf.Fill(%dims, %value) +``` + +**TOSA Lowering** + +``` +int64 total_size = 1 + +for (int32 i = 0; i < %dims.shape[0]; i++) { + total_size *= %dims[i] +} + +vector<%value.dtype> fill_arr(total_size, %value) + +%output = tosa.CONST() {value={fill_arr}} +``` + +### tf.FloorDiv + +Returns x // y element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.FloorDiv(%x, %y) +``` + +**TOSA Lowering** + +``` +%output = lower_floor_div(%lhs, %rhs) +``` + +### tf.FloorMod + +Returns element-wise remainder of division when x < 0 xor x < y is true. + +**TensorFlow Dialect** + +``` +%output = tf.FloorMod(%x, %y) +``` + +**TOSA Lowering** + +``` +%output = lower_floor_mod(%lhs, %rhs) +``` + +### tf.Floor + +This operator is trivially lowered to tosa.FLOOR. + +### tf.FusedBatchNormGrad + +Training profile: TOSA lowering not yet defined. + +### tf.FusedBatchNormGradV2 + +Training profile: TOSA lowering not yet defined. + +### tf.FusedBatchNormGradV3 + +Training profile: TOSA lowering not yet defined. + +### tf.FusedBatchNorm + +Batch normalization. + +**TensorFlow Dialect** + +``` +%output = tf.FusedBatchNorm(%x, %scale, %offset, %mean, %variance) {epsilon, data_format, is_training} + + +assert(data_format == 'NHWC') +assert(is_training == false) + +%epsilon_const = tosa.CONST() {value={epsilon}} + +%op1 = tosa.SUB(%x, %bmean) +%op2 = tosa.ADD(%variance, %epsilon_const) +%op3 = tosa.RSQRT(%op2) +%op4 = tosa.MUL(%op1, %op3) +%op5 = tosa.MUL(%op4, %scale) +%output = tosa.ADD(%op5, %offset) +``` + +### tf.FusedBatchNormV3 + +Batch normalization. + +**TensorFlow Dialect** + +``` +%output = tf.FusedBatchNormV3(%x, %scale, %offset, %mean, %variance) {epsilon, data_format, is_training} +``` + +**TOSA Lowering** + +``` +assert(data_format == 'NHWC') +assert(is_training == false) + +%epsilon_const = tosa.CONST() {value={epsilon}} + +%op1 = tosa.SUB(%x, %bmean) +%op2 = tosa.ADD(%variance, %epsilon_const) +%op3 = tosa.RSQRT(%op2) +%op4 = tosa.MUL(%mean, %op3) +%op5 = tosa.MUL(%op4, %scale) +%output = tosa.ADD(%op5, %offset) +``` + +### tf.GatherNd + +Gather slices from params into a Tensor with shape specified by indices. + +**TensorFlow Dialect** + +``` +%output = tf.GatherNd(%params, %indices) +``` + +**TOSA Lowering** + +``` +%output = lower_gather_nd_op(%params, %indices) +``` + +### tf.Gather + +Gathers slices from params according to indices. + +**TensorFlow Dialect** + +``` +%output = tf.Gather(%params, %indices) +``` + +**TOSA Lowering** + +``` +%output = lower_gather_op(%params, %indices, 0, 0) +``` + +### tf.GatherV2 + +Gathers slices from params axis according to indices. + +**TensorFlow Dialect** + +``` +%output = tf.GatherV2(%params, %indices, %axis) {batch_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_gather_op(%params, %indices, batch_dims, %axis.to_constant()) +``` + +### tf.GreaterEqual + +Returns the truth value of (x >= y) element-wise with broadcasting. + +**TensorFlow Dialect** + +``` +%output = tf.GreaterEqual(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.GREATER_EQUAL. + +### tf.Greater + +RetruReturns the truth value of (x > y) element-wise with broadcasting. + +**TensorFlow Dialect** + +``` +%output = tf.Greater(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.GREATER. + +### tf.HashTableV2 + +No TOSA lowering defined. + +### tf.IdentityN + +Returns a list of tensors with the same shapes and contents as the input. + +**TensorFlow Dialect** + +``` +%output = tf.IdentityN(%input) +``` + +**TOSA Lowering** + +``` +%output = tosa.IDENTITYN(%input) +``` + +### tf.Identity + +Returns a tensor with the same shape and contents as the input. + +**TensorFlow Dialect** + +``` +%output = tf.Identity(%input) +``` + +**TOSA Lowering** + +``` +%output = tosa.IDENTITY(%input) +``` + +### tf.If + +No TOSA lowering defined. + +### tf.Imag + +No TOSA lowering defined. + +### tf.InfeedDequeueTuple + +No TOSA lowering defined. + +### tf.Invert + +This operator is trivially lowered to tosa.BITWISE_NOT. + +### tf.InvertPermutation + +No TOSA lowering defined. + +### tf.IsFinite + +No TOSA lowering defined. + +### tf.IteratorGetNext + +No TOSA lowering defined. + +### tf.L2Loss + +Training profile: TOSA lowering not yet defined. + +### tf.LRN + +No TOSA lowering defined. + +### tf.LeakyRelu + +Computes rectified linear: max(features, features \* alpha). + +**TensorFlow Dialect** + +``` +%output = tf.LeakyRelu(%features) {alpha} +``` + +**TOSA Lowering** + +``` +%alpha_tensor = tosa.CONST() {value={alpha}} +%features_alpha = tosa.MUL(%features, %alpha_tensor) +%greater = tosa.GREATER(%features, %features_alpha) +%output = tosa.SELECT(%greater, %features, %features_alpha) +``` + +### tf.LeftShift + +Computes the bitwise left-shift of x by y bits, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.LeftShift(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.LOGICAL_LEFT_SHIFT. + +### tf.LegacyCall + +No TOSA lowering defined. + +### tf.LessEqual + +Returns the truth value of (x ⇐ y) element-wise with broadcasting. + +**TensorFlow Dialect** + +``` +%output = tf.LessEqual(%x, %y) +``` + +**TOSA Lowering** + +``` +%output_greater = tosa.GREATER(%x, %y) +%output = tosa.LOGICAL_NOT(%output_greater) +``` + +### tf.Less + +Returns the truth value of (x < y) element-wise with broadcasting. + +**TensorFlow Dialect** + +``` +%output = tf.LessEqual(%x, %y) +``` + +**TOSA Lowering** + +``` +%output_greater_equal = tosa.GREATER_EQUAL(%x, %y) +%output = tosa.LOGICAL_NOT(%output_greater_equal) +``` + +### tf.LiNSpace + +No TOSA lowering defined. + +### tf.Log1p + +No TOSA lowering defined. + +### tf.Log + +This operator is trivially lowered to tosa.LOG. + +### tf.LogSoftmax + +Computes log softmax activations. + +**TensorFlow Dialect** + +``` +%output = tf.LogSoftmax(%logits) +``` + +**TOSA Lowering** + +``` +%output = lower_log_softmax_op(%logits) +``` + +### tf.LogicalAnd + +Returns the truth value of x AND y, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.LogicalAnd(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.LOGICAL_AND. + +### tf.LogicalNot + +This operator is trivially lowered to tosa.LOGICAL_NOT. + +### tf.LogicalOr + +Returns the truth value of x OR y, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.LogicalOr(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.LOGICAL_OR. + +### tf.LookupTableFindV2 + +No TOSA lowering defined. + +### tf.LookupTableInputV2 + +No TOSA lowering defined. + +### tf.LookupTableSizeV2 + +No TOSA lowering defined. + +### tf.MatMul + +Multiply the matrix a by the matrix b + +**TensorFlow Dialect** + +``` +%output = tf.MatMul(%a, %b) +``` + +**TOSA Lowering** + +``` +%output = tosa.MATMUL(%a, %b) +``` + +### tf.MatrixDiag + +No TOSA lowering defined. + +### tf.MatrixDiagV2 + +No TOSA lowering defined. + +### tf.MatrixDiagV3 + +No TOSA lowering defined. + +### tf.MatrixSetDiag + +No TOSA lowering defined. + +### tf.MatrixSetDiagV2 + +No TOSA lowering defined. + +### tf.MatrixSetDiagV3 + +No TOSA lowering defined. + +### tf.Max + +Computes the maximum of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Max(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tf.MaxPoolGrad + +Training profile: TOSA lowering not yet defined. + +### tf.MaxPool + +Performs max pooling on the input. + +**TensorFlow Dialect** + +``` +%output = tf.MaxPool(%input) {ksize, strides, padding, data_format} +``` + +**TOSA Lowering** + +``` +assert(data_format == "NHWC") + +tosa_padding = + get_padding_values_from_pad_type(%input, ksize, padding, data_format, + FORMAT_OHWI, strides, {1, 1, 1, 1}) +%output = tosa.MAX_POOL2D(%value) {ksize=ksize, strides=strides, padding=tosa_padding} +``` + +### tf.Maximum + +This operator is trivially lowered to tosa.MAXIMUM. + +### tf.Mean + +Computes the mean of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Mean(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +int32 num_elements_on_axis = 1 +for (int32 axis : %reduction_indices) { + num_elements_on_axis *= %input.shape[axis] +} +float32 div_scale = 1.0 / num_elements_on_axis + +%cst_div_scale = tosa.CONST() {value={div_scale}} +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +%op2_mul_op1 = tosa.MUL(%op1_rsum_in, %cst_div_scale) +``` + +### tf.Min + +Computes the minimum of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Min(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tf.Minimum + +This operator is trivially lowered to tosa.MAXIMUM. + +### tf.MirrorPad + +No TOSA lowering defined. + +### tf.MlirPassthroughOp + +No TOSA lowering defined. + +### tf.MulNoNan + +No TOSA lowering defined. + +### tf.Mul + +Returns the product of x and y, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.Mul(%x, %y) +``` + +**TOSA Lowering** This operator is trivially lowered to tosa.MUL. + +### tf.Neg + +This operator is trivially lowered to tosa.NEGATE. + +### tf.NoOp + +No TOSA lowering defined. + +### tf.NonMaxSuppressionV4 + +No TOSA lowering defined. + +### tf.NonMaxSuppressionV5 + +No TOSA lowering defined. + +### tf.NotEqual + +Returns the truth value of (x != y) element-wise with broadcasting. + +**TensorFlow Dialect** + +``` +%output = tf.NotEqual(%x, %y) +``` + +**TOSA Lowering** + +``` +%equal = tosa.EQUAL(%x, %y) +%output = tosa.NOT(%equal) +``` + +### tf.OneHot + +OneHot operator. + +**TensorFlow Lite Dialect** + +``` +%output = tf.OneHot(%indices, %depth, %on_value, %off_value) {axis} +``` + +**TOSA Lowering** + +``` +%output = lower_one_hot_op(%indices, %depth, %on_value, %off_value, axis) +``` + +### tf.OutputEnqueueTuple + +No TOSA lowering defined. + +### tf.Pack + +Packs a list of N rank-R tensors into one rank-(R+1) tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Pack(%values) {axis} +``` + +**TOSA Lowering** + +``` +%output = lower_pack_op(%values, axis) +``` + +### tf.Pad + +This operator is trivially lowered to tosa.PAD. + +### tf.PadV2 + +No TOSA lowering defined. + +### tf.ParseExampleV2 + +No TOSA lowering defined. + +### tf.PartitionedCall + +No TOSA lowering defined. + +### tf.Placeholder + +Not seen in practice. No lowering needed. + +### tf.PlaceholderWithDefault + +Not seen in practice. No lowering needed. + +### tf.Pow + +This operator is trivially lowered to tosa.POW. + +### tf.PreventGradient + +Training profile: TOSA lowering not yet defined. + +### tf.Prod + +Computes the product of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Prod(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tf.QuantizeAndDequantize + +No TOSA lowering defined. + +### tf.QuantizeAndDequantizeV2 + +No TOSA lowering defined. + +### tf.QuantizeAndDequantizeV3 + +No TOSA lowering defined. + +### tf.RFFT + +No TOSA lowering defined. + +### tf.RandomShuffle + +No TOSA lowering defined. + +### tf.RandomStandardNormal + +No TOSA lowering defined. + +### tf.RandomUniform + +No TOSA lowering defined. + +### tf.Range + +No TOSA lowering defined. + +### tf.Rank + +Returns the rank of the tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Rank(%input) +``` + +**TOSA Lowering** + +``` +%output = tosa.CONST() {value={%input.rank}} +``` + +### tf.ReadVariableOp + +No TOSA lowering defined. + +### tf.RealDiv + +Returns x / y element-wise for real types. + +**TensorFlow Dialect** + +``` +%output = tf.RealDiv(%x, %y) +``` + +**TOSA Lowering** + +``` +%recip = tosa.RECIPROCAL(%y) +%output = tosa.MUL(%x, %recip) +``` + +### tf.Real + +No TOSA lowering defined. + +### tf.Reciprocal + +This operator is trivially lowered to tosa.RECIPROCAL. + +### tf.Relu6 + +Computes rectified linear 6: min(max(features, 0), 6). + +**TensorFlow Dialect** + +``` +%output = tf.Relu6(%features) +``` + +**TOSA Lowering** + +``` +%output = tosa.RELUN(%features) {max_val=6} +``` + +### tf.ReluGrad + +Training profile: TOSA lowering not yet defined. + +### tf.Relu + +Computes rectified linear 6: max(features, 0) + +**TensorFlow Dialect** + +``` +%output = tf.Relu(%features) +``` + +**TOSA Lowering** + +``` +%output = tosa.RELUN(%features) {max_val=0} +``` + +### tf.Reshape + +Reshapes a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Reshape(%tensor, %shape) +``` + +**TOSA Lowering** + +``` +%output = tosa.RESHAPE(%tensor) {new_shape=%shape.as_constant} +``` + +### tf.ResizeBilinear + +Resizes images to size using bilinear interpolation. + +**TensorFlow Dialect** + +``` +%output = tf.ResizeBilinear(%images, %size) {align_corners, half_pixel_centers} +``` + +inferred from output shape. **TOSA Lowering** + +``` +%output = lower_resize_op(%images, %size, float, "BILINEAR") +``` + +### tf.ResizeNearestNeighbor + +Resizes images to size using nearest neighbor interpolation. + +**TensorFlow Dialect** + +``` +%output = tf.ResizeNearestNeighbor(%images, %size) {align_corners, half_pixel_centers} +``` + +inferred from output shape. **TOSA Lowering** + +``` +%output = lower_resize_op(%images, %size, %output, float, "NEAREST_NEIGHBOR") +``` + +### tf.ResourceApplyAdam + +Training profile: TOSA lowering not yet defined. + +### tf.ResourceApplyGradientDescent + +Training profile: TOSA lowering not yet defined. + +### tf.ResourceApplyKerasMomentum + +Training profile: TOSA lowering not yet defined. + +### tf.ResourceGather + +Training profile: TOSA lowering not yet defined. + +### tf.ResourceScatterUpdate + +Training profile: TOSA lowering not yet defined. + +### tf.ReverseSequence + +No TOSA lowering defined. + +### tf.ReverseV2 + +Reverses specific dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.ReverseV2(%tensor, %axis) +``` + +**TOSA Lowering** + +``` +%output = lower_reversev2_op(%tensor, %axis) +``` + +### tf.RightShift + +Computes the bitwise left-shift of x by y bits, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.LeftShift(%x, %y) +``` + +**TOSA Lowering** + +``` +if (is_unsigned(%x.dtype)) { + %output = tosa.LOGICAL_RIGHT_SHIFT(%x, %y) +} else { + %output = tosa.ARITHMETIC_RIGHT_SHIFT(%x, %y) +} +``` + +### tf.Round + +Rounds the values of a tensor to the nearest integer, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.Round(%x) +``` + +**TOSA Lowering** + +``` +%output = lower_round_op(%x) +``` + +### tf.RsqrtGrad + +Training profile: TOSA lowering not yet defined. + +### tf.Rsqrt + +This operator is trivially lowered to tosa.RSQRT. + +### tf.SegmentMax + +No TOSA lowering defined. + +### tf.SegmentMean + +No TOSA lowering defined. + +### tf.SegmentMin + +No TOSA lowering defined. + +### tf.SegmentProd + +No TOSA lowering defined. + +### tf.SegmentSum + +No TOSA lowering defined. + +### tf.Select + +No TOSA lowering defined. + +### tf.SelectV2 + +Selects elements from t or e depending on condition. + +**TensorFlow Dialect** + +``` +%output = tf.SelectV2(%condition, %t, %e) +``` + +**TOSA Lowering** + +``` +%output = lower_selectv2_op(%condition, %t, %e, %output.shape) +``` + +### tf.ShapeN + +No TOSA lowering defined. + +### tf.Shape + +Returns the shape of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Shape(%input) +``` + +**TOSA Lowering** + +``` +%output = lower_shape_op(%input) +``` + +### tf.Sigmoid + +This operator is trivially lowered to tosa.SIGMOID. + +### tf.Sign + +No TOSA lowering defined. + +### tf.Sin + +No TOSA lowering defined. + +### tf.Size + +No TOSA lowering defined. + +### tf.Slice + +Returns a slice from input. + +**TensorFlow Dialect** + +``` +%output = tf.Slice(%input, %begin, %size) +``` + +**TOSA Lowering** + +``` +vector output_size +try { + output_size = %size.as_constant() +} except(ConversionFailed) { + output_size = %output.shape +} + +%output = tosa.SLICE(%input) {start=begin, size=output_size} +``` + +### tf.Snapshot + +No TOSA lowering defined. + +### tf.SoftmaxCrossEntropyWithLogits + +Training profile: TOSA lowering not yet defined. + +### tf.Softmax + +Computes softmax activations + +**TensorFlow Dialect** + +``` +%output = tf.Softmax(%logits) +``` + +**TOSA Lowering** + +``` +%op1 = tosa.EXP(%logits) +%op2 = tosa.REDUCE_SUM(op1) {reduce_axis=(%logits.rank - 1)} +%op3 = tosa.RECIPROCAL(%op2) +%output = tosa.MUL(%op1, %op3) +``` + +### tf.Softplus + +No TOSA lowering defined. + +### tf.SpaceToBatchND + +SpaceToBatch for N-D tensors of type T. + +**TensorFlow Dialect** + +``` +%output = tf.SpaceToBatchND(%input, %block_shape, %paddings) +``` + +**TOSA Lowering** + +``` +%output = lower_space_to_batch_nd_op(%input, %block_shape, %paddings) +``` + +### tf.SpaceToDepth + +SpaceToDepth for tensors of type T. + +**TensorFlow Dialect** + +``` +%output = tf.SpaceToDepth(%input) {block_size, data_format} +``` + +**TOSA Lowering** + +``` +%output = lower_space_to_depth_op(%input, block_size, data_format) +``` + +### tf.SparseMatMul + +No TOSA lowering defined. + +### tf.SparseSoftmaxCrossEntropyWithLogits + +No TOSA lowering defined. + +### tf.SparseToDense + +No TOSA lowering defined. + +### tf.Split + +Splits a tensor into num_split tensors along one dimension + +**TensorFlow Dialect** + +``` +%output = tf.Split(%split_dim, %value) {num_split} +``` + +**TOSA Lowering** + +``` +%output = lower_split_op(%value, %split_dim.as_constant(), num_split) +``` + +### tf.SplitV + +Splits a tensor into num_split tensors along one dimension + +**TensorFlow Dialect** + +``` +%output = tf.SplitV(%value, %size_splits, %split_dim) {num_split} +``` + +**TOSA Lowering** + +``` +%output = lower_splitv_op(%value, %size_splits.as_constant(), %split_dim.as_constant()) +``` + +### tf.Sqrt + +No TOSA lowering defined. + +### tf.Square + +Computes the square of x, element-wise. + +**TensorFlow Dialect** + +``` +%output = tf.Square(%x) +``` + +**TOSA Lowering** + +``` +%output = tosa.MUL(%x, %x) +``` + +### tf.SquareDifference + +Computes (x-y)\*(x-y) element-wise + +**TensorFlow Dialect** + +``` +%output = tf.SquareDifference(%x, %y) +``` + +**TOSA Lowering** + +``` +%diff = tosa.SUB(%x, %y) +%output = tosa.MUL(%diff, %diff) +``` + +### tf.Squeeze + +Removes dimensions of size 1 from the shape of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Squeeze(%input) {squeeze_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_squeeze_op(%input, squeeze_dims) +``` + +### tf.StatefulPartitionedCall + +No TOSA lowering defined. + +### tf.StopGradient + +Training profile: TOSA lowering not yet defined. + +### tf.StridedSliceGrad + +Training profile: TOSA lowering not yet defined. + +### tf.StridedSlice + +Return a strided slice from input. + +**TensorFlow Dialect** + +``` +%output = tf.StridedSlice(%input, %begin, %end, %strides) {begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask} +``` + +**TOSA Lowering** + +``` +%output = lower_strided_slice_op(%input, %begin, %end, %strides, begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask) +``` + +### tf.Sub + +This operator is trivially lowered to tosa.SUB. + +### tf.Sum + +Computes the sum of elements across dimensions of a tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Sum(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tf.TPUCompilationResult + +No TOSA lowering defined. + +### tf.TPUCopyWithLayout + +No TOSA lowering defined. + +### tf.TPUExecuteAndUpdateVariables + +No TOSA lowering defined. + +### tf.TPUExecute + +No TOSA lowering defined. + +### tf.TPUGetLayout + +No TOSA lowering defined. + +### tf.TPUReplicateMetadata + +No TOSA lowering defined. + +### tf.TPUReplicatedInput + +No TOSA lowering defined. + +### tf.TPUReplicatedOutput + +No TOSA lowering defined. + +### tf.TPUReshardVariables + +No TOSA lowering defined. + +### tf.TanhGrad + +Training profile: TOSA lowering not yet defined. + +### tf.Tanh + +This operator is trivially lowered to tosa.TANH. + +### tf.TensorListFromTensor + +No TOSA lowering defined. + +### tf.TensorListGetItem + +No TOSA lowering defined. + +### tf.TensorListLength + +No TOSA lowering defined. + +### tf.TensorListPushBack + +No TOSA lowering defined. + +### tf.TensorListReserve + +No TOSA lowering defined. + +### tf.TensorListResize + +No TOSA lowering defined. + +### tf.TensorListSetItem + +No TOSA lowering defined. + +### tf.TensorListStack + +No TOSA lowering defined. + +### tf.TensorScatterUpdate + +No TOSA lowering defined. + +### tf.Tile + +Constructs a tensor by tiling a given tensor. + +**TensorFlow Dialect** + +``` +%output = tf.Tile(%input, %multiples) +``` + +**TOSA Lowering** + +``` +%output = tosa.TILE(%input) {multiples=%multiples.as_constant()} +``` + +### tf.ToBool + +No TOSA lowering defined. + +### tf.TopKV2 + +No TOSA lowering defined. + +### tf.Transpose + +Shuffle dimensions of x according to a permutation. + +**TensorFlow Dialect** + +``` +%output = tf.Transpose(%x, %perm) +``` + +**TOSA Lowering** + +``` +%output = tosa.TRANSPOSE(%x) {perm=%perm.as_constant()} +``` + +### tf.TruncateDiv + +No TOSA lowering defined. + +### tf.Unique + +No TOSA lowering defined. + +### tf.Unpack + +Unpacks a given dimension of a rank-R tensor into num rank-(R-1) tensors. + +**TensorFlow Dialect** + +``` +%output = tf.Unpack(%value) {axis, num} +``` + +**TOSA Lowering** + +``` +%output = lower_unpack_op(%value, axis, num) +``` + +### tf.UnsortedSegmentMax + +No TOSA lowering defined. + +### tf.UnsortedSegmentMin + +No TOSA lowering defined. === tf.UnsortedSegmentProd + +No TOSA lowering defined. === tf.UnsortedSegmentSum + +No TOSA lowering defined. + +### tf.VarHandle + +No TOSA lowering defined. + +### tf.VariableShape + +No TOSA lowering defined. + +### tf.Where + +No TOSA lowering defined. + +### tf.While + +No TOSA lowering defined. + +### tf.Xdivy + +No TOSA lowering defined. + +### tf.XlaDynamicUpdateSlice + +No TOSA lowering defined. + +### tf.XlaSharding + +No TOSA lowering defined. + +### tf.ZerosLike + +Returns a tensor of zeros with the same shape and type as x. + +**TensorFlow Dialect** + +``` +%output = tf.ZerosLike(%x) +``` + +**TOSA Lowering** + +``` +%output = tosa.CONST() {value={0} * %x.num_elements} +``` + +## TensorFlow Lite MLIR Dialect Legalization (legalize_tfl) + +### tfl.abs + +This operator is trivially lowered to tosa.ABS + +### tfl.add_n + +add_n operator. + +**TensorFlow Lite Dialect** + +``` +%sum = tfl.add_n(%inputs) +``` + +**TOSA Lowering** + +``` +%output = tosa.ADD(%inputs:0, %inputs:1) +for (int32 i = 2 i < %inputs.size i++) { + %output = tosa.ADD(%inputs:i, %output) +} +``` + +### tfl.add + +Element-wise addition operation. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.add(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%result = tosa.ADD(%lhs, %rhs) +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 max_scale_2x = 2.0 * max(%lhs.scale, %rhs.scale) +float64 lhs_scale = float64(1 << input_shift) * %lhs.scale / max_scale_2x +float64 rhs_scale = float64(1 << input_shift) * %rhs.scale / max_scale_2x +float64 output_scale = max_scale_2x / (%output.scale * float64(1 << input_shift)) + +``` + +Legalization: + +``` +%op1_rescale_lhs = tosa.RESCALE(%lhs) {scale=lhs_scale, input_zp=%lhs.zp, output_zp=0} // %lhs.dtype->i32 +%op2_rescale_rhs = tosa.RESCALE(%rhs) {scale=rhs_scale, input_zp=%rhs.zp, output_zp=0} // %rhs.dtype->i32 +%op3_add_op1_op2 = tosa.ADD(%op1_rescale_lhs, %op2_rescale_rhs) +%op4_rescale_op3 = tosa.RESCALE(%op3_add_op1_op2) {scale=output_scale} // i32->%output.dtype +``` + +### tfl.arg_max + +ArgMax operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.arg_max(%input, %dim) +``` + +**TOSA Lowering** + +``` +%result = tosa.ARGMAX(%input) {axis=positive_axis(%dim_const.as_constant(), %input.rank)} +``` + +### tfl.arg_min + +No TOSA lowering defined. + +### tfl.average_pool_2d + +Average_pool_2d operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.average_pool_2d(%input) {filter_height, filter_width, padding, stride_h, stride_w, fused_activation_function} +``` + +**TOSA Lowering** + +Prepare: + +``` +tosa_padding = + get_padding_values_from_pad_type(padding, NHWC, 1, + %input.type, tensor<{filter_height, filter_width}, tosa.int32>, + {1, stride_h, stride_w, 1}, {1, 1, 1, 1}) +``` + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%avgpool2d = tosa.AVG_POOL2D(%input) {kernel={filter_height, filter_width}, stride={stride_h, stride_w}, padding=tosa_padding} +if(fused_activation != NONE) { + %result = convert_fused_activation(%avgpool2d, fused_activation) +} +else { + %result = %avgpool2d +} +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%avgpool2d = tosa.AVG_POOL2D(%input) {kernel={filter_height, filter_width}, stride={stride_h, stride_w}, padding=tosa_padding, quantization_info={input_zp=%input.zp, output_zp=%output.zp}} +if(fused_activation != NONE) { + %result = convert_fused_activation(%avgpool2d, fused_activation) +} +else { + %result = %avgpool2d +} +``` + +### tfl.basic_lstm + +No TOSA lowering defined. + +### tfl.batch_to_space_nd + +BatchToSpaceNd operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.batch_to_space_nd(%input, %block_shape, %indices) +``` + +**TOSA Lowering** + +``` +%result = convert_batch_to_space_nd_op(%input, %block_shape, %indices) +``` + +### tfl.cast + +This operator is trivially lowered to tosa.CAST + +### tfl.ceil + +Ceil operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.ceil(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%result = tosa.CEIL(%x) +``` + +### tfl.concatenation + +Concatenation operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.concatenation(%values) {axis} +``` + +**TOSA Lowering** + +``` +%result = lower_concatv2_op(%values, axis) +``` + +### tfl.pseudo_const + +This operator is trivially lowered to tosa.CONST + +### tfl.conv_2d + +Convolution operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.conv_2d(%input, %filter, %bias) {dilation_h_factor, dilation_w_factor, fused_activation_function, padding, stride_h, stride_w} +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Prepare: + +``` +tosa_padding = + get_padding_values_from_pad_type(padding, NHWC, 1, + %input.type, %filter.type, + {1, stride_h, stride_w, 1}, {1, dilation_h_factor, dilation_w_factor, 1}) +``` + +Legalization: + +``` +%conv2d = tosa.CONV2D(%input, %filter, %bias) {padding=tosa_padding, stride={stride_h, stride_w}, dilation={dilation_h_factor, dilation_w_factor}} +if(fused_activation != NONE) { + %result = convert_fused_activation(%conv2d, fused_activation_function) +} +else { + %result = %conv2d +} +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 output_rescale_scale = (%input.scale * %filter.scale) / %output.scale + +tosa_padding = + get_padding_values_from_pad_type(padding, NHWC, 1, + %input.type, %filter.type, + {1, stride_h, stride_w, 1}, {1, dilation_h_factor, dilation_w_factor, 1}) +``` + +Legalization: + +``` +%conv2d = tosa.CONV2D(%input, %filter, %bias) {padding=tosa_padding, stride={stride_h, stride_w}, dilation={dilation_h_factor, dilation_w_factor}, quantization_info={input_zp=%input.zp, weight_zp=%filter.zp}} +%rescale = tosa.RESCALE(%conv2d) {scale=output_rescale_scale, input_zp=0, output_zp=%output.zp} // %conv2d.dtype->%output.dtype +if(fused_activation != NONE) { + %result = convert_fused_activation(%rescale, fused_activation_function) +} +else { + %result = %rescale +} +``` + +### tfl.convolution_2d_transpose_bias + +No TOSA lowering defined. + +### tfl.cos + +No TOSA lowering defined. + +### tfl.densify + +No TOSA lowering defined. + +### tfl.depth_to_space + +DepthToSpace operator. + +**TensorFlow Dialect** + +``` +%output = tfl.depth_to_space(%input) {block_size} +``` + +**TOSA Lowering** + +``` +%output = lower_depth_to_space_op(%input, block_size, "NHWC") +``` + +### tfl.depthwise_conv_2d + +Depthwise-separable convolution operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.depthwise_conv_2d(%input, %filter, %bias) {dilation_h_factor, dilation_w_factor, fused_activation_function, padding, stride_h, stride_w, depth_multiplier} +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Prepare: + +``` +tosa_padding = + get_padding_values_from_pad_type(padding, NHWC, 1, + %input.type, %filter.type, + {1, stride_h, stride_w, 1}, {1, dilation_h_factor, dilation_w_factor, 1}) +``` + +Legalization: + +``` +%depthwise_conv2d = tosa.DEPTHWISE_CONV2D(%input, %filter, %bias) {padding=tosa_padding, stride={stride_h, stride_w}, dilation={dilation_h_factor, dilation_w_factor}} +if(fused_activation != NONE) { + %result = convert_fused_activation(%depthwise_conv2d, fused_activation_function) +} +else { + %result = %depthwise_conv2d +} +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 output_rescale_scale = (%input.scale * %filter.scale) / %output.scale + +tosa_padding = + get_padding_values_from_pad_type(padding, NHWC, 1, + %input.type, %filter.type, + {1, stride_h, stride_w, 1}, {1, dilation_h_factor, dilation_w_factor, 1}) +``` + +Legalization: + +``` +%depthwise_conv2d = tosa.DEPTHWISE_CONV2D(%input, %filter, %bias) {padding=tosa_padding, stride={stride_h, stride_w}, dilation={dilation_h_factor, dilation_w_factor}, quantization_info={input_zp=%input.zp, weight_zp=%filter.zp}} +%rescale = tosa.RESCALE(%conv2d) {scale=output_rescale_scale, input_zp=0, output_zp=%output.zp} // %depthwise_conv2d.dtype->%output.dtype +if(fused_activation != NONE) { + %result = convert_fused_activation(%rescale, fused_activation_function) +} +else { + %result = %rescale +} +``` + +### tfl.dequantize + +Dequantize operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.dequantize(%input) +``` + +**TOSA Lowering** + +``` +%result = lower_dequantize_op(%input, %input.scale, %input.zp) +``` + +### tfl.div + +Division operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.div(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%rcp = tosa.RECIPROCAL(%rhs) +%mul = tosa.MUL(%lhs, %rcp) +``` + +### tfl.elu + +Exponential Linear Unit operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.elu(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%rcp = lower_elu_op(%x) +``` + +### tfl.embedding_lookup + +Embedding lookup operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.embedding_lookup(%lookup, %value) +``` + +### tfl.equal + +This operator is trivially lowered to tosa.EQUAL + +### tfl.exp + +Natural exponentiation operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.exp(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%result = tosa.EXP(%x) +``` + +### tfl.expand_dims + +Inserts a dimension of 1 into a tensor’s shape. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.expand_dims(%input, %dim) +``` + +**TOSA Lowering** + +``` +%result = lower_expand_dims(%input, %dim.as_constant()) +``` + +### tfl.external_const + +No TOSA lowering defined. + +### tfl.fake_quant + +FakeQuant operator + +**TensorFlow Lite Dialect** + +``` +%output = tfl.fake_quant(%input) {min, max, num_bits, narrow_range} +``` + +**TOSA Lowering** + +``` +%result = convert_fake_quant_op(%input, min, max, num_bits, narrow_range) +``` + +### tfl.fill + +Fill the tensor with given value. + +**TensorFlow Lite Dialect** + +``` +%res = tfl.fill(%dims, %value) +``` + +**TOSA Lowering** + +Prepare: + +``` +total_size = 1 +dim_vec = %dim.as_constant() +for(int32 i = 0 i < dim_vec.size() i++) { + total_size *= dim_vec[i] +} +filled_val = %value.as_constant()[0] +output_type = tensor +``` + +Legalization: + +``` +%result = tosa.CONST() {value={filled_val} * total_size} +``` + +### tfl.floor_div + +Floor div operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.floor_div(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%recip = tosa.RECIPROCAL(%rhs) +%mul = tosa.MUL(%lhs, %recip) +%result = tosa.FLOOR(%mul) +``` + +### tfl.floor_mod + +Division remainder. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.floor_mod(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%recip = tosa.RECIPROCAL(%rhs) +%mul = tosa.MUL(%lhs, %recip) +%floor = tosa.FLOOR(%mul) +%result = tosa.SUB(%mul, %floor) +``` + +### tfl.floor + +This operator is trivially lowered to tosa.FLOOR + +### tfl.fully_connected + +Fully connected op. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.fully_connected(%input, %filter, %bias) {fused_activation_function} +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Prepare: + +``` +// input[N, IC] x filter[OC, IC] + bias[OC] -> output[N, OC] +auto input_reshape_shape = {%input.num_elements / %filter.shape[1], %filter.shape[1]} +``` + +Legalization: + +``` +if(!(%bias)) { + %bias_val = tosa.CONST() {value={0} * %filter.shape[3]} +} +else { + %bias_val = %bias +} +if(%input.rank != 2) { + %input_val = tosa.RESHAPE(%input) {shape=input_reshape_shape} +} +else { + %input_val = %input +} +%fc = tosa.FULLY_CONNECTED(%input_val, %filter, %bias_val) +if(fused_activation != NONE) { + %result = convert_fused_activation(%fc, fused_activation_function) +} +else { + %result = %fc +} +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +auto input_reshape_shape = {%input.num_elements / %filter.shape[1], %filter.shape[1]} +float64 output_rescale_scale = (%input.scale * %filter.scale) / %output.scale +``` + +Legalization: + +``` +if(!(%bias)) { + %bias_val = tosa.CONST() {value={0} * %filter.shape[3]} +} +else { + %bias_val = %bias +} +if(%input.rank != 2) { + %input_val = tosa.RESHAPE(%input) {shape=input_reshape_shape} +} +else { + %input_val = %input +} +%fc = tosa.FULLY_CONNECTED(%input_val, %filter, %bias_val) +%rescale = tosa.RESCALE(%fc) {scale=output_rescale_scale, input_zp=0, output_zp=%output.zp} // %fc.dtype->%output.dtype +if(fused_activation != NONE) { + %result = convert_fused_activation(%rescale, fused_activation_function) +} +else { + %result = %rescale +} +``` + +### tfl.gather_nd + +Gather_nd operator. + +**TensorFlow Dialect** + +``` +%output = tfl.gather_nd(%params, %indices) +``` + +**TOSA Lowering** + +``` +%output = lower_gather_nd_op(%params, %indices) +``` + +### tfl.gather + +Gather operator. + +**TensorFlow Dialect** + +``` +%output = tfl.gather(%params, %indices) {axis} +``` + +**TOSA Lowering** + +``` +%output = lower_gather_op(%params, %indices, 0, axis) +``` + +### tfl.greater_equal + +This operator is trivially lowered to tosa.GREATER_EQUAL + +### tfl.greater + +This operator is trivially lowered to tosa.GREATER + +### tfl.hard_swish + +Hardswish activation function. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.hard_swish(%input) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +``` +%const_3 = tosa.CONST() {value={3.0}} +%const_rcp6 = tosa.CONST() {value={1.0 / 6.0}} +%op1_add_in_3 = tosa.ADD(%input, %const_3) +%op2_relun_op1 = tosa.RELUN(%op1_add_in_3) {max=6.0} +%op3_mul_in_op2 = tosa.MUL(%input, %op2_relun_op1) +%op4_mul_op3_rcp6 = tosa.MUL(%op3, %const_rcp6) +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 input_sample_grain = 1.0 / 64.0 +auto hardswish_func = [input_sample_grain](int32 x) -> int32 { + float64 v = (float64)x * input_sample_grain + float64 w = v + 3.0 + w = (w < 0.0) ? 0.0 : ((w > 6.0) ? 6.0 : w) + v = (v * w) / 6.0 + return std::lround(32768.0 * v) +} +float64 input_rescale_scale = (%input.scale * 128.0) / input_sample_grain +float64 output_rescale_scale = 1.0 / (128.0 * 32768.0 * %output.scale) +int32 quantized_3 = (int32)(std::ceil(3.0 / %input.scale)) + %input.zp +``` + +Legalization: + +``` +%table_const = get_table_const_tensor(hardswish_func) +%const_3 = tosa.CONST() {value={quantized_3}} +%op1_rescale_in = tosa.RESCALE(%input) {scale=input_rescale_scale, input_zp=%input.zp, output_zp=0} // %input.dtype->i16 +%op2_table_op1 = tosa.TABLE(%op1_rescale_in, %table_const) +%op3_rescale_op2 = tosa.RESCALE(%op2_table_op1) {scale=output_rescale_scale, input_zp=0, output_zp=%output.zp} // i32->%output.dtype +%op4_rescale_in = tosa.RESCALE(%input {scale=1.0, input_zp=0, output_zp=0} // %input.dtype->i32 +%op5_ge_op4 = tosa.GREATER_EQUAL(%op4_rescale_in, %const_3) +%op6_select_op5_in_op3 = tosa.SELECT(%op5_ge_op4, %input, %op3_rescale_op2) +``` + +### tfl.l2_normalization + +No TOSA lowering defined. + +### tfl.lstm + +No TOSA lowering defined. + +### tfl.leaky_relu + +Leaky Relu Operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.leaky_relu(%input) {alpha} +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%const_0 = tosa.CONST() {value={0.0}} +%const_alpha = tosa.CONST() {value={alpha}} +%op1_mul_in_alpha = tosa.MUL(%input, %const_alpha) +%op2_ge_in_0 = tosa.GREATER_EQUAL(%input, %const_0) +%op3_select_op2_in_op1 = tosa.SELECT(%op2_ge_in_0, %input, $op1_mul_in_alpha) +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float32 scaled_alpha = (%input.scale * alpha) / %output.scale +float32 scaled_identity = %input.scale / %output.scale +``` + +Legalization: + +``` +%const_0 = tosa.CONST() {value={0}} +%op1_rescale_in = tosa.RESCALE(%input) {scale=1.0, input_zp=%input.zp} // %input.dtype->i32 +%op2_ge_in_0 = tosa.GREATER_EQUAL(%input, %const_0) +%op3_rescale_in_alpha = tosa.RESCALE(%input) {scale=scaled_alpha, input_zp=%input.zp, output_zp=%output_zp} // %input.dtype->%output.dtype +%op4_rescale_in_identity = tosa.RESCALE(%input) {scale=scaled_identity, input_zp=%input.zp, output_zp=%output_zp} // %input.dtype->%output.dtype +%op5_select_op2_op3_op4 = tosa.SELECT(%op2_ge_in_0, %op4_rescale_in_identity, %op3_rescale_in_alpha) +``` + +### tfl.less_equal + +Less_equal operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.less_equal(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_greater_lhs_rhs = tosa.GREATER(%lhs, %rhs) +%op2_not_op1 = tosa.LOGICAL_NOT(%op1_greater_lhs_rhs) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +assert (%lhs.scale == %rhs.scale) && (%lhs.zp == %rhs.zp) + +%op1_rescale_lhs = tosa.RESCALE(%lhs) {scale=1.0, input_zp=%lhs.zp, output_zp=0} // %lhs.dtype->i32 +%op2_rescale_rhs = tosa.RESCALE(%rhs) {scale=1.0, input_zp=%rhs.zp, output_zp=0} // %rhs.dtype->i32 +%op3_greater_op1_op2 = tosa.GREATER(%op1_rescale_lhs, %op2_rescale_rhs) +%op4_not_op3 = tosa.LOGICAL_NOT(%op3_greater_op1_op2) +``` + +### tfl.less + +Less operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.less(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_ge_lhs_rhs = tosa.GREATER_EQUAL(%lhs, %rhs) +%op2_not_op1 = tosa.LOGICAL_NOT(%op1_ge_lhs_rhs) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +assert (%lhs.scale == %rhs.scale) && (%lhs.zp == %rhs.zp) + +%op1_rescale_lhs = tosa.RESCALE(%lhs) {scale=1.0, input_zp=%lhs.zp, output_zp=0} // %lhs.dtype->i32 +%op2_rescale_rhs = tosa.RESCALE(%rhs) {scale=1.0, input_zp=%rhs.zp, output_zp=0} // %rhs.dtype->i32 +%op3_ge_op1_op2 = tosa.GREATER_EQUAL(%op1_rescale_lhs, %op2_rescale_rhs) +%op4_not_op3 = tosa.LOGICAL_NOT(%op3_ge_op1_op2) +``` + +### tfl.local_response_normalization + +No TOSA lowering defined. + +### tfl.log + +No TOSA lowering defined. + +### tfl.log_softmax + +Log softmax operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.log_softmax(%input) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%output = lower_log_softmax_op(%logits) +``` + +No TOSA lowering defined if input/output tensors are all quantized typed. + +### tfl.logical_and + +This operator is trivially lowered to tosa.LOGICAL_AND + +### tfl.logical_not + +This operator is trivially lowered to tosa.LOGICAL_NOT + +### tfl.logical_or + +This operator is trivially lowered to tosa.LOGICAL_OR + +### tfl.logistic + +Logistic operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.logistic(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_sigmoid_in = tosa.SIGMOID(%x) +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 input_sample_grain = 1.0 / 16.0 +auto sigmoid_func = [input_sample_grain](int32 x) -> int32 { + float64 v = static_cast(x) * input_sample_grain + v = 1.0 / (1.0 + std::exp(-v)) + return std::lround(32768.0 * v) +} + +float32 input_rescale_scale = (%x.scale * 128.0) / input_sample_grain +float32 output_rescale_scale = 1.0 / (%y.scale * 32768.0 * 128.0); +``` + +Legalization: + +``` +%table_const = get_table_const_tensor(sigmoid_func) +%op1_rescale_in = tosa.RESCALE(%x) {scale=input_rescale_scale, input_zp=%x.zp, output_zp=0} // %x.dtype->i16 +%op2_table_op1 = tosa.TABLE(%op1_rescale_in, %table_const) +%op3_rescale_op2 = tosa.RESCALE(%op2_table_op1) {scale=output_rescale_scale, input_zp=0, output_zp=%y.zp} // %int32->%y.dtype +``` + +### tfl.matrix_diag + +No TOSA lowering defined. + +### tfl.matrix_set_diag + +No TOSA lowering defined. + +### tfl.max_pool_2d + +Max Pool 2d op. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.max_pool_2d(%input) {filter_height, filter_width, padding, stride_h, stride_w, fused_activation_function} +``` + +**TOSA Lowering** + +Prepare: + +``` +tosa_padding = + get_padding_values_from_pad_type(padding, NHWC, 1, + %input.type, tensor<{filter_height, filter_width}, tosa.int32>, + {1, stride_h, stride_w, 1}, {1, 1, 1, 1}) +``` + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%maxpool2d = tosa.MAX_POOL2D(%input) {kernel={filter_height, filter_width}, stride={stride_h, stride_w}, padding=tosa_padding} +if(fused_activation != NONE) { + %result = convert_fused_activation(%maxpool2d, fused_activation) +} +else { + %result = %maxpool2d +} +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%maxpool2d = tosa.MAX_POOL2D(%input) {kernel={filter_height, filter_width}, stride={stride_h, stride_w}, padding=tosa_padding, quantization_info={input_zp=%input.zp, output_zp=%output.zp}} +if(fused_activation != NONE) { + %result = convert_fused_activation(%maxpool2d, fused_activation) +} +else { + %result = %maxpool2d +} +``` + +### tfl.max_pooling_with_argmax_2d + +No TOSA lowering defined. + +### tfl.max_unpooling_2d + +No TOSA lowering defined. + +### tfl.maximum + +This operator is trivially lowered to tosa.MAXIMUM + +### tfl.mean + +Mean operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.mean(%input, %axis) {keep_dims} +``` + +**TOSA Lowering** + +Prepare: + +``` +int32 num_elements_on_axis = 1 +for (int32 axis : %reduction_indices) { + num_elements_on_axis *= %input.shape[axis] +} +float32 div_scale = 1.0 / num_elements_on_axis +``` + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%cst_div_scale = tosa.CONST() {value={div_scale}} +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %axis, keep_dims) +%op2_mul_op1 = tosa.MUL(%op1_rsum_in, %cst_div_scale) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%rsum = lower_reduce_op(%op1_rescale_in, %output.shape, %reduction_indices, keep_dims, 1.0f, %input_zp, div_scale * %input.scale / %output.scale, %output.zp) +``` + +### tfl.minimum + +This operator is trivially lowered to tosa.MINIMUM + +### tfl.mirror_pad + +No TOSA lowering defined. + +### tfl.mul + +Mul operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.mul(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_mul_in = tosa.MUL(%lhs, %rhs) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%op1_rescale_lhs = tosa.RESCALE(%lhs) {scale=1.0f, input_zp=%lhs.zp, output_zp=0} // %lhs.dtype->i32 +%op2_rescale_rhs = tosa.RESCALE(%rhs) {scale=1.0f, input_zp=%rhs.zp, output_zp=0} // %rhs.dtype->i32 +%op3_mul_op1_op2 = tosa.MUL(%op1_rescale_lhs, %op2_rescale_rhs) +%op4_rescale_op3 = tosa.RESCALE(%op3_mul_op1_op2) {scale=%lhs.scale * %rhs.scale / %output.scale, input_zp=0, output_zp=%output.zp} // i32->%output.dtype +``` + +### tfl.neg + +This operator is trivially lowered to tosa.NEGATE + +### tfl.non_max_suppression_v4 + +No TOSA lowering defined. + +### tfl.non_max_suppression_v5 + +No TOSA lowering defined. + +### tfl.not_equal + +Not_equal operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.not_equal(%lhs, %rhs) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_equal_lhs_rhs = tosa.EQUAL(%lhs, %rhs) +%op2_not_op1 = tosa.LOGICAL_NOT(%op1_equal_lhs_rhs) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +assert (%lhs.scale == %rhs.scale) && (%lhs.zp == %rhs.zp) + +%op1_rescale_lhs = tosa.RESCALE(%lhs) {scale=1.0f, input_zp=%lhs.zp, output_zp=0} // %lhs.dtype->i32 +%op2_rescale_rhs = tosa.RESCALE(%rhs) {scale=1.0f, input_zp=%rhs.zp, output_zp=0} // %rhs.dtype->i32 +%op3_equal_op1_op2 = tosa.EQUAL(%op1_rescale_lhs, %op2_rescale_rhs) +%op4_not_op3 = tosa.LOGICAL_NOT(%op3_equal_op1_op2) // i32->%output.dtype +``` + +### tfl.NumericVerify + +No TOSA lowering defined. + +### tfl.one_hot + +OneHot operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.one_hot(%indices, %depth, %on_value, %off_value) {axis} +``` + +**TOSA Lowering** + +``` +%output = lower_one_hot_op(%indices, %depth, %on_value, %off_value, axis) +``` + +### tfl.prelu + +No TOSA lowering defined. + +### tfl.pack + +Packs a list of tensors along a dimension into one tensor. + +**TensorFlow Dialect** + +``` +%output = tf.pack(%values) {axis} +``` + +**TOSA Lowering** + +``` +%output = lower_pack_op(%values, axis) +``` + +### tfl.pad + +This operator is trivially lowered to tosa.PAD + +### tfl.padv2 + +No TOSA lowering defined. + +### tfl.pow + +No TOSA lowering defined. + +### tfl.pseudo_qconst + +This operator is trivially lowered to tosa.CONST + +### tfl.quantize + +Quantize operator + +**TensorFlow Lite Dialect** + +``` +%output = tfl.quantize(%input) +``` + +**TOSA Lowering** + +Legalization: + +``` +if (isa(%input.dtype)) { + %op1_rescale_in = tosa.RESCALE(%input) {scale=%input.scale / %output.scale, input_zp=%input.zp, output_zp=%output.zp} +} +else { + %output = lower_quantize_op(%output.dtype, %input, %output.zp, %output.scale) +} +``` + +### tfl.range + +No TOSA lowering defined. + +### tfl.rank + +Rank operator + +**TensorFlow Lite Dialect** + +``` +%output = tfl.rank(%input) +``` + +**TOSA Lowering** + +Legalization: + +``` +%const = tosa.CONST() {value={%input.rank}} +``` + +### tfl.reduce_any + +Computes the "logical or" of elements across dimensions of a tensor. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.reduce_any(%input, %reduction_indices) {keep_dims} +``` + +**TOSA Lowering** + +Legalization: + +``` +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tfl.reduce_max + +Max-reduction operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.reduce_max(%input, %axes) {keep_dims} +``` + +**TOSA Lowering** + +Legalization: + +``` +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tfl.reduce_min + +Computes the min reduction along the specified axes. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.reduce_min(%input, %axes) {keep_dims} +``` + +**TOSA Lowering** + +Legalization: + +``` +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tfl.reduce_prod + +Prod-reduction operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.reduce_prod(%input, %axes) {keep_dims} +``` + +**TOSA Lowering** + +If input/output tensors are all float typed, + +Legalization: + +``` +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %reduction_indices, keep_dims) +``` + +### tfl.relu_n1_to_1 + +No TOSA lowering defined. + +### tfl.relu6 + +Relu6 operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.relu6(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_relun_in = tosa.RELUN(%input) {max_int=0, max_fp=6.0} +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%op1_rescale_in = tosa.RESCALE(%lhs) {scale=%x.scale / %y.scale, input_zp=%x.zp, output_zp=0} // %x.dtype->i32 +%op2_relun_op1 = tosa.RELUN(%op1_rescale_in) {max_int=(6.0 / %y.scale), max_fp=0.0} +%op3_rescale_op2 = tosa.RESCALE(%op2_relun_op1) {scale=1.0, input_zp=0, output_zp=%y.zp // i32->%y.dtype +``` + +### tfl.relu + +Relu operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.relu(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_relun_in = tosa.RELUN(%input) {max_int=0, max_fp=std::numeric_limits::max()} +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%op1_rescale_in = tosa.RESCALE(%lhs) {scale=%x.scale / %y.scale, input_zp=%x.zp, output_zp=0} // %x.dtype->i32 +%op2_relun_op1 = tosa.RELUN(%op1_rescale_in) {max_int=std::numeric_limits::max(), max_fp=0.0} +%op3_rescale_op2 = tosa.RESCALE(%op2_relun_op1) {scale=1.0, input_zp=0, output_zp=%y.zp // i32->%y.dtype +``` + +### tfl.reshape + +This operator is trivially lowered to tosa.RESHAPE + +### tfl.resize_bilinear + +ResizeBilinear Op. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.resize_bilinear(%input, %size) {aligned_corners, half_pixel_centers} +``` + +**TOSA Lowering** + +``` +%output = lower_resize_op(%input, %size, %input.dtype, "BILINEAR") +``` + +### tfl.resize_nearest_neighbor + +ResizeBilinear Op. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.resize_bilinear(%input, %size) {aligned_corners, half_pixel_centers} +``` + +**TOSA Lowering** + +``` +%output = lower_resize_op(%input, %size, %input.dtype, "NEAREST_NEIGHBOR") +``` + +### tfl.reverse_sequence + +No TOSA lowering defined. + +### tfl.reverse_v2 + +ReverseV2 Operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.reverse_v2(%input, %axis) +``` + +**TOSA Lowering** + +``` +%output = lower_reversev2_op(%tensor, %axis) +``` + +### tfl.round + +Round operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.round(%input) +``` + +**TOSA Lowering** + +``` +%const_half = tosa.CONST() {value={0.5}} +%op1_add_in_half = tosa.ADD(%input, %const_half) +%op2_floor_op1 = tosa.FLOOR(%op1_add_in_half) +``` + +### tfl.rsqrt + +No TOSA lowering defined. + +### tfl.svdf + +No TOSA lowering defined. + +### tfl.segment_sum + +No TOSA lowering defined. + +### tfl.select + +This operator is trivially lowered to tosa.SELECT + +### tfl.select_v2 + +This operator is trivially lowered to tosa.SELECT + +### tfl.shape + +Shape operator + +**TensorFlow Lite Dialect** + +``` +%output = tfl.shape(%input) +``` + +**TOSA Lowering** + +Legalization: + +``` +%const = tosa.CONST() {value=%input.shape} +``` + +### tfl.sin + +No TOSA lowering defined. + +### tfl.slice + +This operator is trivially lowered to tosa.SLICE + +### tfl.softmax + +Softmax operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.softmax(%input) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_exp_in = tosa.EXP(%input) +%op2_rsum_op1 = tosa.REDUCE_SUM(%op1_exp_in) {axis=(%input.rank-1)} +%op3_rcp_op2 = tosa.RECIPROCAL(%op2) +%op4_mul_op1_op3 = tosa.MUL(%op1, %op3) +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 exp_sample_grain = 1.0 / 16.0 +auto exp_func = [exp_sample_grain](int32 x) -> int32 { + double v = static_cast(x) * exp_sample_grain + v = v < 0.0 ? std::exp(v) : 1.0 + return std::lround(32768.0 * v) +} + +float64 one_over_one_plus_x_sample_grain = 1.0 / 256.0 +auto one_over_one_plus_x_func = [one_over_one_plus_x_sample_grain](int32 x) -> int32 { + double v = static_cast(x) * one_over_one_plus_x_sample_grain + v = v < 0.0 ? 1.0 : 1.0 / (1.0 + v) + return std::lround(32768.0 * v) +} + +float64 op4_rescale_scale = (%input.scale * 128.0) / exp_sample_grain +float64 op19_rescale_scale = 1.0 / (%output.scale * 256.0) +``` + +Legalization: + +``` +%const_exp_table = get_table_const_tensor(exp_func) +%const_one_over_one_plus_x_table = get_table_const_tensor(one_over_one_plus_x_func) +%const_3 = tosa.CONST() {value={3}} +%const_34 = tosa.CONST() {value={12+20-8}} +%const_2_to_31 = tosa.CONST() {value={1<<31}} +%const_16 = tosa.CONST() {value={16}} + +%op1_rescale_in = tosa.RESCALE(%lhs) {scale=1.0f, input_zp=%x.zp, output_zp=0} // %x.dtype->i32 +%op2_rmax_op1 = tosa.REDUCE_MAX(%op1_rescale_in) {axis=(%input.rank-1)} +%op3_sub_op1_op2 = tosa.SUB(%op1_rescale_in, %op2_relun_op1) +%op4_rescale_op3 = tosa.RESCALE(%op3_sub_op1_op2) {scale=op4_rescale_scale, input_zp=0, output_zp=0} // i32->i16 +%op5_table_op4 = tosa.TABLE(%op4_rescale_op3, %const_exp_table) +%op6_rshift_op5_3 = tosa.ARITHMETIC_RIGHT_SHIFT(%op5_table_op4, %const_3) +%op7_rsum_op6 = tosa.REDUCE_SUM(%op6_rshift_op5_3) {axis=(%input.rank-1)} +%op8_clz_op7 = tosa.CLZ(%op7_rsum_op6) +%op9_sub_34_op8 = tosa.SUB(%const_34, %op8_clz_op7) +%op10_lshift_op7_op8 = tosa.LOGICAL_LEFT_SHIFT(%op7_rsum_op6, %op8_clz_op7) +%op11_sub_op10 = tosa.SUB(%op10_lshift_op7_op8, %const_2_to_31) +%op12_rshift_op11_16 = tosa.ARITHMETIC_RIGHT_SHIFT(%op11_sub_op10, %const_16) +%op13_cast_op12 = tosa.CAST(%op12_rshift_op11_16) // i32->i16 +%op14_table_op13 = tosa.TABLE(%op13_cast_op12, %const_one_over_one_plus_x_table) +%op15_rescale_op14 = tosa.RESCALE(%op14_table_op13) {scale=1.0/128.0, input_zp=0, output_zp=0} // i32->i16 +%op16_rescale_op5 = tosa.RESCALE(%op5_table_op4) {scale=1.0/128.0, input_zp=0, output_zp=0} // i32->i16 +%op17_mul_op16_op15 = tosa.MUL(%op15_rescale_op14, %op16_rescale_op5) +%op18_rshift_op17_op9 = tosa.ARITHMETIC_RIGHT_SHIFT(%op17_mul_op16_op15, %op9_sub_34_op8) +%op19_rescale_op18 = tosa.RESCALE(%op18_rshift_op17_op9) {scale=op19_rescale_scale, input_zp=0, output_zp=%output.zp} +``` + +### tfl.space_to_batch_nd + +SpaceToBatchNd operator. + +**TensorFlow Dialect** + +``` +%output = tfl.space_to_batch_nd(%input, %block_shape, %paddings) +``` + +**TOSA Lowering** + +``` +%output = lower_space_to_batch_nd_op(%input, %block_shape, %paddings) +``` + +### tfl.space_to_depth + +SpaceToDepth operator. + +**TensorFlow Dialect** + +``` +%output = tfl.space_to_depth(%input) {block_size} +``` + +**TOSA Lowering** + +``` +%output = lower_space_to_depth_op(%input, block_size, "NHWC") +``` + +### tfl.pseudo_sparse_const + +No TOSA lowering defined. + +### tfl.pseudo_sparse_qconst + +No TOSA lowering defined. + +### tfl.sparse_to_dense + +No TOSA lowering defined. + +### tfl.split + +Splits a tensor into num_split tensors along one dimension. + +**TensorFlow Dialect** + +``` +%output = tfl.split(%split_dim, %value) {num_split} +``` + +**TOSA Lowering** + +``` +%output = lower_split_op(%value, %split_dim.as_constant(), num_split) +``` + +### tfl.split_v + +Splits a tensor into num_split tensors along one dimension. + +**TensorFlow Dialect** + +``` +%output = tfl.split_v(%value, %size_splits, %split_dim) {num_splits} +``` + +**TOSA Lowering** + +``` +%output = lower_splitv_op(%value, %size_splits.as_constant(), %split_dim.as_constant()) +``` + +### tfl.sqrt + +No TOSA lowering defined. + +### tfl.square + +Square operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.square(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_mul_in = tosa.MUL(%x, %x) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%op1_rescale_x = tosa.RESCALE(%x) {scale=1.0f, input_zp=%x.zp, output_zp=0} // %x.dtype->i32 +%op2_mul_op1_op1 = tosa.MUL(%op1_rescale_x, %op1_rescale_x) +%op3_rescale_op2 = tosa.RESCALE(%op2_mul_op1_op1) {scale=%(x.scale * %x.scale) / %output.scale, input_zp=0, output_zp=%y.zp} // i32->%y.dtype +``` + +### tfl.squared_difference + +Squared difference operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.squared_difference(%lhs, %rhs) +``` + +**TOSA Lowering** + +Legalization: + +``` +%op1_sub_in = tosa.SUB(%lhs, %rhs) +%op2_mul_op1 = tosa.MUL(%op1_sub_in, %op1_sub_in) +``` + +### tfl.squeeze + +Removes dimensions of size 1 from the shape of a tensor. + +**TensorFlow Dialect** + +``` +%output = tfl.squeeze(%input) {squeeze_dims} +``` + +**TOSA Lowering** + +``` +%output = lower_squeeze_op(%input, squeeze_dims) +``` + +### tfl.strided_slice + +StridedSlice Op. + +**TensorFlow Dialect** + +``` +%output = tfl.strided_slice(%input, %begin, %end, %strides) {begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask} +``` + +**TOSA Lowering** + +``` +%output = lower_strided_slice_op(%input, %begin, %end, %strides, begin_mask, end_mask, ellipsis_mask, new_axis_mask, shrink_axis_mask) +``` + +### tfl.sub + +This operator is trivially lowered to tosa.SUB + +### tfl.sum + +Sum operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.sum(%input, %axis) {keep_dims} +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_rsum_in = lower_reduce_op(%input, %output.shape, %axis, keep_dims) +``` + +If input/output tensors are all quantized typed, + +Legalization: + +``` +%rsum = lower_reduce_op(%op1_rescale_in, %output.shape, %reduction_indices, keep_dims, 1.0f, %input_zp, (%input.scale / %output.scale), %output.zp) +``` + +### tfl.tanh + +Hyperbolic tangent operator. + +**TensorFlow Lite Dialect** + +``` +%y = tfl.tanh(%x) +``` + +**TOSA Lowering** + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%op1_tanh_in = tosa.TANH(%x) +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 input_sample_grain = 1.0 / 32.0 +auto tanh_func = [input_sample_grain](int32 x) -> int32 { + float64 v = static_cast(x) * input_sample_grain + v = std::exp(-2.0 * v) + v = (1.0 - v) / (1.0 + v) + return std::lround(32768.0 * v) +} + +float32 input_rescale_scale = (%x.scale * 128.0) / input_sample_grain +float32 output_rescale_scale = 1.0 / (%y.scale * 32768.0 * 128.0); +``` + +Legalization: + +``` +%table_const = get_table_const_tensor(tanh_func) +%op1_rescale_in = tosa.RESCALE(%x) {scale=input_rescale_scale, input_zp=%x.zp, output_zp=0} // %x.dtype->i16 +%op2_table_op1 = tosa.TABLE(%op1_rescale_in, %table_const) +%op3_rescale_op2 = tosa.RESCALE(%op2_table_op1) {scale=output_rescale_scale, input_zp=0, output_zp=%y.zp} // %int32->%y.dtype +``` + +### tfl.tile + +This operator is trivially lowered to tosa.TILE + +### tfl.topk_v2 + +No TOSA lowering defined. + +### tfl.transpose_conv + +Transpose convolution operator. + +**TensorFlow Lite Dialect** + +``` +%output = tfl.transpose_conv(%output_shape, %weights, %input) {padding, stride_h, stride_w} +``` + +**TOSA Lowering** + +Prepare: + +``` +tosa_padding = + get_transpose_conv2d_padding_values_from_pad_type(%input.type, %weights.type, %output_shape, padding, "NHWC", FORMAT_HWIO, {stride_h, stride_w}, {1, 1}) +``` + +If input/output tensors are all non-quantized typed, + +Legalization: + +``` +%bias = tosa.CONST() {value={0.0} * %output.shape[3]} +%conv2d = tosa.TRANSPOSE_CONV2D(%input, %weight, %bias) {padding=tosa_padding, stride={stride_h, stride_w}, dilation={1, 1}} +``` + +If input/output tensors are all quantized typed, + +Prepare: + +``` +float64 output_rescale_scale = (%input.scale * %weights.scale) / %output.scale +``` + +Legalization: + +``` +%bias = tosa.CONST() {value={0} * %output.shape[3]} +%conv2d = tosa.TRANSPOSE_CONV2D(%input, %weight, %bias) {padding=tosa_padding, stride={stride_h, stride_w}, dilation={1, 1}} +%rescale = tosa.RESCALE(%conv2d) {scale=output_rescale_scale, input_zp=0, output_zp=%output.zp} // %conv2d.dtype->%output.dtype +``` + +### tfl.transpose + +This operator is trivially lowered to tosa.TRANSPOSE + +### tfl.unidirectional_sequence_lstm + +No TOSA lowering defined. + +### tfl.unidirectional_sequence_rnn + +No TOSA lowering defined. + +### tfl.unique + +No TOSA lowering defined. + +### tfl.unpack + +Unpacks a tensor along a dimension into multiple tensors. + +**TensorFlow Dialect** + +``` +%output = tfl.unpack(%input) {num, axis} +``` + +**TOSA Lowering** + +``` +%output = lower_unpack_op(%input, axis, num) +``` + +### tfl.where + +No TOSA lowering defined. + +### tfl.while + +No TOSA lowering defined. + +### tfl.yield + +This operator is trivially lowered to tosa.YIELD + +### tfl.zeros_like + +ZerosLike operator. + +**TensorFlow Dialect** + +``` +%output = tfl.zeros_like(%input) +``` + +**TOSA Lowering** + +``` +%output = tosa.CONST() {value={0} * %input.num_elements} +``` + +## fuse_tf_bias + +Legalize (tf.Conv2D + tf.BiasAdd) to tosa.CONV2D. This is currently the only N:1 +mapping in TOSA legalization. + +From: + +``` +%conv2d = tf.Conv2D(%input, %filter) {...} +%bias_add = tf.BiasAdd(%conv2d, %bias) +``` + +To: + +``` +%conv2d = tosa.CONV2D(%input, %filter, %bias) +``` + +## convert_tfl_uint8 + +This pass does three things: + +1. Convert const from quantized uint8 to quantized int8, with value within + remapped as well. +2. If input placeholders is quantized uint8 typed, insert "tosa.RESCALE() + {scale=1.0, input_zp=input_zp, output_zp=input_zp-128} // qu8->qi8" in + between +3. If output tensor is quantized uint8 typed, insert "tosa.RESCALE() + {scale=1.0, input_zp=output_zp+128, output_zp=output_zp} // qi8->qu8" in + between diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/glob_lit_test.bzl b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/glob_lit_test.bzl new file mode 100644 index 0000000000000000000000000000000000000000..317eba2c75285ae1ca537b4cca9a63607d24be36 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/glob_lit_test.bzl @@ -0,0 +1,151 @@ +# Test definitions for Lit, the LLVM test runner. +# +# This is reusing the LLVM Lit test runner in the interim until the new build +# rules are upstreamed. +# TODO(b/136126535): remove this custom rule. +"""Lit runner globbing test +""" + +load("@bazel_skylib//lib:paths.bzl", "paths") +load( + "@xla//xla:lit.bzl", + "lit_script_with_xla_gpu_cuda_data_dir", +) + +# Default values used by the test runner. +_default_test_file_exts = ["mlir", ".pbtxt", ".td"] +_default_driver = "@llvm-project//mlir:run_lit.sh" +_default_size = "small" +_default_tags = [] + +# These are patterns which we should never match, for tests, subdirectories, or +# test input data files. +_ALWAYS_EXCLUDE = [ + "**/LICENSE.txt", + "**/README.txt", + "**/lit.local.cfg", + # Exclude input files that have spaces in their names, since bazel + # cannot cope with such "targets" in the srcs list. + "**/* *", + "**/* */**", +] + +def _run_lit_test(name, data, size, tags, driver, features, exec_properties): + """Runs lit on all tests it can find in `data` under tensorflow/compiler/mlir. + + Note that, due to Bazel's hermetic builds, lit only sees the tests that + are included in the `data` parameter, regardless of what other tests might + exist in the directory searched. + + Args: + name: str, the name of the test, including extension. + data: [str], the data input to the test. + size: str, the size of the test. + tags: [str], tags to attach to the test. + driver: str, label of the driver shell script. + Note: use of a custom driver is not currently supported + and specifying a default driver will abort the tests. + features: [str], list of extra features to enable. + """ + + # Disable tests on windows for now, to enable testing rest of all xla and mlir. + native.py_test( + name = name, + srcs = ["@llvm-project//llvm:lit"], + tags = tags + ["no_pip", "no_windows"], + args = [ + "tensorflow/compiler/mlir/tosa/" + paths.basename(data[-1]) + " --config-prefix=runlit -v", + ] + features, + data = data + [ + "//tensorflow/compiler/mlir/tosa:litfiles", + "@llvm-project//llvm:FileCheck", + "@llvm-project//llvm:count", + "@llvm-project//llvm:not", + ], + deps = ["@pypi//lit"], + size = size, + main = "lit.py", + exec_properties = exec_properties, + ) + +def glob_lit_tests( + name = None, + exclude = [], + test_file_exts = _default_test_file_exts, + default_size = _default_size, + size_override = {}, + data = [], + per_test_extra_data = {}, + default_tags = _default_tags, + tags_override = {}, + driver = _default_driver, + features = [], + exec_properties = {}, + use_lit_test_suite = None, # @unused + hermetic_cuda_data_dir = None): + """Creates all plausible Lit tests (and their inputs) under this directory. + + Args: + name: str, name of the test_suite rule to generate for running all tests. + exclude: [str], paths to exclude (for tests and inputs). + test_file_exts: [str], extensions for files that are tests. + default_size: str, the test size for targets not in "size_override". + size_override: {str: str}, sizes to use for specific tests. + data: [str], additional input data to the test. + per_test_extra_data: {str: [str]}, extra data to attach to a given file. + default_tags: [str], additional tags to attach to the test. + tags_override: {str: str}, tags to add to specific tests. + driver: str, label of the driver shell script. + Note: use of a custom driver is not currently supported + and specifying a default driver will abort the tests. + features: [str], list of extra features to enable. + exec_properties: a dictionary of properties to pass on. + hermetic_cuda_data_dir: string. If set, the tests will be run with a + `--xla_gpu_cuda_data_dir` flag set to the hermetic CUDA data directory. + use_lit_test_suite: unused. For compatibility. + """ + + # Ignore some patterns by default for tests and input data. + exclude = _ALWAYS_EXCLUDE + exclude + + tests = native.glob( + ["*." + ext for ext in test_file_exts], + exclude = exclude, + ) + + # Run tests individually such that errors can be attributed to a specific + # failure. + all_tests = [] + for curr_test in tests: + final_test_name = curr_test + if hermetic_cuda_data_dir: + output_file = "with_xla_gpu_cuda_data_dir_{}".format(curr_test) + rule_name = "script_{}".format(output_file) + lit_script_with_xla_gpu_cuda_data_dir( + rule_name, + curr_test, + output_file, + hermetic_cuda_data_dir, + ) + final_test_name = output_file + all_tests.append(final_test_name + ".test") + + # Instantiate this test with updated parameters. + _run_lit_test( + name = final_test_name + ".test", + data = data + [final_test_name] + + per_test_extra_data.get(curr_test, []), + size = size_override.get(curr_test, default_size), + tags = default_tags + tags_override.get(curr_test, []), + driver = driver, + features = features, + exec_properties = exec_properties, + ) + + # TODO: remove this check after making it a required param. + if name: + native.test_suite( + name = name, + tests = all_tests, + tags = ["manual"], + ) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/runlit.cfg.py b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/runlit.cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..b06fc815a395489812747cd545f80bb0816dd7a3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/runlit.cfg.py @@ -0,0 +1,71 @@ +# Copyright 2019 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. +"""Lit runner configuration.""" + +import os +import platform +import sys +import lit.formats +from lit.llvm import llvm_config +from lit.llvm.subst import ToolSubst + +# Lint for undefined variables is disabled as config is not defined inside this +# file, instead config is injected by way of evaluating runlit.cfg.py from +# runlit.site.cfg.py which in turn is evaluated by lit.py. The structure is +# common for lit tests and intended to only persist temporarily (b/136126535). +# pylint: disable=undefined-variable +# Configuration file for the 'lit' test runner. + +# name: The name of this test suite. +config.name = 'MLIR ' + os.path.basename(config.mlir_test_dir) + +config.test_format = lit.formats.ShTest(not llvm_config.use_lit_shell) + +# suffixes: A list of file extensions to treat as test files. +config.suffixes = ['.cc', '.hlo', '.json', '.mlir', '.pbtxt', '.py'] + +# test_source_root: The root path where tests are located. +config.test_source_root = config.mlir_test_dir + +# test_exec_root: The root path where tests should be run. +config.test_exec_root = os.environ['RUNFILES_DIR'] + +if platform.system() == 'Windows': + tool_patterns = [ + ToolSubst('FileCheck.exe', unresolved='fatal'), + # Handle these specially as they are strings searched for during testing. + ToolSubst('count.exe', unresolved='fatal'), + ToolSubst('not.exe', unresolved='fatal') + ] + + llvm_config.config.substitutions.append( + ('%python', '"%s"' % (sys.executable))) + + llvm_config.add_tool_substitutions(tool_patterns, + [llvm_config.config.llvm_tools_dir]) +else: + llvm_config.use_default_substitutions() + +# Tweak the PATH to include the tools dir. +llvm_config.with_environment('PATH', config.llvm_tools_dir, append_path=True) + +tool_dirs = config.mlir_tf_tools_dirs + [ + config.mlir_tools_dir, config.llvm_tools_dir +] +tool_names = [ + 'tf-tosa-opt', +] +tools = [ToolSubst(s, unresolved='ignore') for s in tool_names] +llvm_config.add_tool_substitutions(tools, tool_dirs) +# pylint: enable=undefined-variable diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/runlit.site.cfg.py b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/runlit.site.cfg.py new file mode 100644 index 0000000000000000000000000000000000000000..023d9fc23bc49ada042c38ad8e07ce69e460ebe1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/runlit.site.cfg.py @@ -0,0 +1,63 @@ +# Copyright 2019 Google Inc. 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. +"""Lit runner site configuration.""" + +import os +import platform +import lit.llvm + +# Handle the test srcdir for platforms. On windows, things are weird with bazel. +if platform.system() == 'Windows': + srcdir = os.environ['TEST_SRCDIR'] + real_test_srcdir = srcdir[:srcdir.find('tensorflow/compiler/mlir/tosa')] + external_srcdir = os.path.join(real_test_srcdir, 'external') +else: + real_test_srcdir = os.environ['TEST_SRCDIR'] + external_srcdir = real_test_srcdir + +# Lint for undefined variables is disabled as config is not defined inside this +# file, instead config is injected by lit.py. The structure is common for lit +# tests and intended to only persist temporarily (b/136126535). +# pylint: disable=undefined-variable +config.llvm_tools_dir = os.path.join(external_srcdir, 'llvm-project', 'llvm') +config.mlir_obj_root = os.path.join(real_test_srcdir) +config.mlir_tools_dir = os.path.join(external_srcdir, 'llvm-project', 'mlir') +# TODO(jpienaar): Replace with suffices in build rule. +config.suffixes = ['.td', '.mlir', '.pbtxt'] + +mlir_tf_tools_dirs = [ + 'tensorflow/compiler/mlir/tosa', +] +config.mlir_tf_tools_dirs = [ + os.path.join(real_test_srcdir, os.environ['TEST_WORKSPACE'], s) + for s in mlir_tf_tools_dirs +] +test_dir = os.environ['TEST_TARGET'] +test_dir = test_dir.strip('/').rsplit(':', 1)[0] +config.mlir_test_dir = os.path.join(real_test_srcdir, + os.environ['TEST_WORKSPACE'], test_dir) + +if platform.system() == 'Windows': + # Configure this to work with msys2, TF's preferred windows bash. + config.lit_tools_dir = '/usr/bin' + +lit.llvm.initialize(lit_config, config) + +# Let the main config do the real work. +lit_config.load_config( + config, + os.path.join( + os.path.join(real_test_srcdir, os.environ['TEST_WORKSPACE'], + 'tensorflow/compiler/mlir/tosa/runlit.cfg.py'))) +# pylint: enable=undefined-variable diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..2d48665c8ab65570edefd6176b7ec1a4383040f0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/BUILD @@ -0,0 +1,29 @@ +load("//tensorflow:tensorflow.default.bzl", "filegroup") +load("//tensorflow/compiler/mlir/tosa:glob_lit_test.bzl", "glob_lit_tests") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + licenses = ["notice"], +) + +glob_lit_tests( + name = "all_tests", + data = [":test_utilities"], + default_tags = ["tf_tosa"], + driver = "@llvm-project//mlir:run_lit.sh", + size_override = { + "tf-to-tosa-pipeline.mlir": "medium", + }, + test_file_exts = ["mlir"], +) + +# Bundle together all of the test utilities that are used by tests. +filegroup( + name = "test_utilities", + testonly = True, + data = [ + "//tensorflow/compiler/mlir/tosa:tf-tosa-opt", + "@llvm-project//llvm:FileCheck", + "@llvm-project//llvm:not", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/convert-tfl-uint.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/convert-tfl-uint.mlir new file mode 100644 index 0000000000000000000000000000000000000000..753713a06768825e6140f310a11fc908d467a7d2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/convert-tfl-uint.mlir @@ -0,0 +1,100 @@ +// RUN: tf-tosa-opt --tosa-convert-tfl-uint-to-int --verify-diagnostics --verify-each %s | FileCheck %s + + +// Operations for testing --tosa-convert-tfl-uint-to-int + +// ----- + +// CHECK-LABEL: test_add_u8 +// CHECK: tosa.rescale +// CHECK: tosa.rescale +// CHECK: tfl.add +// CHECK: tosa.rescale +func.func @test_add_u8(%arg0: tensor<14x19x!quant.uniform>, %arg1: tensor<14x19x!quant.uniform>) -> tensor<14x19x!quant.uniform> { + %0 = "tfl.add"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<14x19x!quant.uniform>, tensor<14x19x!quant.uniform>) -> tensor<14x19x!quant.uniform> + func.return %0 : tensor<14x19x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_cast_ui8 +// CHECK-DAG: %[[multiplier:.+]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[shift:.+]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[input_zp:.+]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[output_zp:.+]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: tosa.rescale %arg0, %[[multiplier]], %[[shift]], %[[input_zp]], %[[output_zp]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} +// CHECK: tfl.cast +func.func @test_cast_ui8(%arg0: tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> { + %0 = "tfl.cast"(%arg0) : (tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> + func.return %0 : tensor<1x256x256x3xf32> +} + +// ----- + +// CHECK-LABEL: test_error_tosa_ops +func.func @test_error_tosa_ops(%arg0: tensor<5x10xi8>) -> (tensor<5x10xi8>, none) { + + // Dummy use to TFL dialect to load TFL dialect in MLIR context + %0 = "tfl.no_value"() <{value}> : () -> none + + // expected-error @+1 {{tosa operations are not expected in this pass. Run tosa-convert-tfl-uint-to-int before tosa-legalize-tfl}} + %cst1 = "tosa.const"() <{values = dense<1> : tensor<5x10xi8>}> : () -> tensor<5x10xi8> + // expected-error @+1 {{tosa operations are not expected in this pass. Run tosa-convert-tfl-uint-to-int before tosa-legalize-tfl}} + %1 = "tosa.add"(%arg0, %cst1) : (tensor<5x10xi8>, tensor<5x10xi8>) -> tensor<5x10xi8> + + + func.return %1, %0 : tensor<5x10xi8>, none +} + +// ----- +// CHECK-LABEL: test_cast_ui32_with_zp +// expected-error @+1 {{Input argument has unsigned quantized type with zero point 128 which is not supported by TOSA for bitwidth 32.}} +func.func @test_cast_ui32_with_zp(%arg0: tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> { + %0 = "tfl.cast"(%arg0) : (tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> + func.return %0 : tensor<1x256x256x3xf32> +} + +// ----- +// CHECK-LABEL: func.func @test_cast_ui32( +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> { +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[RESCALE_0:.*]] = tosa.rescale %[[ARG0]], %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x256x256x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<1x256x256x3x!quant.uniform> +// CHECK: %[[VAL_4:.*]] = "tfl.cast"(%[[RESCALE_0]]) : (tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> +// CHECK: return %[[VAL_4]] +func.func @test_cast_ui32(%arg0: tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> { + %0 = "tfl.cast"(%arg0) : (tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> + func.return %0 : tensor<1x256x256x3xf32> +} + +// ----- +// CHECK-LABEL: func.func @test_cast_ui8_small_range( +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>) -> tensor<1x256x256x3xf32> { +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<50> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<-55> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[RESCALE_0:.*]] = tosa.rescale %[[ARG0]], %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x256x256x3x!quant.uniform> +// CHECK: %[[VAL_4:.*]] = "tfl.cast"(%[[RESCALE_0]]) : (tensor<1x256x256x3x!quant.uniform>) -> tensor<1x256x256x3xf32> +// CHECK: return %[[VAL_4]] +func.func @test_cast_ui8_small_range(%arg0: tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>) -> tensor<1x256x256x3xf32> { + %0 = "tfl.cast"(%arg0) : (tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>) -> tensor<1x256x256x3xf32> + func.return %0 : tensor<1x256x256x3xf32> +} + +// ----- +// CHECK-LABEL: func.func @test_cast_ui8_narrow_range( +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>) -> tensor<1x256x256x3xf32> { +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<50> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<-43> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[RESCALE_0:.*]] = tosa.rescale %[[ARG0]], %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x256x256x3x!quant.uniform:f32, 0.0091532344973873428:-43>> +// CHECK: %[[VAL_4:.*]] = "tfl.cast"(%[[RESCALE_0]]) : (tensor<1x256x256x3x!quant.uniform:f32, 0.0091532344973873428:-43>>) -> tensor<1x256x256x3xf32> +// CHECK: return %[[VAL_4]] +func.func @test_cast_ui8_narrow_range(%arg0: tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>) -> tensor<1x256x256x3xf32> { + %0 = "tfl.cast"(%arg0) : (tensor<1x256x256x3x!quant.uniform:f32, 0.015603500418365002:50>>) -> tensor<1x256x256x3xf32> + func.return %0 : tensor<1x256x256x3xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/convert_metadata.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/convert_metadata.mlir new file mode 100644 index 0000000000000000000000000000000000000000..3a03cc2cf44725096475273d1f1d31beef312372 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/convert_metadata.mlir @@ -0,0 +1,26 @@ +// RUN: tf-tosa-opt --split-input-file --pass-pipeline='builtin.module(func.func(tosa-tflite-convert-function-metadata))' %s | FileCheck %s + + +module attributes {tfl.schema_version = 3 : i32} { + // CHECK: func.func @main( + // CHECK-SAME: %arg0: tensor {ml_program.identifier = "input0"}, + // CHECK-SAME: %arg1: tensor {ml_program.identifier = "input1"} + // CHECK-SAME: ) -> ( + // CHECK-SAME: tensor {ml_program.identifier = "output0"}, + // CHECK-SAME: tensor {ml_program.identifier = "output1"}) + func.func @main(%arg0: tensor, %arg1: tensor) -> (tensor, tensor) attributes { + tf.entry_function = {inputs = "input0,input1", outputs = "output0,output1"} + } { + return %arg0, %arg1 : tensor, tensor + } + + // CHECK: func.func @no_input( + // CHECK-SAME: ) -> ( + // CHECK-SAME: tensor<1xf32> {ml_program.identifier = "output0"}) + func.func @no_input() -> (tensor<1xf32>) attributes { + tf.entry_function = {outputs = "output0"} + } { + %0 = "tfl.pseudo_const"() {value = dense<0.000000e+00> : tensor<1xf32>} : () -> tensor<1xf32> + return %0 : tensor<1xf32> + } +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/fuse-bias-tf.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/fuse-bias-tf.mlir new file mode 100644 index 0000000000000000000000000000000000000000..df971ba756b911dde98a8d3fa4242cdf328726df --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/fuse-bias-tf.mlir @@ -0,0 +1,16 @@ +// RUN: tf-tosa-opt --tosa-fuse-bias-tf --verify-each %s | FileCheck %s + + +// Operations for testing --tosa-fuse-bias-tf + +// ---- + +// CHECK-LABEL: test_conv2d_bias +// CHECK: tosa.transpose +// CHECK: tosa.conv2d +func.func @test_conv2d_bias(%arg0: tensor<1x4x4x4xf32>, %arg1: tensor<3x3x4x8xf32>, %arg2: tensor<8xf32>) -> tensor<1x4x4x8xf32> { + %0 = "tf.Conv2D"(%arg0, %arg1) {data_format = "NHWC", device = "", dilations = [1, 1, 1, 1], explicit_paddings = [], padding = "SAME", strides = [1, 1, 1, 1], use_cudnn_on_gpu = true} : (tensor<1x4x4x4xf32>, tensor<3x3x4x8xf32>) -> tensor<1x4x4x8xf32> + %1 = "tf.BiasAdd"(%0, %arg2) {data_format = "NHWC"} : (tensor<1x4x4x8xf32>, tensor<8xf32>) -> tensor<1x4x4x8xf32> + + func.return %1 : tensor<1x4x4x8xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/lower-complex-types.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/lower-complex-types.mlir new file mode 100644 index 0000000000000000000000000000000000000000..fac51a443d07d7d2330f18c647c68f55cd280a75 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/lower-complex-types.mlir @@ -0,0 +1,43 @@ +// RUN: tf-tosa-opt --split-input-file --tosa-lower-complex-types --verify-each %s | FileCheck %s + + +// CHECK-LABEL: test_complex_input +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x4x2xf32> +// CHECK: return %[[VAL_0]] : tensor<1x4x4x2xf32> +func.func @test_complex_input(%arg0: tensor<1x4x4xcomplex>) -> (tensor<1x4x4x2xf32>) { + %0 = builtin.unrealized_conversion_cast %arg0 : tensor<1x4x4xcomplex> to tensor<1x4x4x2xf32> + return %0 : tensor<1x4x4x2xf32> +} + +// ----- + +// CHECK-LABEL: test_complex_output +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x4x2xf32> +// CHECK: return %[[VAL_0]] : tensor<1x4x4x2xf32> +func.func @test_complex_output(%arg0: tensor<1x4x4x2xf32>) -> (tensor<1x4x4xcomplex>) { + %0 = builtin.unrealized_conversion_cast %arg0 : tensor<1x4x4x2xf32> to tensor<1x4x4xcomplex> + return %0 : tensor<1x4x4xcomplex> +} + +// ----- + +// CHECK-LABEL: test_mixed_input +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x4x2xf32>, %[[VAL_1:.*]]: tensor<1x4x4x2xf32>, %[[VAL_2:.*]]: tensor<1x4x4xf32> +// CHECK: return %[[VAL_0]], %[[VAL_1]], %[[VAL_2]] : tensor<1x4x4x2xf32>, tensor<1x4x4x2xf32>, tensor<1x4x4xf32> +func.func @test_mixed_input(%arg0: tensor<1x4x4xcomplex>, %arg1: tensor<1x4x4xcomplex>, %arg2: tensor<1x4x4xf32>) + -> (tensor<1x4x4x2xf32>, tensor<1x4x4x2xf32>, tensor<1x4x4xf32>) { + %0 = builtin.unrealized_conversion_cast %arg0 : tensor<1x4x4xcomplex> to tensor<1x4x4x2xf32> + %1 = builtin.unrealized_conversion_cast %arg1 : tensor<1x4x4xcomplex> to tensor<1x4x4x2xf32> + return %0, %1, %arg2 : tensor<1x4x4x2xf32>, tensor<1x4x4x2xf32>, tensor<1x4x4xf32> +} + +// ----- + +// CHECK-LABEL: test_mixed_output +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x4x2xf32>, %[[VAL_1:.*]]: tensor<1x4x4xf32> +// CHECK: return %[[VAL_0]], %[[VAL_1]] : tensor<1x4x4x2xf32>, tensor<1x4x4xf32> +func.func @test_mixed_output(%arg0: tensor<1x4x4x2xf32>, %arg1: tensor<1x4x4xf32>) + -> (tensor<1x4x4xcomplex>, tensor<1x4x4xf32>) { + %0 = builtin.unrealized_conversion_cast %arg0 : tensor<1x4x4x2xf32> to tensor<1x4x4xcomplex> + return %0, %arg1 : tensor<1x4x4xcomplex>, tensor<1x4x4xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/multi_add.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/multi_add.mlir new file mode 100644 index 0000000000000000000000000000000000000000..aa6ab0f9034f0b650b5be4e282016cb846b68e07 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/multi_add.mlir @@ -0,0 +1,17 @@ +// RUN: tf-tosa-opt --tfl-to-tosa-pipeline=target-compilation-backend %s | FileCheck %s + + +// CHECK: tensor<1x8x8x3xf32> {ml_program.identifier = "a"} +// CHECK-SAME: tensor<1x8x8x3xf32> {ml_program.identifier = "b"} +// CHECK-SAME: tensor<1x8x8x3xf32> {ml_program.identifier = "c"} +// CHECK-SAME: tensor<1x8x8x3xf32> {ml_program.identifier = "d"} +// CHECK-SAME: -> (tensor<1x8x8x3xf32> {ml_program.identifier = "x"}, tensor<1x8x8x3xf32> {ml_program.identifier = "y"}) + +module attributes {tfl.schema_version = 3 : i32} { + func.func @main(%arg0: tensor<1x8x8x3xf32>, %arg1: tensor<1x8x8x3xf32>, %arg2: tensor<1x8x8x3xf32>, %arg3: tensor<1x8x8x3xf32>) -> (tensor<1x8x8x3xf32>, tensor<1x8x8x3xf32>) attributes {tf.entry_function = {inputs = "a,b,c,d", outputs = "x,y"}} { + %0 = tfl.add %arg1, %arg2 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + %1 = tfl.add %arg0, %0 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + %2 = tfl.add %arg3, %0 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + return %1, %2 : tensor<1x8x8x3xf32>, tensor<1x8x8x3xf32> + } +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/retain_call_once_funcs.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/retain_call_once_funcs.mlir new file mode 100644 index 0000000000000000000000000000000000000000..d1680224ec9b80fe3e25bc88ebdeb326a09f99a7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/retain_call_once_funcs.mlir @@ -0,0 +1,22 @@ +// RUN: tf-tosa-opt --split-input-file --pass-pipeline='builtin.module(tflite-retain-call-once-funcs)' %s | FileCheck %s + + +// CHECK-LABEL: module { +module { + // CHECK-LABEL: @main + func.func @main(%arg0: tensor<16x16xf32>) -> (tensor<16x16xf32>) { + // CHECK: "tfl.call_once"() <{session_init_function = "NoOp"}> {session_init_function_symbol = @NoOp} : () -> () + "tfl.call_once"() {session_init_function = "NoOp"} : () -> () + %0 = "tfl.var_handle"() {container = "", shared_name = "Variable"} : () -> tensor<*x!tf_type.resource> + %1 = "tfl.read_variable"(%0) : (tensor<*x!tf_type.resource>) -> tensor<16x16xf32> + %2 = tfl.add %1, %arg0 {fused_activation_function = "NONE"} : tensor<16x16xf32> + "tfl.assign_variable"(%0, %2) : (tensor<*x!tf_type.resource>, tensor<16x16xf32>) -> () + return %2 : tensor<16x16xf32> + } + func.func private @NoOp() { + %0 = "tfl.var_handle"() {container = "", shared_name = "Variable"} : () -> tensor<*x!tf_type.resource> + %1 = "tfl.pseudo_const"() {value = dense<0.000000e+00> : tensor<16x16xf32>} : () -> tensor<16x16xf32> + "tfl.assign_variable"(%0, %1) : (tensor<*x!tf_type.resource>, tensor<16x16xf32>) -> () + return + } +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/strip-quant-types.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/strip-quant-types.mlir new file mode 100644 index 0000000000000000000000000000000000000000..2aded724e55bdfee57c2a1fb17984a0d98011c48 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/strip-quant-types.mlir @@ -0,0 +1,26 @@ +// RUN: tf-tosa-opt --split-input-file --tosa-strip-quant-types --verify-each %s | FileCheck %s + + +// ----- + +// CHECK-LABEL: @test_max_pool2d_qi8 +// CHECK-SAME: %arg0: tensor<1x4x4x4xi8>) -> tensor<1x4x4x4xi8> +func.func @test_max_pool2d_qi8(%arg0: tensor<1x4x4x4x!quant.uniform>) -> tensor<1x4x4x4x!quant.uniform> { + %0 = "tosa.max_pool2d"(%arg0) {kernel = array, pad = array, stride = array} : (tensor<1x4x4x4x!quant.uniform>) -> tensor<1x4x4x4x!quant.uniform> + + // CHECK: %[[VAR0:.+]] = tosa.max_pool2d %arg0 {kernel = array, pad = array, stride = array} : (tensor<1x4x4x4xi8>) -> tensor<1x4x4x4xi8> + // CHECK: return %[[VAR0]] : tensor<1x4x4x4xi8> + func.return %0 : tensor<1x4x4x4x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: @test_bitwise_not_qu8 +// CHECK-SAME: %arg0: tensor) -> tensor +func.func @test_bitwise_not_qu8(%arg0: tensor>) -> tensor> { + %0 = "tosa.bitwise_not"(%arg0) : (tensor>) -> tensor> + + // CHECK: %[[VAR0:.+]] = tosa.bitwise_not %arg0 : (tensor) -> tensor + // CHECK: return %[[VAR0]] : tensor + func.return %0 : tensor> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/strip_metadata.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/strip_metadata.mlir new file mode 100644 index 0000000000000000000000000000000000000000..681e55182034759e883f684fcf0362b684e8c0a7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/strip_metadata.mlir @@ -0,0 +1,15 @@ +// RUN: tf-tosa-opt --pass-pipeline='builtin.module(tosa-tflite-strip-module-metadata,func.func(tosa-tflite-strip-function-metadata))' %s | FileCheck %s + + +// CHECK-LABEL: module { +// CHECK-NOT: tf.schema_version +module attributes {tfl.schema_version = 3 : i32} { + // CHECK: func.func @main + // CHECK-NOT: tf.entry_function + func.func @main(%arg0: tensor<1x8x8x3xf32>) -> tensor<1x8x8x3xf32> attributes {tf.entry_function = {inputs = "input", outputs = "output"}} { + // CHECK-NEXT: tfl.add + %0 = tfl.add %arg0, %arg0 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + %1 = tfl.add %0, %arg0 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + return %1 : tensor<1x8x8x3xf32> + } +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-tfl-to-tosa-pipeline.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-tfl-to-tosa-pipeline.mlir new file mode 100644 index 0000000000000000000000000000000000000000..9429b881a339707ed3182e03c434dc9a01007f9e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-tfl-to-tosa-pipeline.mlir @@ -0,0 +1,21 @@ +// RUN: tf-tosa-opt --split-input-file --tf-tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + + +// These tests focus on TensorFlow and TensorFlow Lite hybrid lowering and focus +// on tfl.custom operations that are Flex ops. + +// This test demonstrates how legalize and shape inference can be performed +// using the flex op legalization, and tensorflow-to-tosa legalization. The +// resulting cast is to maintain the function contract. +// +// To add a Flex op test you will need to compile a TF model with a flex op, +// then import the model. The opaque data is a serialize TF Node proto so not +// feasible to hand edit. +// CHECK-LABEL: func @test_flex_shape +// CHECK-SAME: tensor +func.func @test_flex_shape(%arg0: tensor, %arg1: tensor<1x1x64xf32>) -> tensor<*xf32> { + // CHECK: %[[ADD:.+]] = tosa.add %arg0, %arg1 : (tensor, tensor<1x1x64xf32>) -> tensor + // CHECK: return %[[ADD]] + %0 = "tfl.custom"(%arg0, %arg1) {custom_code = "FlexAddV2", custom_option = #tfl} : (tensor, tensor<1x1x64xf32>) -> tensor<*xf32> + func.return %0: tensor<*xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-to-tosa-pipeline.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-to-tosa-pipeline.mlir new file mode 100644 index 0000000000000000000000000000000000000000..2c7ce1706514e0d5bd0231aba60b56565c507d7f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-to-tosa-pipeline.mlir @@ -0,0 +1,1226 @@ +// RUN: tf-tosa-opt --tf-to-tosa-pipeline --verify-each %s | FileCheck %s + +// RUN: tf-tosa-opt --tf-tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + + +// Operations for testing tf-to-tosa-pipeline +// TODO: These tests are fairly minimal. Expand the checks to be more robust. + +// ----- + +// CHECK-LABEL: test_conv2d +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<16xf32>}> +// CHECK-DAG: %[[VAR3:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %arg1 {perms = array} +// CHECK: %[[VAR4:.*]] = tosa.conv2d %arg0, %[[VAR2]], %[[VAR0]], %[[VAR3]], %[[VAR3]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv2d(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<2x2x8x16xf32>) -> tensor<1x32x32x16xf32> { + %3 = "tf.Conv2D"(%arg0, %arg1) {data_format = "NHWC", dilations = [1, 1, 1, 1], explicit_paddings = [], padding = "SAME", strides = [1, 1, 1, 1], use_cudnn_on_gpu = true} : (tensor<1x32x32x8xf32>, tensor<2x2x8x16xf32>) -> tensor<1x32x32x16xf32> + func.return %3 : tensor<1x32x32x16xf32> +} + +// ----- + +// CHECK-LABEL: test_depthwise_conv2d +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<16xf32>}> +// CHECK-DAG: %[[VAL1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.depthwise_conv2d %arg0, %arg1, %0, %1, %1 {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_depthwise_conv2d(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<2x2x8x2xf32>) -> tensor<1x32x32x16xf32> { + %5 = "tf.DepthwiseConv2dNative"(%arg0, %arg1) {data_format = "NHWC", dilations = [1, 1, 1, 1], explicit_paddings = [], padding = "SAME", strides = [1, 1, 1, 1]} : (tensor<1x32x32x8xf32>, tensor<2x2x8x2xf32>) -> tensor<1x32x32x16xf32> + %6 = "tf.Identity"(%5) : (tensor<1x32x32x16xf32>) -> tensor<1x32x32x16xf32> + func.return %6 : tensor<1x32x32x16xf32> +} + +// ----- + +// CHECK-LABEL: @test_transpose_conv2d +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x32x32x8xf32>, %[[ARG1:.*]]: tensor<1x1x16x8xf32> +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[16, 1, 1, 8]> : tensor<4xindex>} +// CHECK-DAG: %[[CONST:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<16xf32>}> +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[RESHAPE:.*]] = tosa.reshape %[[ARG1]], %[[VAR0]] +// CHECK: %[[TRANSPOSE:.*]] = tosa.transpose_conv2d %[[ARG0]], %[[RESHAPE]], %[[CONST]], %[[ZP]], %[[ZP]] {acc_type = f32, out_pad = array, stride = array} +// CHECK: return %[[TRANSPOSE]] +func.func @test_transpose_conv2d(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<1x1x16x8xf32>) -> tensor<1x32x32x16xf32> { + %3 = "tf.Const"() {value = dense<[1, 32, 32, 16]> : tensor<4xi32>} : () -> tensor<4xi32> + %4 = "tf.Conv2DBackpropInput"(%3, %arg1, %arg0) {data_format = "NHWC", dilations = [1, 1, 1, 1], explicit_paddings = [], padding = "SAME", strides = [1, 1, 1, 1], use_cudnn_on_gpu = true} : (tensor<4xi32>, tensor<1x1x16x8xf32>, tensor<1x32x32x8xf32>) -> tensor<1x32x32x16xf32> + func.return %4 : tensor<1x32x32x16xf32> +} + +// ----- + +// CHECK-LABEL: test_conv3d +// CHECK-SAME: %[[VAL_0:.*]]: tensor<2x4x128x128x8xf32> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<2x3x3x2x4xf32> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<4xf32>}> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_5:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_6:.*]] = tosa.conv3d %[[VAL_0]], %[[VAL_5]], %[[VAL_2]], %[[VAL_4]], %[[VAL_4]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv3d(%arg0: tensor<2x4x128x128x8xf32>, %arg1: tensor<2x3x3x2x4xf32>) -> tensor<2x4x64x64x4xf32> { + %0 = "tf.Conv3D"(%arg0, %arg1) {data_format = "NDHWC", device = "", dilations = [1, 1, 1, 1, 1], padding = "SAME", strides = [1, 1, 2, 2, 1]} : (tensor<2x4x128x128x8xf32>, tensor<2x3x3x2x4xf32>) -> tensor<2x4x64x64x4xf32> + return %0 : tensor<2x4x64x64x4xf32> +} + +// ----- + +// CHECK-LABEL: test_conv3d_bias +// CHECK-SAME: %[[VAL_0:.*]]: tensor<3x32x16x16x5xf32> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<2x3x3x5x10xf32> +// CHECK-SAME: %[[VAL_2:.*]]: tensor<10xf32>) -> tensor<3x32x16x16x10xf32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_5:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_6:.*]] = tosa.conv3d %[[VAL_0]], %[[VAL_5]], %[[VAL_2]], %[[VAL_4]], %[[VAL_4]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv3d_bias(%arg0: tensor<3x32x16x16x5xf32>, %arg1: tensor<2x3x3x5x10xf32>, %bias: tensor<10xf32>) -> tensor<3x32x16x16x10xf32> { + %0 = "tf.Conv3D"(%arg0, %arg1) {data_format = "NDHWC", device = "", dilations = [1, 1, 1, 1, 1], padding = "SAME", strides = [1, 1, 1, 1, 1]} : (tensor<3x32x16x16x5xf32>, tensor<2x3x3x5x10xf32>) -> tensor<3x32x16x16x10xf32> + %1 = "tf.BiasAdd"(%0, %bias) {data_format = "NHWC", device = ""} : (tensor<3x32x16x16x10xf32>, tensor<10xf32>) -> tensor<3x32x16x16x10xf32> + return %1 : tensor<3x32x16x16x10xf32> +} + +// ----- + +// CHECK-LABEL: test_add +// CHECK: %[[VAR0:.*]] = tosa.add %arg0, %arg1 +func.func @test_add(%arg0: tensor<13x21x1xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<*xf32> { + %2 = "tf.Add"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_sub +// CHECK: %[[VAR0:.*]] = tosa.sub %arg0, %arg1 +func.func @test_sub(%arg0: tensor<1x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Sub"(%arg0, %arg1) : (tensor<1x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_mul +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR0:.*]] = tosa.mul %arg0, %arg1, %[[SHIFT]] +func.func @test_mul(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x1x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Mul"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x1x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_real_div +// CHECK: %[[VAR0:.*]] = tosa.intdiv %arg0, %arg1 +func.func @test_real_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor<13x1x3xi32>) -> tensor<13x21x3xi32> { + %2 = "tf.RealDiv"(%arg0, %arg1) : (tensor<13x21x3xi32>, tensor<13x1x3xi32>) -> tensor<13x21x3xi32> + func.return %2 : tensor<13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: func.func @test_floor_div( +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3xi32>, +// CHECK-SAME: %[[VAL_1:.*]]: tensor<13x1x3xi32>) -> tensor<13x21x3xi32> { +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x1x1xi32>}> : () -> tensor<1x1x1xi32> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1> : tensor<1x1x1xi32>}> : () -> tensor<1x1x1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.intdiv %[[VAL_0]], %[[VAL_1]] : (tensor<13x21x3xi32>, tensor<13x1x3xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_6:.*]] = tosa.mul %[[VAL_0]], %[[VAL_1]], %[[VAL_2]] : (tensor<13x21x3xi32>, tensor<13x1x3xi32>, tensor<1xi8>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_7:.*]] = tosa.mul %[[VAL_1]], %[[VAL_5]], %[[VAL_2]] : (tensor<13x1x3xi32>, tensor<13x21x3xi32>, tensor<1xi8>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_8:.*]] = tosa.equal %[[VAL_0]], %[[VAL_7]] : (tensor<13x21x3xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_9:.*]] = tosa.logical_not %[[VAL_8]] : (tensor<13x21x3xi1>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_10:.*]] = tosa.greater %[[VAL_3]], %[[VAL_6]] : (tensor<1x1x1xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_11:.*]] = tosa.sub %[[VAL_5]], %[[VAL_4]] : (tensor<13x21x3xi32>, tensor<1x1x1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_12:.*]] = tosa.logical_and %[[VAL_9]], %[[VAL_10]] : (tensor<13x21x3xi1>, tensor<13x21x3xi1>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_13:.*]] = tosa.select %[[VAL_12]], %[[VAL_11]], %[[VAL_5]] : (tensor<13x21x3xi1>, tensor<13x21x3xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi32> +// CHECK: return %[[VAL_13]] : tensor<13x21x3xi32> +// CHECK: } +func.func @test_floor_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor<13x1x3xi32>) -> tensor<13x21x3xi32> { + %2 = "tf.FloorDiv"(%arg0, %arg1) : (tensor<13x21x3xi32>, tensor<13x1x3xi32>) -> tensor<13x21x3xi32> + func.return %2 : tensor<13x21x3xi32> +} + + +// ----- + +// CHECK-LABEL: test_exp +// CHECK: %[[VAR0:.*]] = tosa.exp %arg0 +func.func @test_exp(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Exp"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_rcp +// CHECK: %[[VAR0:.*]] = tosa.reciprocal %arg0 +func.func @test_rcp(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Reciprocal"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_relu +// CHECK: %[[VAR0:.*]] = tosa.clamp %arg0 {max_val = 3.40282347E+38 : f32, min_val = 0.000000e+00 : f32} +func.func @test_relu(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Relu"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_relu6 +// CHECK: %[[VAR0:.*]] = tosa.clamp %arg0 {max_val = 6.000000e+00 : f32, min_val = 0.000000e+00 : f32} +func.func @test_relu6(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Relu6"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_leaky_relu +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<5.000000e-01> : tensor<1x1xf32>}> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.mul %arg0, %[[VAR1]], %[[SHIFT]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.greater_equal %arg0, %[[VAR0]] +// CHECK: %[[VAR6:.*]] = tosa.select %[[VAR3]], %arg0, %[[VAR2]] +func.func @test_leaky_relu(%arg0: tensor<4x4xf32>) -> tensor<4x4xf32> { + %0 = "tf.LeakyRelu"(%arg0) {alpha = 0.5 : f32} : (tensor<4x4xf32>) -> tensor<4x4xf32> + func.return %0 : tensor<4x4xf32> +} + +// ----- + +// CHECK-LABEL: test_concat +// CHECK: %[[VAR0:.*]] = tosa.concat %arg0, %arg1 {axis = 0 : i32} +func.func @test_concat(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<26x21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor} : () -> tensor + %3 = "tf.ConcatV2"(%arg0, %arg1, %2) : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor) -> tensor<26x21x3xf32> + func.return %3 : tensor<26x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_and +// CHECK: %[[VAR0:.*]] = tosa.bitwise_and %arg0, %arg1 +func.func @test_bitwise_and(%arg0: tensor<13x21x3xi32>, %arg1: tensor<13x21x1xi32>) -> tensor<13x21x3xi32> { + %2 = "tf.BitwiseAnd"(%arg0, %arg1) : (tensor<13x21x3xi32>, tensor<13x21x1xi32>) -> tensor<13x21x3xi32> + func.return %2 : tensor<13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_or +// CHECK: %[[VAR0:.*]] = tosa.bitwise_or %arg0, %arg1 +func.func @test_bitwise_or(%arg0: tensor<13x21x3xi32>, %arg1: tensor<13x1x3xi32>) -> tensor<13x21x3xi32> { + %2 = "tf.BitwiseOr"(%arg0, %arg1) : (tensor<13x21x3xi32>, tensor<13x1x3xi32>) -> tensor<13x21x3xi32> + func.return %2 : tensor<13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_not +// CHECK: %[[VAR0:.*]] = tosa.bitwise_not %arg0 +func.func @test_bitwise_not(%arg0: tensor<13x21x1xi32>) -> tensor<13x21x1xi32> { + %2 = "tf.Invert"(%arg0) : (tensor<13x21x1xi32>) -> tensor<13x21x1xi32> + func.return %2 : tensor<13x21x1xi32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_xor +// CHECK: %[[VAR0:.*]] = tosa.bitwise_xor %arg0, %arg1 +func.func @test_bitwise_xor(%arg0: tensor<13x21x1xi32>, %arg1: tensor<13x21x3xi32>) -> tensor<13x21x3xi32> { + %2 = "tf.BitwiseXor"(%arg0, %arg1) : (tensor<13x21x1xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi32> + func.return %2 : tensor<13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_logical_and +// CHECK: %[[VAR0:.*]] = tosa.logical_and %arg0, %arg1 +func.func @test_logical_and(%arg0: tensor<13x21x3xi1>, %arg1: tensor<13x21x1xi1>) -> tensor<13x21x3xi1> { + %2 = "tf.LogicalAnd"(%arg0, %arg1) : (tensor<13x21x3xi1>, tensor<13x21x1xi1>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_logical_or +// CHECK: %[[VAR0:.*]] = tosa.logical_or %arg0, %arg1 +func.func @test_logical_or(%arg0: tensor<13x1x3xi1>, %arg1: tensor<13x21x3xi1>) -> tensor<13x21x3xi1> { + %2 = "tf.LogicalOr"(%arg0, %arg1) : (tensor<13x1x3xi1>, tensor<13x21x3xi1>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_logical_not +// CHECK: %[[VAR0:.*]] = tosa.logical_not %arg0 +func.func @test_logical_not(%arg0: tensor<1x21x3xi1>) -> tensor<1x21x3xi1> { + %2 = "tf.LogicalNot"(%arg0) : (tensor<1x21x3xi1>) -> tensor<1x21x3xi1> + func.return %2 : tensor<1x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_any +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_any %arg0 {axis = 0 : i32} +// CHECK: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR0]] +func.func @test_reduce_any(%arg0: tensor<13x21x3xi1>) -> tensor<21x3xi1> { + //%2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %2 = "tf.Const"() {value = dense<0> : tensor<1xi64>} : () -> tensor<1xi64> + %3 = "tf.Any"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xi1>, tensor<1xi64>) -> tensor<21x3xi1> + func.return %3 : tensor<21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_all +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_all %arg0 {axis = 0 : i32} +// CHECK: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR0]] +func.func @test_reduce_all(%arg0: tensor<13x21x3xi1>) -> tensor<21x3xi1> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.All"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xi1>, tensor<1xi32>) -> tensor<21x3xi1> + func.return %3 : tensor<21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_min +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_min %arg0 {axis = 0 : i32} +// CHECK: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR0]] +func.func @test_reduce_min(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.Min"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %3 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_max +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_max %arg0 {axis = 0 : i32} +// CHECK: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR0]] +func.func @test_reduce_max(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.Max"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %3 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_sum +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %arg0 {axis = 0 : i32} +// CHECK: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR0]] +func.func @test_reduce_sum(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.Sum"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %3 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_sum_nonzero_axis +// CHECK-SAME: %[[VAL_0:.*]]: tensor<10x20x30x40x50xf32> +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[10, 20, 30, 50]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.reduce_sum %[[VAL_0]] {axis = 3 : i32} : (tensor<10x20x30x40x50xf32>) -> tensor<10x20x30x1x50xf32> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.reshape %[[VAL_2]], %[[VAL_1]] : (tensor<10x20x30x1x50xf32>, !tosa.shape<4>) -> tensor<10x20x30x50xf32> +// CHECK: return %[[VAL_3]] : tensor<10x20x30x50xf32> +func.func @test_reduce_sum_nonzero_axis(%arg0: tensor<10x20x30x40x50xf32> {tf._user_specified_name = "inp_list"}) -> tensor<10x20x30x50xf32> { + %cst = "tf.Const"() {device = "", value = dense<3> : tensor} : () -> tensor + %0 = "tf.Sum"(%arg0, %cst) {device = "", keep_dims = false} : (tensor<10x20x30x40x50xf32>, tensor) -> tensor<10x20x30x50xf32> + %1 = "tf.Identity"(%0) {device = ""} : (tensor<10x20x30x50xf32>) -> tensor<10x20x30x50xf32> + func.return %1 : tensor<10x20x30x50xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_mean +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0.0769230798> : tensor<1x1xf32>}> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAL_4:.*]] = tosa.reduce_sum %[[VAL_0]] {axis = 0 : i32} +// CHECK: %[[VAL_5:.*]] = tosa.reshape %[[VAL_4]], %[[VAL_3]] +// CHECK: %[[VAL_6:.*]] = tosa.mul %[[VAL_5]], %[[VAL_2]], %[[VAL_1]] +func.func @test_reduce_mean(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.Mean"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %3 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_product +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_product %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_product(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.Prod"(%arg0, %2) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %3 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_min +// CHECK: %[[VAR0:.*]] = tosa.minimum %arg0, %arg1 +func.func @test_min(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Minimum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_max +// CHECK: %[[VAR0:.*]] = tosa.maximum %arg0, %arg1 +func.func @test_max(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x1xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Maximum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x21x1xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_pow +// CHECK: %[[VAR0:.*]] = tosa.pow %arg0, %arg1 +func.func @test_pow(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x1xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Pow"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x21x1xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_abs +// CHECK: %[[VAR0:.*]] = tosa.abs %arg0 +func.func @test_abs(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Abs"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_ceil +// CHECK: %[[VAR0:.*]] = tosa.ceil %arg0 +func.func @test_ceil(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Ceil"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_floor +// CHECK: %[[VAR0:.*]] = tosa.floor %arg0 +func.func @test_floor(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Floor"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_log +// CHECK: %[[VAR0:.*]] = tosa.log %arg0 +func.func @test_log(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Log"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_negate +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK-DAG: %[[VAR1:.*]] = tosa.negate %arg0, %[[VAR0]], %[[VAR0]] +func.func @test_negate(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Neg"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_rsqrt +// CHECK: %[[VAR0:.*]] = tosa.rsqrt %arg0 +func.func @test_rsqrt(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Rsqrt"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_sin +// CHECK: %[[VAR0:.*]] = tosa.sin %arg0 +func.func @test_sin(%arg0: tensor<10xf32>) -> tensor<*xf32> { + %0 = "tf.Sin"(%arg0) : (tensor<10xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_cos +// CHECK: %[[VAR0:.*]] = tosa.cos %arg0 +func.func @test_cos(%arg0: tensor<10xf32>) -> tensor<*xf32> { + %0 = "tf.Cos"(%arg0) : (tensor<10xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_sign +// CHECK-SAME: %[[VAL_0:.*]]: tensor<8x33xf32> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x1xf32>}> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<-1.000000e+00> : tensor<1x1xf32>}> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1xf32>}> +// CHECK: %[[VAL_4:.*]] = tosa.greater %[[VAL_0]], %[[VAL_1]] +// CHECK: %[[VAL_5:.*]] = tosa.greater %[[VAL_1]], %[[VAL_0]] +// CHECK: %[[VAL_6:.*]] = tosa.select %[[VAL_5]], %[[VAL_2]], %[[VAL_1]] +// CHECK: %[[VAL_7:.*]] = tosa.select %[[VAL_4]], %[[VAL_3]], %[[VAL_6]] +func.func @test_sign(%arg0: tensor<8x33xf32>) -> tensor<8x33xf32> { + %0 = "tf.Sign"(%arg0) : (tensor<8x33xf32>) -> tensor<8x33xf32> + func.return %0 : tensor<8x33xf32> +} + +// ----- + +// CHECK-LABEL: test_sigmoid +// CHECK: %[[VAR0:.*]] = tosa.sigmoid %arg0 +func.func @test_sigmoid(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Sigmoid"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_square +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR0:.*]] = tosa.mul %arg0, %arg0, %[[SHIFT]] +func.func @test_square(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Square"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_equal +// CHECK: %[[VAR0:.*]] = tosa.equal %arg0, %arg1 +func.func @test_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x1x3xf32>) -> tensor<13x21x3xi1> { + %2 = "tf.Equal"(%arg0, %arg1) {incompatible_shape_error = true} : (tensor<13x21x3xf32>, tensor<13x1x3xf32>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_greater_equal +// CHECK: %[[VAR0:.*]] = tosa.greater_equal %arg0, %arg1 +func.func @test_greater_equal(%arg0: tensor<13x1x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xi1> { + %2 = "tf.GreaterEqual"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_greater +// CHECK: %[[VAR0:.*]] = tosa.greater %arg0, %arg1 +func.func @test_greater(%arg0: tensor<13x21x1xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xi1> { + %2 = "tf.Greater"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_less +// CHECK-DAG: %[[VAR0:.*]] = tosa.greater_equal %arg0, %arg1 +// CHECK: %[[VAR1:.*]] = tosa.logical_not %[[VAR0]] +func.func @test_less(%arg0: tensor<13x1x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xi1> { + %2 = "tf.Less"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_less_equal +// CHECK-DAG: %[[VAR0:.*]] = tosa.greater %arg0, %arg1 +// CHECK: %[[VAR1:.*]] = tosa.logical_not %[[VAR0]] +func.func @test_less_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x21x3xf32>) -> tensor<13x21x3xi1> { + %2 = "tf.LessEqual"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x21x3xf32>) -> tensor<13x21x3xi1> + func.return %2 : tensor<13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_argmax +// CHECK: %[[VAR0:.*]] = tosa.argmax %arg0 {axis = 0 : i32} +func.func @test_argmax(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xi32> { + %2 = "tf.Const"() {value = dense<0> : tensor} : () -> tensor + %3 = "tf.ArgMax"(%arg0, %2) : (tensor<13x21x3xf32>, tensor) -> tensor<21x3xi32> + func.return %3 : tensor<21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_avg_pool2d +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAR0:.*]] = tosa.avg_pool2d %arg0, %[[ZP]], %[[ZP]] {acc_type = f32, kernel = array, pad = array, stride = array} +func.func @test_avg_pool2d(%arg0: tensor<1x32x32x8xf32>) -> tensor<1x32x32x8xf32> { + %2 = "tf.AvgPool"(%arg0) {data_format = "NHWC", ksize = [1, 1, 1, 1], padding = "SAME", strides = [1, 1, 1, 1]} : (tensor<1x32x32x8xf32>) -> tensor<1x32x32x8xf32> + func.return %2 : tensor<1x32x32x8xf32> +} + +// ----- + +// CHECK-LABEL: test_max_pool2d +// CHECK: %[[VAR0:.*]] = tosa.max_pool2d %arg0 {kernel = array, pad = array, stride = array} +func.func @test_max_pool2d(%arg0: tensor<1x32x32x8xf32>) -> tensor<1x32x32x8xf32> { + %2 = "tf.MaxPool"(%arg0) {data_format = "NHWC", explicit_paddings = [], ksize = [1, 1, 1, 1], padding = "SAME", strides = [1, 1, 1, 1]} : (tensor<1x32x32x8xf32>) -> tensor<1x32x32x8xf32> + func.return %2 : tensor<1x32x32x8xf32> +} + +// ----- + +// CHECK-LABEL: test_reshape +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[1, 819]> : tensor<2xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] : (tensor<13x21x3xf32>, !tosa.shape<2>) -> tensor<1x819xf32> +func.func @test_reshape(%arg0: tensor<13x21x3xf32>) -> tensor<1x819xf32> { + %0 = "tf.Const"() {value = dense<[1, 819]> : tensor<2xi32>} : () -> tensor<2xi32> + %3 = "tf.Reshape"(%arg0, %0) : (tensor<13x21x3xf32>, tensor<2xi32>) -> tensor<1x819xf32> + %4 = "tf.Identity"(%3) : (tensor<1x819xf32>) -> tensor<1x819xf32> + func.return %4 : tensor<1x819xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose +// CHECK: %[[VAR1:.*]] = tosa.transpose %arg0 {perms = array} +func.func @test_transpose(%arg0: tensor<13x21x3xf32>) -> tensor<3x13x21xf32> { + %2 = "tf.Const"() {value = dense<[2, 0, 1]> : tensor<3xi32>} : () -> tensor<3xi32> + %3 = "tf.Transpose"(%arg0, %2) : (tensor<13x21x3xf32>, tensor<3xi32>) -> tensor<3x13x21xf32> + func.return %3 : tensor<3x13x21xf32> +} + +// ----- + +// CHECK-LABEL: test_slice +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[4, 11, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[6, 8, 0]> : tensor<3xindex>} +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<4x11x1xf32> +func.func @test_slice(%arg0: tensor<13x21x3xf32>) -> tensor<4x11x1xf32> { + %2 = "tf.Const"() {value = dense<[6, 8, 0]> : tensor<3xi64>} : () -> tensor<3xi64> + %3 = "tf.Const"() {value = dense<[4, 11, 1]> : tensor<3xi64>} : () -> tensor<3xi64> + %4 = "tf.Slice"(%arg0, %2, %3) : (tensor<13x21x3xf32>, tensor<3xi64>, tensor<3xi64>) -> tensor<4x11x1xf32> + func.return %4 : tensor<4x11x1xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[9, 7, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[9, 7, 1, 2]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[9, 7, 3, 2]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[9, 21, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} +// CHECK: %[[VAL_7:.*]] = tosa.slice %[[VAL_0]], %[[VAL_6]], %[[VAL_5]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<9x21x2xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_4]] : (tensor<9x21x2xf32>, !tosa.shape<4>) -> tensor<9x7x3x2xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_2]], %[[VAL_3]] : (tensor<9x7x3x2xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<9x7x1x2xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<9x7x1x2xf32>, !tosa.shape<3>) -> tensor<9x7x2xf32> +func.func @test_strided_slice(%arg0: tensor<13x21x3xf32>) -> tensor<9x7x2xf32> { + %2 = "tf.Const"() {value = dense<[4, 0, 1]> : tensor<3xi64>} : () -> tensor<3xi64> + %3 = "tf.Const"() {value = dense<[13, 21, 3]> : tensor<3xi64>} : () -> tensor<3xi64> + %4 = "tf.Const"() {value = dense<[1, 3, 1]> : tensor<3xi64>} : () -> tensor<3xi64> + %5 = "tf.StridedSlice"(%arg0, %2, %3, %4) {begin_mask = 2 : i64, ellipsis_mask = 0 : i64, end_mask = 3 : i64, new_axis_mask = 0 : i64, shrink_axis_mask = 0 : i64} : (tensor<13x21x3xf32>, tensor<3xi64>, tensor<3xi64>, tensor<3xi64>) -> tensor<9x7x2xf32> + func.return %5 : tensor<9x7x2xf32> +} + +// ----- + +// CHECK-LABEL: test_select +// CHECK: %[[VAR0:.*]] = tosa.const_shape {values = dense<1> : tensor<3xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %arg2, %[[VAR0]] : (tensor<1xi1>, !tosa.shape<3>) -> tensor<1x1x1xi1> +// CHECK: %[[VAR2:.*]] = tosa.select %[[VAR1]], %arg0, %arg1 +func.func @test_select(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<1xi1>) -> tensor<13x21x3xf32> { + %2 = "tf.SelectV2"(%arg2, %arg0, %arg1) : (tensor<1xi1>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_addn +// CHECK-DAG: %[[VAR0:.*]] = tosa.add %arg0, %arg1 +// CHECK-DAG: %[[VAR1:.*]] = tosa.add %arg2, %[[VAR0]] +// CHECK: %[[VAR2:.*]] = tosa.add %arg3, %[[VAR1]] +func.func @test_addn(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.AddN"(%arg0, %arg1, %arg2, %arg3) : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_concatv2 +// CHECK: %[[VAR0:.*]] = tosa.concat %arg0, %arg1, %arg2, %arg3 {axis = 0 : i32} +func.func @test_concatv2(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<52x21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor} : () -> tensor + %3 = "tf.ConcatV2"(%arg0, %arg1, %arg2, %arg3, %2) : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor) -> tensor<52x21x3xf32> + func.return %3 : tensor<52x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_stack +// CHECK-DAG: %[[VAR0:.*]] = tosa.concat %arg0, %arg1, %arg2, %arg3 {axis = 0 : i32} +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[4, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[SHAPE]] +func.func @test_stack(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<4x13x21x3xf32> { + %2 = "tf.Pack"(%arg0, %arg1, %arg2, %arg3) {axis = 0 : i64} : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<4x13x21x3xf32> + func.return %2 : tensor<4x13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_unstack +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[32, 32, 8]> : tensor<3xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR0]] +func.func @test_unstack(%arg0: tensor<1x32x32x8xf32>) -> tensor<32x32x8xf32> { + %2 = "tf.Unpack"(%arg0) {axis = 0 : i64} : (tensor<1x32x32x8xf32>) -> tensor<32x32x8xf32> + %3 = "tf.Identity"(%2) : (tensor<32x32x8xf32>) -> tensor<32x32x8xf32> + func.return %3 : tensor<32x32x8xf32> +} + +// ----- + +// CHECK-LABEL: test_pad +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<1> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[PVAL:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR1:.*]] = tosa.pad %arg0, %[[VAR0]], %[[PVAL]] +func.func @test_pad(%arg0: tensor<13x21x3xf32>) -> tensor<15x23x5xf32> { + %2 = "tf.Const"() {value = dense<1> : tensor<3x2xi32>} : () -> tensor<3x2xi32> + %3 = "tf.Pad"(%arg0, %2) : (tensor<13x21x3xf32>, tensor<3x2xi32>) -> tensor<15x23x5xf32> + func.return %3 : tensor<15x23x5xf32> +} + +// ----- + +// CHECK-LABEL: test_pad_v2 +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<-3.40282347E+38> : tensor<1xf32>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[1, 0, 0, 1, 1, 2]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK: %[[VAL_3:.*]] = tosa.pad %[[VAL_0]], %[[VAL_2]], %[[VAL_1]] +func.func @test_pad_v2(%arg0: tensor<13x21x3xf32>) -> tensor<15x23x5xf32> { + %1 = "tf.Const"() {value = dense<[[1, 0], [0, 1], [1, 2]]> : tensor<3x2xi32>} : () -> tensor<3x2xi32> + %2 = "tf.Const"() {value = dense<-3.40282347E+38> : tensor} : () -> tensor + %3 = "tf.PadV2"(%arg0, %1, %2) : (tensor<13x21x3xf32>, tensor<3x2xi32>, tensor) -> tensor<15x23x5xf32> + func.return %3 : tensor<15x23x5xf32> +} + +// ----- + +// CHECK-LABEL: test_expand_dims +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[1, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims(%arg0: tensor<13x21x3xf32>) -> tensor<1x13x21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor} : () -> tensor + %3 = "tf.ExpandDims"(%arg0, %2) : (tensor<13x21x3xf32>, tensor) -> tensor<1x13x21x3xf32> + func.return %3 : tensor<1x13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_expand_dims_negative_index +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[13, 21, 1, 3]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims_negative_index(%arg0: tensor<13x21x3xf32>) -> tensor<13x1x21x3xf32> { + %2 = "tf.Const"() {value = dense<-2> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.ExpandDims"(%arg0, %2) : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<13x1x21x3xf32> + func.return %3 : tensor<13x1x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_shape +// CHECK: %[[VAR0:.*]] = "tosa.const"() <{values = dense<[13, 21, 3]> : tensor<3xi32>}> +func.func @test_shape() -> tensor<3xi32> { + %3 = "tf.Const"() {value = dense<[13, 21, 3]> : tensor<3xi32>} : () -> tensor<3xi32> + func.return %3 : tensor<3xi32> +} + +// ----- + +// CHECK-LABEL: test_rank +// CHECK: %[[VAR0:.*]] = "tosa.const"() <{values = dense<3> : tensor}> +func.func @test_rank() -> tensor { + %3 = "tf.Const"() {value = dense<3> : tensor} : () -> tensor + func.return %3 : tensor +} + +// ----- + +// CHECK-LABEL: test_elu +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.exp %arg0 +// CHECK-DAG: %[[VAR4:.*]] = tosa.sub %[[VAR2]], %[[VAR0]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.greater_equal %arg0, %[[VAR1]] +// CHECK: %[[VAR7:.*]] = tosa.select %[[VAR6]], %arg0, %[[VAR4]] +func.func @test_elu(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Elu"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_softmax +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_max %arg0 +// CHECK-DAG: %[[VAR1:.*]] = tosa.sub %arg0, %[[VAR0]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.exp %[[VAR1]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.reduce_sum %[[VAR2]] {axis = 2 : i32} +// CHECK-DAG: %[[VAR4:.*]] = tosa.reciprocal %[[VAR3]] +// CHECK: %[[VAR5:.*]] = tosa.mul %[[VAR2]], %[[VAR4]], %[[SHIFT]] +func.func @test_softmax(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Softmax"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_log_softmax +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = tosa.exp %arg0 +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %[[VAR0]] {axis = 2 : i32} +// CHECK-DAG: %[[VAR2:.*]] = tosa.reciprocal %[[VAR1]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.mul %[[VAR0]], %[[VAR2]], %[[SHIFT]] +// CHECK: %[[VAR4:.*]] = tosa.log %[[VAR3]] +func.func @test_log_softmax(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.LogSoftmax"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_batch_matmul_3d +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR0:.*]] = tosa.matmul %arg0, %arg1, %[[ZP]], %[[ZP]] +func.func @test_batch_matmul_3d(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x3x42xf32>) -> tensor<13x21x42xf32> { + %0 = "tf.BatchMatMulV2"(%arg0, %arg1) {adj_x = false, adj_y = false, device = ""} : (tensor<13x21x3xf32>, tensor<13x3x42xf32>) -> tensor<13x21x42xf32> + func.return %0 : tensor<13x21x42xf32> +} + +// ----- + +// CHECK-LABEL: test_batch_matmul_4d +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[65, 21, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[65, 3, 42]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[5, 13, 21, 42]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg1, %[[VAR11]] +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.matmul %[[VAR0]], %[[VAR1]], %[[ZP]], %[[ZP]] +// CHECK: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR12]] +func.func @test_batch_matmul_4d(%arg0: tensor<5x13x21x3xf32>, %arg1: tensor<5x13x3x42xf32>) -> tensor<5x13x21x42xf32> { + %0 = "tf.BatchMatMulV2"(%arg0, %arg1) {adj_x = false, adj_y = false, device = ""} : (tensor<5x13x21x3xf32>, tensor<5x13x3x42xf32>) -> tensor<5x13x21x42xf32> + func.return %0 : tensor<5x13x21x42xf32> +} + +// ----- + +// CHECK-LABEL: test_matmul +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 14, 19]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 19, 28]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[14, 28]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg1, %[[VAR11]] +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.matmul %[[VAR0]], %[[VAR1]], %[[ZP]], %[[ZP]] +// CHECK: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR12]] +func.func @test_matmul(%arg0: tensor<14x19xf32>, %arg1: tensor<19x28xf32>) -> tensor<14x28xf32> { + %2 = "tf.MatMul"(%arg0, %arg1) {transpose_a = false, transpose_b = false} : (tensor<14x19xf32>, tensor<19x28xf32>) -> tensor<14x28xf32> + func.return %2 : tensor<14x28xf32> +} + +// ----- + +// CHECK-LABEL: test_add_scalar +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1x1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.add %arg0, %[[VAR0]] +func.func @test_add_scalar(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Const"() {value = dense<1.000000e+00> : tensor} : () -> tensor + %3 = "tf.Add"(%arg0, %2) : (tensor<13x21x3xf32>, tensor) -> tensor<13x21x3xf32> + func.return %3 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_add_1d +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_sum %arg1 {axis = 0 : i32} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %[[VAR0]] {axis = 1 : i32} +// CHECK: %[[VAR2:.*]] = tosa.add %arg0, %[[VAR1]] +func.func @test_add_1d(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tf.Const"() {value = dense<[0, 1]> : tensor<2xi32>} : () -> tensor<2xi32> + %3 = "tf.Sum"(%arg1, %0) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<2xi32>) -> tensor<3xf32> + %4 = "tf.Add"(%arg0, %3) : (tensor<13x21x3xf32>, tensor<3xf32>) -> tensor<13x21x3xf32> + func.return %4 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_split +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 14, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 7, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[13, 7, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} +// CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: %[[VAL_6:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_1]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +func.func @test_split(%arg0: tensor<13x21x3xf32>) -> (tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32>) { + %6 = "tf.Const"() {value = dense<1> : tensor} : () -> tensor + %7:3 = "tf.Split"(%6, %arg0) : (tensor, tensor<13x21x3xf32>) -> (tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32>) + func.return %7#0, %7#1, %7#2 : tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32> +} + +// ----- + +// CHECK-LABEL: test_tile +// CHECK: tosa.tile +func.func @test_tile(%arg0: tensor<13x21x3xf32>) -> tensor<39x21x6xf32> { + %2 = "tf.Const"() {value = dense<[3, 1, 2]> : tensor<3xi32>} : () -> tensor<3xi32> + %3 = "tf.Tile"(%arg0, %2) : (tensor<13x21x3xf32>, tensor<3xi32>) -> tensor<39x21x6xf32> + %4 = "tf.Identity"(%3) : (tensor<39x21x6xf32>) -> tensor<39x21x6xf32> + func.return %4 : tensor<39x21x6xf32> +} + +// ----- + +// CHECK-LABEL: test_reverse +// CHECK: tosa.reverse +func.func @test_reverse(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.Const"() {value = dense<0> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.ReverseV2"(%arg0, %2) : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<13x21x3xf32> + func.return %3 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_space_to_batch +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 1, 0, 0]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[PVAL:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.pad %arg0, %[[VAR0]], %[[PVAL]] +// CHECK-DAG: %[[VAR13:.*]] = tosa.const_shape {values = dense<[13, 11, 2, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR13]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.transpose %[[VAR3]] {perms = array} +// CHECK-DAG: %[[VAR14:.*]] = tosa.const_shape {values = dense<[26, 11, 3]> : tensor<3xindex>} +// CHECK: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[VAR14]] +func.func @test_space_to_batch(%arg0: tensor<13x21x3xf32>) -> tensor<26x11x3xf32> { + %2 = "tf.Const"() {value = dense<2> : tensor<1xi32>} : () -> tensor<1xi32> + %3 = "tf.Const"() {value = dense<[[0, 1]]> : tensor<1x2xi32>} : () -> tensor<1x2xi32> + %4 = "tf.SpaceToBatchND"(%arg0, %2, %3) : (tensor<13x21x3xf32>, tensor<1xi32>, tensor<1x2xi32>) -> tensor<26x11x3xf32> + func.return %4 : tensor<26x11x3xf32> +} + +// ----- + +// CHECK-LABEL: test_batch_to_space +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %arg0 {perms = array} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[2, 2, 2, 32, 32, 1]> : tensor<6xindex>} +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR10]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.transpose %[[VAR3]] {perms = array} +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[2, 64, 64, 1]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[VAR12]] +// CHECK: return %[[VAR5]] +func.func @test_batch_to_space(%arg0: tensor<1x32x32x8xf32>) -> tensor<2x64x64x1xf32> { + %2 = "tf.Const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %3 = "tf.Const"() {value = dense<0> : tensor<2x2xi32>} : () -> tensor<2x2xi32> + %4 = "tf.Const"() {value = dense<[3, 1, 2, 0]> : tensor<4xi32>} : () -> tensor<4xi32> + %5 = "tf.Transpose"(%arg0, %4) : (tensor<1x32x32x8xf32>, tensor<4xi32>) -> tensor<8x32x32x1xf32> + %6 = "tf.BatchToSpaceND"(%5, %2, %3) : (tensor<8x32x32x1xf32>, tensor<2xi32>, tensor<2x2xi32>) -> tensor<2x64x64x1xf32> + func.return %6 : tensor<2x64x64x1xf32> +} + +// ----- + +// CHECK-LABEL: test_space_to_depth +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 16, 2, 16, 2, 8]> : tensor<6xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %[[VAR1]] {perms = array} +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[1, 16, 16, 32]> : tensor<4xindex>} +// CHECK: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR12]] +func.func @test_space_to_depth(%arg0: tensor<1x32x32x8xf32>) -> tensor<1x16x16x32xf32> { + %2 = "tf.SpaceToDepth"(%arg0) {block_size = 2 : i64, data_format = "NHWC"} : (tensor<1x32x32x8xf32>) -> tensor<1x16x16x32xf32> + func.return %2 : tensor<1x16x16x32xf32> +} + +// ----- + +// CHECK-LABEL: test_depth_to_space +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 32, 32, 2, 2, 2]> : tensor<6xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %[[VAR1]] {perms = array} +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[1, 64, 64, 2]> : tensor<4xindex>} +// CHECK: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR12]] +func.func @test_depth_to_space(%arg0: tensor<1x32x32x8xf32>) -> tensor<1x64x64x2xf32> { + %2 = "tf.DepthToSpace"(%arg0) {block_size = 2 : i64, data_format = "NHWC"} : (tensor<1x32x32x8xf32>) -> tensor<1x64x64x2xf32> + func.return %2 : tensor<1x64x64x2xf32> +} + +// ----- + +// CHECK-LABEL: test_left_shift +// CHECK: %[[VAR0:.*]] = tosa.logical_left_shift %arg0, %arg1 +func.func @test_left_shift(%arg0: tensor<4x4xi32>, %arg1: tensor<1x1xi32>) -> tensor<4x4xi32> { + %0 = "tf.LeftShift"(%arg0, %arg1) : (tensor<4x4xi32>, tensor<1x1xi32>) -> tensor<4x4xi32> + func.return %0 : tensor<4x4xi32> +} + +// ----- + +// CHECK-LABEL: test_right_shift +// CHECK: %[[VAR0:.*]] = tosa.arithmetic_right_shift %arg0, %arg1 {round = false} +func.func @test_right_shift(%arg0: tensor<4x4xi32>, %arg1: tensor<1x1xi32>) -> tensor<4x4xi32> { + %0 = "tf.RightShift"(%arg0, %arg1) : (tensor<4x4xi32>, tensor<1x1xi32>) -> tensor<4x4xi32> + func.return %0 : tensor<4x4xi32> +} + +// ----- + +// CHECK-LABEL: @test_one_hot +// CHECK-SAME: %[[ARG0_0:.*]]: tensor<4x4xi32>, %[[ARG1_0:.*]]: tensor, %[[ARG2:.*]]: tensor +// CHECK-DAG: %[[SHAPE_2:.*]] = tosa.const_shape {values = dense<[4, 4, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[SHAPE_1:.*]] = tosa.const_shape {values = dense<[16, 1]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[CST1:.*]] = tosa.const_shape {values = dense<[16, 1, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[CST2:.*]] = tosa.const_shape {values = dense<[16, 2, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[SHAPE_0:.*]] = tosa.const_shape {values = dense<1> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[RESHAPE_0:.*]] = tosa.reshape %[[ARG1_0]], %[[SHAPE_0]] +// CHECK: %[[TILE:.*]] = tosa.tile %[[RESHAPE_0]], %[[CST1]] +// CHECK: %[[RESHAPE_1:.*]] = tosa.reshape %[[ARG2]], %[[SHAPE_0]] +// CHECK: %[[TILE_0:.*]] = tosa.tile %[[RESHAPE_1]], %[[CST2]] +// CHECK: %[[RESHAPE_2:.*]] = tosa.reshape %[[ARG0_0]], %[[SHAPE_1]] +// CHECK: %[[SCATTER:.*]] = tosa.scatter %[[TILE_0]], %[[RESHAPE_2]], %[[TILE]] +// CHECK: %[[RESHAPE_3:.*]] = tosa.reshape %[[SCATTER]], %[[SHAPE_2]] +// CHECK: return %[[RESHAPE_3]] +func.func @test_one_hot(%arg0: tensor<4x4xi32>, %arg1: tensor, %arg2: tensor) -> tensor<4x4x2xf32> { + %0 = "tf.Const"() {value = dense<2> : tensor} : () -> tensor + %1 = "tf.OneHot"(%arg0, %0, %arg1, %arg2) {axis = -1 : i64} : (tensor<4x4xi32>, tensor, tensor, tensor) -> tensor<4x4x2xf32> + func.return %1 : tensor<4x4x2xf32> +} + +// ----- + +// CHECK-LABEL: test_fakequant_with_min_max_args +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<-2.00003052> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<1.99996948> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<6.10360876E-5> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR3:.*]] = "tosa.const"() <{values = dense<16383.75> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR4:.*]] = "tosa.const"() <{values = dense<5.000000e-01> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR6:.*]] = tosa.minimum %arg0, %[[VAR1]] +// CHECK-DAG: %[[VAR8:.*]] = tosa.maximum %[[VAR6]], %[[VAR0]] +// CHECK-DAG: %[[VAR10:.*]] = tosa.sub %[[VAR8]], %[[VAR0]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.mul %[[VAR10]], %[[VAR3]], %[[SHIFT]] +// CHECK-DAG: %[[VAR14:.*]] = tosa.add %[[VAR12]], %[[VAR4]] +// CHECK-DAG: %[[VAR15:.*]] = tosa.floor %[[VAR14]] +// CHECK-DAG: %[[VAR17:.*]] = tosa.mul %[[VAR15]], %[[VAR2]], %[[SHIFT]] +// CHECK: %[[VAR19:.*]] = tosa.add %[[VAR17]], %[[VAR0]] +func.func @test_fakequant_with_min_max_args(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %2 = "tf.FakeQuantWithMinMaxArgs"(%arg0) {max = 2.000000e+00 : f32, min = -2.000000e+00 : f32, narrow_range = false, num_bits = 16 : i64} : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %2 : tensor<13x21x3xf32> +} + +// ----- +// CHECK-LABEL: test_gather +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[1, 13, 63]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<{{.*}} : tensor<1x49xi32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.const_shape {values = dense<[7, 7, 21, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %arg0, %[[VAR0]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.gather %[[VAR3]], %[[VAR1]] +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[VAR2]] +// CHECK: return %[[VAR5]] +func.func @test_gather(%arg0: tensor<13x21x3xf32>) -> tensor<7x7x21x3xf32> { + %0 = "tf.Const"() {device = "", value = dense<0> : tensor} : () -> tensor + %1 = "tf.Const"() {device = "", value = dense<[[9, 8, 11, 10, 11, 0, 12], [7, 0, 1, 5, 2, 9, 6], [7, 9, 10, 8, 0, 3, 0], [8, 9, 10, 4, 9, 12, 6], [0, 2, 4, 3, 6, 11, 8], [5, 8, 7, 2, 4, 10, 5], [4, 12, 8, 3, 12, 9, 1]]> : tensor<7x7xi32>} : () -> tensor<7x7xi32> + %2 = "tf.GatherV2"(%arg0, %1, %0) {batch_dims = 0 : i64, device = ""} : (tensor<13x21x3xf32>, tensor<7x7xi32>, tensor) -> tensor<7x7x21x3xf32> + %3 = "tf.Identity"(%2) {device = ""} : (tensor<7x7x21x3xf32>) -> tensor<7x7x21x3xf32> + func.return %2 : tensor<7x7x21x3xf32> +} + +// ----- +// CHECK-LABEL: test_gather_nd +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{\[\[}}0, 5, 3, 12, 2, 4, 3, 11, 1, 11, 10, 3, 12, 8, 5, 3, 1, 11, 3, 10, 0, 0, 8, 4, 7, 3, 12, 2, 7, 6, 11, 4, 2, 10, 11, 11, 1, 11, 1, 1, 11, 8]]> : tensor<1x42xi32>}> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[6, 7, 21, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 13, 63]> : tensor<3xindex>} +// CHECK: %[[VAL_4:.*]] = tosa.reshape %[[VAL_0]], %[[VAL_3]] +// CHECK: %[[VAL_5:.*]] = tosa.gather %[[VAL_4]], %[[VAL_1]] +// CHECK: %[[VAL_6:.*]] = tosa.reshape %[[VAL_5]], %[[VAL_2]] +func.func @test_gather_nd(%arg0: tensor<13x21x3xf32>) -> tensor<6x7x21x3xf32> { + %0 = "tf.Const"() {device = "", value = dense<[[[0], [5], [3], [12], [2], [4], [3]], [[11], [1], [11], [10], [3], [12], [8]], [[5], [3], [1], [11], [3], [10], [0]], [[0], [8], [4], [7], [3], [12], [2]], [[7], [6], [11], [4], [2], [10], [11]], [[11], [1], [11], [1], [1], [11], [8]]]> : tensor<6x7x1xi32>} : () -> tensor<6x7x1xi32> + %1 = "tf.GatherNd"(%arg0, %0) {device = ""} : (tensor<13x21x3xf32>, tensor<6x7x1xi32>) -> tensor<6x7x21x3xf32> + %2 = "tf.Identity"(%1) {device = ""} : (tensor<6x7x21x3xf32>) -> tensor<6x7x21x3xf32> + func.return %1 : tensor<6x7x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_scatter_nd +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x224x512xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x2xi32>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.reduce_sum %[[VAR2:.*]] {axis = 1 : i32} : (tensor<1x2xi32>) +// CHECK-DAG: %[[VAR4:.*]] = tosa.scatter %[[VAR1:.*]], %[[VAR3:.*]], %arg0 : (tensor<1x224x512xf32>, tensor<1x1xi32>, tensor<1x1x512xf32>) +// CHECK: return %[[VAR4]] +func.func @test_scatter_nd(%arg0: tensor<1x1x512xf32>) -> tensor<1x224x512xf32> { + %shape = "tf.Const"() {device = "", value = dense<[1, 224, 512]> : tensor<3xi32>} : () -> tensor<3xi32> + %indices = "tf.Const"() {device = "", value = dense<[[[0, 0]]]>: tensor<1x1x2xi32>} : () -> tensor<1x1x2xi32> + %1 = "tf.ScatterNd"(%indices, %arg0, %shape) {device = ""} : (tensor<1x1x2xi32>, tensor<1x1x512xf32>, tensor<3xi32>) -> tensor<1x224x512xf32> + func.return %1 : tensor<1x224x512xf32> +} + +// ----- + +// CHECK-LABEL: test_fused_batch_norm +func.func @test_fused_batch_norm(%arg0: tensor<8x8x8x8xf32>, %arg1: tensor<8xf32>, %arg2: tensor<8xf32>, %arg3: tensor<8xf32>, %arg4: tensor<8xf32>) -> tensor<8x8x8x8xf32> { + // CHECK-DAG: %[[CONST0:.+]] = tosa.const_shape {values = dense<[1, 1, 1, 8]> : tensor<4xindex>} + // CHECK-DAG: %[[ONE:.+]] = "tosa.const"() <{values = dense<1.000000e-03> : tensor<1xf32>}> + // CHECK: %[[RES0:.+]] = tosa.reshape %arg3, %[[CONST0]] + // CHECK: %[[SUB0:.+]] = tosa.sub %arg0, %[[RES0]] + // CHECK: %[[ADD0:.+]] = tosa.add %arg4, %[[ONE]] + // CHECK: %[[RSQR:.+]] = tosa.rsqrt %[[ADD0]] + // CHECK: %[[RES1:.+]] = tosa.reshape %[[RSQR]], %[[CONST0]] + // CHECK: %[[MUL0:.+]] = tosa.mul %[[SUB0]], %[[RES1]] + // CHECK: %[[RES1:.+]] = tosa.reshape %arg1, %[[CONST0]] + // CHECK: %[[MUL1:.+]] = tosa.mul %[[MUL0]], %[[RES1]] + // CHECK: %[[RES2:.+]] = tosa.reshape %arg2, %[[CONST0]] + // CHECK: %[[ADD1:.+]] = tosa.add %[[MUL1]], %[[RES2]] + %0:6 = "tf.FusedBatchNormV3"(%arg0, %arg1, %arg2, %arg3, %arg4) {T = "tfdtype$DT_FLOAT", data_format = "NHWC", epsilon = 0.001 : f32, is_training = false} : (tensor<8x8x8x8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>) -> (tensor<8x8x8x8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<*xf32>) + + // CHECK: return %[[ADD1]] + func.return %0#0 : tensor<8x8x8x8xf32> +} + +// ----- + +// CHECK-LABEL: test_fused_batch_norm_training +func.func @test_fused_batch_norm_training(%arg0: tensor<8x8x8x8xf32>, %arg1: tensor<8xf32>, %arg2: tensor<8xf32>, %arg3: tensor<8xf32>, %arg4: tensor<8xf32>) -> (tensor<8x8x8x8xf32>) { + // CHECK: "tf.FusedBatchNormV3" + %0:6 = "tf.FusedBatchNormV3"(%arg0, %arg1, %arg2, %arg3, %arg4) {T = "tfdtype$DT_FLOAT", data_format = "NHWC", epsilon = 0.001 : f32, exponential_avg_factor = 1.0 : f32, is_training = true} : (tensor<8x8x8x8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>) -> (tensor<8x8x8x8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>, tensor<8xf32>) + func.return %0#0 : tensor<8x8x8x8xf32> +} + +// ----- + +// CHECK-LABEL: mirrorpad_symmetric +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 8]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[8, 2]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[8, 1]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[3, 0]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[2, 10]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[1, 10]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_7:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} +// CHECK: %[[VAL_8:.*]] = tosa.slice %arg0, %[[VAL_7]], %[[VAL_6]] : (tensor<5x10xf32>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<1x10xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_5]] : (tensor<5x10xf32>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<2x10xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reverse %[[VAL_9]] {axis = 0 : i32} : (tensor<2x10xf32>) -> tensor<2x10xf32> +// CHECK: %[[VAL_11:.*]] = tosa.concat %[[VAL_8]], %arg0, %[[VAL_10]] {axis = 0 : i32} : (tensor<1x10xf32>, tensor<5x10xf32>, tensor<2x10xf32>) -> tensor<8x10xf32> +// CHECK: %[[VAL_12:.*]] = tosa.slice %[[VAL_11]], %[[VAL_7]], %[[VAL_3]] : (tensor<8x10xf32>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<8x1xf32> +// CHECK: %[[VAL_13:.*]] = tosa.slice %[[VAL_11]], %[[VAL_1]], %[[VAL_2]] : (tensor<8x10xf32>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<8x2xf32> +// CHECK: %[[VAL_14:.*]] = tosa.reverse %[[VAL_13]] {axis = 1 : i32} : (tensor<8x2xf32>) -> tensor<8x2xf32> +// CHECK: %[[VAL_15:.*]] = tosa.concat %[[VAL_12]], %[[VAL_11]], %[[VAL_14]] {axis = 1 : i32} : (tensor<8x1xf32>, tensor<8x10xf32>, tensor<8x2xf32>) -> tensor<8x13xf32> +func.func @mirrorpad_symmetric(%arg0: tensor<5x10xf32>) -> tensor<8x13xf32> { + %cst = "tf.Const"() {device = "", value = dense<[[1, 2], [1, 2]]> : tensor<2x2xi32>} : () -> tensor<2x2xi32> + %0 = "tf.MirrorPad"(%arg0, %cst) {device = "", mode = "SYMMETRIC"} : (tensor<5x10xf32>, tensor<2x2xi32>) -> tensor<8x13xf32> + %1 = "tf.Identity"(%0) {device = ""} : (tensor<8x13xf32>) -> tensor<8x13xf32> + return %0 : tensor<8x13xf32> +} + +// ----- + +// CHECK-LABEL: mirrorpad_reflect +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 0, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[14, 22, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[0, 1, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[14, 1, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[1, 21, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[1, 0, 0]> : tensor<3xindex>} +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_6]], %[[VAL_5]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<1x21x3xf32> +// CHECK: %[[VAL_8:.*]] = tosa.concat %[[VAL_7]], %arg0 {axis = 0 : i32} : (tensor<1x21x3xf32>, tensor<13x21x3xf32>) -> tensor<14x21x3xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_3]], %[[VAL_4]] : (tensor<14x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<14x1x3xf32> +// CHECK: %[[VAL_10:.*]] = tosa.concat %[[VAL_9]], %[[VAL_8]] {axis = 1 : i32} : (tensor<14x1x3xf32>, tensor<14x21x3xf32>) -> tensor<14x22x3xf32> +// CHECK: %[[VAL_11:.*]] = tosa.slice %[[VAL_10]], %[[VAL_1]], %[[VAL_2]] : (tensor<14x22x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<14x22x1xf32> +// CHECK: %[[VAL_12:.*]] = tosa.concat %[[VAL_11]], %[[VAL_10]] {axis = 2 : i32} : (tensor<14x22x1xf32>, tensor<14x22x3xf32>) -> tensor<14x22x4xf32> +func.func @mirrorpad_reflect(%arg0: tensor<13x21x3xf32>) -> tensor<14x22x4xf32> { + %cst = "tf.Const"() {device = "", value = dense<[[1, 0], [1, 0], [1, 0]]> : tensor<3x2xi32>} : () -> tensor<3x2xi32> + %0 = "tf.MirrorPad"(%arg0, %cst) {device = "", mode = "REFLECT"} : (tensor<13x21x3xf32>, tensor<3x2xi32>) -> tensor<14x22x4xf32> + %1 = "tf.Identity"(%0) {device = ""} : (tensor<14x22x4xf32>) -> tensor<14x22x4xf32> + return %0 : tensor<14x22x4xf32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_f32 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<-0.000000e+00> : tensor<3x3x13x7xf32>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xf32>, !tosa.shape<4>) -> tensor<1x1x13x1xf32> +// CHECK: %[[VAL_2:.*]] = tosa.add %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xf32>, tensor<3x3x13x7xf32>) -> tensor<3x3x13x7xf32> +// CHECK: return %[[VAL_2]] : tensor<3x3x13x7xf32> +func.func @test_broadcast_to_f32(%arg0: tensor<13x1xf32>) -> (tensor<3x3x13x7xf32>) { + %shape = "tf.Const"() {value = dense<[3, 3, 1, 7]> : tensor<4xi32>} : () -> tensor<4xi32> + %1 = "tf.BroadcastTo"(%arg0, %shape) : (tensor<13x1xf32>, tensor<4xi32>) -> tensor<3x3x13x7xf32> + return %1 : tensor<3x3x13x7xf32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_i32 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<0> : tensor<7x7x13x3xi32>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xi32>, !tosa.shape<4>) -> tensor<1x1x13x1xi32> +// CHECK: %[[VAL_2:.*]] = tosa.add %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xi32>, tensor<7x7x13x3xi32>) -> tensor<7x7x13x3xi32> +// CHECK: return %[[VAL_2]] : tensor<7x7x13x3xi32> +func.func @test_broadcast_to_i32(%arg0: tensor<13x1xi32>) -> (tensor<3x3x13x3xi32>) { + %shape = "tf.Const"() {value = dense<[7, 7, 13, 3]> : tensor<4xi32>} : () -> tensor<4xi32> + %1 = "tf.BroadcastTo"(%arg0, %shape) : (tensor<13x1xi32>, tensor<4xi32>) -> tensor<3x3x13x3xi32> + return %1 : tensor<3x3x13x3xi32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_i1 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense : tensor<7x7x13x7xi1>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xi1>, !tosa.shape<4>) -> tensor<1x1x13x1xi1> +// CHECK: %[[VAL_2:.*]] = tosa.logical_or %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xi1>, tensor<7x7x13x7xi1>) -> tensor<7x7x13x7xi1> +// CHECK: return %[[VAL_2]] : tensor<7x7x13x7xi1> +func.func @test_broadcast_to_i1(%arg0: tensor<13x1xi1>) -> (tensor<7x7x13x7xi1>) { + %shape = "tf.Const"() {value = dense<[7, 7, 13, 7]> : tensor<4xi32>} : () -> tensor<4xi32> + %1 = "tf.BroadcastTo"(%arg0, %shape) : (tensor<13x1xi1>, tensor<4xi32>) -> tensor<7x7x13x7xi1> + return %1 : tensor<7x7x13x7xi1> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_i16 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<0> : tensor<7x7x13x3xi32>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] +// CHECK: %[[VAL_2:.*]] = tosa.cast %[[VAL_1]] : (tensor<1x1x13x1xi16>) -> tensor<1x1x13x1xi32> +// CHECK: %[[VAL_3:.*]] = tosa.add %[[VAL_2]], %[[VAL_0]] : (tensor<1x1x13x1xi32>, tensor<7x7x13x3xi32>) -> tensor<7x7x13x3xi32> +// CHECK: %[[VAL_4:.*]] = tosa.cast %[[VAL_3]] : (tensor<7x7x13x3xi32>) -> tensor<7x7x13x3xi16> +// CHECK: return %[[VAL_4]] : tensor<7x7x13x3xi16> +func.func @test_broadcast_to_i16(%arg0: tensor<13x1xi16>) -> (tensor<7x7x13x3xi16>) { + %shape = "tf.Const"() {value = dense<[7, 7, 1, 3]> : tensor<4xi32>} : () -> tensor<4xi32> + %1 = "tf.BroadcastTo"(%arg0, %shape) : (tensor<13x1xi16>, tensor<4xi32>) -> tensor<7x7x13x3xi16> + return %1 : tensor<7x7x13x3xi16> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_smaller_rank +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<[13, 7]> : tensor<2xi32>} +// CHECK: %[[VAL_1:.*]] = "tf.BroadcastTo"(%arg0, %[[VAL_0]]) : (tensor<2x3x13x1xi32>, tensor<2xi32>) -> tensor<13x7xi32> +// CHECK: return %[[VAL_1]] : tensor<13x7xi32> +func.func @test_broadcast_to_smaller_rank(%arg0: tensor<2x3x13x1xi32>) -> (tensor<13x7xi32>) { + %s = "tf.Const"() {value = dense<[13, 7]> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tf.BroadcastTo"(%arg0, %s) : (tensor<2x3x13x1xi32>, tensor<2xi32>) -> tensor<13x7xi32> + return %1 : tensor<13x7xi32> +} + +// ----- + +// CHECK-LABEL: test_erf +// CHECK: %[[VAR0:.*]] = tosa.erf %arg0 : +func.func @test_erf(%arg0: tensor<4x4xf32>) -> tensor<4x4xf32> { + %0 = "tf.Erf"(%arg0) : (tensor<4x4xf32>) -> tensor<4x4xf32> + func.return %0 : tensor<4x4xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-unequal-ranks.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-unequal-ranks.mlir new file mode 100644 index 0000000000000000000000000000000000000000..aa698816d5eb76ee530c3661c6a4284b230b3d4c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tf-unequal-ranks.mlir @@ -0,0 +1,186 @@ +// RUN: tf-tosa-opt --split-input-file --tf-to-tosa-pipeline --verify-each %s | FileCheck %s + +// Test tf legalization that produce TOSA ResultsBroadcastableShape operators with unequal ranks + +// ----- + +// CHECK-LABEL: test_add +func.func @test_add(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<*xf32> { + // CHECK: tosa.add + %2 = "tf.Add"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_add +func.func @test_addn(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>, %arg2: tensor<21x3xf32>, %arg3: tensor<3xf32>) -> tensor<*xf32> { + // CHECK: tosa.add + // CHECK: tosa.add + // CHECK: tosa.add + %2 = "tf.AddN"(%arg0, %arg1, %arg2, %arg3) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>, tensor<21x3xf32>, tensor<3xf32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_and +func.func @test_bitwise_and(%arg0: tensor<8x13x21x3xi32>, %arg1: tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> { + // CHECK: tosa.bitwise_and + %2 = "tf.BitwiseAnd"(%arg0, %arg1) : (tensor<8x13x21x3xi32>, tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> + func.return %2 : tensor<8x13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_sub +func.func @test_sub(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<*xf32> { + // CHECK: tosa.sub + %2 = "tf.Sub"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_or +func.func @test_bitwise_or(%arg0: tensor<8x13x21x3xi32>, %arg1: tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> { + // CHECK: tosa.bitwise_or + %2 = "tf.BitwiseOr"(%arg0, %arg1) : (tensor<8x13x21x3xi32>, tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> + func.return %2 : tensor<8x13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_bitwise_xor +func.func @test_bitwise_xor(%arg0: tensor<8x13x21x3xi32>, %arg1: tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> { + // CHECK: tosa.bitwise_xor + %2 = "tf.BitwiseXor"(%arg0, %arg1) : (tensor<8x13x21x3xi32>, tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> + func.return %2 : tensor<8x13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_logical_and +func.func @test_logical_and(%arg0: tensor<8x13x21x3xi1>, %arg1: tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> { + // CHECK: tosa.logical_and + %2 = "tf.LogicalAnd"(%arg0, %arg1) : (tensor<8x13x21x3xi1>, tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> + func.return %2 : tensor<8x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_logical_or +func.func @test_logical_or(%arg0: tensor<8x13x21x3xi1>, %arg1: tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> { + // CHECK: tosa.logical_or + %2 = "tf.LogicalOr"(%arg0, %arg1) : (tensor<8x13x21x3xi1>, tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> + func.return %2 : tensor<8x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_floor_div +// CHECK: tosa.intdiv +// CHECK: tosa.select +func.func @test_floor_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor<1x13x1x3xi32>) -> tensor<1x13x21x3xi32> { + %2 = "tf.FloorDiv"(%arg0, %arg1) : (tensor<13x21x3xi32>, tensor<1x13x1x3xi32>) -> tensor<1x13x21x3xi32> + func.return %2 : tensor<1x13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_real_div +// CHECK: tosa.intdiv +func.func @test_real_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor<1x13x1x3xi32>) -> tensor<1x13x21x3xi32> { + %2 = "tf.RealDiv"(%arg0, %arg1) : (tensor<13x21x3xi32>, tensor<1x13x1x3xi32>) -> tensor<1x13x21x3xi32> + func.return %2 : tensor<1x13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_left_shift +func.func @test_left_shift(%arg0: tensor<4x4xi32>, %arg1: tensor<1x1x1xi32>) -> tensor<1x4x4xi32> { + // CHECK: tosa.logical_left_shift + %0 = "tf.LeftShift"(%arg0, %arg1) : (tensor<4x4xi32>, tensor<1x1x1xi32>) -> tensor<1x4x4xi32> + func.return %0 : tensor<1x4x4xi32> +} + +// ----- + +// CHECK-LABEL: test_right_shift +func.func @test_right_shift(%arg0: tensor<4x4xi32>, %arg1: tensor<1x1x1xi32>) -> tensor<1x4x4xi32> { + // CHECK: tosa.arithmetic_right_shift + %0 = "tf.RightShift"(%arg0, %arg1) : (tensor<4x4xi32>, tensor<1x1x1xi32>) -> tensor<1x4x4xi32> + func.return %0 : tensor<1x4x4xi32> +} + +// ----- + +// CHECK-LABEL: test_max +func.func @test_max(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x21x1xf32>) -> tensor<1x13x21x3xf32> { + // CHECK: tosa.maximum + %2 = "tf.Maximum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x13x21x1xf32>) -> tensor<1x13x21x3xf32> + func.return %2 : tensor<1x13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_min +func.func @test_min(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x21x1xf32>) -> tensor<1x13x21x3xf32> { + // CHECK: tosa.minimum + %2 = "tf.Minimum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x13x21x1xf32>) -> tensor<1x13x21x3xf32> + func.return %2 : tensor<1x13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_power +func.func @test_power(%arg0: tensor<8x13x21x3xi32>, %arg1: tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> { + // CHECK: tosa.pow + %2 = "tf.Pow"(%arg0, %arg1) : (tensor<8x13x21x3xi32>, tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> + func.return %2 : tensor<8x13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_equal +// CHECK: tosa.equal +func.func @test_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x1x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tf.Equal"(%arg0, %arg1) {incompatible_shape_error = true} : (tensor<13x21x3xf32>, tensor<1x13x1x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_greater_equal +// CHECK: tosa.greater_equal +func.func @test_greater_equal(%arg0: tensor<13x1x3xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tf.GreaterEqual"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_greater +// CHECK: tosa.greater +func.func @test_greater(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tf.Greater"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_less +// CHECK: tosa.greater_equal +// CHECK: tosa.logical_not +func.func @test_less(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tf.Less"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- +// CHECK-LABEL: test_select +// CHECK: tosa.select +func.func @test_select(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x21x3xf32>, %arg2: tensor<1xi1>) -> tensor<1x13x21x3xf32> { + %2 = "tf.SelectV2"(%arg2, %arg0, %arg1) : (tensor<1xi1>, tensor<13x21x3xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xf32> + func.return %2 : tensor<1x13x21x3xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-dequantize_softmax.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-dequantize_softmax.mlir new file mode 100644 index 0000000000000000000000000000000000000000..e86d9b96320f3e811be9c8eec70034c2eab9a3a8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-dequantize_softmax.mlir @@ -0,0 +1,17 @@ +// RUN: tf-tosa-opt --tosa-dequantize-tfl-softmax %s | FileCheck %s + + +// ----- + +// CHECK-LABEL: test_softmax_qi8 +// CHECK-SAME: %[[INPUT:.*]]: tensor<8x!quant.uniform> +// CHECK: %[[DEQUANTIZED_INPUT:.*]] = "tfl.dequantize"(%[[INPUT]]) +// CHECK: %[[FLOAT_SOFTMAX:.*]] = "tfl.softmax"(%[[DEQUANTIZED_INPUT]]) +// CHECK: %[[QUANTIZED_FLOAT_SOFTMAX:.*]] = "tfl.quantize"(%[[FLOAT_SOFTMAX]]) +// CHECK: return %[[QUANTIZED_FLOAT_SOFTMAX]] +func.func @test_softmax_qi8(%arg0: tensor<8x!quant.uniform>) -> tensor<8x!quant.uniform> { + %0 = "tfl.softmax"(%arg0) {beta = 1.2 : f32} : (tensor<8x!quant.uniform>) -> tensor<8x!quant.uniform> + func.return %0 : tensor<8x!quant.uniform> +} + +// ----- diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-pipeline-filtered.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-pipeline-filtered.mlir new file mode 100644 index 0000000000000000000000000000000000000000..f0cda6823c1e03849a13c088f5efabe2e0fd1133 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-pipeline-filtered.mlir @@ -0,0 +1,46 @@ +// RUN: tf-tosa-opt --pass-pipeline='builtin.module(func.func(tosa-legalize-tfl{disable-patterns=TFLConv2D,TFLSoftmax, enable-patterns=TFLFullyConnected,TFLTranspose}))' %s | FileCheck %s + + +// ----- + +// CHECK-LABEL: test_conv2d +// CHECK-DAG: %[[VAR0:.*]] = arith.constant dense<0.000000e+00> : tensor<16xf32> +// CHECK: %[[VAR1:.*]] = "tfl.conv_2d"(%arg0, %arg1, %[[VAR0]]) <{dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32}> +func.func @test_conv2d(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<16x2x2x8xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<0.000000e+00> : tensor<16xf32> + %0 = "tfl.conv_2d"(%arg0, %arg1, %cst) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>, tensor<16x2x2x8xf32>, tensor<16xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: func @test_softmax( +// CHECK-SAME:%[[VAR0:.*]]: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { +// CHECK: %[[VAR1:.*]] = "tfl.softmax"(%[[VAR0]]) <{beta = 1.000000e+00 : f32}> : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: return %[[VAR1]] : tensor<13x21x3xf32> +func.func @test_softmax(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.softmax"(%arg0) {beta = 1.000000e+00 : f32} : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_matmul +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[14, 1, 1, 19]> : tensor<4xindex>} +// CHECK-DAG: %[[CONST1:.*]] = tosa.const_shape {values = dense<[28, 1, 1, 19]> : tensor<4xindex>} +// CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[14, 28]> : tensor<2xindex>} +// CHECK-DAG: %[[CONST3:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR1:.*]] = tosa.transpose %arg1 {perms = array} +// CHECK-DAG: %[[VAR2:.*]] = tosa.reshape %arg0, %[[CONST0]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR1]], %[[CONST1]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.conv2d %[[VAR2]], %[[VAR3]], %[[CONST3]], %[[CONST3]], %[[CONST3]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[CONST2]] +func.func @test_matmul(%arg0: tensor<14x19xf32>, %arg1: tensor<19x28xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[1, 0]> : tensor<2xi32> + %cst_0 = "tfl.no_value"() {value = unit} : () -> none + %0 = "tfl.transpose"(%arg1, %cst) : (tensor<19x28xf32>, tensor<2xi32>) -> tensor<*xf32> + %1 = "tfl.fully_connected"(%arg0, %0, %cst_0) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor<14x19xf32>, tensor<*xf32>, none) -> tensor<*xf32> + func.return %1 : tensor<*xf32> +} + +// ----- diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-pipeline.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-pipeline.mlir new file mode 100644 index 0000000000000000000000000000000000000000..a499b283e0eb49b3f6d85f1d9c11ddf7866e28af --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-pipeline.mlir @@ -0,0 +1,4377 @@ +// RUN: tf-tosa-opt --split-input-file --tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + +// RUN: tf-tosa-opt --split-input-file --tf-tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + + +// Operations for testing tfl-to-tosa-pipeline + +// TODO: For all quantized tests: compute and add checks on rescale attribute +// values +// TODO: These tests are fairly minimal. Expand the checks to be more robust. + + +// ----- + +// CHECK-LABEL: test_conv2d +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<16xf32>}> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_4:.*]] = tosa.conv2d %arg0, %arg1, %[[VAL_2]], %[[VAL_3]], %[[VAL_3]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv2d(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<16x2x2x8xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<0.000000e+00> : tensor<16xf32> + %0 = "tfl.conv_2d"(%arg0, %arg1, %cst) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>, tensor<16x2x2x8xf32>, tensor<16xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_conv2d_dynamic +// CHECK: tosa.conv2d +// CHECK-SAME: tensor +func.func @test_conv2d_dynamic(%arg0: tensor, %arg1: tensor<16x1x1x8xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<0.000000e+00> : tensor<16xf32> + %0 = "tfl.conv_2d"(%arg0, %arg1, %cst) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor, tensor<16x1x1x8xf32>, tensor<16xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_conv2d_bias +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_4:.*]] = tosa.conv2d %arg0, %arg1, %arg2, %[[VAL_3]], %[[VAL_3]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-SAME: tensor<1x32x32x16xf32> +func.func @test_conv2d_bias(%arg0: tensor<1x32x32x8xf32>, %cst: tensor<16x2x2x8xf32>, %cst_0: tensor<16xf32>) -> tensor<*xf32> { + %0 = "tfl.conv_2d"(%arg0, %cst, %cst_0) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>, tensor<16x2x2x8xf32>, tensor<16xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_conv2d_slicing +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[2, 31, 30, 8]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_6:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] +// CHECK: %[[VAL_7:.*]] = tosa.conv2d %[[VAL_6]], %arg1, %arg2, %[[VAL_5]], %[[VAL_5]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-SAME: tensor<2x15x10x16xf32> +func.func @test_conv2d_slicing(%arg0: tensor<2x32x32x8xf32>, %arg1: tensor<16x3x3x8xf32>, %arg2: tensor<16xf32>) -> tensor<2x15x10x16xf32> { + %0 = "tfl.conv_2d"(%arg0, %arg1, %arg2) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "VALID", stride_h = 2 : i32, stride_w = 3 : i32} : (tensor<2x32x32x8xf32>, tensor<16x3x3x8xf32>, tensor<16xf32>) -> tensor<2x15x10x16xf32> + func.return %0 : tensor<2x15x10x16xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose_conv2d +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.transpose_conv2d %arg0, %arg1, %[[VAR1]], %[[VAR1]], %[[VAR1]] {acc_type = f32, out_pad = array, stride = array} +func.func @test_transpose_conv2d(%arg0: tensor<1x32x32x8xf32>, %cst_0: tensor<16x1x1x8xf32>) -> tensor<1x32x32x16xf32> { + %cst = arith.constant dense<[1, 32, 32, 16]> : tensor<4xi32> + %cst_1 = "tfl.no_value"() {value = unit} : () -> none + %0 = "tfl.transpose_conv"(%cst, %cst_0, %arg0, %cst_1) {padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32, fused_activation_function = "NONE"} : (tensor<4xi32>, tensor<16x1x1x8xf32>, tensor<1x32x32x8xf32>, none) -> tensor<1x32x32x16xf32> + func.return %0 : tensor<1x32x32x16xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose_conv2d_relu +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.transpose_conv2d %arg0, %arg1, %[[VAR1]], %[[VAR1]], %[[VAR1]] {acc_type = f32, out_pad = array, stride = array} +// CHECK: %[[VAR3:.*]] = tosa.clamp %[[VAR2]] {max_val = 3.40282347E+38 : f32, min_val = 0.000000e+00 : f32} +func.func @test_transpose_conv2d_relu(%arg0: tensor<1x32x32x8xf32>, %cst_0: tensor<16x1x1x8xf32>) -> tensor<1x32x32x16xf32> { + %cst = arith.constant dense<[1, 32, 32, 16]> : tensor<4xi32> + %cst_1 = "tfl.no_value"() {value = unit} : () -> none + %0 = "tfl.transpose_conv"(%cst, %cst_0, %arg0, %cst_1) {padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32, fused_activation_function = "RELU"} : (tensor<4xi32>, tensor<16x1x1x8xf32>, tensor<1x32x32x8xf32>, none) -> tensor<1x32x32x16xf32> + func.return %0 : tensor<1x32x32x16xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose_conv2d_outpad +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.transpose_conv2d %arg0, %arg1, %[[VAR0]], %[[VAR0]], %[[VAR0]] {acc_type = f32, out_pad = array, stride = array} +func.func @test_transpose_conv2d_outpad(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<16x1x1x8xf32>) -> tensor<1x33x33x16xf32> { + %cst = arith.constant dense<[1, 33, 33, 16]> : tensor<4xi32> + %cst_1 = "tfl.no_value"() {value = unit} : () -> none + %0 = "tfl.transpose_conv"(%cst, %arg1, %arg0, %cst_1) + {padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32, + fused_activation_function = "NONE"} + : (tensor<4xi32>, tensor<16x1x1x8xf32>, tensor<1x32x32x8xf32>, none) -> tensor<1x33x33x16xf32> + func.return %0 : tensor<1x33x33x16xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose_conv2d_int16_input_int32_variable_bias +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[SHAPE2:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[TRANSPOSE_CONV:.*]] = tosa.transpose_conv2d %arg0, %arg1, %[[VAL_6]], %[[VAL_7]], %[[VAL_8]] {acc_type = i48, out_pad = array, stride = array} : (tensor<1x12x12x8x!quant.uniform>, tensor<4x3x3x8x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x24x24x4xi48> +// CHECK: %[[RESCALE1:.*]] = tosa.rescale %[[TRANSPOSE_CONV]], %[[VAL_5]], %[[VAL_4]], %[[VAL_6]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x24x24x4xi48>, tensor<1xi32>, tensor<1xi8>, tensor<1xi48>, tensor<1xi32>) -> tensor<1x24x24x4xi32> +// CHECK: %[[RESCALE2:.*]] = tosa.rescale %arg2, %[[VAL_5]], %[[VAL_4]], %[[VAL_3]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<4x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<4xi32> +// CHECK: %[[RESHAPE:.*]] = tosa.reshape %[[RESCALE2]], %[[SHAPE2]] : (tensor<4xi32>, !tosa.shape<4>) -> tensor<1x1x1x4xi32> +// CHECK: %[[ADD:.*]] = tosa.add %[[RESCALE1]], %[[RESHAPE]] : (tensor<1x24x24x4xi32>, tensor<1x1x1x4xi32>) -> tensor<1x24x24x4xi32> +// CHECK: %[[RESCALE3:.*]] = tosa.rescale %[[ADD]], %[[VAL_1]], %[[VAL_0]], %[[VAL_3]], %[[VAL_7]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x24x24x4xi32>, tensor<1xi16>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) -> tensor<1x24x24x4x!quant.uniform> +// CHECK: return %[[RESCALE3]] : tensor<1x24x24x4x!quant.uniform> +func.func @test_transpose_conv2d_int16_input_int32_variable_bias(%input: tensor<1x12x12x8x!quant.uniform>, %filter: tensor<4x3x3x8x!quant.uniform>, %bias: tensor<4x!quant.uniform>) -> tensor<1x24x24x4x!quant.uniform> { + %out_shape = arith.constant dense<[1, 24, 24, 4]> : tensor<4xi32> + %0 = "tfl.transpose_conv"(%out_shape, %filter, %input, %bias) {stride_h = 2 : i32, stride_w = 2 : i32, padding = "SAME", fused_activation_function = "NONE"} : (tensor<4xi32>, tensor<4x3x3x8x!quant.uniform>, tensor<1x12x12x8x!quant.uniform>, tensor<4x!quant.uniform>) -> tensor<1x24x24x4x!quant.uniform> + return %0 : tensor<1x24x24x4x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_conv2d_qi8 +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<16x2x2x8xi8>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0> : tensor<16xi32>}> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.conv2d %arg0, %[[VAR0]], %[[VAR1]], %[[VAR2]], %[[VAR2]] {acc_type = i32, dilation = array, pad = array, stride = array} +// CHECK: %[[VAR4:.*]] = tosa.rescale %[[VAR3]] +func.func @test_conv2d_qi8(%arg0: tensor<1x32x32x8x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<16x2x2x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, value = dense<42> : tensor<16x2x2x8xi8>} : () -> tensor<16x2x2x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1} >> + %1 = "tfl.pseudo_qconst"() {qtype = tensor<16x!quant.uniform>, value = dense<0> : tensor<16xi32>} : () -> tensor<16x!quant.uniform> + %2 = "tfl.conv_2d"(%arg0, %0, %1) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<16x2x2x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, tensor<16x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> + func.return %2 : tensor<1x32x32x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_conv2d_qi8_2 +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<16x2x2x8xi8>}> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1> : tensor<16xi32>}> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAL_6:.*]] = tosa.conv2d %arg0, %[[VAL_3]], %[[VAL_4]], %[[VAL_5]], %[[VAL_5]] {acc_type = i32, dilation = array, pad = array, stride = array} +// CHECK: %[[VAL_7:.*]] = tosa.rescale %[[VAL_6]] +func.func @test_conv2d_qi8_2(%arg0: tensor<1x32x32x8x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<16x2x2x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, value = dense<42> : tensor<16x2x2x8xi8>} : () -> tensor<16x2x2x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1} >> + %1 = "tfl.pseudo_qconst"() {qtype = tensor<16x!quant.uniform>, value = dense<1> : tensor<16xi8>} : () -> tensor<16x!quant.uniform> + %2 = "tfl.conv_2d"(%arg0, %0, %1) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<16x2x2x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, tensor<16x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> + func.return %2 : tensor<1x32x32x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_conv2d_qi16 +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0> : tensor<16xi48>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<16x1x1x8xi8>}> +// CHECK-DAG: %[[VAR3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> +// CHECK-DAG: %[[VAR4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR5:.*]] = tosa.conv2d %arg0, %[[VAR1]], %[[VAR0]], %[[VAR3]], %[[VAR4]] {acc_type = i48, dilation = array, pad = array, stride = array} +// CHECK: %[[VAR6:.*]] = tosa.rescale %[[VAR5]] +func.func @test_conv2d_qi16(%arg0: tensor<1x32x32x8x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<16x1x1x8x!quant.uniform>, value = dense<42> : tensor<16x1x1x8xi8>} : () -> tensor<16x1x1x8x!quant.uniform> + %1 = "arith.constant"() {value = dense<0> : tensor<16xi64>} : () -> tensor<16xi64> + %2 = "tfl.conv_2d"(%arg0, %0, %1) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<16x1x1x8x!quant.uniform>, tensor<16xi64>) -> tensor<1x32x32x16x!quant.uniform> + func.return %2 : tensor<1x32x32x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: @test_depthwise_conv2d_bias_qi8 +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x32x32x8x!quant.uniform> +// CHECK-DAG: %[[shift:.*]] = "tosa.const"() <{values = dense<[36, 36, 36, 36, 32, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36, 36]> : tensor<16xi8>}> : () -> tensor<16xi8> +// CHECK-DAG: %[[multiplier:.*]] = "tosa.const"() <{values = dense<[1373724854, 1373724854, 1373724854, 1373724854, 1803013871, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854, 1373724854]> : tensor<16xi32>}> : () -> tensor<16xi32> +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[2, 2, 8, 2]> : tensor<4xindex>} +// CHECK-DAG: %[[CONST1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<16xi32>}> +// CHECK-DAG: %[[CONST2:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x2x16xi8>}> +// CHECK-DAG: %[[INPUT_ZP:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> +// CHECK-DAG: %[[WEIGHT_ZP:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[RESHAPE:.*]] = tosa.reshape %[[CONST2]], %[[CONST0]] +// CHECK-DAG: %[[DEPTHWISE:.*]] = tosa.depthwise_conv2d %[[ARG0]], %[[RESHAPE]], %[[CONST1]], %[[INPUT_ZP]], %[[WEIGHT_ZP]] {acc_type = i32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[RESCALE:.*]] = tosa.rescale %[[DEPTHWISE]] +// CHECK: return %[[RESCALE]] +func.func @test_depthwise_conv2d_bias_qi8(%arg0: tensor<1x32x32x8x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<1x2x2x16x!quant.uniform:f32:3, {0.1,0.1,0.1,0.1,2.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, value = dense<[[[[-127, 127, 127, -127, -127, -127, -127, -127, -127, 127, 127, 127, 127, 127, -127, 127], [-127, 127, 127, -127, -127, -127, -127, -127, -127, 127, 127, 127, 127, 127, -127, 127]], [[-127, 127, 127, -127, -127, -127, -127, -127, -127, 127, 127, 127, 127, 127, -127, 127], [-127, 127, 127, -127, -127, -127, -127, -127, -127, 127, 127, 127, 127, 127, -127, 127]]]]> : tensor<1x2x2x16xi8>} : () -> tensor<1x2x2x16x!quant.uniform:f32:3, {0.1,0.1,0.1,0.1,2.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1} >> + %1 = "tfl.pseudo_qconst"() {qtype = tensor<16x!quant.uniform>, value = dense<[-2879, 6636, 3531, 23376, -79787, -6142, 5582, -30384, 17330, -4549, -3518, 16215, 2695, -2670, 8399, -12223]> : tensor<16xi32>} : () -> tensor<16x!quant.uniform> + %2 = "tfl.depthwise_conv_2d"(%arg0, %0, %1) {depth_multiplier = 2 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<1x2x2x16x!quant.uniform:f32:3, {0.1,0.1,0.1,0.1,2.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, tensor<16x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> + func.return %2 : tensor<1x32x32x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_grouped_convolution +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 4, 1, 64]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[64, 1, 1, 64]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<64> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_7:.*]] = tosa.const_shape {values = dense<0> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_8:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 64]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_9:.*]] = tosa.const_shape {values = dense<[64, 0, 0, 0]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[INPUT_SLICE_1:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] +// CHECK-DAG: %[[FILTER_SLICE_1:.*]] = tosa.slice %arg1, %[[VAL_4]], %[[VAL_5]] +// CHECK-DAG: %[[BIAS_SLICE_1:.*]] = tosa.slice %arg2, %[[VAL_7]], %[[VAL_6]] +// CHECK-DAG: %[[CONV_1:.*]] = tosa.conv2d %[[INPUT_SLICE_1]], %[[FILTER_SLICE_1]], %[[BIAS_SLICE_1]], %[[VAL_10]], %[[VAL_10]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[INPUT_SLICE_2:.*]] = tosa.slice %arg0, %[[VAL_8]], %[[VAL_3]] +// CHECK-DAG: %[[FILTER_SLICE_2:.*]] = tosa.slice %arg1, %[[VAL_9]], %[[VAL_5]] +// CHECK-DAG: %[[BIAS_SLICE_2:.*]] = tosa.slice %arg2, %[[VAL_6]], %[[VAL_6]] +// CHECK-DAG: %[[CONV_2:.*]] = tosa.conv2d %[[INPUT_SLICE_2]], %[[FILTER_SLICE_2]], %[[BIAS_SLICE_2]], %[[VAL_10]], %[[VAL_10]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[CONV_1]], %[[CONV_2]] {axis = 3 : i32} +// CHECK: return %[[CONCAT]] +func.func @test_conv2d_grouped_convolution(%input: tensor<1x4x1x128xf32>, %weights: tensor<128x1x1x64xf32>, %bias: tensor<128xf32>) -> tensor<1x4x1x128xf32> { + %0 = "tfl.conv_2d"(%input, %weights, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x4x1x128xf32>, tensor<128x1x1x64xf32>, tensor<128xf32>) -> (tensor<1x4x1x128xf32>) + return %0 : tensor<1x4x1x128xf32> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_grouped_strided_convolution +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 3, 1, 16]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[128, 3, 1, 16]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<128> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_7:.*]] = tosa.const_shape {values = dense<0> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_8:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 16]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_9:.*]] = tosa.const_shape {values = dense<[128, 0, 0, 0]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 32]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_11:.*]] = tosa.const_shape {values = dense<[256, 0, 0, 0]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_12:.*]] = tosa.const_shape {values = dense<256> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_13:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 48]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_14:.*]] = tosa.const_shape {values = dense<[384, 0, 0, 0]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_15:.*]] = tosa.const_shape {values = dense<384> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_16:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[INPUT_SLICE_1:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] +// CHECK-DAG: %[[FILTER_SLICE_1:.*]] = tosa.slice %arg1, %[[VAL_4]], %[[VAL_5]] +// CHECK-DAG: %[[BIAS_SLICE_1:.*]] = tosa.slice %arg2, %[[VAL_7]], %[[VAL_6]] +// CHECK-DAG: %[[CONV_1:.*]] = tosa.conv2d %[[INPUT_SLICE_1]], %[[FILTER_SLICE_1]], %[[BIAS_SLICE_1]], %[[VAL_16]], %[[VAL_16]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[INPUT_SLICE_2:.*]] = tosa.slice %arg0, %[[VAL_8]], %[[VAL_3]] +// CHECK-DAG: %[[FILTER_SLICE_2:.*]] = tosa.slice %arg1, %[[VAL_9]], %[[VAL_5]] +// CHECK-DAG: %[[BIAS_SLICE_2:.*]] = tosa.slice %arg2, %[[VAL_6]], %[[VAL_6]] +// CHECK-DAG: %[[CONV_2:.*]] = tosa.conv2d %[[INPUT_SLICE_2]], %[[FILTER_SLICE_2]], %[[BIAS_SLICE_2]], %[[VAL_16]], %[[VAL_16]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[INPUT_SLICE_3:.*]] = tosa.slice %arg0, %[[VAL_10]], %[[VAL_3]] +// CHECK-DAG: %[[FILTER_SLICE_3:.*]] = tosa.slice %arg1, %[[VAL_11]], %[[VAL_5]] +// CHECK-DAG: %[[BIAS_SLICE_3:.*]] = tosa.slice %arg2, %[[VAL_12]], %[[VAL_6]] +// CHECK-DAG: %[[CONV_3:.*]] = tosa.conv2d %[[INPUT_SLICE_3]], %[[FILTER_SLICE_3]], %[[BIAS_SLICE_3]], %[[VAL_16]], %[[VAL_16]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[INPUT_SLICE_4:.*]] = tosa.slice %arg0, %[[VAL_13]], %[[VAL_3]] +// CHECK-DAG: %[[FILTER_SLICE_4:.*]] = tosa.slice %arg1, %[[VAL_14]], %[[VAL_5]] +// CHECK-DAG: %[[BIAS_SLICE_4:.*]] = tosa.slice %arg2, %[[VAL_15]], %[[VAL_6]] +// CHECK-DAG: %[[CONV_4:.*]] = tosa.conv2d %[[INPUT_SLICE_4]], %[[FILTER_SLICE_4]], %[[BIAS_SLICE_4]], %[[VAL_16]], %[[VAL_16]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[CONV_1]], %[[CONV_2]], %[[CONV_3]], %[[CONV_4]] {axis = 3 : i32} +// CHECK: return %[[CONCAT]] +func.func @test_conv2d_grouped_strided_convolution(%input: tensor<1x3x1x64xf32>, %weights: tensor<512x3x1x16xf32>, %bias: tensor<512xf32>) -> tensor<1x2x1x512xf32> { + %0 = "tfl.conv_2d"(%input, %weights, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 2 : i32, stride_w = 1 : i32} : (tensor<1x3x1x64xf32>, tensor<512x3x1x16xf32>, tensor<512xf32>) -> (tensor<1x2x1x512xf32>) + return %0 : tensor<1x2x1x512xf32> +} + +// ----- +// CHECK-LABEL: test_conv2d_q_grouped_convolution +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x1x16x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[8, 0, 0, 0]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 8]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<36> : tensor<8xi8>}> : () -> tensor<8xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1374257539> : tensor<8xi32>}> : () -> tensor<8xi32> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_7:.*]] = tosa.const_shape {values = dense<8> : tensor<1xindex>} : () -> !tosa.shape<1> +// CHECK: %[[VAL_8:.*]] = tosa.const_shape {values = dense<0> : tensor<1xindex>} : () -> !tosa.shape<1> +// CHECK: %[[VAL_9:.*]] = tosa.const_shape {values = dense<[8, 1, 1, 8]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<42> : tensor<16x1x1x8xi8>}> : () -> tensor<16x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>> +// CHECK: %[[VAL_11:.*]] = "tosa.const"() <{values = dense<0> : tensor<16xi32>}> : () -> tensor<16x!quant.uniform> +// CHECK: %[[VAL_12:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_13:.*]] = tosa.const_shape {values = dense<[1, 4, 1, 8]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_14:.*]] = tosa.slice %[[VAL_0]], %[[VAL_12]], %[[VAL_13]] : (tensor<1x4x1x16x!quant.uniform>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x4x1x8x!quant.uniform> +// CHECK: %[[VAL_15:.*]] = tosa.slice %[[VAL_10]], %[[VAL_12]], %[[VAL_9]] : (tensor<16x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<8x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>> +// CHECK: %[[VAL_16:.*]] = tosa.slice %[[VAL_11]], %[[VAL_8]], %[[VAL_7]] : (tensor<16x!quant.uniform>, !tosa.shape<1>, !tosa.shape<1>) -> tensor<8x!quant.uniform> +// CHECK: %[[VAL_17:.*]] = tosa.conv2d %[[VAL_14]], %[[VAL_15]], %[[VAL_16]], %[[VAL_6]], %[[VAL_6]] {acc_type = i32, dilation = array, pad = array, stride = array} : (tensor<1x4x1x8x!quant.uniform>, tensor<8x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>>, tensor<8x!quant.uniform>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x4x1x8xi32> +// CHECK: %[[VAL_18:.*]] = tosa.rescale %[[VAL_17]], %[[VAL_4]], %[[VAL_3]], %[[VAL_5]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = true, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x4x1x8xi32>, tensor<8xi32>, tensor<8xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x4x1x8x!quant.uniform> +// CHECK: %[[VAL_19:.*]] = tosa.slice %[[VAL_0]], %[[VAL_2]], %[[VAL_13]] : (tensor<1x4x1x16x!quant.uniform>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x4x1x8x!quant.uniform> +// CHECK: %[[VAL_20:.*]] = tosa.slice %[[VAL_10]], %[[VAL_1]], %[[VAL_9]] : (tensor<16x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<8x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>> +// CHECK: %[[VAL_21:.*]] = tosa.slice %[[VAL_11]], %[[VAL_7]], %[[VAL_7]] : (tensor<16x!quant.uniform>, !tosa.shape<1>, !tosa.shape<1>) -> tensor<8x!quant.uniform> +// CHECK: %[[VAL_22:.*]] = tosa.conv2d %[[VAL_19]], %[[VAL_20]], %[[VAL_21]], %[[VAL_6]], %[[VAL_6]] {acc_type = i32, dilation = array, pad = array, stride = array} : (tensor<1x4x1x8x!quant.uniform>, tensor<8x1x1x8x!quant.uniform:f32:0, {1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01,1.000000e-01}>>, tensor<8x!quant.uniform>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x4x1x8xi32> +// CHECK: %[[VAL_23:.*]] = tosa.rescale %[[VAL_22]], %[[VAL_4]], %[[VAL_3]], %[[VAL_5]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = true, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x4x1x8xi32>, tensor<8xi32>, tensor<8xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x4x1x8x!quant.uniform> +// CHECK: %[[VAL_24:.*]] = tosa.concat %[[VAL_18]], %[[VAL_23]] {axis = 3 : i32} : (tensor<1x4x1x8x!quant.uniform>, tensor<1x4x1x8x!quant.uniform>) -> tensor<1x4x1x16x!quant.uniform> +func.func @test_conv2d_q_grouped_convolution(%input: tensor<1x4x1x16x!quant.uniform>) -> tensor<1x4x1x16x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<16x1x1x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, value = dense<42> : tensor<16x1x1x8xi8>} : () -> tensor<16x1x1x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1} >> + %1 = "tfl.pseudo_qconst"() {qtype = tensor<16x!quant.uniform>, value = dense<0> : tensor<16xi32>} : () -> tensor<16x!quant.uniform> + %2 = "tfl.conv_2d"(%input, %0, %1) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x4x1x16x!quant.uniform>, tensor<16x1x1x8x!quant.uniform:f32:0, {0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1}>>, tensor<16x!quant.uniform>) -> tensor<1x4x1x16x!quant.uniform> + return %2 : tensor<1x4x1x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_depthwise_conv2d_bias_inferred +func.func @test_depthwise_conv2d_bias_inferred(%arg0: tensor, %arg1 : tensor<1x1x1x16xf32>, %arg2 : tensor<16xf32>) -> tensor { + // CHECK: tosa.depthwise_conv2d + // CHECK-SAME: tensor + %2 = "tfl.depthwise_conv_2d"(%arg0, %arg1, %arg2) {depth_multiplier = 2 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor, tensor<1x1x1x16xf32>, tensor<16xf32>) -> tensor + func.return %2 : tensor +} + +// ----- + +// CHECK-LABEL: test_depthwise_conv2d_slicing +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[3, 3, 8, 2]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[1, 31, 31, 8]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_7:.*]] = tosa.reshape %arg1, %[[VAL_3]] +// CHECK: %[[VAL_8:.*]] = tosa.slice %arg0, %[[VAL_5]], %[[VAL_4]] +// CHECK: %[[VAL_9:.*]] = tosa.depthwise_conv2d %[[VAL_8]], %[[VAL_7]], %arg2, %[[VAL_6]], %[[VAL_6]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK-SAME: tensor<1x15x15x16xf32> +func.func @test_depthwise_conv2d_slicing(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<1x3x3x16xf32>, %arg2: tensor<16xf32>) -> tensor<1x15x15x16xf32> { + %0 = "tfl.depthwise_conv_2d"(%arg0, %arg1, %arg2) {depth_multiplier = 2 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "VALID", stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x32x32x8xf32>, tensor<1x3x3x16xf32>, tensor<16xf32>) -> tensor<1x15x15x16xf32> + func.return %0 : tensor<1x15x15x16xf32> +} + +// ----- + +// CHECK-LABEL: test_depthwise_conv2d_int16_input_int32_variable_bias +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[SHAPE2:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK-DAG: %[[SHAPE9:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[RESHAPE1:.*]] = tosa.reshape %arg1, %[[SHAPE9]] : (tensor<1x3x3x8x!quant.uniform>, !tosa.shape<4>) -> tensor<3x3x8x1x!quant.uniform> +// CHECK: %[[DEPTHWISE_CONV:.*]] = tosa.depthwise_conv2d %arg0, %[[RESHAPE1]], %[[VAL_8]], %[[VAL_7]], %[[VAL_6]] {acc_type = i48, dilation = array, pad = array, stride = array} : (tensor<1x24x24x8x!quant.uniform>, tensor<3x3x8x1x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x24x24x8xi48> +// CHECK: %[[RESCALE1:.*]] = tosa.rescale %[[DEPTHWISE_CONV]], %[[VAL_5]], %[[VAL_4]], %[[VAL_8]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x24x24x8xi48>, tensor<1xi32>, tensor<1xi8>, tensor<1xi48>, tensor<1xi32>) -> tensor<1x24x24x8xi32> +// CHECK: %[[RESCALE2:.*]] = tosa.rescale %arg2, %[[VAL_5]], %[[VAL_4]], %[[VAL_3]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<8x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<8xi32> +// CHECK: %[[RESHAPE2:.*]] = tosa.reshape %[[RESCALE2]], %[[SHAPE2]] : (tensor<8xi32>, !tosa.shape<4>) -> tensor<1x1x1x8xi32> +// CHECK: %[[ADD:.*]] = tosa.add %[[RESCALE1]], %[[RESHAPE2]] : (tensor<1x24x24x8xi32>, tensor<1x1x1x8xi32>) -> tensor<1x24x24x8xi32> +// CHECK: %[[RESCALE2:.*]] = tosa.rescale %[[ADD]], %[[VAL_1]], %[[VAL_0]], %[[VAL_3]], %[[VAL_7]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x24x24x8xi32>, tensor<1xi16>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) -> tensor<1x24x24x8x!quant.uniform> +// CHECK: return %[[RESCALE2]] : tensor<1x24x24x8x!quant.uniform> +func.func @test_depthwise_conv2d_int16_input_int32_variable_bias(%input: tensor<1x24x24x8x!quant.uniform>, %filter: tensor<1x3x3x8x!quant.uniform>, %bias: tensor<8x!quant.uniform>) -> tensor<1x24x24x8x!quant.uniform> { + %0 = "tfl.depthwise_conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32, depth_multiplier = 1 : i32} : (tensor<1x24x24x8x!quant.uniform>, tensor<1x3x3x8x!quant.uniform>, tensor<8x!quant.uniform>) -> tensor<1x24x24x8x!quant.uniform> + return %0 : tensor<1x24x24x8x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_conv3d +// CHECK-SAME: %[[VAL_0:.*]]: tensor<2x2x7x7x2xf32> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<2x3x3x2x4xf32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_5:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_6:.*]] = tosa.conv3d %[[VAL_0]], %[[VAL_5]], %[[VAL_4]], %[[VAL_4]], %[[VAL_4]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv3d(%arg0: tensor<2x2x7x7x2xf32>, %arg1: tensor<2x3x3x2x4xf32>) -> tensor<2x2x7x7x4xf32> { + %cst = "tfl.no_value"() {value} : () -> none + %0 = "tfl.conv_3d"(%arg0, %arg1, %cst) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_d = 1 : i32, stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<2x2x7x7x2xf32>, tensor<2x3x3x2x4xf32>, none) -> tensor<2x2x7x7x4xf32> + func.return %0 : tensor<2x2x7x7x4xf32> +} + +// ----- + +// CHECK-LABEL: test_conv3d_dynamic +// CHECK-SAME: %[[VAL_0:.*]]: tensor +// CHECK-SAME: %[[VAL_1:.*]]: tensor<3x1x1x8x16xf32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_5:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_6:.*]] = tosa.conv3d %[[VAL_0]], %[[VAL_5]], %[[VAL_4]], %[[VAL_4]], %[[VAL_4]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv3d_dynamic(%arg0: tensor, %arg1: tensor<3x1x1x8x16xf32>) -> tensor<*xf32> { + %cst = "tfl.no_value"() {value} : () -> none + %0 = "tfl.conv_3d"(%arg0, %arg1, %cst) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_d = 1 : i32, stride_h = 1 : i32, stride_w = 1 : i32} : (tensor, tensor<3x1x1x8x16xf32>, none) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_conv3d_bias +// CHECK-SAME: %[[VAL_0:.*]]: tensor<10x3x64x64x12xf32> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<16x2x2x12x8xf32> +// CHECK-SAME: %[[VAL_2:.*]]: tensor<8xf32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_5:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_6:.*]] = tosa.conv3d %[[VAL_0]], %[[VAL_5]], %[[VAL_2]], %[[VAL_4]], %[[VAL_4]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv3d_bias(%arg0: tensor<10x3x64x64x12xf32>, %arg1: tensor<16x2x2x12x8xf32>, %cst: tensor<8xf32>) -> tensor<10x3x64x64x8xf32> { + %0 = "tfl.conv_3d"(%arg0, %arg1, %cst) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_d = 1 : i32, stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<10x3x64x64x12xf32>, tensor<16x2x2x12x8xf32>, tensor<8xf32>) -> tensor<10x3x64x64x8xf32> + func.return %0 : tensor<10x3x64x64x8xf32> +} + +// ----- + +// CHECK-LABEL: test_conv3d_slicing +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 31, 31, 31, 8]> : tensor<5xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<5xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] +// CHECK: %[[VAL_8:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_9:.*]] = tosa.conv3d %[[VAL_7]], %[[VAL_8]], %arg2, %[[VAL_6]], %[[VAL_6]] {acc_type = f32, dilation = array, pad = array, stride = array} +func.func @test_conv3d_slicing(%arg0: tensor<1x32x32x32x8xf32>, %arg1: tensor<3x3x3x8x16xf32>, %arg2: tensor<16xf32>) -> tensor<1x15x15x15x16xf32> { + %0 = "tfl.conv_3d"(%arg0, %arg1, %arg2) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "VALID", stride_d = 2 : i32, stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x32x32x32x8xf32>, tensor<3x3x3x8x16xf32>, tensor<16xf32>) -> tensor<1x15x15x15x16xf32> + func.return %0 : tensor<1x15x15x15x16xf32> +} + +// ----- + +// CHECK-LABEL: test_conv3d_qi8( +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x8x21x17x!quant.uniform> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<2x3x3x17x34xf32>) -> tensor<1x4x8x11x34x!quant.uniform> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0.0156862643> : tensor<1x1x1x1x1xf32>} +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1.11982894> : tensor<1x1x1x1x1xf32>} +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<-4> : tensor<1x1x1x1x1xi32>} +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[BIAS_ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAL_8:.*]] = tosa.cast %[[VAL_0]] +// CHECK: %[[VAL_10:.*]] = tosa.mul %[[VAL_8]], %[[VAL_3]], %[[SHIFT]] +// CHECK: %[[VAL_11:.*]] = tosa.transpose %[[VAL_1]] {perms = array} +// CHECK: %[[VAL_12:.*]] = tosa.conv3d %[[VAL_10]], %[[VAL_11]], %[[BIAS_ZP]], %[[BIAS_ZP]], %[[BIAS_ZP]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK: %[[VAL_13:.*]] = tosa.mul %[[VAL_12]], %[[VAL_4]], %[[SHIFT]] +// CHECK: %[[VAL_14:.*]] = tosa.cast %[[VAL_13]] +// CHECK: %[[VAL_15:.*]] = tosa.add %[[VAL_14]], %[[VAL_5]] +// CHECK: %[[VAL_16:.*]] = tosa.cast %[[VAL_15]] +// CHECK: return %[[VAL_16]] +func.func @test_conv3d_qi8(%arg0: tensor<1x4x8x21x17x!quant.uniform>, %arg1: tensor<2x3x3x17x34xf32>) -> (tensor<1x4x8x11x34x!quant.uniform>) { + %0 = "tfl.dequantize"(%arg0) : (tensor<1x4x8x21x17x!quant.uniform>) -> tensor<1x4x8x21x17xf32> + %2 = "tfl.no_value"() {value} : () -> none + %3 = "tfl.conv_3d"(%0, %arg1, %2) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_d = 1 : i32, stride_h = 1 : i32, stride_w = 2 : i32} : (tensor<1x4x8x21x17xf32>, tensor<2x3x3x17x34xf32>, none) -> tensor<1x4x8x11x34xf32> + %4 = "tfl.quantize"(%3) {qtype = tensor<1x4x8x11x34x!quant.uniform>} : (tensor<1x4x8x11x34xf32>) -> tensor<1x4x8x11x34x!quant.uniform> + return %4 : tensor<1x4x8x11x34x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_conv3d_qi16 +// CHECK: %[[BIAS:.+]] = "tosa.const"() <{values = dense<123> : tensor<16xi48>}> : () -> tensor<16xi48> +// CHECK: tosa.conv3d {{.+}}, %[[BIAS]], %{{.+}} {acc_type = i48, {{.+}}} : {{.+}} -> tensor<1x15x15x15x16xi48> +func.func @test_conv3d_qi16(%input: tensor<1x32x32x32x8x!quant.uniform>, %filter: tensor<3x3x3x8x16x!quant.uniform>) -> tensor<1x15x15x15x16x!quant.uniform> { + %bias = "tfl.pseudo_qconst"() {qtype = tensor<16x!quant.uniform>, value = dense<123> : tensor<16xi16>} : () -> tensor<16x!quant.uniform> + %0 = "tfl.conv_3d"(%input, %filter, %bias) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "VALID", stride_d = 2 : i32, stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x32x32x32x8x!quant.uniform>, tensor<3x3x3x8x16x!quant.uniform>, tensor<16x!quant.uniform>) -> tensor<1x15x15x15x16x!quant.uniform> + func.return %0 : tensor<1x15x15x15x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_conv3d_qi16_variable_bias +// CHECK-SAME: (%arg0: tensor<1x32x32x32x8x!quant.uniform>, %arg1: tensor<3x3x3x8x16x!quant.uniform>, %arg2: tensor<16x!quant.uniform>) +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[SHAPE2:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK-DAG: %[[SHAPE9:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[SHAPE10:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK: %[[SLICE:.*]] = tosa.slice %arg0, %[[SHAPE9]], %[[SHAPE10]] : (tensor<1x32x32x32x8x!quant.uniform>, !tosa.shape<5>, !tosa.shape<5>) -> tensor<1x31x31x31x8x!quant.uniform> +// CHECK: %[[TRANSPOSE:.*]] = tosa.transpose %arg1 {perms = array} : (tensor<3x3x3x8x16x!quant.uniform>) -> tensor<16x3x3x3x8x!quant.uniform> +// CHECK: %[[CONV3D:.*]] = tosa.conv3d %[[SLICE]], %[[TRANSPOSE]], %[[VAL_8]], %[[VAL_7]], %[[VAL_6]] {acc_type = i48, dilation = array, pad = array, stride = array} : (tensor<1x31x31x31x8x!quant.uniform>, tensor<16x3x3x3x8x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x15x15x15x16xi48> +// CHECK: %[[RESCALE1:.*]] = tosa.rescale %[[CONV3D]], %[[VAL_5]], %[[VAL_4]], %[[VAL_8]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x15x15x15x16xi48>, tensor<1xi32>, tensor<1xi8>, tensor<1xi48>, tensor<1xi32>) -> tensor<1x15x15x15x16xi32> +// CHECK: %[[RESCALE2:.*]] = tosa.rescale %arg2, %[[VAL_5]], %[[VAL_4]], %[[VAL_7]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<16x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi32>) -> tensor<16xi32> +// CHECK: %[[RESHAPE:.*]] = tosa.reshape %[[RESCALE2]], %[[SHAPE2]] : (tensor<16xi32>, !tosa.shape<5>) -> tensor<1x1x1x1x16xi32> +// CHECK: %[[ADD:.*]] = tosa.add %[[RESCALE1]], %[[RESHAPE]] : (tensor<1x15x15x15x16xi32>, tensor<1x1x1x1x16xi32>) -> tensor<1x15x15x15x16xi32> +// CHECK: %[[RESCALE3:.*]] = tosa.rescale %[[ADD]], %[[VAL_1]], %[[VAL_0]], %[[VAL_3]], %[[VAL_7]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x15x15x15x16xi32>, tensor<1xi16>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) -> tensor<1x15x15x15x16x!quant.uniform> +// CHECK: return %[[RESCALE3]] : tensor<1x15x15x15x16x!quant.uniform> +func.func @test_conv3d_qi16_variable_bias(%input: tensor<1x32x32x32x8x!quant.uniform>, %filter: tensor<3x3x3x8x16x!quant.uniform>, %bias: tensor<16x!quant.uniform>) -> tensor<1x15x15x15x16x!quant.uniform> { + %0 = "tfl.conv_3d"(%input, %filter, %bias) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "VALID", stride_d = 2 : i32, stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x32x32x32x8x!quant.uniform>, tensor<3x3x3x8x16x!quant.uniform>, tensor<16x!quant.uniform>) -> tensor<1x15x15x15x16x!quant.uniform> + func.return %0 : tensor<1x15x15x15x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_add +// CHECK: %[[VAR0:.*]] = tosa.add %arg0, %arg1 +func.func @test_add(%arg0: tensor<13x21x1xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.add"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x1xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_add_unranked +// CHECK: %[[VAR0:.*]] = tosa.add %arg0, %arg1 +func.func @test_add_unranked(%arg0: tensor<13x21x1xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.add"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x1xf32>, tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_sub +// CHECK: %[[VAR0:.*]] = tosa.sub %arg0, %arg1 +func.func @test_sub(%arg0: tensor<1x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.sub"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<1x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_sub_unranked +// CHECK: %[[VAR0:.*]] = tosa.sub %arg0, %arg1 +func.func @test_sub_unranked(%arg0: tensor<1x21x3xf32>, %arg1: tensor<1x1x1xf32>) -> tensor<*xf32> { + %0 = "tfl.sub"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<1x21x3xf32>, tensor<1x1x1xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_mul +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR0:.*]] = tosa.mul %arg0, %arg1, %[[SHIFT]] +func.func @test_mul(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x1x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.mul"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3xf32>, tensor<13x1x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_mul_unranked +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR0:.*]] = tosa.mul %arg0, %arg1, %[[SHIFT]] +func.func @test_mul_unranked(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x1x1xf32>) -> tensor<*xf32> { + %0 = "tfl.mul"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3xf32>, tensor<1x1x1xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_exp +// CHECK: %[[VAR0:.*]] = tosa.exp %arg0 +func.func @test_exp(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.exp"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_exp_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.+}}> : tensor<256xi8>}> +// CHECK: %[[VAL_2:.*]] = tosa.table %[[VAL_0]], %[[VAL_1]] +func.func @test_exp_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> (tensor<13x21x3x!quant.uniform>) { + %0 = "tfl.exp"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_exp_qi16 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.+}}> : tensor<513xi16>}> +// CHECK: %[[VAL_2:.*]] = tosa.table %[[VAL_0]], %[[VAL_1]] +func.func @test_exp_qi16(%arg0: tensor<13x21x3x!quant.uniform>) -> (tensor<13x21x3x!quant.uniform>) { + %0 = "tfl.exp"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_rcp +// CHECK-DAG: %[[VAR0:.*]] = tosa.reciprocal %arg0 +func.func @test_rcp(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<1.000000e+00> : tensor + %0 = "tfl.div"(%cst, %arg0) {fused_activation_function = "NONE"} : (tensor, tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_div +// CHECK-DAG: %[[RESHAPE:.*]] = tosa.reshape %arg1 +// CHECK: %[[VAR0:.*]] = tosa.intdiv %arg0, %[[RESHAPE]] +func.func @test_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor) -> tensor<*xi32> { + %0 = "tfl.div"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3xi32>, tensor) -> tensor<*xi32> + func.return %0 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: func.func @test_floor_div( +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3xi32>, +// CHECK-SAME: %[[VAL_1:.*]]: tensor) -> tensor<13x21x3xi32> { +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x1x1xi32>}> : () -> tensor<1x1x1xi32> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1> : tensor<1x1x1xi32>}> : () -> tensor<1x1x1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<1> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_6:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_5]] : (tensor, !tosa.shape<3>) -> tensor<1x1x1xi32> +// CHECK: %[[VAL_7:.*]] = tosa.intdiv %[[VAL_0]], %[[VAL_6]] : (tensor<13x21x3xi32>, tensor<1x1x1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_5]] : (tensor, !tosa.shape<3>) -> tensor<1x1x1xi32> +// CHECK: %[[VAL_9:.*]] = tosa.mul %[[VAL_0]], %[[VAL_8]], %[[VAL_2]] : (tensor<13x21x3xi32>, tensor<1x1x1xi32>, tensor<1xi8>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_5]] : (tensor, !tosa.shape<3>) -> tensor<1x1x1xi32> +// CHECK: %[[VAL_11:.*]] = tosa.mul %[[VAL_10]], %[[VAL_7]], %[[VAL_2]] : (tensor<1x1x1xi32>, tensor<13x21x3xi32>, tensor<1xi8>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_12:.*]] = tosa.equal %[[VAL_0]], %[[VAL_11]] : (tensor<13x21x3xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_13:.*]] = tosa.logical_not %[[VAL_12]] : (tensor<13x21x3xi1>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_14:.*]] = tosa.greater %[[VAL_3]], %[[VAL_9]] : (tensor<1x1x1xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_15:.*]] = tosa.sub %[[VAL_7]], %[[VAL_4]] : (tensor<13x21x3xi32>, tensor<1x1x1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_16:.*]] = tosa.logical_and %[[VAL_13]], %[[VAL_14]] : (tensor<13x21x3xi1>, tensor<13x21x3xi1>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_17:.*]] = tosa.select %[[VAL_16]], %[[VAL_15]], %[[VAL_7]] : (tensor<13x21x3xi1>, tensor<13x21x3xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi32> +// CHECK: return %[[VAL_17]] : tensor<13x21x3xi32> +// CHECK: } +func.func @test_floor_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor) -> tensor<13x21x3xi32> { + %0 = "tfl.floor_div"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3xi32>, tensor) -> tensor<13x21x3xi32> + func.return %0 : tensor<13x21x3xi32> +} + +// ----- + +// CHECK-LABEL: test_relu1 +// CHECK: %[[VAL0:.*]] = tosa.clamp %arg0 {max_val = 1.000000e+00 : f32, min_val = -1.000000e+00 : f32} +func.func @test_relu1(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.relu_n1_to_1"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_relu0To1 +// CHECK: %[[VAL0:.*]] = tosa.clamp %arg0 {max_val = 1.000000e+00 : f32, min_val = 0.000000e+00 : f32} +func.func @test_relu0To1(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.relu_0_to_1"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_relu6 +// CHECK: %[[VAR0:.*]] = tosa.clamp %arg0 {max_val = 6.000000e+00 : f32, min_val = 0.000000e+00 : f32} +func.func @test_relu6(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.relu6"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_relu6_dynamic +// CHECK: %[[VAR0:.*]] = tosa.clamp %arg0 {max_val = 6.000000e+00 : f32, min_val = 0.000000e+00 : f32} +// CHECK-SAME: -> tensor +func.func @test_relu6_dynamic(%arg0: tensor) -> tensor { + %0 = "tfl.relu6"(%arg0) : (tensor) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_leaky_relu +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.707330704> : tensor<1x1x1xf32>}> +// CHECK: %[[VAR1:.*]] = tosa.mul %arg0, %[[VAR0]], %[[SHIFT]] +// CHECK: %[[VAR2:.*]] = tosa.maximum %[[VAR1]], %arg0 : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: return %[[VAR2]] : tensor<13x21x3xf32> +func.func @test_leaky_relu(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.leaky_relu"(%arg0) {alpha = 0.707330704 : f32} : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_prelu +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 2, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg1, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.mul %arg0, %[[VAR1]], %[[SHIFT]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.greater_equal %arg0, %[[VAR0]] +// CHECK: %[[VAR4:.*]] = tosa.select %[[VAR3]], %arg0, %[[VAR2]] +func.func @test_prelu(%arg0: tensor<4x2x3xf32>, %arg1: tensor<2x3xf32>) -> tensor<4x2x3xf32> { + %0 = "tfl.prelu"(%arg0, %arg1) : (tensor<4x2x3xf32>, tensor<2x3xf32>) -> tensor<4x2x3xf32> + func.return %0 : tensor<4x2x3xf32> +} + +// ----- + +// CHECK-LABEL: test_prelu_qu8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1472433039> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<37> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1130006236> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[1, 8, 4, 17]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x1x1x1xi32>}> : () -> tensor<1x1x1x1xi32> +// CHECK: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<"0x1{{.*}}"> : tensor<8x4x17xi8>}> : () -> tensor<8x4x17x!quant.uniform:f32, 0.023982547223567963>> +// CHECK: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<5> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<-123> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_11:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_12:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_13:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_14:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_15:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_11]], %[[VAL_12]], %[[VAL_13]], %[[VAL_14]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_16:.*]] = tosa.rescale %[[VAL_15]], %[[VAL_11]], %[[VAL_12]], %[[VAL_14]], %[[VAL_14]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_17:.*]] = tosa.rescale %[[VAL_16]], %[[VAL_11]], %[[VAL_12]], %[[VAL_14]], %[[VAL_7]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<1x8x4x17xi32> +// CHECK: %[[VAL_18:.*]] = tosa.greater_equal %[[VAL_17]], %[[VAL_6]] : (tensor<1x8x4x17xi32>, tensor<1x1x1x1xi32>) -> tensor<1x8x4x17xi1> +// CHECK: %[[VAL_19:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_11]], %[[VAL_12]], %[[VAL_14]], %[[VAL_7]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<8x4x17x!quant.uniform:f32, 0.023982547223567963>>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<8x4x17xi32> +// CHECK: %[[VAL_20:.*]] = tosa.reshape %[[VAL_19]], %[[VAL_5]] : (tensor<8x4x17xi32>, !tosa.shape<4>) -> tensor<1x8x4x17xi32> +// CHECK: %[[VAL_21:.*]] = tosa.mul %[[VAL_17]], %[[VAL_20]], %[[VAL_14]] : (tensor<1x8x4x17xi32>, tensor<1x8x4x17xi32>, tensor<1xi8>) -> tensor<1x8x4x17xi32> +// CHECK: %[[VAL_22:.*]] = tosa.rescale %[[VAL_21]], %[[VAL_4]], %[[VAL_3]], %[[VAL_7]], %[[VAL_9]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_23:.*]] = tosa.rescale %[[VAL_16]], %[[VAL_2]], %[[VAL_1]], %[[VAL_14]], %[[VAL_9]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_24:.*]] = tosa.select %[[VAL_18]], %[[VAL_23]], %[[VAL_22]] : (tensor<1x8x4x17xi1>, tensor<1x8x4x17x!quant.uniform>, tensor<1x8x4x17x!quant.uniform>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_25:.*]] = tosa.rescale %[[VAL_24]], %[[VAL_11]], %[[VAL_12]], %[[VAL_9]], %[[VAL_9]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_26:.*]] = tosa.rescale %[[VAL_25]], %[[VAL_11]], %[[VAL_12]], %[[VAL_9]], %[[VAL_10]] {input_unsigned = false, output_unsigned = true, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +func.func @test_prelu_qu8(%arg0: tensor<1x8x4x17x!quant.uniform>) -> tensor<1x8x4x17x!quant.uniform> { + %0 = "tfl.quantize"(%arg0) {qtype = tensor<1x8x4x17x!quant.uniform>} : (tensor<1x8x4x17x!quant.uniform>) -> tensor<1x8x4x17x!quant.uniform> + %1 = "tfl.pseudo_qconst"() {qtype = tensor<8x4x17x!quant.uniform:f32, 0.023982547223567963>>, value = dense<"0x191D0557FF212FA1137FDE2B247CE8BA2A8B2213F6B109FA12232EC613FEEE03EF2D265BE5E4F6CB0E09F7F0A95606DA1709EDE632D0F92A2002E98E61F9213997D3FCEBFA0D2DFC4DD00D0700C60C0705F3CFCB01D30C3617C7144C294DAE27061A62E70665021AF50827F40EC9E0172D42B9FB01FB076A09553006F7F710211A031EC9F11BCF130FCC1906D5FED8E5F64E06EAEAFEFD2515F20BB6E3401023C89DFCF8DEC0390B37D8CA2001E1F7BC270ADDE92DFC6D230CE1FEEE1DE8F90ABF9E3ECAEEBC311DF6FDE41F0E31ED0AC309B3121533E7EC2D1B0F1E04D44513E627F4ED5E491D10E53EEA45FF23E31D11D1DE2E0A3B1015AF06102329DEED5C1C180402000B0D071BF0D4FBC0DE0C3BF012E018D80716351D1922F8D508CF2708BA0CEAFE14E4972732FDFD283ED9342A1506F4F137200A12F436D6C9EC071FBCBDEBF4F8051426B8201EC410F9C3C7EFF7CD04D7AC34E2F9D73A5A05CFFA0FF7FD21D6BBEA03F16AF8330C1105285605C9FFE72BE04726DA06F2DCDCDC14C1310CF4E32F06BE0941420B10C9293DD10EFE28D4D20716E6E6EE0A101FFE3AAF1716120EF62FECEBC0F0D72A0903F9E74425EDF82E290E0413BB69F3F45AF30A22D4D024411B4D243BE13FB9CBE0F5FA16A1D7532007AEF62837C42406E3ED3CCE0408CA1C0CFA18B40C0BF7261E06D3E504B8E714BCF6F010DB12373739E200E609E9DAEF1922A2C338FEF2C519F0E5101E2AE917DCA3FA27D245DD10F0EBCE"> : tensor<8x4x17xi8>} : () -> tensor<8x4x17x!quant.uniform:f32, 0.023982547223567963>> + %2 = "tfl.prelu"(%0, %1) : (tensor<1x8x4x17x!quant.uniform>, tensor<8x4x17x!quant.uniform:f32, 0.023982547223567963>>) -> tensor<1x8x4x17x!quant.uniform> + %3 = "tfl.quantize"(%2) {qtype = tensor<1x8x4x17x!quant.uniform>} : (tensor<1x8x4x17x!quant.uniform>) -> tensor<1x8x4x17x!quant.uniform> + func.return %3 : tensor<1x8x4x17x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func.func @test_prelu_qi8( +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1582183328> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<1> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<37> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<1103996759> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[1, 8, 4, 17]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x1x1x1xi32>}> : () -> tensor<1x1x1x1xi32> +// CHECK: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<"0xD{{.*}}"> : tensor<8x4x17xi8>}> : () -> tensor<8x4x17x!quant.uniform:f32, 0.021805247291922569>> +// CHECK: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_11:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_12:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_13:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_9]], %[[VAL_10]], %[[VAL_11]], %[[VAL_12]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<1x8x4x17xi32> +// CHECK: %[[VAL_14:.*]] = tosa.greater_equal %[[VAL_13]], %[[VAL_7]] : (tensor<1x8x4x17xi32>, tensor<1x1x1x1xi32>) -> tensor<1x8x4x17xi1> +// CHECK: %[[VAL_15:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_9]], %[[VAL_10]], %[[VAL_11]], %[[VAL_12]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<8x4x17x!quant.uniform:f32, 0.021805247291922569>>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<8x4x17xi32> +// CHECK: %[[VAL_16:.*]] = tosa.reshape %[[VAL_15]], %[[VAL_6]] : (tensor<8x4x17xi32>, !tosa.shape<4>) -> tensor<1x8x4x17xi32> +// CHECK: %[[VAL_17:.*]] = tosa.mul %[[VAL_13]], %[[VAL_16]], %[[VAL_11]] : (tensor<1x8x4x17xi32>, tensor<1x8x4x17xi32>, tensor<1xi8>) -> tensor<1x8x4x17xi32> +// CHECK: %[[VAL_18:.*]] = tosa.rescale %[[VAL_17]], %[[VAL_5]], %[[VAL_4]], %[[VAL_12]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_19:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_2]], %[[VAL_1]], %[[VAL_11]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x8x4x17x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x8x4x17x!quant.uniform> +// CHECK: %[[VAL_20:.*]] = tosa.select %[[VAL_14]], %[[VAL_19]], %[[VAL_18]] : (tensor<1x8x4x17xi1>, tensor<1x8x4x17x!quant.uniform>, tensor<1x8x4x17x!quant.uniform>) -> tensor<1x8x4x17x!quant.uniform> +func.func @test_prelu_qi8(%arg0: tensor<1x8x4x17x!quant.uniform>) -> tensor<1x8x4x17x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<8x4x17x!quant.uniform:f32, 0.021805247291922569>>, value = dense<"0xDAFDEBC120CBE1E028231F05CF04F52484B2F0AC0041E618200308F820FE308FFCF2E1E02A06D00606FB1044C928D8D811E3FCCE350E25C4DE2B0D00E20AC1E215940D0D12C809290D480FE9E2DB26E31E50F5F4FDD31EFF21C210E717E187144F27C848E820C5D503E31729218D96D2D6D3D9C43BF13014EFCB043631AE4403FE2D4CDF1F16E2D13BA20AE92CEAB7323405F728CF3DF4E9BBFAFEFEE120ECA7FA120609030FF0FCF0E5D40939172EE7E256BADEC5ECFFB32C35F4E936E2F8092FE2E3EFE22B0C02F5EE1D36DE03CBE02FF346081C30ED882AECCAF4E4E3361604EABF133CB6371DDAFCDA4F2D32034A270BF0120A0048131331E50D11CAEB1DEE0ADFC0F12531E8351DD7BDEB2821FF3ECC34F8D42EE4D6FF2AE5FEEDFC3DF7463CED10192CE4B728151827A92E000EE31CF3C5DF193DAC2836181BD916D339E914192B14F0163C58C500BDC6BAEFFB03EC33DA24E7FF0E292CE30504B3070AB5FDE6D7E7CB4CB0D818F90919EAEF5DFDF2DB6C4132DF8EF2E40AF7EA04F1D496F22F2971420FF01D012E2954D5081C0AF2C5E5DED2CCD8C6157416201AFF3A2B29FBDD9EF06340B021F45C322A202DDD86111EBDF44BE9110E29F3FE7FDEDDFB5FDEDBD933E2ED0DD4E21C4BC6FD28E31934C821CE10F61C12740A100F1BE205CC01434BD7E3FB14F01CE0E406710022E464E0F0D8FB3D01C733C9C94017FAC50BE812D202E2B10C04E70AF326CEFD0DE20ABD153D3D14171C34061DE5FC5A"> : tensor<8x4x17xi8>} : () -> tensor<8x4x17x!quant.uniform:f32, 0.021805247291922569>> + %1 = "tfl.prelu"(%arg0, %0) : (tensor<1x8x4x17x!quant.uniform>, tensor<8x4x17x!quant.uniform:f32, 0.021805247291922569>>) -> tensor<1x8x4x17x!quant.uniform> + func.return %1 : tensor<1x8x4x17x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_logical_and +// CHECK: %[[VAR0:.*]] = tosa.logical_and %arg0, %arg1 +func.func @test_logical_and(%arg0: tensor<13x21x3xi1>, %arg1: tensor<13x21x1xi1>) -> tensor<*xi1> { + %0 = "tfl.logical_and"(%arg0, %arg1) : (tensor<13x21x3xi1>, tensor<13x21x1xi1>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_logical_or +// CHECK: %[[VAR0:.*]] = tosa.logical_or %arg0, %arg1 +func.func @test_logical_or(%arg0: tensor<13x1x3xi1>, %arg1: tensor<13x21x3xi1>) -> tensor<*xi1> { + %0 = "tfl.logical_or"(%arg0, %arg1) : (tensor<13x1x3xi1>, tensor<13x21x3xi1>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_bitwise_xor_int8 +// CHECK: %[[VAR0:.*]] = tosa.bitwise_xor %arg0, %arg1 : (tensor<1x11x5xi8>, tensor<29x11x5xi8>) -> tensor<29x11x5xi8> +func.func @test_bitwise_xor_int8(%arg0: tensor<1x11x5xi8>, %arg1: tensor<29x11x5xi8>) -> tensor<29x11x5xi8> { + %0 = "tfl.bitwise_xor"(%arg0, %arg1) : (tensor<1x11x5xi8>, tensor<29x11x5xi8>) -> tensor<29x11x5xi8> + func.return %0 : tensor<29x11x5xi8> +} + +// ----- + +// CHECK-LABEL: test_bitwise_xor_int16 +// CHECK: %[[VAR0:.*]] = tosa.bitwise_xor %arg0, %arg1 : (tensor<1x11x5xi16>, tensor<29x11x5xi16>) -> tensor<29x11x5xi16> +func.func @test_bitwise_xor_int16(%arg0: tensor<1x11x5xi16>, %arg1: tensor<29x11x5xi16>) -> tensor<*xi16> { + %0 = "tfl.bitwise_xor"(%arg0, %arg1) : (tensor<1x11x5xi16>, tensor<29x11x5xi16>) -> tensor<*xi16> + func.return %0 : tensor<*xi16> +} + +// ----- + +// CHECK-LABEL: test_bitwise_xor_int32 +// CHECK: %[[VAR0:.*]] = tosa.bitwise_xor %arg0, %arg1 : (tensor<4x16x1xi32>, tensor<1x16x1xi32>) -> tensor<4x16x1xi32> +func.func @test_bitwise_xor_int32(%arg0: tensor<4x16x1xi32>, %arg1: tensor<1x16x1xi32>) -> tensor<4x16x1xi32> { + %0 = "tfl.bitwise_xor"(%arg0, %arg1) : (tensor<4x16x1xi32>, tensor<1x16x1xi32>) -> tensor<4x16x1xi32> + func.return %0 : tensor<4x16x1xi32> +} + +// ----- + +// CHECK-LABEL: test_logical_not +// CHECK: %[[VAR0:.*]] = tosa.logical_not %arg0 +func.func @test_logical_not(%arg0: tensor<1x21x3xi1>) -> tensor<1x21x3xi1> { + %0 = "tfl.logical_not"(%arg0) : (tensor<1x21x3xi1>) -> tensor<1x21x3xi1> + func.return %0 : tensor<1x21x3xi1> +} + +// ----- + +// CHECK: @test_reduce_sum_axis_out_of_bounds +func.func @test_reduce_sum_axis_out_of_bounds(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %cst = arith.constant dense<1094795585> : tensor<1xi32> + %0 = "tfl.sum"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %0 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_all_axis_1_keep_true +// CHECK-SAME: %[[VAL_0:.+]]: tensor<1x4x8x19xi1> +// CHECK: %[[VAL_1:.*]] = tosa.reduce_all %[[VAL_0]] {axis = 1 : i32} : (tensor<1x4x8x19xi1>) -> tensor<1x1x8x19xi1> +func.func @test_reduce_all_axis_1_keep_true(%arg0: tensor<1x4x8x19xi1>) -> tensor<1x1x8x19xi1> { + %cst = arith.constant dense<1> : tensor<1xi32> + %0 = "tfl.reduce_all"(%arg0, %cst) {keep_dims = true} : (tensor<1x4x8x19xi1>, tensor<1xi32>) -> tensor<1x1x8x19xi1> + func.return %0 : tensor<1x1x8x19xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_all_axis_1_keep_false +// CHECK-SAME: %[[VAL_0:.+]]: tensor<1x4x8x19xi1> +// CHECK-DAG: %[[VAL_10:.+]] = tosa.const_shape {values = dense<[1, 8, 19]> : tensor<3xindex>} +// CHECK: %[[VAL_1:.*]] = tosa.reduce_all %[[VAL_0]] {axis = 1 : i32} : (tensor<1x4x8x19xi1>) -> tensor<1x1x8x19xi1> +// CHECK: %[[VAL_2:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_10]] : (tensor<1x1x8x19xi1>, !tosa.shape<3>) -> tensor<1x8x19xi1> +func.func @test_reduce_all_axis_1_keep_false(%arg0: tensor<1x4x8x19xi1>) -> tensor<1x8x19xi1> { + %cst = arith.constant dense<1> : tensor<1xi32> + %0 = "tfl.reduce_all"(%arg0, %cst) {keep_dims = false} : (tensor<1x4x8x19xi1>, tensor<1xi32>) -> tensor<1x8x19xi1> + func.return %0 : tensor<1x8x19xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_all_axis_2_keep_true +// CHECK-SAME: %[[VAL_0:.+]]: tensor<1x4x8x19xi1> +// CHECK: %[[VAL_1:.*]] = tosa.reduce_all %[[VAL_0]] {axis = 2 : i32} : (tensor<1x4x8x19xi1>) -> tensor<1x4x1x19xi1> +func.func @test_reduce_all_axis_2_keep_true(%arg0: tensor<1x4x8x19xi1>) -> tensor<1x4x1x19xi1> { + %cst = arith.constant dense<2> : tensor<1xi32> + %0 = "tfl.reduce_all"(%arg0, %cst) {keep_dims = true} : (tensor<1x4x8x19xi1>, tensor<1xi32>) -> tensor<1x4x1x19xi1> + func.return %0 : tensor<1x4x1x19xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_all_axis_2_keep_false +// CHECK-SAME: %[[VAL_0:.+]]: tensor<1x4x8x19xi1> +// CHECK: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 4, 19]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_1:.*]] = tosa.reduce_all %[[VAL_0]] {axis = 2 : i32} : (tensor<1x4x8x19xi1>) -> tensor<1x4x1x19xi1> +// CHECK: %[[VAL_2:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_10]] : (tensor<1x4x1x19xi1>, !tosa.shape<3>) -> tensor<1x4x19xi1> +func.func @test_reduce_all_axis_2_keep_false(%arg0: tensor<1x4x8x19xi1>) -> tensor<1x4x19xi1> { + %cst = arith.constant dense<2> : tensor<1xi32> + %0 = "tfl.reduce_all"(%arg0, %cst) {keep_dims = false} : (tensor<1x4x8x19xi1>, tensor<1xi32>) -> tensor<1x4x19xi1> + func.return %0 : tensor<1x4x19xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_any +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_any %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_any(%arg0: tensor<13x21x3xi1>) -> tensor<21x3xi1> { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.reduce_any"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xi1>, tensor<1xi32>) -> tensor<21x3xi1> + func.return %0 : tensor<21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_reduce_any_dynamic_output +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_any %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_any_dynamic_output(%arg0: tensor<13x21x3xi1>) -> tensor { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.reduce_any"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xi1>, tensor<1xi32>) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_reduce_min +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_min %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_min(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.reduce_min"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %0 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_max +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_max %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_max(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.reduce_max"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %0 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_sum +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_sum %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_sum(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.sum"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %0 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_sum_nonzero_axis +// CHECK-SAME: %[[VAL_0:.*]]: tensor<10x20x30x40x50xf32> +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[10, 20, 30, 50]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.reduce_sum %[[VAL_0]] {axis = 3 : i32} : (tensor<10x20x30x40x50xf32>) -> tensor<10x20x30x1x50xf32> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.reshape %[[VAL_2]], %[[VAL_1]] : (tensor<10x20x30x1x50xf32>, !tosa.shape<4>) -> tensor<10x20x30x50xf32> +// CHECK: return %[[VAL_3]] : tensor<10x20x30x50xf32> +func.func @test_reduce_sum_nonzero_axis(%arg0: tensor<10x20x30x40x50xf32> {tf._user_specified_name = "inp_list"}) -> tensor<10x20x30x50xf32> { + %cst = arith.constant dense<3> : tensor + %0 = "tfl.sum"(%arg0, %cst) {device = "", keep_dims = false} : (tensor<10x20x30x40x50xf32>, tensor) -> tensor<10x20x30x50xf32> + func.return %0 : tensor<10x20x30x50xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_sum_5D +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[6, 8]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %arg0 {axis = 0 : i32} : (tensor<4x5x6x7x8xf32>) -> tensor<1x5x6x7x8xf32> +// CHECK-DAG: %[[VAR2:.*]] = tosa.reduce_sum %[[VAR1]] {axis = 1 : i32} : (tensor<1x5x6x7x8xf32>) -> tensor<1x1x6x7x8xf32> +// CHECK-DAG: %[[VAR3:.*]] = tosa.reduce_sum %[[VAR2]] {axis = 3 : i32} : (tensor<1x1x6x7x8xf32>) -> tensor<1x1x6x1x8xf32> +// CHECK-DAG: %[[VAR4:.*]] = tosa.reshape %[[VAR3]], %[[VAR0]] : (tensor<1x1x6x1x8xf32>, !tosa.shape<2>) -> tensor<6x8xf32> +// CHECK: return %[[VAR4]] +func.func @test_reduce_sum_5D(%arg0: tensor<4x5x6x7x8xf32>) -> tensor<6x8xf32> { + %cst = arith.constant dense<[0, 1, 3]> : tensor<3xi32> + %0 = "tfl.sum"(%arg0, %cst) {keep_dims = false} : (tensor<4x5x6x7x8xf32>, tensor<3xi32>) -> tensor<6x8xf32> + func.return %0 : tensor<6x8xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_mean +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.0769230798> : tensor<1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR10]] +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR4:.*]] = tosa.mul %[[VAR2]], %[[VAR0]], %[[SHIFT]] +func.func @test_reduce_mean(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.mean"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %0 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_mean_dynamic_output +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<0.0769230798> : tensor<1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR2:.*]] = tosa.reshape %[[VAR1]], %[[VAR10]] +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR4:.*]] = tosa.mul %[[VAR2]], %[[VAR0]], %[[SHIFT]] +func.func @test_reduce_mean_dynamic_output(%arg0: tensor<13x21x3xf32>) -> tensor { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.mean"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_reduce_mean_out_of_bounds +// CHECK: "tfl.mean" +func.func @test_reduce_mean_out_of_bounds(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<123> : tensor<1xi32> + %0 = "tfl.mean"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_reduce_mean_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x2x2x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<31> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1105078632> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_7:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_3]], %[[VAL_4]], %[[VAL_5]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x2x2x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<1x2x2xi32> +// CHECK: %[[VAL_8:.*]] = tosa.reduce_sum %[[VAL_7]] {axis = 2 : i32} : (tensor<1x2x2xi32>) -> tensor<1x2x1xi32> +// CHECK: %[[VAL_9:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_2]], %[[VAL_1]], %[[VAL_6]], %[[VAL_5]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x2x1xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x2x1x!quant.uniform> +func.func @test_reduce_mean_qi8(%arg0: tensor<1x2x2x!quant.uniform>) -> (tensor<1x2x1x!quant.uniform>) { +%0 = "tfl.pseudo_const"() {value = dense<-1> : tensor} : () -> tensor +%1 = "tfl.mean"(%arg0, %0) {keep_dims = true} : (tensor<1x2x2x!quant.uniform>, tensor) -> tensor<1x2x1x!quant.uniform> +return %1 : tensor<1x2x1x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_reduce_product +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_product %arg0 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[21, 3]> : tensor<2xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_reduce_product(%arg0: tensor<13x21x3xf32>) -> tensor<21x3xf32> { + %cst = arith.constant dense<0> : tensor<1xi32> + %0 = "tfl.reduce_prod"(%arg0, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<1xi32>) -> tensor<21x3xf32> + func.return %0 : tensor<21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_min +// CHECK: %[[VAR0:.*]] = tosa.minimum %arg0, %arg1 +func.func @test_min(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.minimum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_max +// CHECK: %[[VAR0:.*]] = tosa.maximum %arg0, %arg1 +func.func @test_max(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x1xf32>) -> tensor<*xf32> { + %0 = "tfl.maximum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x21x1xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_max_dynamic +// CHECK: %[[VAR0:.*]] = tosa.maximum %arg0, %arg1 +// CHECK-SAME: -> tensor<13x21x?xf32> +func.func @test_max_dynamic(%arg0: tensor<13x1x?xf32>, %arg1: tensor<13x21x1xf32>) -> tensor { + %0 = "tfl.maximum"(%arg0, %arg1) : (tensor<13x1x?xf32>, tensor<13x21x1xf32>) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_pow +// CHECK: %[[VAR0:.*]] = tosa.pow %arg0, %arg1 +func.func @test_pow(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x1xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.pow"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x21x1xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_pow_dynamic +// CHECK: %[[VAR0:.*]] = tosa.pow %arg0, %arg1 +// CHECK-SAME: -> tensor<13x21x3xf32> +func.func @test_pow_dynamic(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x1xf32>) -> tensor<*xf32> { + %0 = "tfl.pow"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x21x1xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_abs +// CHECK: %[[VAR0:.*]] = tosa.abs %arg0 +func.func @test_abs(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.abs"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_ceil +// CHECK: %[[VAR0:.*]] = tosa.ceil %arg0 +func.func @test_ceil(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.ceil"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_floor +// CHECK: %[[VAR0:.*]] = tosa.floor %arg0 +func.func @test_floor(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.floor"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_log +// CHECK: %[[VAR0:.*]] = tosa.log %arg0 +func.func @test_log(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.log"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_log_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.+}}> : tensor<256xi8>}> +// CHECK: %[[VAL_2:.*]] = tosa.table %[[VAL_0]], %[[VAL_1]] +func.func @test_log_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> (tensor<13x21x3x!quant.uniform>) { + %0 = "tfl.log"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_log_qi16 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.+}}> : tensor<513xi16>}> +// CHECK: %[[VAL_2:.*]] = tosa.table %[[VAL_0]], %[[VAL_1]] +func.func @test_log_qi16(%arg0: tensor<13x21x3x!quant.uniform>) -> (tensor<13x21x3x!quant.uniform>) { + %0 = "tfl.log"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_negate +// CHECK-DAG: %[[CONST_0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK-DAG: %[[VAR0:.*]] = tosa.negate %arg0, %[[CONST_0]], %[[CONST_0]] +func.func @test_negate(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.neg"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_rsqrt +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3xf32> +// CHECK: %[[VAL_1:.*]] = tosa.rsqrt %[[VAL_0]] : (tensor<13x21x3xf32> +func.func @test_rsqrt(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.rsqrt"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_rsqrt_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.+}}> : tensor<256xi8>}> +// CHECK: %[[VAL_2:.*]] = tosa.table %[[VAL_0]], %[[VAL_1]] +func.func @test_rsqrt_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> (tensor<13x21x3x!quant.uniform>) { + %0 = "tfl.rsqrt"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_sign +// CHECK-SAME: %[[VAL_0:.*]]: tensor<21x45xi32> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<1> : tensor<1x1xi32>}> +// CHECK: %[[VAL_4:.*]] = tosa.greater %[[VAL_0]], %[[VAL_1]] +// CHECK: %[[VAL_5:.*]] = tosa.greater %[[VAL_1]], %[[VAL_0]] +// CHECK: %[[VAL_6:.*]] = tosa.select %[[VAL_5]], %[[VAL_2]], %[[VAL_1]] +// CHECK: %[[VAL_7:.*]] = tosa.select %[[VAL_4]], %[[VAL_3]], %[[VAL_6]] +func.func @test_sign(%arg0: tensor<21x45xi32>) -> tensor<21x45xi32> { + %0 = "tfl.sign"(%arg0) : (tensor<21x45xi32>) -> tensor<21x45xi32> + func.return %0 : tensor<21x45xi32> +} + +// ----- + +// CHECK-LABEL: test_sin +// CHECK-SAME: %[[VAL_0:.*]]: tensor<10xf32> +// CHECK: %[[VAL_1:.*]] = tosa.sin %[[VAL_0]] : (tensor<10xf32> +func.func @test_sin(%arg0: tensor<10xf32>) -> tensor<*xf32> { + %0 = "tfl.sin"(%arg0) : (tensor<10xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_cos +// CHECK-SAME: %[[VAL_0:.*]]: tensor<10xf32> +// CHECK: %[[VAL_1:.*]] = tosa.cos %[[VAL_0]] : (tensor<10xf32> +func.func @test_cos(%arg0: tensor<10xf32>) -> tensor<*xf32> { + %0 = "tfl.cos"(%arg0) : (tensor<10xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_atan2 +// CHECK-SAME: -> tensor<13x21x3xf32> +// CHECK-DAG: %[[CONST_0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<2.000000e+00> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<3.276700e+04> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<2.38418579E-7> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<1.57079637> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<3.14159274> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x1x1xf32>}> : () -> tensor<1x1x1xf32> +// CHECK-DAG: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<{{.+}}> : tensor<513xi16>}> : () -> tensor<513xi16> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAL_10:.*]] = tosa.abs %arg0 : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_11:.*]] = tosa.abs %arg1 : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_12:.*]] = tosa.minimum %[[VAL_10]], %[[VAL_11]] : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_13:.*]] = tosa.maximum %[[VAL_10]], %[[VAL_11]] : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_14:.*]] = tosa.reciprocal %[[VAL_13]] : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_15:.*]] = tosa.mul %[[VAL_14]], %[[VAL_12]], %[[SHIFT]] : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<1xi8>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_16:.*]] = tosa.mul %[[VAL_15]], %[[VAL_2]], %[[SHIFT]] : (tensor<13x21x3xf32>, tensor<1x1x1xf32>, tensor<1xi8>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_17:.*]] = tosa.sub %[[VAL_16]], %[[VAL_3]] : (tensor<13x21x3xf32>, tensor<1x1x1xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_18:.*]] = tosa.mul %[[VAL_17]], %[[VAL_4]], %[[SHIFT]] : (tensor<13x21x3xf32>, tensor<1x1x1xf32>, tensor<1xi8>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_19:.*]] = tosa.cast %[[VAL_18]] : (tensor<13x21x3xf32>) -> tensor<13x21x3xi16> +// CHECK: %[[VAL_20:.*]] = tosa.table %[[VAL_19]], %[[VAL_9]] : (tensor<13x21x3xi16>, tensor<513xi16>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_21:.*]] = tosa.cast %[[VAL_20]] : (tensor<13x21x3xi32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_22:.*]] = tosa.mul %[[VAL_21]], %[[VAL_5]], %[[SHIFT]] : (tensor<13x21x3xf32>, tensor<1x1x1xf32>, tensor<1xi8>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_23:.*]] = tosa.sub %[[VAL_6]], %[[VAL_22]] : (tensor<1x1x1xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_24:.*]] = tosa.greater %[[VAL_10]], %[[VAL_11]] : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_25:.*]] = tosa.select %[[VAL_24]], %[[VAL_23]], %[[VAL_22]] : (tensor<13x21x3xi1>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_26:.*]] = tosa.sub %[[VAL_7]], %[[VAL_25]] : (tensor<1x1x1xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_27:.*]] = tosa.greater %[[VAL_8]], %arg1 : (tensor<1x1x1xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_28:.*]] = tosa.select %[[VAL_27]], %[[VAL_26]], %[[VAL_25]] : (tensor<13x21x3xi1>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_29:.*]] = tosa.negate %[[VAL_28]], %[[CONST_0]], %[[CONST_0]] : (tensor<13x21x3xf32>, tensor<1xf32>, tensor<1xf32>) -> tensor<13x21x3xf32> +// CHECK: %[[VAL_30:.*]] = tosa.greater %[[VAL_8]], %arg0 : (tensor<1x1x1xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xi1> +// CHECK: %[[VAL_31:.*]] = tosa.select %[[VAL_30]], %[[VAL_29]], %[[VAL_28]] : (tensor<13x21x3xi1>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> +// CHECK: return %[[VAL_31]] : tensor<13x21x3xf32> +func.func @test_atan2(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.atan2"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + + +// CHECK-LABEL: test_sigmoid +// CHECK: %[[VAR0:.*]] = tosa.sigmoid %arg0 +func.func @test_sigmoid(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.logistic"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_square +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR0:.*]] = tosa.mul %arg0, %arg0, %[[SHIFT]] +func.func @test_square(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.square"(%arg0) : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_equal +// CHECK: %[[VAR0:.*]] = tosa.equal %arg0, %arg1 +func.func @test_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x1x3xf32>) -> tensor<*xi1> { + %0 = "tfl.equal"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<13x1x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_greater_equal +// CHECK: %[[VAR0:.*]] = tosa.greater_equal %arg0, %arg1 +func.func @test_greater_equal(%arg0: tensor<13x1x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<*xi1> { + %0 = "tfl.greater_equal"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<13x21x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_greater +// CHECK: %[[VAR0:.*]] = tosa.greater %arg0, %arg1 +func.func @test_greater(%arg0: tensor<13x21x1xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<*xi1> { + %0 = "tfl.greater"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<13x21x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_less +// CHECK: %[[VAR0:.*]] = tosa.greater %arg1, %arg0 +func.func @test_less(%arg0: tensor<13x1x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<*xi1> { + %0 = "tfl.less"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<13x21x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_less_dynamic +// CHECK: %[[VAR0:.*]] = tosa.greater %arg1, %arg0 +// CHECK-SAME: -> tensor<13x?x3xi1> +func.func @test_less_dynamic(%arg0: tensor<13x1x3xf32>, %arg1: tensor<13x?x3xf32>) -> tensor<*xi1> { + %0 = "tfl.less"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<13x?x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_less_equal +// CHECK: %[[VAR0:.*]] = tosa.greater_equal %arg1, %arg0 +func.func @test_less_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x21x3xf32>) -> tensor<*xi1> { + %0 = "tfl.less_equal"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x21x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_less_equal_dynamic +// CHECK: %[[VAR0:.*]] = tosa.greater_equal %arg1, %arg0 +// CHECK-SAME: -> tensor<13x?x3xi1> +func.func @test_less_equal_dynamic(%arg0: tensor<13x1x3xf32>, %arg1: tensor<13x?x3xf32>) -> tensor<*xi1> { + %0 = "tfl.less_equal"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<13x?x3xf32>) -> tensor<*xi1> + func.return %0 : tensor<*xi1> +} + +// ----- + +// CHECK-LABEL: test_avg_pool2d +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAR0:.*]] = tosa.avg_pool2d %arg0, %[[ZP]], %[[ZP]] {acc_type = f32, kernel = array, pad = array, stride = array} +func.func @test_avg_pool2d(%arg0: tensor<1x32x32x8xf32>) -> tensor<*xf32> { + %0 = "tfl.average_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_avg_pool2d_dynamic +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAR0:.*]] = tosa.avg_pool2d %arg0, %[[ZP]], %[[ZP]] {acc_type = f32, kernel = array, pad = array, stride = array} +func.func @test_avg_pool2d_dynamic(%arg0: tensor) -> tensor<*xf32> { + %0 = "tfl.average_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_avg_pool2d_slicing +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[1, 31, 31, 8]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<1x32x32x8xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x31x31x8xf32> +// CHECK: %[[VAL_4:.*]] = tosa.avg_pool2d %[[VAL_3]], %[[ZP]], %[[ZP]] {acc_type = f32, kernel = array, pad = array, stride = array} : (tensor<1x31x31x8xf32>, tensor<1xf32>, tensor<1xf32>) -> tensor<1x15x15x8xf32> +func.func @test_avg_pool2d_slicing(%arg0: tensor<1x32x32x8xf32>) -> tensor<*xf32> { + %0 = "tfl.average_pool_2d"(%arg0) {filter_height = 3 : i32, filter_width = 3 : i32, fused_activation_function = "NONE", padding = "VALID", stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x32x32x8xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_max_pool2d +// CHECK: %[[VAR0:.*]] = tosa.max_pool2d %arg0 {kernel = array, pad = array, stride = array} +func.func @test_max_pool2d(%arg0: tensor<1x32x32x8xf32>) -> tensor<*xf32> { + %0 = "tfl.max_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_max_pool2d_dynamic +// CHECK: %[[VAR0:.*]] = tosa.max_pool2d %arg0 {kernel = array, pad = array, stride = array} +func.func @test_max_pool2d_dynamic(%arg0: tensor) -> tensor<*xf32> { + %0 = "tfl.max_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_max_pool2d_slicing +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[1, 31, 31, 8]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_3:.*]] = tosa.slice %[[VAL_0]], %[[VAL_2]], %[[VAL_1]] : (tensor<1x32x32x8xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x31x31x8xf32> +// CHECK: %[[VAL_4:.*]] = tosa.max_pool2d %[[VAL_3]] {kernel = array, pad = array, stride = array} : (tensor<1x31x31x8xf32>) -> tensor<1x15x15x8xf32> +func.func @test_max_pool2d_slicing(%arg0: tensor<1x32x32x8xf32>) -> tensor<*xf32> { + %0 = "tfl.max_pool_2d"(%arg0) {filter_height = 3 : i32, filter_width = 3 : i32, fused_activation_function = "NONE", padding = "VALID", stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x32x32x8xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- +// CHECK-LABEL: max_pool_same_padding_static_dims +// CHECK-NOT: tfl.max_pool_2d +// CHECK: tosa.max_pool2d +func.func @max_pool_same_padding_static_dims(%arg0: tensor) -> (tensor) { +%0 = "tfl.max_pool_2d"(%arg0) <{filter_height = 1 : i32, filter_width = 4 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 4 : i32}> : (tensor) -> tensor +return %0 : tensor +} + +// ----- +// CHECK-LABEL: max_pool_same_padding_unit_stride_dynamic_dims +// CHECK-NOT: tfl.max_pool_2d +// CHECK: tosa.max_pool2d +func.func @max_pool_same_padding_unit_stride_dynamic_dims(%arg0: tensor) -> (tensor) { +%0 = "tfl.max_pool_2d"(%arg0) <{filter_height = 1 : i32, filter_width = 4 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32}> : (tensor) -> tensor +return %0 : tensor +} + + +// ----- + +// CHECK-LABEL: test_reshape +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 819]> : tensor<2xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +func.func @test_reshape(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[1, 819]> : tensor<2xi32> + %0 = "tfl.reshape"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor<2xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_reshape_unknown +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[9, 91]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-SAME: -> tensor<9x91xf32> +func.func @test_reshape_unknown(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[9, -1]> : tensor<2xi32> + %0 = "tfl.reshape"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor<2xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_reshape_dynamic +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[3, -1]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-SAME: -> tensor<3x?xf32> +func.func @test_reshape_dynamic(%arg0: tensor<13x21x?xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[3, -1]> : tensor<2xi32> + %0 = "tfl.reshape"(%arg0, %cst) : (tensor<13x21x?xf32>, tensor<2xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_reshape_dynamic_ranked_output +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, -1, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +func.func @test_reshape_dynamic_ranked_output(%arg0: tensor) -> tensor<1x?x2xf32> { + %cst = arith.constant dense<[1, -1, 2]> : tensor<3xi32> + %0 = "tfl.reshape"(%arg0, %cst) : (tensor, tensor<3xi32>) -> tensor<1x?x2xf32> + func.return %0 : tensor<1x?x2xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose +// CHECK: %[[VAR1:.*]] = tosa.transpose %arg0 {perms = array} +func.func @test_transpose(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[2, 0, 1]> : tensor<3xi32> + %0 = "tfl.transpose"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose_dynamic +// CHECK: %[[VAR1:.*]] = tosa.transpose %arg0 {perms = array} +func.func @test_transpose_dynamic(%arg0: tensor<13x?x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[2, 0, 1]> : tensor<3xi32> + %0 = "tfl.transpose"(%arg0, %cst) : (tensor<13x?x3xf32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_slice +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[4, 11, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[6, 8, 0]> : tensor<3xindex>} +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<4x11x1xf32> +func.func @test_slice(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[6, 8, 0]> : tensor<3xi32> + %cst_0 = arith.constant dense<[4, 11, 1]> : tensor<3xi32> + %0 = "tfl.slice"(%arg0, %cst, %cst_0) : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_slice_minus1_size +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[4, 13, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[6, 8, 0]> : tensor<3xindex>} +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<4x13x1xf32> +func.func @test_slice_minus1_size(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[6, 8, 0]> : tensor<3xi32> + %cst_0 = arith.constant dense<[4, -1, 1]> : tensor<3xi32> + %0 = "tfl.slice"(%arg0, %cst, %cst_0) : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_simple +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[9, 7, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[9, 7, 1, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[9, 7, 3, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[9, 21, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_6]], %[[VAL_5]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<9x21x2xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_4]] : (tensor<9x21x2xf32>, !tosa.shape<4>) -> tensor<9x7x3x2xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_2]], %[[VAL_3]] : (tensor<9x7x3x2xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<9x7x1x2xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<9x7x1x2xf32>, !tosa.shape<3>) -> tensor<9x7x2xf32> +func.func @test_strided_slice_simple(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0, 1]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, 21, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, 3, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_simple_negative +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[9, 18, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[9, 6, 3, 2]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[9, 6, 1, 2]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[9, 6, 2]> : tensor<3xindex>} +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_3]] +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_5]], %[[VAL_4]] +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_6]] +func.func @test_strided_slice_simple_negative(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0, 1]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, -3, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, 3, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 1 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_strideless +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[9, 2]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[9, 1, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_4:.*]] = tosa.slice %arg0, %[[VAL_3]], %[[VAL_2]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<9x1x2xf32> +// CHECK: %[[VAL_5:.*]] = tosa.reshape %[[VAL_4]], %[[VAL_1]] : (tensor<9x1x2xf32>, !tosa.shape<2>) -> tensor<9x2xf32> +func.func @test_strided_slice_strideless(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0, 1]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, 21, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, 1, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 2 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_shrink +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<7> : tensor<1xindex>} : () -> !tosa.shape<1> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 7, 1, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[1, 7, 3, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[1, 21, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_6]], %[[VAL_5]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<1x21x1xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_4]] : (tensor<1x21x1xf32>, !tosa.shape<4>) -> tensor<1x7x3x1xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_2]], %[[VAL_3]] : (tensor<1x7x3x1xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x7x1x1xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<1x7x1x1xf32>, !tosa.shape<1>) -> tensor<7xf32> +func.func @test_strided_slice_shrink(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0, 1]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, 21, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, 3, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 5 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_shrink_ignore_stride +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[1, 1, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<2> : tensor<1xindex>} +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<1x1x2xf32> +// CHECK: %[[VAL_4:.*]] = tosa.reshape %[[VAL_3]], %[[CONST0]] : (tensor<1x1x2xf32>, !tosa.shape<1>) -> tensor<2xf32> +func.func @test_strided_slice_shrink_ignore_stride(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0, 1]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, 21, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, 3, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 3 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_unstrided +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[9, 21, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[4, 0, 1]> : tensor<3xindex>} +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<9x21x2xf32> +// CHECK: %[[VAL_4:.*]] = tosa.reverse %[[VAL_3]] {axis = 2 : i32} : (tensor<9x21x2xf32>) -> tensor<9x21x2xf32> +func.func @test_strided_slice_unstrided(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0, 1]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, 21, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, 1, -1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_unstrided_shorter +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[9, 21, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[4, 0, 0]> : tensor<3xindex>} +// CHECK: %[[VAL_3:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<9x21x3xf32> +// CHECK: %[[VAL_4:.*]] = tosa.reverse %[[VAL_3]] {axis = 1 : i32} : (tensor<9x21x3xf32>) -> tensor<9x21x3xf32> +func.func @test_strided_slice_unstrided_shorter(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[4, 0]> : tensor<2xi32> + %cst_0 = arith.constant dense<[13, 21]> : tensor<2xi32> + %cst_1 = arith.constant dense<[1, -1]> : tensor<2xi32> + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<13x21x3xf32>, tensor<2xi32>, tensor<2xi32>, tensor<2xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_dynamic_masked +// CHECK-SAME: -> tensor<10x?x?xf32> +// CHECK: %[[VAR0:.*]] = tosa.reverse %arg0 {axis = 1 : i32} +// CHECK: %[[VAR1:.*]] = tosa.reverse %[[VAR0]] {axis = 2 : i32} +// CHECK: return %[[VAR1]] +func.func @test_strided_slice_dynamic_masked(%arg0: tensor<10x?x?xf32>, %arg1: tensor<3xi32>) -> tensor<*xf32> { + %cst_0 = arith.constant dense<[13, -1, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, -1, -1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %arg1, %cst_0, %cst_1) {begin_mask = 7 : i32, ellipsis_mask = 0 : i32, end_mask = 7 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<10x?x?xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// Its possible that the begin mask is not set but the begin index is 0, which +// is equivalent to being at the beginning. However as we are bypassing the +// entire operation the operand type may not match and will need to be cast to +// the result type. These casts can be removed during shape inference. +// CHECK-LABEL: test_strided_slice_dynamic_begin +// CHECK-SAME: tensor<10x?x?xf32> +func.func @test_strided_slice_dynamic_begin(%arg0: tensor<10x?x?xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[0, 2, 0]> : tensor<3xi32> + %cst_0 = arith.constant dense<[13, -1, 3]> : tensor<3xi32> + %cst_1 = arith.constant dense<[1, -1, -1]> : tensor<3xi32> + // CHECK: %[[VAR0:.*]] = tosa.reverse %arg0 {axis = 1 : i32} + // CHECK: %[[VAR1:.*]] = tosa.reverse %[[VAR0]] {axis = 2 : i32} + // CHECK: return %[[VAR1]] + %0 = "tfl.strided_slice"(%arg0, %cst, %cst_0, %cst_1) {begin_mask = 2 : i32, ellipsis_mask = 0 : i32, end_mask = 7 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<10x?x?xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_dynamic_end +// CHECK-SAME: 10x?x?xf32> +func.func @test_strided_slice_dynamic_end(%arg0: tensor<10x?x?xf32>) -> tensor<*xf32> { + %begin = arith.constant dense<[0, 1, 2]> : tensor<3xi32> + %end = arith.constant dense<[7, -1, 6]> : tensor<3xi32> + %stride = arith.constant dense<[1, 2, -1]> : tensor<3xi32> + + // CHECK-DAG: %[[CONST0:.+]] = tosa.const_shape {values = dense<[7, -1, 2, 1]> : tensor<4xindex>} + // CHECK-DAG: %[[CONST1:.+]] = tosa.const_shape {values = dense<[7, -1]> : tensor<2xindex>} + // CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} + // CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[7, -1, 1, 1]> : tensor<4xindex>} + // CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[7, -1, 1]> : tensor<3xindex>} + // CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[0, 1, 2]> : tensor<3xindex>} + // CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<10x?x?xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<7x?x1xf32> + // CHECK: %[[VAL_6:.*]] = tosa.reshape %[[VAL_5]], %[[CONST0]] + // CHECK: %[[VAL_7:.*]] = tosa.slice %[[VAL_6]], %[[VAL_1]], %[[VAL_2]] : (tensor<7x?x2x1xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<7x?x1x1xf32> + // CHECK: %[[RESHAPE2:.*]] = tosa.reshape %[[VAL_7]], %[[CONST1]] + %0 = "tfl.strided_slice"(%arg0, %begin, %end, %stride) {begin_mask = 0 : i32, ellipsis_mask = 0 : i32, end_mask = 2 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 4 : i32, offset = false} : (tensor<10x?x?xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + // CHECK: return %[[RESHAPE2]] + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_padding_even +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[4, 4, 64]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[4, 1, 4, 1, 64]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[4, 2, 4, 2, 64]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[0, 1, 0, 1, 0, 0]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAL_7:.*]] = tosa.pad %arg0, %[[VAL_5]], %[[VAL_6]] : (tensor<7x7x64xf32>, !tosa.shape<6>, tensor<1xf32>) -> tensor<8x8x64xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_4]] : (tensor<8x8x64xf32>, !tosa.shape<5>) -> tensor<4x2x4x2x64xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_2]], %[[VAL_3]] : (tensor<4x2x4x2x64xf32>, !tosa.shape<5>, !tosa.shape<5>) -> tensor<4x1x4x1x64xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<4x1x4x1x64xf32>, !tosa.shape<3>) -> tensor<4x4x64xf32> +func.func @test_strided_slice_padding_even(%arg0: tensor<7x7x64xf32>) -> tensor<*xf32> { + %begin = arith.constant dense<[0, 0, 0]> : tensor<3xi32> + %end = arith.constant dense<[0, 0, 64]> : tensor<3xi32> + %stride = arith.constant dense<[2, 2, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %begin, %end, %stride) {begin_mask = 15 : i32, ellipsis_mask = 0 : i32, end_mask = 15 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<7x7x64xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_padding_odd +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[5, 5, 32]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[5, 1, 5, 1, 32]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[5, 3, 5, 3, 32]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[0, 1, 0, 1, 0, 0]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAL_7:.*]] = tosa.pad %arg0, %[[VAL_5]], %[[VAL_6]] : (tensor<14x14x32xf32>, !tosa.shape<6>, tensor<1xf32>) -> tensor<15x15x32xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_4]] : (tensor<15x15x32xf32>, !tosa.shape<5>) -> tensor<5x3x5x3x32xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_2]], %[[VAL_3]] : (tensor<5x3x5x3x32xf32>, !tosa.shape<5>, !tosa.shape<5>) -> tensor<5x1x5x1x32xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<5x1x5x1x32xf32>, !tosa.shape<3>) -> tensor<5x5x32xf32> +func.func @test_strided_slice_padding_odd(%arg0: tensor<14x14x32xf32>) -> tensor<*xf32> { + %begin = arith.constant dense<[0, 0, 0]> : tensor<3xi32> + %end = arith.constant dense<[0, 0, 32]> : tensor<3xi32> + %stride = arith.constant dense<[3, 3, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %begin, %end, %stride) {begin_mask = 0 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<14x14x32xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_strided_slice_padding_pad_greater_than_1 +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[5, 5, 32]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[5, 1, 5, 1, 32]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[5, 3, 5, 3, 32]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[0, 2, 0, 2, 0, 0]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAL_7:.*]] = tosa.pad %arg0, %[[VAL_5]], %[[VAL_6]] : (tensor<13x13x32xf32>, !tosa.shape<6>, tensor<1xf32>) -> tensor<15x15x32xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_4]] : (tensor<15x15x32xf32>, !tosa.shape<5>) -> tensor<5x3x5x3x32xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_2]], %[[VAL_3]] : (tensor<5x3x5x3x32xf32>, !tosa.shape<5>, !tosa.shape<5>) -> tensor<5x1x5x1x32xf32> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<5x1x5x1x32xf32>, !tosa.shape<3>) -> tensor<5x5x32xf32> +func.func @test_strided_slice_padding_pad_greater_than_1(%arg0: tensor<13x13x32xf32>) -> tensor<*xf32> { + %begin = arith.constant dense<[0, 0, 0]> : tensor<3xi32> + %end = arith.constant dense<[0, 0, 32]> : tensor<3xi32> + %stride = arith.constant dense<[3, 3, 1]> : tensor<3xi32> + %0 = "tfl.strided_slice"(%arg0, %begin, %end, %stride) {begin_mask = 0 : i32, ellipsis_mask = 0 : i32, end_mask = 3 : i32, new_axis_mask = 0 : i32, shrink_axis_mask = 0 : i32, offset = false} : (tensor<13x13x32xf32>, tensor<3xi32>, tensor<3xi32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_select +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<1> : tensor<3xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %arg2, %[[VAR0]] : (tensor<1xi1>, !tosa.shape<3>) -> tensor<1x1x1xi1> +// CHECK: %[[VAR2:.*]] = tosa.select %[[VAR1]], %arg0, %arg1 +func.func @test_select(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<1xi1>) -> tensor<13x21x3xf32> { + %0 = "tfl.select_v2"(%arg2, %arg0, %arg1) : (tensor<1xi1>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_select_with_unranked +func.func @test_select_with_unranked(%arg0: tensor, %arg1: tensor, %arg2: tensor) -> tensor<*xf32> { + // CHECK: tosa.select + // CHECK-SAME: (tensor, tensor, tensor) -> tensor + %57 = "tfl.select"(%arg0, %arg1, %arg2) : (tensor, tensor, tensor) -> tensor<*xf32> + return %57 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_addn +// CHECK-DAG: %[[VAR0:.*]] = tosa.add %arg0, %arg1 +// CHECK-DAG: %[[VAR1:.*]] = tosa.add %arg2, %[[VAR0]] +// CHECK: %[[VAR2:.*]] = tosa.add %arg3, %[[VAR1]] +func.func @test_addn(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<*xf32> { + %0 = "tfl.add_n"(%arg0, %arg1, %arg2, %arg3) : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_concatv2 +// CHECK: %[[VAR0:.*]] = tosa.concat %arg0, %arg1, %arg2, %arg3 {axis = 0 : i32} +func.func @test_concatv2(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<52x21x3xf32> { + %0 = "tfl.concatenation"(%arg0, %arg1, %arg2, %arg3) {axis = 0 : i32, fused_activation_function = "NONE"} : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<52x21x3xf32> + func.return %0 : tensor<52x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_pack +// CHECK-DAG: %[[VAR0:.*]] = tosa.concat %arg0, %arg1, %arg2, %arg3 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[4, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_pack(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<4x13x21x3xf32> { + %0 = "tfl.pack"(%arg0, %arg1, %arg2, %arg3) {axis = 0 : i32, values_count = 4 : i32} : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<4x13x21x3xf32> + func.return %0 : tensor<4x13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_pack_end +// CHECK-DAG: %[[VAR0:.*]] = tosa.concat %arg0, %arg1 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[2, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +// CHECK: %[[TRANSPOSE:.*]] = tosa.transpose %[[VAR1]] {perms = array} +func.func @test_pack_end(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3x2xf32> { + %0 = "tfl.pack"(%arg0, %arg1) {axis = 3 : i32, values_count = 2 : i32} : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3x2xf32> + func.return %0 : tensor<13x21x3x2xf32> +} + +// ----- + +// CHECK-LABEL: test_pack_neg_begin +// CHECK-DAG: %[[VAR0:.*]] = tosa.concat %arg0, %arg1, %arg2, %arg3 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[4, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +func.func @test_pack_neg_begin(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>, %arg2: tensor<13x21x3xf32>, %arg3: tensor<13x21x3xf32>) -> tensor<4x13x21x3xf32> { + %0 = "tfl.pack"(%arg0, %arg1, %arg2, %arg3) {axis = -4 : i32, values_count = 4 : i32} : (tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<4x13x21x3xf32> + func.return %0 : tensor<4x13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_pack_neg_end +// CHECK-DAG: %[[VAR0:.*]] = tosa.concat %arg0, %arg1 {axis = 0 : i32} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[2, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %[[VAR0]], %[[VAR10]] +// CHECK: %[[TRANSPOSE:.*]] = tosa.transpose %[[VAR1]] {perms = array} +func.func @test_pack_neg_end(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<13x21x3x2xf32> { + %0 = "tfl.pack"(%arg0, %arg1) {axis = -1 : i32, values_count = 2 : i32} : (tensor<13x21x3xf32>, tensor<13x21x3xf32>) -> tensor<13x21x3x2xf32> + func.return %0 : tensor<13x21x3x2xf32> +} + +// ----- + +// CHECK-LABEL: test_pack_unknown_input_dims +// CHECK-DAG: %[[OUT_SHAPE:.*]] = tosa.const_shape {values = dense<[3, 1, 2, 4]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[C0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C2:.*]] = tosa.const_shape {values = dense<[1, 2, 4]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[RESHAPE1:.*]] = tosa.reshape %arg0, %[[C2]] : (tensor<*xi32>, !tosa.shape<3>) -> tensor<1x2x4xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[RESHAPE1]], %[[C0]], %[[C1]] {axis = 0 : i32} : (tensor<1x2x4xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<3x2x4xi32> +// CHECK-DAG: %[[RESHAPE2:.*]] = tosa.reshape %[[CONCAT]], %[[OUT_SHAPE]] : (tensor<3x2x4xi32>, !tosa.shape<4>) -> tensor<3x1x2x4xi32> +func.func @test_pack_unknown_input_dims(%arg0: tensor<*xi32>) -> tensor<3x1x2x4xi32> { + %0 = arith.constant dense<[[[120, 4, 85, 12], [6, 12, 5, 1]]]> : tensor<1x2x4xi32> + %1 = arith.constant dense<[[[65, 45, 7, 12], [6, 12, 13, 7]]]> : tensor<1x2x4xi32> + %2 = "tfl.pack"(%arg0, %0, %1) {axis = 0 : i32, values_count = 3 : i32} : (tensor<*xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<3x1x2x4xi32> + func.return %2 : tensor<3x1x2x4xi32> +} + +// ----- + +// CHECK-LABEL: test_pack_unknown_input_dims2 +// CHECK-DAG: %[[OUT_SHAPE:.*]] = tosa.const_shape {values = dense<[1, 2, 3, 4]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[C0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C2:.*]] = tosa.const_shape {values = dense<[1, 2, 4]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[RESHAPE1:.*]] = tosa.reshape %arg0, %[[C2]] : (tensor<*xi32>, !tosa.shape<3>) -> tensor<1x2x4xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[C0]], %[[RESHAPE1]], %[[C1]] {axis = 2 : i32} : (tensor<1x2x4xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<1x2x12xi32> +// CHECK-DAG: %[[RESHAPE2:.*]] = tosa.reshape %[[CONCAT]], %[[OUT_SHAPE]] : (tensor<1x2x12xi32>, !tosa.shape<4>) -> tensor<1x2x3x4xi32> +func.func @test_pack_unknown_input_dims2(%arg0: tensor<*xi32>) -> tensor<1x2x3x4xi32> { + %0 = arith.constant dense<[[[1202, 5, 85, 3], [6, 13, 5, 7]]]> : tensor<1x2x4xi32> + %1 = arith.constant dense<[[[80, 45, 16, 12], [2, 5, 5, 7]]]> : tensor<1x2x4xi32> + %2 = "tfl.pack"(%0, %arg0, %1) {axis = 2 : i32, values_count = 3 : i32} : (tensor<1x2x4xi32>, tensor<*xi32>, tensor<1x2x4xi32>) -> tensor<1x2x3x4xi32> + return %2 : tensor<1x2x3x4xi32> +} + +// ----- + +// CHECK-LABEL: test_pack_unknown_input_dim_negative_axis +// CHECK-DAG: %[[OUT_SHAPE:.*]] = tosa.const_shape {values = dense<[1, 3, 2, 4]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[C0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C2:.*]] = tosa.const_shape {values = dense<[1, 2, 4]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[RESHAPE1:.*]] = tosa.reshape %arg0, %[[C2]] : (tensor<*xi32>, !tosa.shape<3>) -> tensor<1x2x4xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[C0]], %[[RESHAPE1]], %[[C1]] {axis = 1 : i32} : (tensor<1x2x4xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<1x6x4xi32> +// CHECK-DAG: %[[RESHAPE2:.*]] = tosa.reshape %[[CONCAT]], %[[OUT_SHAPE]] : (tensor<1x6x4xi32>, !tosa.shape<4>) -> tensor<1x3x2x4xi32> +// CHECK: return %[[RESHAPE2]] : tensor<1x3x2x4xi32> +func.func @test_pack_unknown_input_dim_negative_axis(%arg0: tensor<*xi32>) -> tensor<1x3x2x4xi32> { + %0 = arith.constant dense<[[[115, 5, 12, 45], [6, 12, 5, 505]]]> : tensor<1x2x4xi32> + %1 = arith.constant dense<[[[85, 45, 6, 3], [6, 12, 3, 7]]]> : tensor<1x2x4xi32> + %2 = "tfl.pack"(%0, %arg0, %1) {axis = -3 : i32, values_count = 3 : i32} : (tensor<1x2x4xi32>, tensor<*xi32>, tensor<1x2x4xi32>) -> tensor<1x3x2x4xi32> + return %2 : tensor<1x3x2x4xi32> +} + +// ----- + +// CHECK-LABEL: test_pack_unknown_output_dims +// CHECK-DAG: %[[C0:.*]] = tosa.const_shape {values = dense<[3, 1, 2, 4]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C2:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[C1]], %arg0, %[[C2]] {axis = 0 : i32} : (tensor<1x2x4xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<3x2x4xi32> +// CHECK-DAG: %[[RESHAPE:.*]] = tosa.reshape %[[CONCAT]], %[[C0]] : (tensor<3x2x4xi32>, !tosa.shape<4>) -> tensor<3x1x2x4xi32> +// CHECK-DAG: %[[TRANSPOSE:.*]] = tosa.transpose %[[RESHAPE]] {perms = array} : (tensor<3x1x2x4xi32>) -> tensor<1x2x4x3xi32> +// CHECK: return %[[TRANSPOSE]] : tensor<1x2x4x3xi32> +func.func @test_pack_unknown_output_dims(%arg0: tensor<1x2x4xi32>) -> tensor<*xi32> { + %0 = arith.constant dense<[[[32, 5, 1250, 45], [6, 12, 14, 7]]]> : tensor<1x2x4xi32> + %1 = arith.constant dense<[[[17, 17, 17, 17], [6, 12, 5, 5]]]> : tensor<1x2x4xi32> + %2 = "tfl.pack"(%0, %arg0, %1) {axis = -1 : i32, values_count = 3 : i32} : (tensor<1x2x4xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<*xi32> + return %2 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: test_pack_unknown_output_dims2 +// CHECK-DAG: %[[SHAPE4:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[C2:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1x2x4xi32>}> : () -> tensor<1x2x4xi32> +// CHECK-DAG: %[[SHAPE3:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[RESHAPE1:.*]] = tosa.reshape %arg0, %[[SHAPE3]] : (tensor<*xi32>, !tosa.shape<3>) -> tensor<1x2x4xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[RESHAPE1]], %[[C1]], %[[C2]] {axis = 2 : i32} : (tensor<1x2x4xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<1x2x12xi32> +// CHECK-DAG: %[[RESHAPE2:.*]] = tosa.reshape %[[CONCAT]], %[[SHAPE4]] : (tensor<1x2x12xi32>, !tosa.shape<4>) -> tensor<1x2x3x4xi32> +// CHECK: return %[[RESHAPE2]] : tensor<1x2x3x4xi32> +func.func @test_pack_unknown_output_dims2(%arg0: tensor<*xi32>) -> tensor<*xi32> { + %0 = arith.constant dense<[[[9, 115, 8, 5], [600, 12, 5, 71]]]> : tensor<1x2x4xi32> + %1 = arith.constant dense<[[[85, 45, 6, 12], [6, 50, 41, 7]]]> : tensor<1x2x4xi32> + %2 = "tfl.pack"(%arg0, %0, %1) {axis = 2 : i32, values_count = 3 : i32} : (tensor<*xi32>, tensor<1x2x4xi32>, tensor<1x2x4xi32>) -> tensor<*xi32> + return %2 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: test_pack_unknown_input_dim_rank0 +// CHECK-DAG: %[[C0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<1xindex>} : () -> !tosa.shape<1> +// CHECK-DAG: %[[RESHAPE:.*]] = tosa.reshape %arg0, %[[SHAPE]] : (tensor<*xi32>, !tosa.shape<1>) -> tensor<1xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[RESHAPE]], %[[C1]], %[[C0]] {axis = 0 : i32} : (tensor<1xi32>, tensor<1xi32>, tensor<1xi32>) -> tensor<3xi32> +// CHECK: return %[[CONCAT]] : tensor<3xi32> +func.func @test_pack_unknown_input_dim_rank0(%arg0: tensor<*xi32>) -> tensor<3xi32> { + %0 = arith.constant dense<1200> : tensor + %1 = arith.constant dense<85> : tensor + %2 = "tfl.pack"(%arg0, %0, %1) {axis = 0 : i32, values_count = 3 : i32} : (tensor<*xi32>, tensor, tensor) -> tensor<3xi32> + return %2 : tensor<3xi32> +} + +// ----- + +//CHECK-LABEL: test_pack_unknown_output_dim_rank0 +// CHECK-DAG: %[[C0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[C1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<1xindex>} : () -> !tosa.shape<1> +// CHECK-DAG: %[[RESHAPE:.*]] = tosa.reshape %arg0, %[[SHAPE]] : (tensor, !tosa.shape<1>) -> tensor<1xi32> +// CHECK-DAG: %[[CONCAT:.*]] = tosa.concat %[[RESHAPE]], %[[C1]], %[[C0]] {axis = 0 : i32} : (tensor<1xi32>, tensor<1xi32>, tensor<1xi32>) -> tensor<3xi32> +// CHECK: return %[[CONCAT]] : tensor<3xi32> +func.func @test_pack_unknown_output_dim_rank0(%arg0: tensor) -> tensor<*xi32> { + %0 = arith.constant dense<78> : tensor + %1 = arith.constant dense<79> : tensor + %2 = "tfl.pack"(%arg0, %0, %1) {axis = 0 : i32, values_count = 3 : i32} : (tensor, tensor, tensor) -> tensor<*xi32> + return %2 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: test_unstack +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[32, 32, 8]> : tensor<3xindex>} +// CHECK: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR0]] +func.func @test_unstack(%arg0: tensor<1x32x32x8xf32>) -> tensor<*xf32> { + %0 = "tfl.unpack"(%arg0) {axis = 0 : i32, num = 1 : i32} : (tensor<1x32x32x8xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_pad +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[1, 1, 2, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[PVAL:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR1:.*]] = tosa.pad %arg0, %[[VAR0]], %[[PVAL]] +func.func @test_pad(%arg0: tensor<2x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[[1, 1], [2, 2]]> : tensor<2x2xi32> + %0 = "tfl.pad"(%arg0, %cst) : (tensor<2x3xf32>, tensor<2x2xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + + +// ----- + +// CHECK-LABEL: test_pad_v2 +// CHECK-SAME: -> tensor<1x257x9x28xf32> +func.func @test_pad_v2(%arg0: tensor<1x256x8x25xf32>) -> (tensor<*xf32>) { + // CHECK-DAG: %[[PADDING:.+]] = tosa.const_shape {values = dense<[0, 0, 1, 0, 0, 1, 1, 2]> : tensor<8xindex>} : () -> !tosa.shape<8> + %0 = "tfl.pseudo_const"() {value = dense<[[0, 0], [1, 0], [0, 1], [1, 2]]> : tensor<4x2xi32>} : () -> tensor<4x2xi32> + + // CHECK-DAG: %[[VAL:.+]] = "tosa.const"() <{values = dense<-3.40282347E+38> : tensor<1xf32>}> + %1 = "tfl.pseudo_const"() {value = dense<-3.40282347E+38> : tensor} : () -> tensor + + // CHECK-DAG: %[[PAD:.+]] = tosa.pad %arg0, %[[PADDING]], %[[VAL]] : (tensor<1x256x8x25xf32>, !tosa.shape<8>, tensor<1xf32>) -> tensor<1x257x9x28xf32> + %2 = "tfl.padv2"(%arg0, %0, %1) : (tensor<1x256x8x25xf32>, tensor<4x2xi32>, tensor) -> tensor<*xf32> + + // CHECK: return %[[PAD]] + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_pad_v2_quant +// CHECK-DAG: %[[VAL0:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1x!quant.uniform> +// CHECK-DAG: %[[VAL1:.*]] = tosa.const_shape {values = dense<[0, 1, 0, 1, 0, 1, 0, 1]> : tensor<8xindex>} : () -> !tosa.shape<8> +// CHECK: %[[VAL2:.*]] = tosa.pad %arg0, %[[VAL1]], %[[VAL0]] +// CHECK: return %[[VAL2]] +func.func @test_pad_v2_quant(%arg0: tensor<1x7x7x9x!quant.uniform>) -> (tensor<2x8x8x10x!quant.uniform>) { + %0 = "tfl.pseudo_const"() <{value = dense<[[0, 1], [0, 1], [0, 1], [0, 1]]> : tensor<4x2xi32>}> : () -> tensor<4x2xi32> + %1 = "tfl.pseudo_qconst"() <{qtype = tensor>, value = dense<-128> : tensor}> : () -> tensor> + %2 = "tfl.padv2"(%arg0, %0, %1) : (tensor<1x7x7x9x!quant.uniform>, tensor<4x2xi32>, tensor>) -> tensor<2x8x8x10x!quant.uniform> + return %2 : tensor<2x8x8x10x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_expand_dims +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[VAR10]] +func.func @test_expand_dims(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[1, 13, 21, 3]> : tensor<4xi32> + %0 = "tfl.reshape"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor<4xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_expand_dims_minus_1 +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[13, 21, 3, 1]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims_minus_1(%arg0: tensor<13x21x3xf32>) -> tensor { + %cst = "tfl.pseudo_const"() {value = dense<-1> : tensor} : () -> tensor + %0 = "tfl.expand_dims"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_expand_dims_minus_2 +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[13, 21, 1, 3]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims_minus_2(%arg0: tensor<13x21x3xf32>) -> tensor { + %cst = "tfl.pseudo_const"() {value = dense<-2> : tensor} : () -> tensor + %0 = "tfl.expand_dims"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_expand_dims_0 +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[1, 13, 21, 3]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims_0(%arg0: tensor<13x21x3xf32>) -> tensor { + %cst = "tfl.pseudo_const"() {value = dense<0> : tensor} : () -> tensor + %0 = "tfl.expand_dims"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_expand_dims_2 +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[13, 21, 1, 3]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims_2(%arg0: tensor<13x21x3xf32>) -> tensor { + %cst = "tfl.pseudo_const"() {value = dense<2> : tensor} : () -> tensor + %0 = "tfl.expand_dims"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_expand_dims_size +// CHECK-DAG: %[[SHAPE:.*]] = tosa.const_shape {values = dense<[13, 21, 3, 1]> : tensor<4xindex>} +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg0, %[[SHAPE]] +func.func @test_expand_dims_size(%arg0: tensor<13x21x3xf32>) -> tensor { + %cst = "tfl.pseudo_const"() {value = dense<3> : tensor} : () -> tensor + %0 = "tfl.expand_dims"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_shape +// CHECK: %[[VAR0:.*]] = "tosa.const"() <{values = dense<[13, 21, 3]> : tensor<3xi32>}> +func.func @test_shape() -> tensor<3xi32> { + %cst = arith.constant dense<[13, 21, 3]> : tensor<3xi32> + func.return %cst : tensor<3xi32> +} + +// ----- + +// CHECK-LABEL: test_rank +// CHECK: %[[VAR0:.*]] = "tosa.const"() <{values = dense<3> : tensor}> +func.func @test_rank() -> tensor { + %cst = arith.constant dense<3> : tensor + func.return %cst : tensor +} + +// ----- + +// CHECK-LABEL: test_elu +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.exp %arg0 +// CHECK-DAG: %[[VAR4:.*]] = tosa.sub %[[VAR2]], %[[VAR0]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.greater_equal %arg0, %[[VAR1]] +// CHECK: %[[VAR7:.*]] = tosa.select %[[VAR6]], %arg0, %[[VAR4]] +func.func @test_elu(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.elu"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_softmax +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_max %arg0 +// CHECK-DAG: %[[VAR1:.*]] = tosa.sub %arg0, %[[VAR0]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.exp %[[VAR1]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.reduce_sum %[[VAR2]] {axis = 2 : i32} +// CHECK-DAG: %[[VAR4:.*]] = tosa.reciprocal %[[VAR3]] +// CHECK: %[[VAR5:.*]] = tosa.mul %[[VAR2]], %[[VAR4]], %[[SHIFT]] +func.func @test_softmax(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.softmax"(%arg0) {beta = 1.000000e+00 : f32} : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_l2normalization +func.func @test_l2normalization(%arg0: tensor<16x16xf32>) -> (tensor<16x16xf32>) { + // CHECK-DAG: %[[MIN:.+]] = "tosa.const"() <{values = dense<1.08420217E-19> : tensor<1x1xf32>}> + // CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> + // CHECK-DAG: %[[SQR:.+]] = tosa.mul %arg0, %arg0, %[[SHIFT]] + // CHECK-DAG: %[[SUM:.+]] = tosa.reduce_sum %[[SQR]] {axis = 1 : i32} + // CHECK-DAG: %[[MAX:.+]] = tosa.maximum %[[SUM]], %[[MIN]] + // CHECK-DAG: %[[RSQRT:.+]] = tosa.rsqrt %[[MAX]] + // CHECK-DAG: %[[MUL:.+]] = tosa.mul %[[RSQRT]], %arg0, %[[SHIFT]] + // CHECK: %[[CLAMP:.+]] = tosa.clamp %[[MUL]] {max_val = 3.40282347E+38 : f32, min_val = 0.000000e+00 : f32} + %0 = "tfl.l2_normalization"(%arg0) {fused_activation_function = "RELU"} : (tensor<16x16xf32>) -> tensor<16x16xf32> + func.return %0 : tensor<16x16xf32> +} + +// ----- + +// CHECK-LABEL: test_log_softmax +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = tosa.exp %arg0 +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %[[VAR0]] {axis = 2 : i32} +// CHECK-DAG: %[[VAR2:.*]] = tosa.reciprocal %[[VAR1]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.mul %[[VAR0]], %[[VAR2]], %[[SHIFT]] +// CHECK: %[[VAR4:.*]] = tosa.log %[[VAR3]] +func.func @test_log_softmax(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.log_softmax"(%arg0) : (tensor<13x21x3xf32>) -> tensor<13x21x3xf32> + func.return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_matmul +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[14, 1, 1, 19]> : tensor<4xindex>} +// CHECK-DAG: %[[CONST1:.*]] = tosa.const_shape {values = dense<[28, 1, 1, 19]> : tensor<4xindex>} +// CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[14, 28]> : tensor<2xindex>} +// CHECK-DAG: %[[CONST3:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.transpose %arg1 {perms = array} +// CHECK: %[[VAR3:.*]] = tosa.reshape %arg0, %[[CONST0]] +// CHECK: %[[VAR4:.*]] = tosa.reshape %[[VAR2]], %[[CONST1]] +// CHECK: %[[VAR5:.*]] = tosa.conv2d %[[VAR3]], %[[VAR4]], %[[CONST3]], %[[CONST3]], %[[CONST3]] {acc_type = f32, dilation = array, pad = array, stride = array} +// CHECK: %[[VAR6:.*]] = tosa.reshape %[[VAR5]], %[[CONST2]] +func.func @test_matmul(%arg0: tensor<14x19xf32>, %arg1: tensor<19x28xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[1, 0]> : tensor<2xi32> + %cst_0 = "tfl.no_value"() {value = unit} : () -> none + %0 = "tfl.transpose"(%arg1, %cst) : (tensor<19x28xf32>, tensor<2xi32>) -> tensor<*xf32> + %1 = "tfl.fully_connected"(%arg0, %0, %cst_0) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor<14x19xf32>, tensor<*xf32>, none) -> tensor<*xf32> + func.return %1 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: @test_batch_matmul +func.func @test_batch_matmul(%arg0: tensor<1x16x128xf32>, %arg1: tensor<1x128x32xf32>) -> (tensor<1x16x32xf32> ) { + // CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> + // CHECK: %[[VAR0:.*]] = tosa.matmul %arg0, %arg1, %[[ZP]], %[[ZP]] + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false} : (tensor<1x16x128xf32>, tensor<1x128x32xf32>) -> tensor<1x16x32xf32> + func.return %0 : tensor<1x16x32xf32> +} + +// ----- + +// CHECK-LABEL: @test_batch_matmul2d +func.func @test_batch_matmul2d(%arg0: tensor<16x128xf32>, %arg1: tensor<128x32xf32>) -> (tensor<16x32xf32> ) { + // CHECK-DAG: %[[VAR_10:.*]] = tosa.const_shape {values = dense<[1, 16, 128]> : tensor<3xindex>} + // CHECK-DAG: %[[VAR_11:.*]] = tosa.const_shape {values = dense<[1, 128, 32]> : tensor<3xindex>} + // CHECK-DAG: %[[VAR_12:.*]] = tosa.const_shape {values = dense<[16, 32]> : tensor<2xindex>} + // CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> + // CHECK: %[[VAL_0:.*]] = tosa.reshape %arg0, %[[VAR_10]] + // CHECK: %[[VAL_1:.*]] = tosa.reshape %arg1, %[[VAR_11]] + // CHECK: %[[VAL_2:.*]] = tosa.matmul %[[VAL_0]], %[[VAL_1]], %[[ZP]], %[[ZP]] + // CHECK: %[[VAL_3:.*]] = tosa.reshape %[[VAL_2]], %[[VAR_12]] + // CHECK: return %[[VAL_3]] + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false} : (tensor<16x128xf32>, tensor<128x32xf32>) -> tensor<16x32xf32> + func.return %0 : tensor<16x32xf32> +} + +// ----- + +// CHECK-LABEL: @test_batch_matmul_4d +func.func @test_batch_matmul_4d(%arg0: tensor<4x5x16x128xf32>, %arg1: tensor<4x5x128x32xf32>) -> (tensor<4x5x16x32xf32> ) { + // CHECK-DAG: %[[C0:.*]] = tosa.const_shape {values = dense<[20, 16, 128]> : tensor<3xindex>} + // CHECK-DAG: %[[C1:.*]] = tosa.const_shape {values = dense<[20, 128, 32]> : tensor<3xindex>} + // CHECK-DAG: %[[C2:.*]] = tosa.const_shape {values = dense<[4, 5, 16, 32]> : tensor<4xindex>} + // CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> + // CHECK: %[[R0:.*]] = tosa.reshape %arg0, %[[C0]] + // CHECK: %[[R1:.*]] = tosa.reshape %arg1, %[[C1]] + // CHECK: %[[MM:.*]] = tosa.matmul %[[R0]], %[[R1]], %[[ZP]], %[[ZP]] + // CHECK: tosa.reshape %[[MM]], %[[C2]] + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false} : (tensor<4x5x16x128xf32>, tensor<4x5x128x32xf32>) -> tensor<4x5x16x32xf32> + func.return %0 : tensor<4x5x16x32xf32> +} + +// ----- + +// CHECK-LABEL: @test_batch_matmul_transpose +func.func @test_batch_matmul_transpose(%arg0: tensor<1x16x128xf32>, %arg1: tensor<1x128x32xf32>) -> (tensor<1x32x16xf32> ) { + // CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> + // CHECK-DAG: %[[TP0:.+]] = tosa.transpose %arg0 {perms = array} + // CHECK-DAG: %[[TP1:.+]] = tosa.transpose %arg1 {perms = array} + // CHECK: tosa.matmul %[[TP1]], %[[TP0]], %[[ZP]], %[[ZP]] + %0 = "tfl.batch_matmul"(%arg1, %arg0) {adj_x = true, adj_y = true} : (tensor<1x128x32xf32>, tensor<1x16x128xf32>) -> tensor<1x32x16xf32> + func.return %0 : tensor<1x32x16xf32> +} + +// ----- + +// CHECK-LABEL: @test_batch_matmul_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x3x4x4x!quant.uniform> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<1x3x4x3x!quant.uniform> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<40> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<1488699087> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[1, 3, 4, 3]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_7:.*]] = tosa.const_shape {values = dense<[3, 4, 3]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_8:.*]] = tosa.const_shape {values = dense<[3, 4, 4]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_9:.*]] = tosa.reshape %[[VAL_0]], %[[VAL_8]] : (tensor<1x3x4x4x!quant.uniform>, !tosa.shape<3>) -> tensor<3x4x4x!quant.uniform> +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_7]] : (tensor<1x3x4x3x!quant.uniform>, !tosa.shape<3>) -> tensor<3x4x3x!quant.uniform> +// CHECK: %[[VAL_11:.*]] = tosa.matmul %[[VAL_9]], %[[VAL_10]], %[[VAL_6]], %[[VAL_6]] : (tensor<3x4x4x!quant.uniform>, tensor<3x4x3x!quant.uniform>, tensor<1xi8>, tensor<1xi8>) -> tensor<3x4x3xi32> +// CHECK: %[[VAL_12:.*]] = tosa.reshape %[[VAL_11]], %[[VAL_5]] : (tensor<3x4x3xi32>, !tosa.shape<4>) -> tensor<1x3x4x3xi32> +// CHECK: %[[VAL_13:.*]] = tosa.rescale %[[VAL_12]], %[[VAL_3]], %[[VAL_2]], %[[VAL_4]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x3x4x3xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x3x4x3x!quant.uniform> +func.func @test_batch_matmul_qi8(%arg0: tensor<1x3x4x4x!quant.uniform>, %arg1: tensor<1x3x4x3x!quant.uniform>) -> tensor<1x3x4x3x!quant.uniform> { + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false, asymmetric_quantize_inputs = false} : (tensor<1x3x4x4x!quant.uniform>, tensor<1x3x4x3x!quant.uniform>) -> tensor<1x3x4x3x!quant.uniform> + return %0 : tensor<1x3x4x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_batch_matmul_with_input_broadcast +// CHECK-SAME: %[[ARG0:.*]]: tensor<25x12x14x14x64xf32> +// CHECK-SAME: %[[ARG1:.*]]: tensor<14x64x14xf32> +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[1, 1, 14, 64, 14]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<-0.000000e+00> : tensor<25x12x14x64x14xf32>}> : () -> tensor<25x12x14x64x14xf32> +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %[[ARG1]], %[[VAR0]] : (tensor<14x64x14xf32>, !tosa.shape<5>) -> tensor<1x1x14x64x14xf32> +// CHECK: tosa.add %[[VAR5]], %[[VAR1]] : (tensor<1x1x14x64x14xf32>, tensor<25x12x14x64x14xf32>) -> tensor<25x12x14x64x14xf32> +func.func @test_batch_matmul_with_input_broadcast(%arg0: tensor<25x12x14x14x64xf32>, %arg1: tensor<14x64x14xf32>) -> (tensor<25x12x14x14x14xf32> ) { + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false} : (tensor<25x12x14x14x64xf32>, tensor<14x64x14xf32>) -> tensor<25x12x14x14x14xf32> + func.return %0 : tensor<25x12x14x14x14xf32> +} + +// ----- + +// CHECK-LABEL: test_batch_matmul_qi16 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x3x4x4x!quant.uniform> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<1x3x4x3x!quant.uniform> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<31> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<20139> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[1, 3, 4, 3]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAL_7:.*]] = tosa.const_shape {values = dense<[3, 4, 3]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_8:.*]] = tosa.const_shape {values = dense<[3, 4, 4]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_9:.*]] = tosa.reshape %[[VAL_0]], %[[VAL_8]] : (tensor<1x3x4x4x!quant.uniform>, !tosa.shape<3>) +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_7]] : (tensor<1x3x4x3x!quant.uniform>, !tosa.shape<3>) +// CHECK: %[[VAL_11:.*]] = tosa.matmul %[[VAL_9]], %[[VAL_10]], %[[VAL_6]], %[[VAL_6]] : (tensor<3x4x4x!quant.uniform>, tensor<3x4x3x!quant.uniform>, tensor<1xi16>, tensor<1xi16>) +// CHECK: %[[VAL_12:.*]] = tosa.reshape %[[VAL_11]], %[[VAL_5]] : (tensor<3x4x3xi48>, !tosa.shape<4>) -> tensor<1x3x4x3xi48> +// CHECK: %[[VAL_13:.*]] = tosa.rescale %[[VAL_12]], %[[VAL_3]], %[[VAL_2]], %[[VAL_4]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x3x4x3xi48>, tensor<1xi16>, tensor<1xi8>, tensor<1xi48>, tensor<1xi16>) +// CHECK: return %[[VAL_13]] : tensor<1x3x4x3x!quant.uniform> +func.func @test_batch_matmul_qi16(%arg0: tensor<1x3x4x4x!quant.uniform>, %arg1: tensor<1x3x4x3x!quant.uniform>) -> (tensor<1x3x4x3x!quant.uniform>) { +%0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false, asymmetric_quantize_inputs = false} : (tensor<1x3x4x4x!quant.uniform>, tensor<1x3x4x3x!quant.uniform>) -> tensor<1x3x4x3x!quant.uniform> +return %0 : tensor<1x3x4x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_batch_matmul_with_input_broadcast_1 +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x256x256x32xf32> +// CHECK-SAME: %[[ARG1:.*]]: tensor<1x32x4xf32> +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[1, 1, 32, 4]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<-0.000000e+00> : tensor<1x256x32x4xf32>}> : () -> tensor<1x256x32x4xf32> +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %[[ARG1]], %[[VAR0]] : (tensor<1x32x4xf32>, !tosa.shape<4>) -> tensor<1x1x32x4xf32> +// CHECK-DAG: %[[VAR6:.*]] = tosa.add %[[VAR5]], %[[VAR1]] : (tensor<1x1x32x4xf32>, tensor<1x256x32x4xf32>) -> tensor<1x256x32x4xf32> +func.func @test_batch_matmul_with_input_broadcast_1(%arg0: tensor<1x256x256x32xf32>, %arg1: tensor<1x32x4xf32>) -> (tensor<1x256x256x4xf32>) { + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false} : (tensor<1x256x256x32xf32>, tensor<1x32x4xf32>) -> tensor<1x256x256x4xf32> + func.return %0 : tensor<1x256x256x4xf32> +} + +// ----- + +// CHECK-LABEL: test_batch_matmul_with_input_broadcast_qi8 +// CHECK-SAME: %[[ARG0:.*]]: tensor<25x12x14x14x64x!quant.uniform> +// CHECK-SAME: %[[ARG1:.*]]: tensor<14x64x14x!quant.uniform> +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[1, 1, 14, 64, 14]> : tensor<5xindex>} : () -> !tosa.shape<5> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0> : tensor<25x12x14x64x14xi32>}> : () -> tensor<25x12x14x64x14xi32> +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[ARG1]], %[[VAR0]] : (tensor<14x64x14x!quant.uniform>, !tosa.shape<5>) -> tensor<1x1x14x64x14x!quant.uniform> +// CHECK-DAG: %[[VAR8:.*]] = tosa.cast %[[VAR7]] : (tensor<1x1x14x64x14x!quant.uniform>) -> tensor<1x1x14x64x14xi32> +// CHECK-DAG: %[[VAR9:.*]] = tosa.add %[[VAR8]], %[[VAR1]] : (tensor<1x1x14x64x14xi32>, tensor<25x12x14x64x14xi32>) -> tensor<25x12x14x64x14xi32> +// CHECK: tosa.cast %[[VAR9]] : (tensor<25x12x14x64x14xi32>) -> tensor<25x12x14x64x14x!quant.uniform> +func.func @test_batch_matmul_with_input_broadcast_qi8(%arg0: tensor<25x12x14x14x64x!quant.uniform>, %arg1: tensor<14x64x14x!quant.uniform>) -> (tensor<25x12x14x14x14x!quant.uniform>) { + %0 = "tfl.batch_matmul"(%arg0, %arg1) {adj_x = false, adj_y = false, asymmetric_quantize_inputs = false} : (tensor<25x12x14x14x64x!quant.uniform>, tensor<14x64x14x!quant.uniform>) -> tensor<25x12x14x14x14x!quant.uniform> + func.return %0 : tensor<25x12x14x14x14x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_add_scalar +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1x1xf32>}> +// CHECK: %[[VAR2:.*]] = tosa.add %arg0, %[[VAR0]] +func.func @test_add_scalar(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<1.000000e+00> : tensor + %0 = "tfl.add"(%arg0, %cst) {fused_activation_function = "NONE"} : (tensor<13x21x3xf32>, tensor) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_add_1d +// CHECK-DAG: %[[VAR0:.*]] = tosa.reduce_sum %arg1 {axis = 0 : i32} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reduce_sum %[[VAR0]] {axis = 1 : i32} +// CHECK: %[[VAR2:.*]] = tosa.add %arg0, %[[VAR1]] +func.func @test_add_1d(%arg0: tensor<13x21x3xf32>, %arg1: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[0, 1]> : tensor<2xi32> + %0 = "tfl.sum"(%arg1, %cst) {keep_dims = false} : (tensor<13x21x3xf32>, tensor<2xi32>) -> tensor<3xf32> + %1 = "tfl.add"(%arg0, %0) {fused_activation_function = "NONE"} : (tensor<13x21x3xf32>, tensor<3xf32>) -> tensor<*xf32> + func.return %1 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: func @test_fused_activation_relun_clamp +func.func @test_fused_activation_relun_clamp( + %arg0: tensor<10x!quant.uniform>, + %arg1: tensor<10x!quant.uniform>) -> + tensor<10x!quant.uniform> { + %cst = arith.constant dense<1.000000e+00> : tensor + // CHECK: tosa.clamp %{{.+}} {max_val = -67 : i8, min_val = -127 : i8} + %0 = "tfl.add"(%arg0, %arg0) {fused_activation_function = "RELU6"} : (tensor<10x!quant.uniform>, tensor<10x!quant.uniform>) -> tensor<10x!quant.uniform> + func.return %0 : tensor<10x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func @test_fused_activation_relun_noclamp +func.func @test_fused_activation_relun_noclamp( + %arg0: tensor<10x!quant.uniform>, + %arg1: tensor<10x!quant.uniform>) -> + tensor<10x!quant.uniform> { + %cst = arith.constant dense<1.000000e+00> : tensor + // CHECK: tosa.clamp %{{.+}} {max_val = 127 : i8, min_val = -128 : i8} + %0 = "tfl.add"(%arg0, %arg0) {fused_activation_function = "RELU6"} : (tensor<10x!quant.uniform>, tensor<10x!quant.uniform>) -> tensor<10x!quant.uniform> + func.return %0 : tensor<10x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func @test_fused_activation_relun1to1_noclamp +func.func @test_fused_activation_relun1to1_noclamp( + %arg0: tensor<10x!quant.uniform>, + %arg1: tensor<10x!quant.uniform>) -> tensor<10x!quant.uniform> { + %cst = arith.constant dense<1.000000e+00> : tensor + // CHECK: tosa.clamp %{{.}} {max_val = 127 : i8, min_val = -128 : i8} + %0 = "tfl.add"(%arg0, %arg0) {fused_activation_function = "RELU_N1_TO_1"} : (tensor<10x!quant.uniform>, tensor<10x!quant.uniform>) -> tensor<10x!quant.uniform> + func.return %0 : tensor<10x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func @test_fused_activation_relun1to1_clamp +func.func @test_fused_activation_relun1to1_clamp( + %arg0: tensor<10x!quant.uniform>, + %arg1: tensor<10x!quant.uniform>) -> tensor<10x!quant.uniform> { + %cst = arith.constant dense<1.000000e+00> : tensor + // CHECK: tosa.clamp %{{.}} {max_val = 90 : i8, min_val = -110 : i8} + %0 = "tfl.add"(%arg0, %arg0) {fused_activation_function = "RELU_N1_TO_1"} : (tensor<10x!quant.uniform>, tensor<10x!quant.uniform>) -> tensor<10x!quant.uniform> + func.return %0 : tensor<10x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_split +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 14, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 7, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[13, 7, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} +// CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: %[[VAL_6:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_1]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +func.func @test_split(%arg0: tensor<13x21x3xf32>) -> (tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32>) { + %cst_0 = arith.constant dense<1> : tensor + %0:3 = "tfl.split"(%cst_0, %arg0) {num_splits = 3 : i32} : (tensor, tensor<13x21x3xf32>) -> (tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32>) + func.return %0#0, %0#1, %0#2 : tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32> +} + +// ----- + +// CHECK-LABEL: test_split_dynamic +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 2, 0, 0]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 1, 0, 0]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[13, -1, 3]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[13, 1, -1, 3]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[13, 3, -1, 3]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_7:.*]] = tosa.reshape %arg0, %[[VAL_6]] : (tensor<13x?x3xf32>, !tosa.shape<4>) -> tensor<13x3x?x3xf32> +// CHECK: %[[VAL_8:.*]] = tosa.slice %[[VAL_7]], %[[VAL_4]], %[[VAL_5]] : (tensor<13x3x?x3xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<13x1x?x3xf32> +// CHECK: %[[VAL_9:.*]] = tosa.reshape %[[VAL_8]], %[[VAL_3]] : (tensor<13x1x?x3xf32>, !tosa.shape<3>) -> tensor<13x?x3xf32> +// CHECK: %[[VAL_10:.*]] = tosa.slice %[[VAL_7]], %[[VAL_2]], %[[VAL_5]] : (tensor<13x3x?x3xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<13x1x?x3xf32> +// CHECK: %[[VAL_11:.*]] = tosa.reshape %[[VAL_10]], %[[VAL_3]] : (tensor<13x1x?x3xf32>, !tosa.shape<3>) -> tensor<13x?x3xf32> +// CHECK: %[[VAL_12:.*]] = tosa.slice %[[VAL_7]], %[[VAL_1]], %[[VAL_5]] : (tensor<13x3x?x3xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<13x1x?x3xf32> +// CHECK: %[[VAL_13:.*]] = tosa.reshape %[[VAL_12]], %[[VAL_3]] : (tensor<13x1x?x3xf32>, !tosa.shape<3>) -> tensor<13x?x3xf32> +func.func @test_split_dynamic(%arg0: tensor<13x?x3xf32>) -> (tensor<13x?x3xf32>, tensor<13x?x3xf32>, tensor<13x?x3xf32>) { + %cst_0 = arith.constant dense<1> : tensor + %0:3 = "tfl.split"(%cst_0, %arg0) {num_splits = 3 : i32} : (tensor, tensor<13x?x3xf32>) -> (tensor<13x?x3xf32>, tensor<13x?x3xf32>, tensor<13x?x3xf32>) + func.return %0#0, %0#1, %0#2 : tensor<13x?x3xf32>, tensor<13x?x3xf32>, tensor<13x?x3xf32> +} + + +// ----- + +// CHECK-LABEL: test_split_neg +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 14, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 7, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[13, 7, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} +// CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: %[[VAL_6:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_1]], %[[VAL_3]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x7x3xf32> +// CHECK: return %[[VAL_5]], %[[VAL_6]], %[[VAL_7]] : tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32> +func.func @test_split_neg(%arg0: tensor<13x21x3xf32>) -> (tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32>) { + %cst_0 = arith.constant dense<-2> : tensor + %0:3 = "tfl.split"(%cst_0, %arg0) {num_splits = 3 : i32} : (tensor, tensor<13x21x3xf32>) -> (tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32>) + func.return %0#0, %0#1, %0#2 : tensor<13x7x3xf32>, tensor<13x7x3xf32>, tensor<13x7x3xf32> +} + +// ----- + +// CHECK-LABEL: test_split_axis_0 +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[14, 0, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[7, 0, 0]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[7, 13, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} +// CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<21x13x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<7x13x3xf32> +// CHECK: %[[VAL_6:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_3]] : (tensor<21x13x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<7x13x3xf32> +// CHECK: %[[VAL_7:.*]] = tosa.slice %arg0, %[[VAL_1]], %[[VAL_3]] : (tensor<21x13x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<7x13x3xf32> +func.func @test_split_axis_0(%arg0: tensor<21x13x3xf32>) -> (tensor<7x13x3xf32>, tensor<7x13x3xf32>, tensor<7x13x3xf32>) { + %cst_0 = arith.constant dense<0> : tensor + %0:3 = "tfl.split"(%cst_0, %arg0) {num_splits = 3 : i32} : (tensor, tensor<21x13x3xf32>) -> (tensor<7x13x3xf32>, tensor<7x13x3xf32>, tensor<7x13x3xf32>) + func.return %0#0, %0#1, %0#2 : tensor<7x13x3xf32>, tensor<7x13x3xf32>, tensor<7x13x3xf32> +} + +// ----- + +// CHECK-LABEL: test_split_v_neg_axis +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[2, 3, 3, 5]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[2, 3, 3, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} +// CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<2x3x3x8xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<2x3x3x3xf32> +// CHECK: %[[VAL_6:.*]] = tosa.slice %arg0, %[[VAL_1]], %[[VAL_2]] : (tensor<2x3x3x8xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<2x3x3x5xf32> +func.func @test_split_v_neg_axis(%arg0: tensor<2x3x3x8xf32>) -> (tensor<2x3x3x3xf32>, tensor<2x3x3x5xf32>) { + %split_size = arith.constant dense<[3, 5]> : tensor<2xi32> + %axis = arith.constant dense<-1> : tensor + %0, %1 = "tfl.split_v"(%arg0, %split_size, %axis) {num_splits = 2 : i32} : (tensor<2x3x3x8xf32>, tensor<2xi32>, tensor) -> (tensor<2x3x3x3xf32>, tensor<2x3x3x5xf32>) + func.return %0, %1 : tensor<2x3x3x3xf32>, tensor<2x3x3x5xf32> +} + +// ----- + +// CHECK-LABEL: test_tile +// CHECK: tosa.tile +func.func @test_tile(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<[3, 1, 2]> : tensor<3xi32> + %0 = "tfl.tile"(%arg0, %cst) : (tensor<13x21x3xf32>, tensor<3xi32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_space_to_batch +// CHECK-DAG: %[[VAR0:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 1, 0, 0]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[PVAL:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.pad %arg0, %[[VAR0]], %[[PVAL]] +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[13, 11, 2, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR10]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.transpose %[[VAR3]] {perms = array} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[26, 11, 3]> : tensor<3xindex>} +// CHECK: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[VAR11]] +func.func @test_space_to_batch(%arg0: tensor<13x21x3xf32>) -> tensor<26x11x3xf32> { + %cst = arith.constant dense<2> : tensor<1xi32> + %cst_0 = arith.constant dense<[[0, 1]]> : tensor<1x2xi32> + %0 = "tfl.space_to_batch_nd"(%arg0, %cst, %cst_0) : (tensor<13x21x3xf32>, tensor<1xi32>, tensor<1x2xi32>) -> tensor<26x11x3xf32> + func.return %0 : tensor<26x11x3xf32> +} + +// ----- + +// CHECK-LABEL: test_space_to_batch_dyn +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[-1, 81, 1, 80]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[-1, 81, 3, 1, 1, 80]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 2, 0, 0, 0, 0]> : tensor<8xindex>} : () -> !tosa.shape<8> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAL_6:.*]] = tosa.pad %arg0, %[[VAL_4]], %[[VAL_5]] : (tensor, !tosa.shape<8>, tensor<1xf32>) -> tensor +// CHECK: %[[VAL_7:.*]] = tosa.reshape %[[VAL_6]], %[[VAL_3]] : (tensor, !tosa.shape<6>) -> tensor +// CHECK: %[[VAL_8:.*]] = tosa.transpose %[[VAL_7]] {perms = array} : (tensor) -> tensor<3x1x?x81x1x80xf32> +// CHECK: %[[VAL_9:.*]] = tosa.reshape %[[VAL_8]], %[[VAL_1]] : (tensor<3x1x?x81x1x80xf32>, !tosa.shape<4>) -> tensor +func.func @test_space_to_batch_dyn(%arg0 : tensor) -> (tensor) { + %0 = "tfl.pseudo_const"() {value = dense<[3, 1]> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.pseudo_const"() {value = dense<[[0, 2], [0, 0]]> : tensor<2x2xi32>} : () -> tensor<2x2xi32> + %2 = "tfl.space_to_batch_nd"(%arg0, %0, %1) : (tensor, tensor<2xi32>, tensor<2x2xi32>) -> tensor + func.return %2 : tensor +} + +// ----- + +// CHECK-LABEL: test_batch_to_space +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %arg0 {perms = array} +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[2, 2, 2, 32, 32, 1]> : tensor<6xindex>} +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR10]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.transpose %[[VAR3]] {perms = array} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[2, 64, 64, 1]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[VAR11]] +// CHECK: return %[[VAR5:.*]] +func.func @test_batch_to_space(%arg0: tensor<1x32x32x8xf32>) -> tensor<2x64x64x1xf32> { + %cst = arith.constant dense<2> : tensor<2xi32> + %cst_0 = arith.constant dense<0> : tensor<2x2xi32> + %cst_1 = arith.constant dense<[3, 1, 2, 0]> : tensor<4xi32> + %0 = "tfl.transpose"(%arg0, %cst_1) : (tensor<1x32x32x8xf32>, tensor<4xi32>) -> tensor<8x32x32x1xf32> + %1 = "tfl.batch_to_space_nd"(%0, %cst, %cst_0) : (tensor<8x32x32x1xf32>, tensor<2xi32>, tensor<2x2xi32>) -> tensor<2x64x64x1xf32> + func.return %1 : tensor<2x64x64x1xf32> +} + +// ----- + +// CHECK-LABEL: @test_batch_to_space_dyn +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[-1, 235, 1, 80]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[-1, 237, 1, 80]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[3, 1, -1, 79, 1, 80]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK: %[[VAL_6:.*]] = tosa.reshape %arg0, %[[VAL_5]] : (tensor, !tosa.shape<6>) -> tensor<3x1x?x79x1x80xf32> +// CHECK: %[[VAL_7:.*]] = tosa.transpose %[[VAL_6]] {perms = array} : (tensor<3x1x?x79x1x80xf32>) -> tensor +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_3]] : (tensor, !tosa.shape<4>) -> tensor +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_1]], %[[VAL_2]] : (tensor, !tosa.shape<4>, !tosa.shape<4>) -> tensor +func.func @test_batch_to_space_dyn(%arg0 : tensor) -> (tensor) { + %0 = "tfl.pseudo_const"() {value = dense<[3, 1]> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.pseudo_const"() {value = dense<[[0, 2], [0, 0]]> : tensor<2x2xi32>} : () -> tensor<2x2xi32> + %2 = "tfl.batch_to_space_nd"(%arg0, %0, %1) : (tensor, tensor<2xi32>, tensor<2x2xi32>) -> tensor + func.return %2 : tensor +} + +// ----- + +// CHECK-LABEL: @test_batch_to_space_shape_infer +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[1, 135, 240, 384]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 136, 240, 384]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[2, 2, 1, 68, 120, 384]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK: %[[VAL_6:.*]] = tosa.reshape %arg0, %[[VAL_5]] : (tensor<4x68x120x384xf32>, !tosa.shape<6>) -> tensor<2x2x1x68x120x384xf32> +// CHECK: %[[VAL_7:.*]] = tosa.transpose %[[VAL_6]] {perms = array} : (tensor<2x2x1x68x120x384xf32>) -> tensor<1x68x2x120x2x384xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_7]], %[[VAL_3]] : (tensor<1x68x2x120x2x384xf32>, !tosa.shape<4>) -> tensor<1x136x240x384xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_1]], %[[VAL_2]] : (tensor<1x136x240x384xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x135x240x384xf32> +func.func @test_batch_to_space_shape_infer(%arg0 : tensor<4x68x120x384xf32>) -> (tensor) { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.pseudo_const"() {value = dense<[[0, 1], [0, 0]]> : tensor<2x2xi32>} : () -> tensor<2x2xi32> + %2 = "tfl.batch_to_space_nd"(%arg0, %0, %1) : (tensor<4x68x120x384xf32>, tensor<2xi32>, tensor<2x2xi32>) -> tensor + func.return %2 : tensor +} + +// ----- + +// CHECK-LABEL: test_space_to_depth +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 16, 2, 16, 2, 8]> : tensor<6xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %[[VAR1]] {perms = array} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 16, 16, 32]> : tensor<4xindex>} +// CHECK: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR11]] +func.func @test_space_to_depth(%arg0: tensor<1x32x32x8xf32>) -> tensor<1x16x16x32xf32> { + %0 = "tfl.space_to_depth"(%arg0) {block_size = 2 : i32} : (tensor<1x32x32x8xf32>) -> tensor<1x16x16x32xf32> + func.return %0 : tensor<1x16x16x32xf32> +} + +// ----- + +// CHECK-LABEL: test_depth_to_space +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 32, 32, 2, 2, 2]> : tensor<6xindex>} +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.transpose %[[VAR1]] {perms = array} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 64, 64, 2]> : tensor<4xindex>} +// CHECK: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR11]] +func.func @test_depth_to_space(%arg0: tensor<1x32x32x8xf32>) -> tensor<1x64x64x2xf32> { + %0 = "tfl.depth_to_space"(%arg0) {block_size = 2 : i32} : (tensor<1x32x32x8xf32>) -> tensor<1x64x64x2xf32> + func.return %0 : tensor<1x64x64x2xf32> +} + +// ----- + +// CHECK-LABEL: @test_bucketize +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[2, 5]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[2, 5, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> + +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{\[\[\[}}0.000000e+00, 3.000000e+00, 8.000000e+00, 1.100000e+01]]]> : tensor<1x1x4xf32>}> +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[CONST2]] +// CHECK: %[[VAL_2:.*]] = tosa.greater_equal %[[VAL_1]], %[[VAL_0]] +// CHECK: %[[VAL_3:.*]] = tosa.cast %[[VAL_2]] : (tensor<2x5x4xi1>) -> tensor<2x5x4xi32> +// CHECK: %[[VAL_4:.*]] = tosa.reduce_sum %[[VAL_3]] {axis = 2 : i32} +// CHECK: %[[VAL_5:.*]] = tosa.reshape %[[VAL_4]], %[[CONST0]] +func.func @test_bucketize(%arg0: tensor<2x5xf32>) -> tensor<2x5xi32> { + %0 = "tfl.bucketize"(%arg0) {boundaries = [0.000000e+00 : f32, 3.000000e+00 : f32, 8.000000e+00 : f32, 1.100000e+01 : f32]} : (tensor<2x5xf32>) -> tensor<2x5xi32> + func.return %0 : tensor<2x5xi32> +} + +// ----- + +// CHECK-LABEL: @test_bucketize +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[2, 5]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[2, 5, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> + +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{\[\[\[}}0.000000e+00, 3.000000e+00, 8.000000e+00, 1.100000e+01]]]> : tensor<1x1x4xf32>}> +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[CONST2]] +// CHECK: %[[VAL_2:.*]] = tosa.greater_equal %[[VAL_1]], %[[VAL_0]] +// CHECK: %[[VAL_3:.*]] = tosa.cast %[[VAL_2]] : (tensor<2x5x4xi1>) -> tensor<2x5x4xi32> +// CHECK: %[[VAL_4:.*]] = tosa.reduce_sum %[[VAL_3]] {axis = 2 : i32} +// CHECK: %[[VAL_5:.*]] = tosa.reshape %[[VAL_4]], %[[CONST0]] +func.func @test_bucketize(%arg0: tensor<2x5xf32>) -> tensor<2x5xi32> { + %0 = "tfl.bucketize"(%arg0) {boundaries = [0.000000e+00 : f32, 3.000000e+00 : f32, 8.000000e+00 : f32, 1.100000e+01 : f32]} : (tensor<2x5xf32>) -> tensor<2x5xi32> + func.return %0 : tensor<2x5xi32> +} + +// ----- + +// CHECK-LABEL: @test_one_hot +// CHECK-SAME: %[[ARG0:.*]]: tensor<4x4xi32>, %[[ARG1:.*]]: tensor, %[[ARG2:.*]]: tensor +// CHECK-DAG: %[[CST0:.*]] = tosa.const_shape {values = dense<1> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[CST1:.*]] = tosa.const_shape {values = dense<[16, 1, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[CST2:.*]] = tosa.const_shape {values = dense<[16, 2, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[CST3:.*]] = tosa.const_shape {values = dense<[16, 1]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[CST4:.*]] = tosa.const_shape {values = dense<[4, 4, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[RESHAPE:.*]] = tosa.reshape %[[ARG1]], %[[CST0]] +// CHECK-DAG: %[[TILE:.*]] = tosa.tile %[[RESHAPE]], %[[CST1]] +// CHECK-DAG: %[[RESHAPE_0:.*]] = tosa.reshape %[[ARG2]], %[[CST0]] +// CHECK-DAG: %[[TILE_0:.*]] = tosa.tile %[[RESHAPE_0]], %[[CST2]] +// CHECK-DAG: %[[RESHAPE_1:.*]] = tosa.reshape %[[ARG0]], %[[CST3]] +// CHECK-DAG: %[[SCATTER:.*]] = tosa.scatter %[[TILE_0]], %[[RESHAPE_1]], %[[TILE]] +// CHECK-DAG: %[[RESHAPE_2:.*]] = tosa.reshape %[[SCATTER]], %[[CST4]] +// CHECK: return %[[RESHAPE_2]] +func.func @test_one_hot(%arg0: tensor<4x4xi32>, %arg1: tensor, %arg2: tensor) -> tensor<4x4x2xf32> { + %0 = arith.constant dense<2> : tensor + %1 = "tfl.one_hot"(%arg0, %0, %arg1, %arg2) {axis = -1 : i32} : (tensor<4x4xi32>, tensor, tensor, tensor) -> tensor<4x4x2xf32> + func.return %1 : tensor<4x4x2xf32> +} + +// ----- + +// CHECK-LABEL: test_fakequant_with_min_max_args +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<6.10360876E-5> : tensor<1x1x1xf32>} +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<16383.75> : tensor<1x1x1xf32>} +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.mul %arg0, %[[VAR2]], %[[SHIFT]] +// CHECK-DAG: %[[VAR5:.*]] = tosa.cast %[[VAR3]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.cast %[[VAR5]] +// CHECK-DAG: %[[VAR8:.*]] = tosa.mul %[[VAR6]], %[[VAR1]], %[[SHIFT]] +func.func @test_fakequant_with_min_max_args(%arg0: tensor<13x21x3xf32>) -> tensor<13x21x3xf32> { + %0 = "tfl.quantize"(%arg0) {qtype = tensor<13x21x3x!quant.uniform>} : (tensor<13x21x3xf32>) -> tensor<*x!quant.uniform> + %1 = "tfl.dequantize"(%0) : (tensor<*x!quant.uniform>) -> tensor<13x21x3xf32> + func.return %1 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: @test_dequantize_float +// CHECK-SAME: -> tensor<10xf32> +func.func @test_dequantize_float(%arg0: tensor<10xf16>) -> tensor<*xf32> { + // CHECK: %[[VAR0:.+]] = tosa.cast %arg0 : (tensor<10xf16>) -> tensor<10xf32> + %0 = "tfl.dequantize"(%arg0) : (tensor<10xf16>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: @test_dequantize_quant_uniform +func.func @test_dequantize_quant_uniform(%arg0: tensor<4x!quant.uniform>) -> tensor<*xf32> { + // CHECK-DAG: %[[VAL0:.+]] = "tosa.const"() <{values = dense<-1.000000e+00> : tensor<1xf32>}> + // CHECK-DAG: %[[VAL1:.+]] = tosa.cast %arg0 + // CHECK-DAG: %[[VAL2:.+]] = tosa.sub %[[VAL1]], %[[VAL0]] + %0 = "tfl.dequantize"(%arg0) : (tensor<4x!quant.uniform>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} +// ----- + +// CHECK-LABEL: @test_dequantize_quant_per_axis +func.func @test_dequantize_quant_per_axis(%arg0: tensor<1x4x!quant.uniform>) -> tensor<*xf32> { + // CHECK-DAG: %[[VAL0:.+]] = "tosa.const"() <{values = dense<{{\[}}[1.000000e+00, 2.000000e+00, 3.000000e+00, 4.000000e+00]]> : tensor<1x4xf32>}> + // CHECK-DAG: %[[VAL1:.+]] = "tosa.const"() <{values = dense<{{\[}}[5.000000e+00, 6.000000e+00, 7.000000e+00, 8.000000e+00]]> : tensor<1x4xf32>}> + // CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> + // CHECK-DAG: %[[VAL2:.+]] = tosa.cast %arg0 : (tensor<1x4x!quant.uniform>) -> tensor<1x4xf32> + // CHECK-DAG: %[[VAL3:.+]] = tosa.sub %[[VAL2]], %[[VAL1]] : (tensor<1x4xf32>, tensor<1x4xf32>) -> tensor<1x4xf32> + // CHECK: %[[VAL4:.+]] = tosa.mul %[[VAL3]], %[[VAL0]], %[[SHIFT]] : (tensor<1x4xf32>, tensor<1x4xf32>, tensor<1xi8>) -> tensor<1x4xf32> + %0 = "tfl.dequantize"(%arg0) : (tensor<1x4x!quant.uniform>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_quantfork.stats +func.func @test_quantfork.stats(%arg0: tensor<2x1xf32>) -> (tensor<2x1xf32>) { + // CHECK-NOT: quantfork.stats + %0 = "quantfork.stats"(%arg0) {layerStats = dense<[1.0, 1.0]> : tensor<2xf32>}: (tensor<2x1xf32>) -> tensor<2x1xf32> + func.return %0 : tensor<2x1xf32> +} + +// ----- + +// CHECK-LABEL: test_add_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x1x!quant.uniform> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<50> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<1075580483> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<11> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<2147311776> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<10> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_11:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_7]], %[[VAL_8]], %[[VAL_9]], %[[VAL_10]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x1x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<13x21x1xi32> +// CHECK: %[[VAL_12:.*]] = tosa.rescale %[[VAL_11]], %[[VAL_6]], %[[VAL_5]], %[[VAL_10]], %[[VAL_10]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x1xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<13x21x1xi32> +// CHECK: %[[VAL_13:.*]] = tosa.rescale %[[VAL_1]], %[[VAL_7]], %[[VAL_4]], %[[VAL_9]], %[[VAL_10]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_14:.*]] = tosa.add %[[VAL_12]], %[[VAL_13]] : (tensor<13x21x1xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_15:.*]] = tosa.rescale %[[VAL_14]], %[[VAL_3]], %[[VAL_2]], %[[VAL_10]], %[[VAL_9]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x3xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<13x21x3x!quant.uniform> +// CHECK: return %[[VAL_15]] : tensor<13x21x3x!quant.uniform> +func.func @test_add_qi8(%arg0: tensor<13x21x1x!quant.uniform>, %arg1: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = tfl.add(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x1x!quant.uniform>, tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_sub_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x21x3x!quant.uniform> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<50> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1076408862> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<11> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<2147427038> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<10> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_11:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_12:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_8]], %[[VAL_9]], %[[VAL_10]], %[[VAL_11]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<1x21x3xi32> +// CHECK: %[[VAL_13:.*]] = tosa.rescale %[[VAL_12]], %[[VAL_7]], %[[VAL_6]], %[[VAL_11]], %[[VAL_11]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x21x3xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<1x21x3xi32> +// CHECK: %[[VAL_14:.*]] = tosa.rescale %[[VAL_1]], %[[VAL_8]], %[[VAL_5]], %[[VAL_10]], %[[VAL_11]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_15:.*]] = tosa.sub %[[VAL_13]], %[[VAL_14]] : (tensor<1x21x3xi32>, tensor<13x21x3xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_16:.*]] = tosa.rescale %[[VAL_15]], %[[VAL_4]], %[[VAL_3]], %[[VAL_11]], %[[VAL_2]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x3xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<13x21x3x!quant.uniform> +func.func @test_sub_qi8(%arg0: tensor<1x21x3x!quant.uniform>, %arg1: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = tfl.sub(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<1x21x3x!quant.uniform>, tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_mul_qi8 +// CHECK-DAG: %[[shift35:.*]] = "tosa.const"() <{values = dense<35> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[mult1075664768:.*]] = "tosa.const"() <{values = dense<1075664768> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[const0:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[mult1073741824:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[shift30:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAR0:.*]] = tosa.rescale %arg0, %[[mult1073741824]], %[[shift30]] +// CHECK-DAG: %[[VAR1:.*]] = tosa.rescale %arg1, %[[mult1073741824]], %[[shift30]] +// CHECK: %[[VAR2:.*]] = tosa.mul %[[VAR0]], %[[VAR1]], %[[const0]] +// CHECK: %[[VAR3:.*]] = tosa.rescale %[[VAR2]], %[[mult1075664768]], %[[shift35]] +func.func @test_mul_qi8(%arg0: tensor<13x21x3x!quant.uniform>, %arg1: tensor<13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.mul"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3x!quant.uniform>, tensor<13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_avg_pool2d_qi8 +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAR0:.*]] = tosa.avg_pool2d %arg0, %[[ZP]], %[[ZP]] {acc_type = i32, kernel = array, pad = array, stride = array} +// CHECK-SAME: -> tensor<1x32x32x8x!quant.uniform> +func.func @test_avg_pool2d_qi8(%arg0: tensor<1x32x32x8x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.average_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_avg_pool2d_i16 +// CHECK-DAG: %[[ZP:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAR0:.*]] = tosa.avg_pool2d %arg0, %[[ZP]], %[[ZP]] {acc_type = i32, kernel = array, pad = array, stride = array} +// CHECK-SAME: -> tensor<1x32x32x8xi16> +func.func @test_avg_pool2d_i16(%arg0: tensor<1x32x32x8xi16>) -> tensor<*xi16> { + %0 = "tfl.average_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xi16>) -> tensor<*xi16> + func.return %0 : tensor<*xi16> +} + +// ----- + +// CHECK-LABEL: test_max_pool2d_qi8 +// CHECK: %[[VAR0:.*]] = tosa.max_pool2d %arg0 {kernel = array, pad = array, stride = array} +func.func @test_max_pool2d_qi8(%arg0: tensor<1x32x32x8x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.max_pool_2d"(%arg0) {filter_height = 1 : i32, filter_width = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_softmax_qi8 +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<35> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<4> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR3:.*]] = "tosa.const"() <{values = dense<536870912> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR4:.*]] = "tosa.const"() <{values = dense<1515870810> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR5:.*]] = "tosa.const"() <{values = dense<-1010580540> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR6:.*]] = "tosa.const"() <{values = dense<1> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR7:.*]] = "tosa.const"() <{values = dense<12> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR8:.*]] = "tosa.const"() <{values = dense<7> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR9:.*]] = "tosa.const"() <{values = dense<9> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR10:.*]] = "tosa.const"() <{values = dense<17> : tensor<1x1x1xi32>}> +// CHECK-DAG: %[[VAR11:.*]] = "tosa.const"() <{values = dense<"0x5{{.*}}"> : tensor<513xi16>}> +// CHECK-DAG: %[[VAR12:.*]] = "tosa.const"() <{values = dense<"0xE{{.*}}"> : tensor<513xi16>}> +// CHECK-DAG: %[[VAR13:.*]] = "tosa.const"() <{values = dense<"0x4{{.*}}"> : tensor<513xi16>}> +// CHECK-DAG: %[[VAR14:.*]] = "tosa.const"() <{values = dense<"0x0{{.*}}"> : tensor<513xi16>}> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[SHIFT_31:.*]] = "tosa.const"() <{values = dense<31> : tensor<1xi8>}> +// CHECK-DAG: %[[mult1073741824:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[shift30:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[shift23:.*]] = "tosa.const"() <{values = dense<23> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[input_zp1:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> +// CHECK-DAG: %[[zp0i32:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> +// CHECK-DAG: %[[output_zp128:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL27:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> +// CHECK-DAG: %[[VAR15:.*]] = tosa.rescale %arg0, %[[mult1073741824]], %[[shift30]], %[[input_zp1]], %[[zp0i32]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} +// CHECK-DAG: %[[VAR16:.*]] = tosa.reduce_max %[[VAR15]] {axis = 2 : i32} +// CHECK-DAG: %[[VAR17:.*]] = tosa.sub %[[VAR15]], %[[VAR16]] +// CHECK-DAG: %[[VAR18:.*]] = tosa.rescale %[[VAR17]], %[[mult1073741824]], %[[shift23]], %[[zp0i32]], %[[VAL27]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} +// CHECK-DAG: %[[VAR19:.*]] = tosa.table %[[VAR18]], %[[VAR14]] +// CHECK-DAG: %[[VAR20:.*]] = tosa.table %[[VAR18]], %[[VAR13]] +// CHECK-DAG: %[[VAR21:.*]] = tosa.table %[[VAR18]], %[[VAR12]] +// CHECK-DAG: %[[VAR22:.*]] = tosa.table %[[VAR18]], %[[VAR11]] +// CHECK-DAG: %[[VAR23:.*]] = tosa.logical_left_shift %[[VAR19]], %[[VAR10]] +// CHECK-DAG: %[[VAR24:.*]] = tosa.logical_left_shift %[[VAR20]], %[[VAR9]] +// CHECK-DAG: %[[VAR25:.*]] = tosa.logical_left_shift %[[VAR21]], %[[VAR6]] +// CHECK-DAG: %[[VAR26:.*]] = tosa.arithmetic_right_shift %[[VAR22]], %[[VAR8]] {round = true} +// CHECK-DAG: %[[VAR27:.*]] = tosa.add %[[VAR23]], %[[VAR24]] +// CHECK-DAG: %[[VAR28:.*]] = tosa.add %[[VAR27]], %[[VAR25]] +// CHECK-DAG: %[[VAR29:.*]] = tosa.add %[[VAR28]], %[[VAR26]] +// CHECK-DAG: %[[VAR30:.*]] = tosa.arithmetic_right_shift %[[VAR29]], %[[VAR7]] {round = true} +// CHECK-DAG: %[[VAR31:.*]] = tosa.reduce_sum %[[VAR30]] {axis = 2 : i32} +// CHECK-DAG: %[[VAR32:.*]] = tosa.clz %[[VAR31]] +// CHECK-DAG: %[[VAR33:.*]] = tosa.sub %[[VAR32]], %[[VAR6]] +// CHECK-DAG: %[[VAR34:.*]] = tosa.logical_left_shift %[[VAR31]], %[[VAR33]] +// CHECK-DAG: %[[VAR35:.*]] = tosa.mul %[[VAR34]], %[[VAR5]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR36:.*]] = tosa.add %[[VAR35]], %[[VAR4]] +// CHECK-DAG: %[[VAR37:.*]] = tosa.mul %[[VAR36]], %[[VAR34]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR38:.*]] = tosa.sub %[[VAR3]], %[[VAR37]] +// CHECK-DAG: %[[VAR39:.*]] = tosa.mul %[[VAR36]], %[[VAR38]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR40:.*]] = tosa.mul %[[VAR39]], %[[VAR2]], %[[SHIFT]] +// CHECK-DAG: %[[VAR41:.*]] = tosa.add %[[VAR36]], %[[VAR40]] +// CHECK-DAG: %[[VAR42:.*]] = tosa.mul %[[VAR41]], %[[VAR34]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR43:.*]] = tosa.sub %[[VAR3]], %[[VAR42]] +// CHECK-DAG: %[[VAR44:.*]] = tosa.mul %[[VAR41]], %[[VAR43]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR45:.*]] = tosa.mul %[[VAR44]], %[[VAR2]], %[[SHIFT]] +// CHECK-DAG: %[[VAR46:.*]] = tosa.add %[[VAR41]], %[[VAR45]] +// CHECK-DAG: %[[VAR47:.*]] = tosa.mul %[[VAR46]], %[[VAR34]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR48:.*]] = tosa.sub %[[VAR3]], %[[VAR47]] +// CHECK-DAG: %[[VAR49:.*]] = tosa.mul %[[VAR46]], %[[VAR48]], %[[SHIFT_31]] +// CHECK-DAG: %[[VAR50:.*]] = tosa.mul %[[VAR49]], %[[VAR2]], %[[SHIFT]] +// CHECK-DAG: %[[VAR51:.*]] = tosa.add %[[VAR46]], %[[VAR50]] +// CHECK-DAG: %[[VAR52:.*]] = tosa.mul %[[VAR29]], %[[VAR51]], %[[shift30]] +// CHECK-DAG: %[[VAR53:.*]] = tosa.sub %[[VAR1]], %[[VAR32]] +// CHECK-DAG: %[[VAR54:.*]] = tosa.arithmetic_right_shift %[[VAR52]], %[[VAR53]] {round = true} +// CHECK: %[[VAR55:.*]] = tosa.rescale %[[VAR54]], %[[mult1073741824]], %[[shift30]], %[[zp0i32]], %[[output_zp128]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} +func.func @test_softmax_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = "tfl.softmax"(%arg0) {beta = 1.000000e+00 : f32} : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_softmax_qi16 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<14x19x!quant.uniform> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<31> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<"0xF{{.*}}"> : tensor<513xi16>}> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<32768> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<14> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<1> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<7> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<32767> : tensor<1x1xi32>}> +// CHECK-DAG: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL_11:.*]] = "tosa.const"() <{values = dense<1717965619> : tensor<1xi32>}> +// CHECK-DAG: %[[VAL_12:.*]] = "tosa.const"() <{values = dense<"0x0{{.*}}"> : tensor<513xi16>}> +// CHECK-DAG: %[[VAL_13:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> +// CHECK-DAG: %[[VAL_14:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL_15:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> +// CHECK-DAG: %[[VAL_16:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> +// CHECK-DAG: %[[VAL_17:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_13]], %[[VAL_14]], %[[VAL_15]], %[[VAL_16]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<14x19x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi32>) -> tensor<14x19xi32> +// CHECK-DAG: %[[VAL_18:.*]] = tosa.reduce_max %[[VAL_17]] +// CHECK-DAG: %[[VAL_19:.*]] = tosa.sub %[[VAL_17]], %[[VAL_18]] +// CHECK-DAG: %[[VAL_20:.*]] = tosa.rescale %[[VAL_19]], %[[VAL_11]], %[[VAL_10]], %[[VAL_16]], %[[VAL_16]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<14x19xi32> +// CHECK-DAG: %[[VAL_21:.*]] = tosa.add %[[VAL_20]], %[[VAL_9]] +// CHECK-DAG: %[[VAL_22:.*]] = tosa.cast %[[VAL_21]] +// CHECK-DAG: %[[VAL_23:.*]] = tosa.table %[[VAL_22]], %[[VAL_12]] +// CHECK-DAG: %[[VAL_24:.*]] = tosa.arithmetic_right_shift %[[VAL_23]], %[[VAL_8]] +// CHECK-DAG: %[[VAL_25:.*]] = tosa.reduce_sum %[[VAL_24]] +// CHECK-DAG: %[[VAL_26:.*]] = tosa.clz %[[VAL_25]] +// CHECK-DAG: %[[VAL_27:.*]] = tosa.sub %[[VAL_26]], %[[VAL_7]] +// CHECK-DAG: %[[VAL_28:.*]] = tosa.logical_left_shift %[[VAL_25]], %[[VAL_27]] +// CHECK-DAG: %[[VAL_29:.*]] = tosa.sub %[[VAL_28]], %[[VAL_6]] +// CHECK-DAG: %[[VAL_30:.*]] = tosa.arithmetic_right_shift %[[VAL_29]], %[[VAL_5]] +// CHECK-DAG: %[[VAL_31:.*]] = tosa.sub %[[VAL_30]], %[[VAL_4]] +// CHECK-DAG: %[[VAL_32:.*]] = tosa.cast %[[VAL_31]] +// CHECK-DAG: %[[VAL_33:.*]] = tosa.table %[[VAL_32]], %[[VAL_3]] +// CHECK-DAG: %[[VAL_34:.*]] = tosa.arithmetic_right_shift %[[VAL_33]], %[[VAL_8]] +// CHECK-DAG: %[[VAL_35:.*]] = tosa.mul %[[VAL_34]], %[[VAL_24]], %[[VAL_2]] +// CHECK-DAG: %[[VAL_36:.*]] = tosa.sub %[[VAL_1]], %[[VAL_26]] +// CHECK-DAG: %[[VAL_37:.*]] = tosa.arithmetic_right_shift %[[VAL_35]], %[[VAL_36]] +// CHECK-DAG: %[[VAL_38:.*]] = tosa.rescale %[[VAL_37]], %[[VAL_13]], %[[VAL_14]], %[[VAL_16]], %[[VAL_15]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<14x19xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) +func.func @test_softmax_qi16(%arg0: tensor<14x19x!quant.uniform>) -> tensor<14x19x!quant.uniform> { + %0 = "tfl.softmax"(%arg0) {beta = 1.000000e+00 : f32} : (tensor<14x19x!quant.uniform>) -> tensor<14x19x!quant.uniform> + func.return %0 : tensor<14x19x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_sigmoid_qi8 +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<256xi8>}> +// CHECK: %[[VAR1:.*]] = tosa.table %arg0, %[[VAR0]] +func.func @test_sigmoid_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.logistic"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_tanh_qi8 +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<256xi8>}> +// CHECK: %[[VAR1:.*]] = tosa.table %arg0, %[[VAR0]] +func.func @test_tanh_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.tanh"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_relu_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<2147471153> : tensor<1xi32>}> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> +// CHECK: %[[VAL_5:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) +// CHECK: %[[VAL_6:.*]] = tosa.clamp %[[VAL_5]] {max_val = 127 : i8, min_val = -128 : i8} : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> +func.func @test_relu_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = "tfl.relu"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func.func @test_relu_qu16( +// CHECK-SAME: %[[ARG0:.*]]: tensor>) -> tensor> { +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[RESCALE_0:.*]] = tosa.rescale %[[ARG0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_0]], %[[VAL_0]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi16>) -> tensor> +// CHECK: %[[RESCALE_1:.*]] = tosa.rescale %[[RESCALE_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_0]], %[[VAL_0]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi16>) -> tensor> +// CHECK: %[[CLAMP_0:.*]] = tosa.clamp %[[RESCALE_1]] {max_val = 32767 : i16, min_val = 0 : i16} : (tensor>) -> tensor> +// CHECK: %[[RESCALE_2:.*]] = tosa.rescale %[[CLAMP_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_0]], %[[VAL_0]] {input_unsigned = false, output_unsigned = true, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi16>) -> tensor> +// CHECK: return %[[RESCALE_2]] +func.func @test_relu_qu16(%arg0:tensor>) -> (tensor>) { + %0 = "tfl.relu"(%arg0) : (tensor>) -> tensor> + return %0 : tensor> +} + +// ----- + +// CHECK-LABEL: test_relu0To1_qi8 +// CHECK-DAG: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<2147449478> : tensor<1xi32>}> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) +// CHECK: %[[VAL_5:.*]] = tosa.clamp %[[VAL_4]] {max_val = 126 : i8, min_val = -128 : i8} +func.func @test_relu0To1_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = "tfl.relu_n1_to_1"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_relu6_qi8( +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<2147467328> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_6:.*]] = tosa.clamp %[[VAL_5]] {max_val = 127 : i8, min_val = -128 : i8} : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> +func.func @test_relu6_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = "tfl.relu6"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %0 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_relu6_qu8 +// CHECK: %[[VAL_1:.*]] = tosa.rescale %arg0 +// CHECK: %[[VAL_2:.*]] = tosa.rescale %[[VAL_1]] +// CHECK: %[[VAL_3:.*]] = tosa.rescale %[[VAL_2]] +// CHECK: %[[VAL_4:.*]] = tosa.clamp %[[VAL_3]] {max_val = 127 : i8, min_val = -128 : i8} +// CHECK: %[[VAL_5:.*]] = tosa.rescale %[[VAL_4]] +// CHECK: %[[VAL_6:.*]] = tosa.rescale %[[VAL_5]] +func.func @test_relu6_qu8(%arg0: tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> { + %0 = "tfl.quantize"(%arg0) {qtype = tensor<13x21x3x!quant.uniform>} : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + %1 = "tfl.relu6"(%0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + %2 = "tfl.quantize"(%1) {qtype = tensor<13x21x3x!quant.uniform>} : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3x!quant.uniform> + func.return %2 : tensor<13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_leaky_relu_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<14x19x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<2037371008> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<31> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_7:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_3]], %[[VAL_4]], %[[VAL_5]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<14x19xi32> +// CHECK: %[[VAL_8:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_2]], %[[VAL_1]], %[[VAL_5]], %[[VAL_6]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<14x19xi32> +// CHECK: %[[VAL_9:.*]] = tosa.maximum %[[VAL_8]], %[[VAL_7]] +// CHECK: %[[VAL_10:.*]] = tosa.rescale %[[VAL_9]], %[[VAL_2]], %[[VAL_1]], %[[VAL_6]], %[[VAL_5]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) +func.func @test_leaky_relu_qi8(%arg0: tensor<14x19x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.leaky_relu"(%arg0) {alpha = 0.948724806 : f32} : (tensor<14x19x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_leaky_relu_qi16 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<14x19x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1126059648> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_6:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_2]], %[[VAL_3]], %[[VAL_4]], %[[VAL_5]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi32>) -> tensor<14x19xi32> +// CHECK: %[[VAL_7:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_1]], %[[VAL_3]], %[[VAL_4]], %[[VAL_5]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi32>) -> tensor<14x19xi32> +// CHECK: %[[VAL_8:.*]] = tosa.minimum %[[VAL_7]], %[[VAL_6]] +// CHECK: %[[VAL_9:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_1]], %[[VAL_3]], %[[VAL_5]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<14x19xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) +func.func @test_leaky_relu_qi16(%arg0: tensor<14x19x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.leaky_relu"(%arg0) {alpha = 1.048724806 : f32} : (tensor<14x19x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x80x80x2x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<38> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[16, 2, 16, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_6:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAL_7:.*]] = tosa.const_shape {values = dense<14> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAL_8:.*]] = tosa.resize %[[VAL_0]], %[[VAL_5]], %[[VAL_6]], %[[VAL_7]] {mode = BILINEAR} : (tensor<1x80x80x2x!quant.uniform>, !tosa.shape<4>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<1x640x640x2xi32> +// CHECK: %[[VAL_9:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_4]], %[[VAL_3]], %[[VAL_2]], %[[VAL_1]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x640x640x2xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) +func.func @test_resize_bilinear_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = false, half_pixel_centers = false} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_half_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[16, 2, 16, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<-7> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<7> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = BILINEAR} +func.func @test_resize_bilinear_half_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = false, half_pixel_centers = true} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_align_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[1278, 158, 1278, 158]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[CONST0]], %[[CONST0]] {mode = BILINEAR} +func.func @test_resize_bilinear_align_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = true, half_pixel_centers = false} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_align_half_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[1278, 158, 1278, 158]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[KM560:.*]] = tosa.const_shape {values = dense<-560> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[KM560]], %[[KM560]] {mode = BILINEAR} +func.func @test_resize_bilinear_align_half_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = true, half_pixel_centers = true} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_nearest_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[16, 2, 16, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<14> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = false, half_pixel_centers = false} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + + +// ----- + +// CHECK-LABEL: test_resize_nearest_half_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[16, 2, 16, 2]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<15> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_half_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = false, half_pixel_centers = true} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_nearest_align_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[1278, 158, 1278, 158]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[K639:.*]] = tosa.const_shape {values = dense<639> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[K639]], %[[K639]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_align_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = true, half_pixel_centers = false} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_nearest_align_half_qi8 +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[1278, 158, 1278, 158]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[K718:.*]] = tosa.const_shape {values = dense<718> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[K718]], %[[K718]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_align_half_qi8(%arg0: tensor<1x80x80x2x!quant.uniform>) -> tensor<1x640x640x2x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<640> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = true, half_pixel_centers = true} : (tensor<1x80x80x2x!quant.uniform>, tensor<2xi32>) -> tensor<1x640x640x2x!quant.uniform> + func.return %1 : tensor<1x640x640x2x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_f32_scalar_input +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[2, 1, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = BILINEAR} +func.func @test_resize_bilinear_f32_scalar_input(%arg0: tensor<3x1x1x7xf32>) -> tensor<3x2x2x7xf32> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = false, half_pixel_centers = false} : (tensor<3x1x1x7xf32>, tensor<2xi32>) -> tensor<3x2x2x7xf32> + func.return %1 : tensor<3x2x2x7xf32> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_half_qi8_scalar_input +// CHECK-SAME: %[[VAL_0:.*]]: tensor<3x1x1x7x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[2, 1, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_6:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAL_7:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAL_8:.*]] = tosa.resize %[[VAL_0]], %[[VAL_5]], %[[VAL_6]], %[[VAL_7]] {mode = BILINEAR} : (tensor<3x1x1x7x!quant.uniform>, !tosa.shape<4>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<3x2x2x7xi32> +// CHECK: %[[VAL_9:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_4]], %[[VAL_3]], %[[VAL_2]], %[[VAL_1]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<3x2x2x7xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) +func.func @test_resize_bilinear_half_qi8_scalar_input(%arg0: tensor<3x1x1x7x!quant.uniform>) -> tensor<3x2x2x7x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = false, half_pixel_centers = true} : (tensor<3x1x1x7x!quant.uniform>, tensor<2xi32>) -> tensor<3x2x2x7x!quant.uniform> + func.return %1 : tensor<3x2x2x7x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_bilinear_align_qi8_scalar_input +// CHECK-SAME: %[[VAL_0:.*]]: tensor<3x1x1x7x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<32> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[2, 1, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_6:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAL_7:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK: %[[VAL_8:.*]] = tosa.resize %[[VAL_0]], %[[VAL_5]], %[[VAL_6]], %[[VAL_7]] {mode = BILINEAR} : (tensor<3x1x1x7x!quant.uniform>, !tosa.shape<4>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<3x2x2x7xi32> +// CHECK: %[[VAL_9:.*]] = tosa.rescale %[[VAL_8]], %[[VAL_4]], %[[VAL_3]], %[[VAL_2]], %[[VAL_1]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<3x2x2x7xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) +func.func @test_resize_bilinear_align_qi8_scalar_input(%arg0: tensor<3x1x1x7x!quant.uniform>) -> tensor<3x2x2x7x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_bilinear"(%arg0, %0) {align_corners = true, half_pixel_centers = false} : (tensor<3x1x1x7x!quant.uniform>, tensor<2xi32>) -> tensor<3x2x2x7x!quant.uniform> + func.return %1 : tensor<3x2x2x7x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_nearest_f32_scalar_input +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[2, 1, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAL_1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_f32_scalar_input(%arg0: tensor<3x1x1x7xf32>) -> tensor<3x2x2x7xf32> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = false, half_pixel_centers = false} : (tensor<3x1x1x7xf32>, tensor<2xi32>) -> tensor<3x2x2x7xf32> + func.return %1 : tensor<3x2x2x7xf32> +} + +// ----- + +// CHECK-LABEL: test_resize_nearest_half_qi8_scalar_input +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[2, 1, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAL_1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_half_qi8_scalar_input(%arg0: tensor<3x1x1x7x!quant.uniform>) -> tensor<3x2x2x7x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = false, half_pixel_centers = true} : (tensor<3x1x1x7x!quant.uniform>, tensor<2xi32>) -> tensor<3x2x2x7x!quant.uniform> + func.return %1 : tensor<3x2x2x7x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_resize_nearest_align_qi8_scalar_input +// CHECK-DAG: %[[SCALE:.*]] = tosa.const_shape {values = dense<[2, 1, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[OFFSET:.*]] = tosa.const_shape {values = dense<0> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[BORDER:.*]] = tosa.const_shape {values = dense<1> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAL_1:.*]] = tosa.resize %arg0, %[[SCALE]], %[[OFFSET]], %[[BORDER]] {mode = NEAREST_NEIGHBOR} +func.func @test_resize_nearest_align_qi8_scalar_input(%arg0: tensor<3x1x1x7x!quant.uniform>) -> tensor<3x2x2x7x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.resize_nearest_neighbor"(%arg0, %0) {align_corners = true, half_pixel_centers = false} : (tensor<3x1x1x7x!quant.uniform>, tensor<2xi32>) -> tensor<3x2x2x7x!quant.uniform> + func.return %1 : tensor<3x2x2x7x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_fullyconnected_qi16 +// CHECK: %[[BIAS:.+]] = "tosa.const"() <{values = dense<123> : tensor<3xi48>}> : () -> tensor<3xi48> +// CHECK: tosa.conv2d {{.+}}, %[[BIAS]], %{{.+}} {acc_type = i48, {{.+}}} : {{.+}} -> tensor<1x1x1x3xi48> +func.func @test_fullyconnected_qi16(%input: tensor<1x7x!quant.uniform>, %filter: tensor<3x7x!quant.uniform>) -> tensor<1x3x!quant.uniform> { + %bias = "tfl.pseudo_qconst"() {qtype = tensor<3x!quant.uniform>, value = dense<123> : tensor<3xi32>} : () -> tensor<3x!quant.uniform> + %0 = "tfl.fully_connected"(%input, %filter, %bias) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor<1x7x!quant.uniform>, tensor<3x7x!quant.uniform>, tensor<3x!quant.uniform>) -> tensor<1x3x!quant.uniform> + return %0 : tensor<1x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func.func @test_fullyconnected_qi16_input_variable_bias +// CHECK-DAG: %[[SHAPE0:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[SHAPE3:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK-DAG: %[[SHAPE10:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[SHAPE11:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[RESHAPE0:.*]] = tosa.reshape %arg0, %[[SHAPE11]] : (tensor<1x7x!quant.uniform>, !tosa.shape<4>) -> tensor<1x1x1x7x!quant.uniform> +// CHECK: %[[RESHAPE1:.*]] = tosa.reshape %arg1, %[[SHAPE10]] : (tensor<3x7x!quant.uniform>, !tosa.shape<4>) -> tensor<3x1x1x7x!quant.uniform> +// CHECK: %[[CONV:.*]] = tosa.conv2d %[[RESHAPE0]], %[[RESHAPE1]], %[[VAL_9]], %[[VAL_8]], %[[VAL_7]] {acc_type = i48, dilation = array, pad = array, stride = array} : (tensor<1x1x1x7x!quant.uniform>, tensor<3x1x1x7x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x1x1x3xi48> +// CHECK: %[[RESCALE1:.*]] = tosa.rescale %[[CONV]], %[[VAL_6]], %[[VAL_5]], %[[VAL_9]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x1x1x3xi48>, tensor<1xi32>, tensor<1xi8>, tensor<1xi48>, tensor<1xi32>) -> tensor<1x1x1x3xi32> +// CHECK: %[[RESCALE2:.*]] = tosa.rescale %arg2, %[[VAL_6]], %[[VAL_5]], %[[VAL_4]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<3xi32> +// CHECK: %[[RESHAPE2:.*]] = tosa.reshape %[[RESCALE2]], %[[SHAPE3]] : (tensor<3xi32>, !tosa.shape<4>) -> tensor<1x1x1x3xi32> +// CHECK: %[[ADD:.*]] = tosa.add %[[RESCALE1]], %[[RESHAPE2]] : (tensor<1x1x1x3xi32>, tensor<1x1x1x3xi32>) -> tensor<1x1x1x3xi32> +// CHECK: %[[RESCALE3:.*]] = tosa.rescale %[[ADD]], %2, %1, %4, %8 {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x1x1x3xi32>, tensor<1xi16>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) -> tensor<1x1x1x3x!quant.uniform> +// CHECK: %[[RESHAPE3:.*]] = tosa.reshape %[[RESCALE3]], %[[SHAPE0]] : (tensor<1x1x1x3x!quant.uniform>, !tosa.shape<2>) -> tensor<1x3x!quant.uniform> +// CHECK: return %[[RESHAPE3]] : tensor<1x3x!quant.uniform> +func.func @test_fullyconnected_qi16_input_variable_bias(%input: tensor<1x7x!quant.uniform>, %filter: tensor<3x7x!quant.uniform>, %bias: tensor<3x!quant.uniform>) -> tensor<1x3x!quant.uniform> { + %0 = "tfl.fully_connected"(%input, %filter, %bias) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor<1x7x!quant.uniform>, tensor<3x7x!quant.uniform>, tensor<3x!quant.uniform>) -> tensor<1x3x!quant.uniform> + return %0 : tensor<1x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: @test_fullyconnected_dynamic_output +func.func @test_fullyconnected_dynamic_output(%arg0: tensor<1x2048xf32>, %arg1: tensor<1000x2048xf32>, %arg2: tensor<1000xf32>) -> tensor { + // CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[1, 1, 1, 2048]> : tensor<4xindex>} + // CHECK-DAG: %[[CONST1:.*]] = tosa.const_shape {values = dense<[1000, 1, 1, 2048]> : tensor<4xindex>} + // CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[1, 1000]> : tensor<2xindex>} + // CHECK-DAG: %[[CONST3:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> + // CHECK: %[[VAL0:.*]] = tosa.reshape %arg0, %[[CONST0]] + // CHECK: %[[VAL1:.*]] = tosa.reshape %arg1, %[[CONST1]] + // CHECK: %[[VAL2:.*]] = tosa.conv2d %[[VAL0]], %[[VAL1]], %arg2, %[[CONST3]], %[[CONST3]] {acc_type = f32, dilation = array, pad = array, stride = array} + // CHECK: %[[VAL3:.*]] = tosa.reshape %[[VAL2]], %[[CONST2]] + // return %[[VAL3]] + %0 = "tfl.fully_connected"(%arg0, %arg1, %arg2) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor<1x2048xf32>, tensor<1000x2048xf32>, tensor<1000xf32>) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: @test_fullyconnected_dynamic_batch +func.func @test_fullyconnected_dynamic_batch(%arg0: tensor, %arg1: tensor<256x512xf32>, %arg2: tensor<256xf32>) -> tensor { + // CHECK-DAG: %[[OUT_SHAPE:.*]] = tosa.const_shape {values = dense<[-1, 256]> : tensor<2xindex>} : () -> !tosa.shape<2> + // CHECK-DAG: %[[FILTER_SHAPE:.*]] = tosa.const_shape {values = dense<[256, 1, 1, 512]> : tensor<4xindex>} : () -> !tosa.shape<4> + // CHECK-DAG: %[[IN_SHAPE:.*]] = tosa.const_shape {values = dense<[-1, 1, 1, 512]> : tensor<4xindex>} : () -> !tosa.shape<4> + // CHECK: %[[RESHAPE_IN:.*]] = tosa.reshape %arg0, %[[IN_SHAPE]] + // CHECK: %[[RESHAPE_FILTER:.*]] = tosa.reshape %arg1, %[[FILTER_SHAPE]] + // CHECK: %[[CONV:.*]] = tosa.conv2d %[[RESHAPE_IN]], %[[RESHAPE_FILTER]], %arg2, {{.*}}, {{.*}} + // CHECK: tosa.reshape %[[CONV]], %[[OUT_SHAPE]] + %0 = "tfl.fully_connected"(%arg0, %arg1, %arg2) {fused_activation_function = "NONE", keep_num_dims = false, weights_format = "DEFAULT"} : (tensor, tensor<256x512xf32>, tensor<256xf32>) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: @test_fullyconnected_keep_dims +func.func @test_fullyconnected_keep_dims(%arg0: tensor<1x64x64x768x!quant.uniform>, %arg1: tensor<3072x768x!quant.uniform:f32, 0.003333511995151639>>, %arg2: tensor<3072x!quant.uniform>) -> tensor<1x64x64x3072x!quant.uniform> { + // CHECK-DAG: %[[CONST_SHAPE0:.*]] = tosa.const_shape {values = dense<[1, 64, 64, 3072]> : tensor<4xindex>} + // CHECK-DAG: %[[CONST0:.*]] = "tosa.const"() <{values = dense<38> : tensor<1xi8>}> + // CHECK-DAG: %[[CONST1:.*]] = "tosa.const"() <{values = dense<1241512252> : tensor<1xi32>}> + // CHECK-DAG: %[[CONST2:.*]] = "tosa.const"() <{values = dense<45> : tensor<1xi8>}> + // CHECK-DAG: %[[CONST3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> + // CHECK-DAG: %[[CONST4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> + // CHECK-DAG: %[[CONST5:.*]] = "tosa.const"() <{values = dense<5> : tensor<1xi8>}> + // CHECK-DAG: %[[CONST_SHAPE1:.*]] = tosa.const_shape {values = dense<[3072, 1, 1, 768]> : tensor<4xindex>} + // CHECK-DAG: %[[CONST_SHAPE2:.*]] = tosa.const_shape {values = dense<[4096, 1, 1, 768]> : tensor<4xindex>} + // CHECK: %[[RESHAPE_IN:.*]] = tosa.reshape %arg0, %[[CONST_SHAPE2]] : (tensor<1x64x64x768x!quant.uniform>, !tosa.shape<4>) + // CHECK: %[[RESHAPE_FILT:.*]] = tosa.reshape %arg1, %[[CONST_SHAPE1]] : (tensor<3072x768x!quant.uniform:f32, 0.003333511995151639>>, !tosa.shape<4>) + // CHECK: %[[CONV:.*]] = tosa.conv2d %[[RESHAPE_IN]], %[[RESHAPE_FILT]], %arg2, %[[CONST5]], %[[CONST4]] {acc_type = i32, dilation = array, pad = array, stride = array} : (tensor<4096x1x1x768x!quant.uniform>, tensor<3072x1x1x768x!quant.uniform:f32, 0.003333511995151639>>, tensor<3072x!quant.uniform>, tensor<1xi8>, tensor<1xi8>) + // CHECK: %[[RESCALE:.*]] = tosa.rescale %[[CONV]], %[[CONST1]], %[[CONST0]], %[[CONST3]], %[[CONST2]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<4096x1x1x3072xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) + // CHECK: %[[RESHAPE_OUT:.*]] = tosa.reshape %[[RESCALE]], %[[CONST_SHAPE0]] : (tensor<4096x1x1x3072x!quant.uniform>, !tosa.shape<4>) -> tensor<1x64x64x3072x!quant.uniform> + // CHECK: return %[[RESHAPE_OUT]] + %0 = "tfl.fully_connected"(%arg0, %arg1, %arg2) {asymmetric_quantize_inputs = false, fused_activation_function = "NONE", keep_num_dims = true, weights_format = "DEFAULT"} : (tensor<1x64x64x768x!quant.uniform>, tensor<3072x768x!quant.uniform:f32, 0.003333511995151639>>, tensor<3072x!quant.uniform>) -> tensor<1x64x64x3072x!quant.uniform> + func.return %0 : tensor<1x64x64x3072x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_gather +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 13, 63]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR4:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 49]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %arg1, %[[VAR11]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.gather %[[VAR4]], %[[VAR5]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[7, 7, 21, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR6]], %[[VAR12]] +// CHECK: return %[[VAR7]] +func.func @test_gather(%arg0: tensor<13x21x3xf32>, %arg1: tensor<7x7xi32>) -> tensor<*xf32> { + %2 = "tfl.gather"(%arg0, %arg1) {axis = 0 : i32} : (tensor<13x21x3xf32>, tensor<7x7xi32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- +// CHECK-LABEL: test_gather_dyn +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, -1, 63]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAR4:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 49]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %arg1, %[[VAR11]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.gather %[[VAR4]], %[[VAR5]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[7, 7, 21, 3]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR6]], %[[VAR12]] +// CHECK: return %[[VAR7]] +func.func @test_gather_dyn(%arg0: tensor, %arg1 : tensor<7x7xi32>) -> tensor<*xf32> { + %2 = "tfl.gather"(%arg0, %arg1) {axis = 0 : i32} : (tensor, tensor<7x7xi32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + + +// ----- +// CHECK-LABEL: test_gather_channel_dyn +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 13, -1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAR4:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 49]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %arg1, %[[VAR11]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.gather %[[VAR4]], %[[VAR5]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[7, 7, 21, -1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR6]], %[[VAR12]] +// CHECK: return %[[VAR7]] +func.func @test_gather_channel_dyn(%arg0: tensor<13x21x?xf32>, %arg1: tensor<7x7xi32>) -> tensor<*xf32> { + %2 = "tfl.gather"(%arg0, %arg1) {axis = 0 : i32} : (tensor<13x21x?xf32>, tensor<7x7xi32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- +// CHECK-LABEL: test_gather_indices_dyn +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 13, 63]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAR4:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, -1]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %arg1, %[[VAR11]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.gather %[[VAR4]], %[[VAR5]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[-1, 7, 21, 3]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR6]], %[[VAR12]] +// CHECK: return %[[VAR7]] +func.func @test_gather_indices_dyn(%arg0: tensor<13x21x3xf32>, %arg1: tensor) -> tensor<*xf32> { + %2 = "tfl.gather"(%arg0, %arg1) {axis = 0 : i32} : (tensor<13x21x3xf32>, tensor) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- +// CHECK-LABEL: test_gather_batch +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 4, 16]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 3, 4, 4]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<{{\[\[}}0, 3, 1]]> : tensor<1x3xi32> +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.gather %[[VAR1]], %[[VAR0]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR11]] +// CHECK: return %[[VAR3]] +func.func @test_gather_batch(%arg0: tensor<1x4x4x4xi32>) -> tensor<1x3x4x4xi32> { + %0 = "tfl.pseudo_const"() {value = dense<[[0, 3, 1]]> : tensor<1x3xi32>} : () -> tensor<1x3xi32> + %1 = "tfl.gather"(%arg0, %0) {axis = 1 : i32, batch_dims = 1 : i32} : (tensor<1x4x4x4xi32>, tensor<1x3xi32>) -> tensor<1x3x4x4xi32> + func.return %1 : tensor<1x3x4x4xi32> +} + +// ----- + +// CHECK-LABEL: test_gather_batch_dyn +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[-1, 4, 16]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAR1:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR2:.*]] = tosa.gather %[[VAR1]], %arg1 +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[-1, 3, 4, 4]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR2]], %[[VAR11]] +// CHECK: return %[[VAR3]] +func.func @test_gather_batch_dyn(%arg0: tensor, %arg1: tensor) -> tensor { + %1 = "tfl.gather"(%arg0, %arg1) {axis = 1 : i32, batch_dims = 1 : i32} : (tensor, tensor) -> tensor + func.return %1 : tensor +} + +// ----- +// CHECK-LABEL: test_gather_nd +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[1, 273, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[CONST1:.*]] = tosa.const_shape {values = dense<[42, 2]> : tensor<2xindex>} +// CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[1, 42]> : tensor<2xindex>} +// CHECK-DAG: %[[CONST3:.*]] = tosa.const_shape {values = dense<[6, 7, 3]> : tensor<3xindex>} +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const" +// CHECK-DAG: %[[VAR2:.*]] = tosa.reshape %arg0, %[[CONST0]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %arg1, %[[CONST1]] +// CHECK-DAG: %[[VAR5:.*]] = tosa.mul %[[VAR3]], %[[VAR1]], %[[SHIFT]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.reduce_sum %[[VAR5]] {axis = 1 : i32} +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR6]], %[[CONST2]] +// CHECK-DAG: %[[VAR8:.*]] = tosa.gather %[[VAR2]], %[[VAR7]] +// CHECK: %[[VAR9:.*]] = tosa.reshape %[[VAR8]], %[[CONST3]] +func.func @test_gather_nd(%arg0: tensor<13x21x3xf32>, %arg1: tensor<6x7x2xi32>) -> tensor<6x7x3xf32> { + %1 = "tfl.gather_nd"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<6x7x2xi32>) -> tensor<6x7x3xf32> + func.return %1 : tensor<6x7x3xf32> +} + +// ----- +// CHECK-LABEL: test_gather_cast +// CHECK-DAG: %[[VAR1:.*]] = tosa.cast %arg1 +// CHECK-DAG: %[[VAR10:.*]] = tosa.const_shape {values = dense<[1, 13, 63]> : tensor<3xindex>} +// CHECK-DAG: %[[VAR2:.*]] = tosa.reshape %arg0, %[[VAR10]] +// CHECK-DAG: %[[VAR11:.*]] = tosa.const_shape {values = dense<[1, 49]> : tensor<2xindex>} +// CHECK-DAG: %[[VAR3:.*]] = tosa.reshape %[[VAR1]], %[[VAR11]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.gather %[[VAR2]], %[[VAR3]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.const_shape {values = dense<[7, 7, 21, 3]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR5:.*]] = tosa.reshape %[[VAR4]], %[[VAR12]] +// CHECK: return %[[VAR5]] +func.func @test_gather_cast(%arg0: tensor<13x21x3xf32>, %arg1: tensor<7x7xi64>) -> tensor<*xf32> { + %2 = "tfl.gather"(%arg0, %arg1) {axis = 0 : i32} : (tensor<13x21x3xf32>, tensor<7x7xi64>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- +// CHECK-LABEL: test_gather_dont_fold_quantized +// CHECK: tosa.gather +func.func @test_gather_dont_fold_quantized() -> tensor<4x4x4x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() <{qtype = tensor<4x3x!quant.uniform>, value = dense<[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]> : tensor<4x3xi8>}> : () -> tensor<4x3x!quant.uniform> + %1 = "tfl.pseudo_const"() <{value = dense<[[0, 1, 2, 0], [2, 1, 0, 2], [1, 0, 2, 1], [0, 2, 1, 0]]> : tensor<4x4xi32>}> : () -> tensor<4x4xi32> + %2 = "tfl.gather"(%0, %1) <{axis = 1 : i32, batch_dims = 0 : i32}> : (tensor<4x3x!quant.uniform>, tensor<4x4xi32>) -> tensor<4x4x4x!quant.uniform> + func.return %2 : tensor<4x4x4x!quant.uniform> +} + +// ----- +// CHECK-LABEL: test_sparse_to_dense +// CHECK-DAG: %[[CONST0:.*]] = tosa.const_shape {values = dense<[1, -1, 1]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[CONST1:.*]] = tosa.const_shape {values = dense<[1, -1]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[CONST2:.*]] = tosa.const_shape {values = dense<[1, 48]> : tensor<2xindex>} : () -> !tosa.shape<2> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<{{\[\[}}48, 1]]> : tensor<1x2xi32>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1x48x1xi64>}> +// CHECK-DAG: %[[VAR2:.*]] = tosa.cast %arg0 +// CHECK-DAG: %[[VAR4:.*]] = tosa.mul %[[VAR2]], %[[VAR0]], %[[SHIFT]] +// CHECK-DAG: %[[VAR5:.*]] = tosa.reduce_sum %[[VAR4]] {axis = 1 : i32} +// CHECK-DAG: %[[VAR6:.*]] = tosa.reshape %arg1, %[[CONST0]] +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR5]], %[[CONST1]] +// CHECK-DAG: %[[VAR8:.*]] = tosa.scatter %[[VAR1]], %[[VAR7]], %[[VAR6]] +// CHECK-DAG: %[[VAR9:.*]] = tosa.reshape %[[VAR8]], %[[CONST2]] +// CHECK: return %[[VAR9]] +func.func @test_sparse_to_dense(%arg0 : tensor, %arg1 : tensor) -> (tensor<1x48xi64>) { + %0 = arith.constant dense<[1, 48]> : tensor<2xi64> + %1 = arith.constant dense<-1> : tensor + %2 = "tfl.sparse_to_dense"(%arg0, %0, %arg1, %1) : (tensor, tensor<2xi64>, tensor, tensor) -> tensor<1x48xi64> + func.return %2 : tensor<1x48xi64> +} + +// ----- + +// CHECK-LABEL: test_scatter_nd +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x224x512xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x2xi32>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.reduce_sum %[[VAR2:.*]] {axis = 1 : i32} : (tensor<1x2xi32>) +// CHECK-DAG: %[[VAR5:.*]] = tosa.scatter %[[VAR1:.*]], %[[VAR3:.*]], %arg0 : (tensor<1x224x512xf32>, tensor<1x1xi32>, tensor<1x1x512xf32>) +// CHECK: return %[[VAR5]] +func.func @test_scatter_nd(%arg0: tensor<1x1x512xf32>) -> tensor<1x224x512xf32> { + %shape = "tfl.pseudo_const"() <{value = dense<[1, 224, 512]> : tensor<3xi32>}> : () -> tensor<3xi32> + %indices = "tfl.pseudo_const"() <{value = dense<[[[0, 0]]]> : tensor<1x1x2xi32>}> : () -> tensor<1x1x2xi32> + %0 = "tfl.scatter_nd"(%indices, %arg0, %shape) : (tensor<1x1x2xi32>, tensor<1x1x512xf32>, tensor<3xi32>) -> tensor<1x224x512xf32> + func.return %0 : tensor<1x224x512xf32> +} + +// ----- + +// CHECK-LABEL: test_scatter_nd_reshape +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<{{\[\[}}8, 4, 1]]> : tensor<1x3xi32>}> : () +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x16x4xf32>}> : () +// CHECK-DAG: %[[VAR3:.*]] = "tosa.const"() <{values = dense<{{\[\[}}0, 0, 0], [0, 0, 1], [0, 0, 2], [0, 0, 3], [1, 0, 0], [1, 0, 1], [1, 0, 2], [1, 0, 3]]> : tensor<8x3xi32>}> : () +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[NEW_SHAPE:.*]] = tosa.const_shape {values = dense<[1, 8, 4]> : tensor<3xindex>} +// CHECK-DAG: %[[NEW_SHAPE1:.*]] = tosa.const_shape {values = dense<[1, 8]> : tensor<2xindex>} +// CHECK-DAG: %[[NEW_SHAPE2:.*]] = tosa.const_shape {values = dense<[2, 2, 4, 4]> : tensor<4xindex>} +// CHECK-DAG: %[[VAR4:.*]] = tosa.reshape %arg0, %[[NEW_SHAPE]] : (tensor<2x2x2x4xf32>, !tosa.shape<3>) +// CHECK-DAG: %[[VAR5:.*]] = tosa.mul %[[VAR3]], %[[VAR1]], %[[SHIFT]] : (tensor<8x3xi32>, tensor<1x3xi32>, tensor<1xi8>) +// CHECK-DAG: %[[VAR6:.*]] = tosa.reduce_sum %[[VAR5]] {axis = 1 : i32} : (tensor<8x3xi32>) +// CHECK-DAG: %[[VAR7:.*]] = tosa.reshape %[[VAR6]], %[[NEW_SHAPE1]] : (tensor<8x1xi32>, !tosa.shape<2>) +// CHECK-DAG: %[[VAR8:.*]] = tosa.scatter %[[VAR2]], %[[VAR7]], %[[VAR4]] : (tensor<1x16x4xf32>, tensor<1x8xi32>, tensor<1x8x4xf32>) +// CHECK-DAG: %[[VAR9:.*]] = tosa.reshape %[[VAR8]], %[[NEW_SHAPE2]] : (tensor<1x16x4xf32>, !tosa.shape<4>) +// CHECK-DAG: return %[[VAR9]] +func.func @test_scatter_nd_reshape(%arg0: tensor<2x2x2x4xf32>) -> tensor<2x2x4x4xf32> { + %shape = "tfl.pseudo_const"() <{value = dense<[2, 2, 4, 4]> : tensor<4xi32>}> : () -> tensor<4xi32> + %indices = "tfl.pseudo_const"() <{value = dense<[[[[0, 0, 0], [0, 0, 1]], [[0, 0, 2], [0, 0, 3]]], [[[1, 0, 0], [1, 0, 1]], [[1, 0, 2], [1, 0, 3]]]]> : tensor<2x2x2x3xi32>}> : () -> tensor<2x2x2x3xi32> + %0 = "tfl.scatter_nd"(%indices, %arg0, %shape) : (tensor<2x2x2x3xi32>, tensor<2x2x2x4xf32>, tensor<4xi32>) -> tensor<2x2x4x4xf32> + func.return %0 : tensor<2x2x4x4xf32> +} + +// ----- + +// CHECK-LABEL: test_scatter_nd_qi8 +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x224x512xi8>}> : () -> tensor<1x224x512x!quant.uniform> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1x2xi32>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.reduce_sum %[[VAR2:.*]] {axis = 1 : i32} : (tensor<1x2xi32>) +// CHECK-DAG: %[[VAR4:.*]] = tosa.scatter %[[VAR1:.*]], %[[VAR3:.*]], %arg0 : (tensor<1x224x512x!quant.uniform>, tensor<1x1xi32>, tensor<1x1x512x!quant.uniform>) +// CHECK: return %[[VAR4]] +func.func @test_scatter_nd_qi8(%arg0: tensor<1x1x512x!quant.uniform>) -> tensor<1x224x512x!quant.uniform> { + %shape = "tfl.pseudo_const"() <{value = dense<[1, 224, 512]> : tensor<3xi32>}> : () -> tensor<3xi32> + %indices = "tfl.pseudo_const"() <{value = dense<[[[0, 0]]]> : tensor<1x1x2xi32>}> : () -> tensor<1x1x2xi32> + %0 = "tfl.scatter_nd"(%indices, %arg0, %shape) : (tensor<1x1x2xi32>, tensor<1x1x512x!quant.uniform>, tensor<3xi32>) -> tensor<1x224x512x!quant.uniform> + func.return %0 : tensor<1x224x512x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_scatter_nd_duplicate_indices +// CHECK: tfl.scatter_nd +func.func @test_scatter_nd_duplicate_indices(%arg0: tensor<2x2x2x4xf32>) -> tensor<2x2x4x4xf32> { + %shape = "tfl.pseudo_const"() <{value = dense<[2, 2, 4, 4]> : tensor<4xi32>}> : () -> tensor<4xi32> + %indices = "tfl.pseudo_const"() <{value = dense<[[[[0, 0, 0], [0, 0, 1]], [[0, 0, 2], [0, 0, 3]]], [[[1, 0, 0], [1, 0, 0]], [[1, 0, 2], [1, 0, 3]]]]> : tensor<2x2x2x3xi32>}> : () -> tensor<2x2x2x3xi32> + %0 = "tfl.scatter_nd"(%indices, %arg0, %shape) : (tensor<2x2x2x3xi32>, tensor<2x2x2x4xf32>, tensor<4xi32>) -> tensor<2x2x4x4xf32> + func.return %0 : tensor<2x2x4x4xf32> +} + +// ----- + +// CHECK-LABEL: @test_arg_max +func.func @test_arg_max(%arg0: tensor<13x21x3xf32>) -> tensor<*xi32> { + // CHECK: %[[ARGMAX:.+]] = tosa.argmax %arg0 {axis = 1 : i32} + %0 = "tfl.pseudo_const"() {value = dense<1> : tensor} : () -> tensor + %1 = "tfl.arg_max"(%arg0, %0) : (tensor<13x21x3xf32>, tensor) -> tensor<*xi32> + func.return %1 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: @test_arg_max_negative_dim +func.func @test_arg_max_negative_dim(%arg0: tensor<13x21x3xf32>) -> tensor<13x21xi32> { + // CHECK: %[[ARGMAX:.+]] = tosa.argmax %arg0 {axis = 2 : i32} + %0 = "tfl.pseudo_const"() {value = dense<-1> : tensor} : () -> tensor + %1 = "tfl.arg_max"(%arg0, %0) : (tensor<13x21x3xf32>, tensor) -> tensor<13x21xi32> + func.return %1 : tensor<13x21xi32> +} + +// ----- + +// CHECK-LABEL: @test_arg_min_f32 +func.func @test_arg_min_f32(%arg0: tensor<13x21x3xf32>) -> tensor<*xi32> { + // CHECK-DAG: %[[CONST_0:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> + // CHECK-DAG: %[[NEG:.+]] = tosa.negate %arg0, %[[CONST_0]], %[[CONST_0]] : (tensor<13x21x3xf32>, tensor<1xf32>, tensor<1xf32>) -> tensor<13x21x3xf32> + // CHECK-DAG: tosa.argmax %[[NEG]] {axis = 1 : i32} + %0 = "tfl.pseudo_const"() {value = dense<1> : tensor} : () -> tensor + %1 = "tfl.arg_min"(%arg0, %0) : (tensor<13x21x3xf32>, tensor) -> tensor<*xi32> + func.return %1 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: @test_arg_min_i32 +func.func @test_arg_min_i32(%arg0: tensor<13x21x3xi32>) -> tensor<*xi32> { + // CHECK: %[[ONE:.+]] = "tosa.const"() <{values = dense<-1> : tensor<1x1x1xi32>}> + // CHECK: %[[SUB:.+]] = tosa.sub %[[ONE]], %arg0 + // CHECK: %[[ARGMAX:.+]] = tosa.argmax %[[SUB]] {axis = 1 : i32} + %0 = "tfl.pseudo_const"() {value = dense<1> : tensor} : () -> tensor + %1 = "tfl.arg_min"(%arg0, %0) : (tensor<13x21x3xi32>, tensor) -> tensor<*xi32> + func.return %1 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: test_arg_min_ui8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3xui8> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1x1x1xi8>}> : () -> tensor<1x1x1xi8> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_4]], %[[VAL_5]], %[[VAL_3]], %[[VAL_2]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x21x3xui8>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_7:.*]] = tosa.cast %[[VAL_6]] : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3xi8> +// CHECK: %[[VAL_8:.*]] = tosa.sub %[[VAL_1]], %[[VAL_7]] : (tensor<1x1x1xi8>, tensor<13x21x3xi8>) -> tensor<13x21x3xi8> +// CHECK: %[[VAL_9:.*]] = tosa.argmax %[[VAL_8]] {axis = 1 : i32} : (tensor<13x21x3xi8>) -> tensor<13x3xi8> +// CHECK: %[[VAL_10:.*]] = tosa.rescale %[[VAL_9]], %[[VAL_4]], %[[VAL_5]], %[[VAL_3]], %[[VAL_2]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x3xi8>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<13x3x!quant.uniform> +// CHECK: %[[VAL_11:.*]] = tosa.rescale %[[VAL_10]], %[[VAL_4]], %[[VAL_5]], %[[VAL_2]], %[[VAL_3]] {input_unsigned = false, output_unsigned = true, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<13x3xui8> +// CHECK: %[[VAL_12:.*]] = tensor.cast %[[VAL_11]] : tensor<13x3xui8> to tensor<*xui8> +// CHECK: return %[[VAL_12]] : tensor<*xui8> +func.func @test_arg_min_ui8(%arg0: tensor<13x21x3xui8>) -> tensor<*xui8> { + %0 = "tfl.pseudo_const"() {value = dense<1> : tensor} : () -> tensor + %1 = "tfl.arg_min"(%arg0, %0) : (tensor<13x21x3xui8>, tensor) -> tensor<*xui8> + func.return %1 : tensor<*xui8> +} + +// ----- + +// CHECK-LABEL: test_fakequant +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<-2.00003052> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<1.99996948> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<6.10360876E-5> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR3:.*]] = "tosa.const"() <{values = dense<16383.75> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[VAR4:.*]] = "tosa.const"() <{values = dense<5.000000e-01> : tensor<1x1x1xf32>}> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR6:.*]] = tosa.minimum %arg0, %[[VAR1]] +// CHECK-DAG: %[[VAR8:.*]] = tosa.maximum %[[VAR6]], %[[VAR0]] +// CHECK-DAG: %[[VAR10:.*]] = tosa.sub %[[VAR8]], %[[VAR0]] +// CHECK-DAG: %[[VAR12:.*]] = tosa.mul %[[VAR10]], %[[VAR3]], %[[SHIFT]] +// CHECK-DAG: %[[VAR14:.*]] = tosa.add %[[VAR12]], %[[VAR4]] +// CHECK-DAG: %[[VAR15:.*]] = tosa.floor %[[VAR14]] +// CHECK-DAG: %[[VAR17:.*]] = tosa.mul %[[VAR15]], %[[VAR2]], %[[SHIFT]] +// CHECK: %[[VAR19:.*]] = tosa.add %[[VAR17]], %[[VAR0]] +func.func @test_fakequant(%arg0: tensor<13x21x3xf32>) -> tensor<*xf32> { + %2 = "tfl.fake_quant"(%arg0) {max = 2.000000e+00 : f32, min = -2.000000e+00 : f32, narrow_range = false, num_bits = 16 : i32} : (tensor<13x21x3xf32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_infer +// CHECK: -> tensor<1x32x32x16xf32> +func.func @test_conv2d_infer(%arg0: tensor<1x32x32x8xf32>, %arg1: tensor<16x2x2x8xf32>) -> tensor<*xf32> { + %cst = arith.constant dense<0.000000e+00> : tensor<16xf32> + // CHECK: tosa.add + // CHECK: tosa.conv2d + %0 = "tfl.add"(%arg1, %arg1) { fused_activation_function = "NONE" } : (tensor<16x2x2x8xf32>, tensor<16x2x2x8xf32>) -> tensor<*xf32> + %1 = "tfl.conv_2d"(%arg0, %0, %cst) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>, tensor<*xf32>, tensor<16xf32>) -> tensor<*xf32> + func.return %1 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_no_bias +// CHECK-DAG: %[[CONST0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[CONST1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[CONST2:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK-DAG: %[[CONST3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[CONST4:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[CONV2D:.*]] = tosa.conv2d %arg0, %arg1, %[[CONST2]], %[[CONST3]], %[[CONST4]] {acc_type = i48, dilation = array, pad = array, stride = array} : (tensor<1x32x32x8x!quant.uniform>, tensor<3x3x8x16x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x32x32x3xi48> +// CHECK: %[[RESCALE:.*]] = tosa.rescale %[[CONV2D]], %[[CONST1]], %[[CONST0]], %[[CONST2]], %[[CONST3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x32x32x3xi48>, tensor<1xi16>, tensor<1xi8>, tensor<1xi48>, tensor<1xi16>) -> tensor<1x32x32x3x!quant.uniform> +// CHECK: return %[[RESCALE]] : tensor<1x32x32x3x!quant.uniform> +func.func @test_conv2d_no_bias(%input: tensor<1x32x32x8x!quant.uniform>, %filter: tensor<3x3x8x16x!quant.uniform>) -> tensor<1x32x32x3x!quant.uniform> { + %bias = "tfl.no_value"() {value} : () -> none + %0 = "tfl.conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<3x3x8x16x!quant.uniform>, none) -> tensor<1x32x32x3x!quant.uniform> + return %0 : tensor<1x32x32x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_int16_input_int32_variable_bias +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[SHAPE2:.*]] = tosa.const_shape {values = dense<{{.*}}> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK-DAG: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK-DAG: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[CONV:.*]] = tosa.conv2d %arg0, %arg1, %[[VAL_6]], %[[VAL_7]], %[[VAL_8]] {acc_type = i48, dilation = array, pad = array, stride = array} : (tensor<1x30x34x8x!quant.uniform>, tensor<10x3x3x8x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x30x34x10xi48> +// CHECK: %[[RESCALE1:.*]] = tosa.rescale %[[CONV]], %[[VAL_5]], %[[VAL_4]], %[[VAL_6]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x30x34x10xi48>, tensor<1xi32>, tensor<1xi8>, tensor<1xi48>, tensor<1xi32>) -> tensor<1x30x34x10xi32> +// CHECK: %[[RESCALE2:.*]] = tosa.rescale %arg2, %[[VAL_5]], %[[VAL_4]], %[[VAL_3]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<10x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<10xi32> +// CHECK: %[[RESHAPE:.*]] = tosa.reshape %[[RESCALE2]], %[[SHAPE2]] : (tensor<10xi32>, !tosa.shape<4>) -> tensor<1x1x1x10xi32> +// CHECK: %[[ADD:.*]] = tosa.add %[[RESCALE1]], %[[RESHAPE]] : (tensor<1x30x34x10xi32>, tensor<1x1x1x10xi32>) -> tensor<1x30x34x10xi32> +// CHECK: %[[RESCALE3:.*]] = tosa.rescale %[[ADD]], %[[VAL_1]], %[[VAL_0]], %[[VAL_3]], %[[VAL_7]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x30x34x10xi32>, tensor<1xi16>, tensor<1xi8>, tensor<1xi32>, tensor<1xi16>) -> tensor<1x30x34x10x!quant.uniform> +// CHECK: return %[[RESCALE3]] : tensor<1x30x34x10x!quant.uniform> +func.func @test_conv2d_int16_input_int32_variable_bias(%input: tensor<1x30x34x8x!quant.uniform>, %filter: tensor<10x3x3x8x!quant.uniform>, %bias: tensor<10x!quant.uniform>) -> tensor<1x30x34x10x!quant.uniform> { + %0 = "tfl.conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32,fused_activation_function = "NONE",padding = "SAME",stride_h = 1 : i32,stride_w = 1 : i32} : (tensor<1x30x34x8x!quant.uniform>, tensor<10x3x3x8x!quant.uniform>, tensor<10x!quant.uniform>) -> tensor<1x30x34x10x!quant.uniform> + return %0 : tensor<1x30x34x10x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_f32_input_variable_bias +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[CONV2D:.*]] = tosa.conv2d %arg0, %arg1, %arg2, %[[VAL_0]], %[[VAL_0]] {acc_type = f32, dilation = array, pad = array, stride = array} : (tensor<1x32x32x8xf32>, tensor<5x3x3x8xf32>, tensor<5xf32>, tensor<1xf32>, tensor<1xf32>) -> tensor<1x32x32x5xf32> +// CHECK: return %[[CONV2D]] : tensor<1x32x32x5xf32> +func.func @test_conv2d_f32_input_variable_bias(%input: tensor<1x32x32x8xf32>, %filter: tensor<5x3x3x8xf32>, %bias: tensor<5xf32>) -> tensor<1x32x32x5xf32> { + %0 = "tfl.conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8xf32>, tensor<5x3x3x8xf32>, tensor<5xf32>) -> tensor<1x32x32x5xf32> + return %0 : tensor<1x32x32x5xf32> +} + +// ----- + +// CHECK-LABEL: @test_conv2d_int8_input_variable_bias +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[CONV2D:.*]] = tosa.conv2d %arg0, %arg1, %arg2, %[[VAL_3]], %[[VAL_3]] {acc_type = i32, dilation = array, pad = array, stride = array} : (tensor<1x32x32x8x!quant.uniform>, tensor<16x3x3x8x!quant.uniform>, tensor<16x!quant.uniform>, tensor<1xi8>, tensor<1xi8>) -> tensor<1x32x32x16xi32> +// CHECK: %[[RESCALE:.*]] = tosa.rescale %[[CONV2D]], %[[VAL_1]], %[[VAL_0]], %[[VAL_2]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x32x32x16xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x32x32x16x!quant.uniform> +// CHECK: return %[[RESCALE]] : tensor<1x32x32x16x!quant.uniform> +func.func @test_conv2d_int8_input_variable_bias(%input: tensor<1x32x32x8x!quant.uniform>, %filter: tensor<16x3x3x8x!quant.uniform>, %bias: tensor<16x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> { + %0 = "tfl.conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<16x3x3x8x!quant.uniform>, tensor<16x!quant.uniform>) -> tensor<1x32x32x16x!quant.uniform> + return %0 : tensor<1x32x32x16x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: func.func @test_conv2d_qu16( +// CHECK-SAME: %[[ARG0:.*]]: tensor<1x32x32x8x!quant.uniform>, +// CHECK-SAME: %[[ARG1:.*]]: tensor<3x3x8x16x!quant.uniform>) -> tensor<1x32x32x3x!quant.uniform> { +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<14> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<16384> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi48>}> : () -> tensor<1xi48> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi16>}> : () -> tensor<1xi16> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[RESCALE_0:.*]] = tosa.rescale %[[ARG0]], %[[VAL_5]], %[[VAL_6]], %[[VAL_4]], %[[VAL_4]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x32x32x8x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi16>) -> tensor<1x32x32x8x!quant.uniform> +// CHECK: %[[VAL_7:.*]] = tosa.conv2d %[[RESCALE_0]], %[[ARG1]], %[[VAL_3]], %[[VAL_4]], %[[VAL_2]] {acc_type = i48, dilation = array, pad = array, stride = array} : (tensor<1x32x32x8x!quant.uniform>, tensor<3x3x8x16x!quant.uniform>, tensor<1xi48>, tensor<1xi16>, tensor<1xi8>) -> tensor<1x32x32x3xi48> +// CHECK: %[[RESCALE_1:.*]] = tosa.rescale %[[VAL_7]], %[[VAL_1]], %[[VAL_0]], %[[VAL_3]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = false} : (tensor<1x32x32x3xi48>, tensor<1xi16>, tensor<1xi8>, tensor<1xi48>, tensor<1xi16>) -> tensor<1x32x32x3x!quant.uniform> +// CHECK: %[[RESCALE_2:.*]] = tosa.rescale %[[RESCALE_1]], %[[VAL_5]], %[[VAL_6]], %[[VAL_4]], %[[VAL_4]] {input_unsigned = false, output_unsigned = true, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<1x32x32x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi16>, tensor<1xi16>) -> tensor<1x32x32x3x!quant.uniform> +// CHECK: return %[[RESCALE_2]] +func.func @test_conv2d_qu16(%input: tensor<1x32x32x8x!quant.uniform>, %filter: tensor<3x3x8x16x!quant.uniform>) -> tensor<1x32x32x3x!quant.uniform> { + %bias = "tfl.no_value"() {value} : () -> none + %0 = "tfl.conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 1 : i32} : (tensor<1x32x32x8x!quant.uniform>, tensor<3x3x8x16x!quant.uniform>, none) -> tensor<1x32x32x3x!quant.uniform> + return %0 : tensor<1x32x32x3x!quant.uniform> +} +// ----- + +// CHECK-LABEL: @test_squeeze +func.func @test_squeeze(%arg0: tensor<2x1x3x1xf32>) -> tensor<2x3x1xf32> { + // CHECK: tosa.reshape + // CHECK: -> tensor<2x3x1xf32> + %0 = "tfl.squeeze"(%arg0) {squeeze_dims = [1]} : (tensor<2x1x3x1xf32>) -> tensor<2x3x1xf32> + func.return %0 : tensor<2x3x1xf32> +} + +// ----- + +// CHECK-LABEL: @test_squeeze_neg +func.func @test_squeeze_neg(%arg0: tensor<2x1x3x1xf32>) -> tensor<2x1x3xf32> { + // CHECK: tosa.reshape + // CHECK: -> tensor<2x1x3xf32> + %0 = "tfl.squeeze"(%arg0) {squeeze_dims = [-1]} : (tensor<2x1x3x1xf32>) -> tensor<2x1x3xf32> + func.return %0 : tensor<2x1x3xf32> +} + +// ----- + +// CHECK-LABEL: test_gelu +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x4x8x19xf32> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<3.000000e+00> : tensor<1x1x1x1xf32>}> +// CHECK-DAG: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<4.471500e-02> : tensor<1x1x1x1xf32>}> +// CHECK-DAG: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0.797884583> : tensor<1x1x1x1xf32>}> +// CHECK-DAG: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<1x1x1x1xf32>}> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<5.000000e-01> : tensor<1x1x1x1xf32>}> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAL_6:.*]] = tosa.pow %[[VAL_0]], %[[VAL_1]] +// CHECK: %[[VAL_7:.*]] = tosa.mul %[[VAL_6]], %[[VAL_2]], %[[SHIFT]] +// CHECK: %[[VAL_8:.*]] = tosa.add %[[VAL_0]], %[[VAL_7]] +// CHECK: %[[VAL_9:.*]] = tosa.mul %[[VAL_8]], %[[VAL_3]], %[[SHIFT]] +// CHECK: %[[VAL_10:.*]] = tosa.tanh %[[VAL_9]] +// CHECK: %[[VAL_11:.*]] = tosa.add %[[VAL_10]], %[[VAL_4]] +// CHECK: %[[VAL_12:.*]] = tosa.mul %[[VAL_0]], %[[VAL_5]], %[[SHIFT]] +// CHECK: %[[VAL_13:.*]] = tosa.mul %[[VAL_12]], %[[VAL_11]], %[[SHIFT]] +func.func @test_gelu(%arg0: tensor<1x4x8x19xf32>) -> tensor<1x4x8x19xf32> { + %0 = "tfl.gelu"(%arg0) {approximate = true} : (tensor<1x4x8x19xf32>) -> tensor<1x4x8x19xf32> + func.return %0 : tensor<1x4x8x19xf32> +} + +// ----- + +// CHECK-LABEL: test_gelu_qi8 +// CHECK-SAME: %[[VAR0:.*]]: tensor<1x4x4x4x!quant.uniform> +// CHECK: %[[VAR1:.*]] = "tosa.const"() <{values = dense<{{.*}}> : tensor<256xi8>}> +// CHECK: %[[VAR2:.*]] = tosa.table %[[VAR0]], %[[VAR1]] : (tensor<1x4x4x4x!quant.uniform>, tensor<256x!quant.uniform> +func.func @test_gelu_qi8(%arg0: tensor<1x4x4x4x!quant.uniform>) -> tensor<1x4x4x4x!quant.uniform> { + %0 = "tfl.gelu"(%arg0) {approximate = true} : (tensor<1x4x4x4x!quant.uniform>) -> tensor<1x4x4x4x!quant.uniform> + func.return %0 : tensor<1x4x4x4x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: mirrorpad_reflect +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[0, 7]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[7, 1]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[0, 1]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[7, 2]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_5:.*]] = tosa.const_shape {values = dense<[2, 0]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[1, 9]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_7:.*]] = tosa.const_shape {values = dense<[2, 9]> : tensor<2xindex>} +// CHECK-DAG: %[[VAL_8:.*]] = tosa.const_shape {values = dense<[1, 0]> : tensor<2xindex>} +// CHECK: %[[VAL_9:.*]] = tosa.slice %arg0, %[[VAL_8]], %[[VAL_7]] : (tensor<4x9x!quant.uniform>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<2x9x!quant.uniform> +// CHECK: %[[VAL_10:.*]] = tosa.reverse %[[VAL_9]] {axis = 0 : i32} : (tensor<2x9x!quant.uniform>) -> tensor<2x9x!quant.uniform> +// CHECK: %[[VAL_11:.*]] = tosa.slice %arg0, %[[VAL_5]], %[[VAL_6]] : (tensor<4x9x!quant.uniform>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<1x9x!quant.uniform> +// CHECK: %[[VAL_12:.*]] = tosa.concat %[[VAL_10]], %arg0, %[[VAL_11]] {axis = 0 : i32} : (tensor<2x9x!quant.uniform>, tensor<4x9x!quant.uniform>, tensor<1x9x!quant.uniform>) -> tensor<7x9x!quant.uniform> +// CHECK: %[[VAL_13:.*]] = tosa.slice %[[VAL_12]], %[[VAL_3]], %[[VAL_4]] : (tensor<7x9x!quant.uniform>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<7x2x!quant.uniform> +// CHECK: %[[VAL_14:.*]] = tosa.reverse %[[VAL_13]] {axis = 1 : i32} : (tensor<7x2x!quant.uniform>) -> tensor<7x2x!quant.uniform> +// CHECK: %[[VAL_15:.*]] = tosa.slice %[[VAL_12]], %[[VAL_1]], %[[VAL_2]] : (tensor<7x9x!quant.uniform>, !tosa.shape<2>, !tosa.shape<2>) -> tensor<7x1x!quant.uniform> +// CHECK: %[[VAL_16:.*]] = tosa.concat %[[VAL_14]], %[[VAL_12]], %[[VAL_15]] {axis = 1 : i32} : (tensor<7x2x!quant.uniform>, tensor<7x9x!quant.uniform>, tensor<7x1x!quant.uniform>) -> tensor<7x12x!quant.uniform> +func.func @mirrorpad_reflect(%arg0: tensor<4x9x!quant.uniform>) -> tensor<7x12x!quant.uniform> { + %0 = "tfl.pseudo_const"() {value = dense<[[2, 1], [2, 1]]> : tensor<2x2xi32>} : () -> tensor<2x2xi32> + %1 = "tfl.mirror_pad"(%arg0, %0) {mode = #tfl} : (tensor<4x9x!quant.uniform>, tensor<2x2xi32>) -> tensor<7x12x!quant.uniform> + return %1 : tensor<7x12x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: mirrorpad_symmetric +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[16, 24, 1]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[16, 1, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 23, 2]> : tensor<3xindex>} +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} +// CHECK: %[[VAL_5:.*]] = tosa.slice %arg0, %[[VAL_4]], %[[VAL_3]] : (tensor<15x23x2xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<1x23x2xf32> +// CHECK: %[[VAL_6:.*]] = tosa.concat %[[VAL_5]], %arg0 {axis = 0 : i32} : (tensor<1x23x2xf32>, tensor<15x23x2xf32>) -> tensor<16x23x2xf32> +// CHECK: %[[VAL_7:.*]] = tosa.slice %[[VAL_6]], %[[VAL_4]], %[[VAL_2]] : (tensor<16x23x2xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<16x1x2xf32> +// CHECK: %[[VAL_8:.*]] = tosa.concat %[[VAL_7]], %[[VAL_6]] {axis = 1 : i32} : (tensor<16x1x2xf32>, tensor<16x23x2xf32>) -> tensor<16x24x2xf32> +// CHECK: %[[VAL_9:.*]] = tosa.slice %[[VAL_8]], %[[VAL_4]], %[[VAL_1]] : (tensor<16x24x2xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<16x24x1xf32> +// CHECK: %[[VAL_10:.*]] = tosa.concat %[[VAL_9]], %[[VAL_8]] {axis = 2 : i32} : (tensor<16x24x1xf32>, tensor<16x24x2xf32>) -> tensor<16x24x3xf32> +func.func @mirrorpad_symmetric(%arg0: tensor<15x23x2xf32>) -> tensor<16x24x3xf32> { + %0 = "tfl.pseudo_const"() {value = dense<[[1, 0], [1, 0], [1, 0]]> : tensor<3x2xi32>} : () -> tensor<3x2xi32> + %1 = "tfl.mirror_pad"(%arg0, %0) {mode = #tfl} : (tensor<15x23x2xf32>, tensor<3x2xi32>) -> tensor<16x24x3xf32> + return %1 : tensor<16x24x3xf32> +} + +// ----- + +// CHECK-LABEL: @test_reverse_works +func.func @test_reverse_works(%arg0: tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32> { + // CHECK: %[[VAL0:.+]] = tosa.reverse %arg0 {axis = 1 : i32} + // CHECK: %[[VAL1:.+]] = tosa.reverse %[[VAL0]] {axis = 2 : i32} + %0 = "tfl.pseudo_const"() {value = dense<[1, -2]> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.reverse_v2"(%arg0, %0): (tensor<1x2x3x4xf32>, tensor<2xi32>) -> tensor<1x2x3x4xf32> + func.return %1 : tensor<1x2x3x4xf32> +} + +// ----- + +// CHECK-LABEL: @test_reverse_fail +func.func @test_reverse_fail(%arg0: tensor<1x2x3x4xf32>) -> tensor<1x2x3x4xf32> { + // CHECK: "tfl.reverse_v2" + %0 = "tfl.pseudo_const"() {value = dense<[1, 1111]> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.reverse_v2"(%arg0, %0): (tensor<1x2x3x4xf32>, tensor<2xi32>) -> tensor<1x2x3x4xf32> + func.return %1 : tensor<1x2x3x4xf32> +} + +// ----- + +// CHECK-LABEL: test_tfl_custom +// CHECK-SAME: %[[ARG_0:.*]]: tensor<1x64x64x32xf32> +// CHECK: %[[VAL_0:.*]] = tosa.custom %[[ARG_0]] {domain_name = "TFL", implementation_attrs = "{{.*}}", operator_name = "MaxPoolingWithArgmax2D"} : (tensor<1x64x64x32xf32>) -> (tensor<1x32x32x32xf32>, tensor<1x32x32x32xf32>) +func.func @test_tfl_custom(%arg0: tensor<1x64x64x32xf32>) -> (tensor<1x32x32x32xf32>, tensor<1x32x32x32xf32>) { + // custom op for "tfl.max_pooling_with_argmax_2d"(%arg0) {filter_h = 2 : i32, filter_w = 2 : i32, padding = "SAME", stride_h = 2 : i32, stride_w = 2 : i32} : (tensor<1x64x64x32xf32>) -> (tensor<1x32x32x32xf32>, tensor<1x32x32x32xf32>) + %0, %1 = "tfl.custom"(%arg0) {custom_option = #tfl, custom_code = "MaxPoolingWithArgmax2D"} : (tensor<1x64x64x32xf32>) -> (tensor<1x32x32x32xf32>, tensor<1x32x32x32xf32>) + func.return %0, %1 : tensor<1x32x32x32xf32>, tensor<1x32x32x32xf32> +} + +// ----- + +// CHECK-LABEL: test_tfl_while_loop +// CHECK: %[[VAL_0:.*]]: tensor<1x4x4x4xf32> {tf_saved_model.index_path = ["placeholder_0"]}) -> (tensor<1x4x4x4xf32> {tf_saved_model.index_path = ["output_0"]}) { +// CHECK-DAG: %[[VAL_20:.*]] = tosa.const_shape {values = dense<1> : tensor<1xindex>} +// CHECK-DAG: %[[VAL_21:.*]] = tosa.const_shape {values = dense<> : tensor<0xindex>} +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<2.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAL_2:.*]] = tosa.while_loop (%[[VAL_3:.*]] = %[[VAL_0]]) : (tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> { +// CHECK: %[[VAL_4:.*]] = tosa.reduce_sum %[[VAL_3]] {axis = 1 : i32} : (tensor<1x4x4x4xf32>) -> tensor<1x1x4x4xf32> +// CHECK: %[[VAL_5:.*]] = tosa.reduce_sum %[[VAL_4]] {axis = 2 : i32} : (tensor<1x1x4x4xf32>) -> tensor<1x1x1x4xf32> +// CHECK: %[[VAL_6:.*]] = tosa.reduce_sum %[[VAL_5]] {axis = 3 : i32} : (tensor<1x1x1x4xf32>) -> tensor<1x1x1x1xf32> +// CHECK: %[[VAL_7:.*]] = tosa.reshape %[[VAL_6]], %[[VAL_20]] : (tensor<1x1x1x1xf32>, !tosa.shape<1>) -> tensor<1xf32> +// CHECK: %[[VAL_8:.*]] = tosa.greater %[[VAL_1]], %[[VAL_7]] : (tensor<1xf32>, tensor<1xf32>) -> tensor<1xi1> +// CHECK: %[[VAL_9:.*]] = tosa.reshape %[[VAL_8]], %[[VAL_21]] : (tensor<1xi1>, !tosa.shape<0>) -> tensor +// CHECK: tosa.yield %[[VAL_9]] : tensor +// CHECK: } do { +// CHECK: ^bb0(%[[VAL_10:.*]]: tensor<1x4x4x4xf32>): +// CHECK: %[[VAL_11:.*]] = tosa.sigmoid %[[VAL_10]] : (tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> +// CHECK: %[[VAL_12:.*]] = tosa.add %[[VAL_10]], %[[VAL_11]] : (tensor<1x4x4x4xf32>, tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> +// CHECK: tosa.yield %[[VAL_12]] : tensor<1x4x4x4xf32> +// CHECK: } +// CHECK: return %[[VAL_2]] : tensor<1x4x4x4xf32> +// CHECK: } +func.func @test_tfl_while_loop(%arg0: tensor<1x4x4x4xf32> {tf_saved_model.index_path = ["placeholder_0"]}) -> (tensor<1x4x4x4xf32> {tf_saved_model.index_path = ["output_0"]}) { + %0 = "tfl.while"(%arg0) ({ + ^bb0(%arg1: tensor<1x4x4x4xf32>): + %1 = func.call @result_cond(%arg1) : (tensor<1x4x4x4xf32>) -> tensor + "tfl.yield"(%1) : (tensor) -> () + }, { + ^bb0(%arg1: tensor<1x4x4x4xf32>): + %1 = func.call @result_body(%arg1) : (tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> + "tfl.yield"(%1) : (tensor<1x4x4x4xf32>) -> () + }) : (tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> + func.return %0 : tensor<1x4x4x4xf32> +} +func.func private @result_cond(%arg0: tensor<1x4x4x4xf32>) -> tensor { + %0 = "tfl.pseudo_const"() {value = dense<[0, 1, 2, 3]> : tensor<4xi32>} : () -> tensor<4xi32> + %1 = "tfl.sum"(%arg0, %0) {keep_dims = false} : (tensor<1x4x4x4xf32>, tensor<4xi32>) -> tensor + %2 = "tfl.pseudo_const"() {value = dense<2.000000e+00> : tensor<1xf32>} : () -> tensor<1xf32> + %3 = tfl.less(%1, %2) : (tensor, tensor<1xf32>) -> tensor<1xi1> + %4 = "tfl.pseudo_const"() {value = dense<> : tensor<0xi32>} : () -> tensor<0xi32> + %5 = "tfl.reshape"(%3, %4) : (tensor<1xi1>, tensor<0xi32>) -> tensor + func.return %5 : tensor +} +func.func private @result_body(%arg0: tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> { + %0 = "tfl.logistic"(%arg0) : (tensor<1x4x4x4xf32>) -> tensor<1x4x4x4xf32> + %1 = tfl.add %arg0, %0 {fused_activation_function = "NONE"} : tensor<1x4x4x4xf32> + func.return %1 : tensor<1x4x4x4xf32> +} + +// ----- + +// CHECK-LABEL: test_rfft2d +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x8x16xf32> +// CHECK: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 8, 9, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_1:.*]], %[[VAL_2:.*]] = tosa.rfft2d %[[VAL_0]] : (tensor<1x8x16xf32>) -> (tensor<1x8x9xf32>, tensor<1x8x9xf32>) +// CHECK: %[[VAL_3:.*]] = tosa.reshape %[[VAL_1]], %[[VAL_10]] : (tensor<1x8x9xf32>, !tosa.shape<4>) -> tensor<1x8x9x1xf32> +// CHECK: %[[VAL_4:.*]] = tosa.reshape %[[VAL_2]], %[[VAL_10]] : (tensor<1x8x9xf32>, !tosa.shape<4>) -> tensor<1x8x9x1xf32> +// CHECK: %[[VAL_5:.*]] = tosa.concat %[[VAL_3]], %[[VAL_4]] {axis = 3 : i32} : (tensor<1x8x9x1xf32>, tensor<1x8x9x1xf32>) -> tensor<1x8x9x2xf32> +// CHECK: return %[[VAL_5]] : tensor<1x8x9x2xf32> +func.func @test_rfft2d(%arg0: tensor<1x8x16xf32>) -> tensor<1x8x9xcomplex> { + %0 = "tfl.pseudo_const"() {value = dense<[8, 16]> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.rfft2d"(%arg0, %0) : (tensor<1x8x16xf32>, tensor<2xi32>) -> tensor<1x8x9xcomplex> + return %1 : tensor<1x8x9xcomplex> +} + +// ----- + +// CHECK-LABEL: test_rfft2d_crop_input +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[13, 2, 2, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[13, 2, 2]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[VAL_4:.*]] = tosa.slice %arg0, %[[VAL_3]], %[[VAL_2]] : (tensor<13x21x3xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x2x2xf32> +// CHECK: %[[VAL_5:.*]], %[[VAL_6:.*]] = tosa.rfft2d %[[VAL_4]] : (tensor<13x2x2xf32>) -> (tensor<13x2x2xf32>, tensor<13x2x2xf32>) +// CHECK: %[[VAL_7:.*]] = tosa.reshape %[[VAL_5]], %[[VAL_1]] : (tensor<13x2x2xf32>, !tosa.shape<4>) -> tensor<13x2x2x1xf32> +// CHECK: %[[VAL_8:.*]] = tosa.reshape %[[VAL_6]], %[[VAL_1]] : (tensor<13x2x2xf32>, !tosa.shape<4>) -> tensor<13x2x2x1xf32> +// CHECK: %[[VAL_9:.*]] = tosa.concat %[[VAL_7]], %[[VAL_8]] {axis = 3 : i32} : (tensor<13x2x2x1xf32>, tensor<13x2x2x1xf32>) -> tensor<13x2x2x2xf32> +func.func @test_rfft2d_crop_input(%arg0: tensor<13x21x3xf32>) -> tensor<13x2x2xcomplex> { + %0 = "tfl.pseudo_const"() {value = dense<2> : tensor<2xi32>} : () -> tensor<2xi32> + %1 = "tfl.rfft2d"(%arg0, %0) : (tensor<13x21x3xf32>, tensor<2xi32>) -> tensor<13x2x2xcomplex> + return %1 : tensor<13x2x2xcomplex> +} + +// ----- + +// CHECK-LABEL: test_rfft2d_pad_input +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3xf32> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 11, 0, 5]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[13, 32, 5, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_3:.*]] = tosa.pad %[[VAL_0]], %[[VAL_2]], %[[VAL_1]] : (tensor<13x21x3xf32>, !tosa.shape<6>, tensor<1xf32>) -> tensor<13x32x8xf32> +// CHECK: %[[VAL_4:.*]], %[[VAL_5:.*]] = tosa.rfft2d %[[VAL_3]] : (tensor<13x32x8xf32>) -> (tensor<13x32x5xf32>, tensor<13x32x5xf32>) +// CHECK: %[[VAL_6:.*]] = tosa.reshape %[[VAL_4]], %[[VAL_10]] : (tensor<13x32x5xf32>, !tosa.shape<4>) -> tensor<13x32x5x1xf32> +// CHECK: %[[VAL_7:.*]] = tosa.reshape %[[VAL_5]], %[[VAL_10]] : (tensor<13x32x5xf32>, !tosa.shape<4>) -> tensor<13x32x5x1xf32> +// CHECK: %[[VAL_8:.*]] = tosa.concat %[[VAL_6]], %[[VAL_7]] {axis = 3 : i32} : (tensor<13x32x5x1xf32>, tensor<13x32x5x1xf32>) -> tensor<13x32x5x2xf32> +// CHECK: return %[[VAL_8]] : tensor<13x32x5x2xf32> +func.func @test_rfft2d_pad_input(%arg0: tensor<13x21x3xf32>) -> (tensor<13x32x5xcomplex>) { + %0 = "tfl.pseudo_const"() {value = dense<[[0, 0], [0, 11], [0, 5]]> : tensor<3x2xi32>} : () -> tensor<3x2xi32> + %1 = "tfl.pad"(%arg0, %0) : (tensor<13x21x3xf32>, tensor<3x2xi32>) -> tensor<13x32x8xf32> + %2 = "tfl.pseudo_const"() {value = dense<[32, 8]> : tensor<2xi32>} : () -> tensor<2xi32> + %3 = "tfl.rfft2d"(%1, %2) : (tensor<13x32x8xf32>, tensor<2xi32>) -> tensor<13x32x5xcomplex> + return %3 : tensor<13x32x5xcomplex> +} + +// ----- + +// CHECK-LABEL: test_rfft2d_crop_height_pad_width +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[13, 2, 9, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[13, 2, 16]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_4:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 0, 0, 13]> : tensor<6xindex>} : () -> !tosa.shape<6> +// CHECK-DAG: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> : () -> tensor<1xf32> +// CHECK: %[[VAL_6:.*]] = tosa.pad %arg0, %[[VAL_4]], %[[VAL_5]] : (tensor<13x21x3xf32>, !tosa.shape<6>, tensor<1xf32>) -> tensor<13x21x16xf32> +// CHECK: %[[VAL_7:.*]] = tosa.slice %[[VAL_6]], %[[VAL_2]], %[[VAL_3]] : (tensor<13x21x16xf32>, !tosa.shape<3>, !tosa.shape<3>) -> tensor<13x2x16xf32> +// CHECK: %[[VAL_8:.*]], %[[VAL_9:.*]] = tosa.rfft2d %[[VAL_7]] : (tensor<13x2x16xf32>) -> (tensor<13x2x9xf32>, tensor<13x2x9xf32>) +// CHECK: %[[VAL_10:.*]] = tosa.reshape %[[VAL_8]], %[[VAL_1]] : (tensor<13x2x9xf32>, !tosa.shape<4>) -> tensor<13x2x9x1xf32> +// CHECK: %[[VAL_11:.*]] = tosa.reshape %[[VAL_9]], %[[VAL_1]] : (tensor<13x2x9xf32>, !tosa.shape<4>) -> tensor<13x2x9x1xf32> +// CHECK: %[[VAL_12:.*]] = tosa.concat %[[VAL_10]], %[[VAL_11]] {axis = 3 : i32} : (tensor<13x2x9x1xf32>, tensor<13x2x9x1xf32>) -> tensor<13x2x9x2xf32> +func.func @test_rfft2d_crop_height_pad_width(%arg0: tensor<13x21x3xf32>) -> (tensor<13x2x9xcomplex>) { + %0 = "tfl.pseudo_const"() {value = dense<[[0, 0], [0, 0], [0, 13]]> : tensor<3x2xi32>} : () -> tensor<3x2xi32> + %1 = "tfl.pad"(%arg0, %0) : (tensor<13x21x3xf32>, tensor<3x2xi32>) -> tensor<13x21x16xf32> + %2 = "tfl.pseudo_const"() {value = dense<[2, 16]> : tensor<2xi32>} : () -> tensor<2xi32> + %3 = "tfl.rfft2d"(%1, %2) : (tensor<13x21x16xf32>, tensor<2xi32>) -> tensor<13x2x9xcomplex> + return %3 : tensor<13x2x9xcomplex> +} + +// ----- + +// CHECK-LABEL: test_real +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[1, 8, 9]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<0> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 8, 9, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_4:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_3]] : (tensor<1x8x9x2xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x8x9x1xf32> +// CHECK: %[[VAL_5:.*]] = tosa.reshape %[[VAL_4]], %[[VAL_1]] : (tensor<1x8x9x1xf32>, !tosa.shape<3>) -> tensor<1x8x9xf32> +func.func @test_real(%arg0: tensor<1x8x9xcomplex>) -> (tensor<1x8x9xf32>) { + %0 = "tfl.real"(%arg0) {} : (tensor<1x8x9xcomplex>) -> tensor<1x8x9xf32> + return %0 : tensor<1x8x9xf32> +} + +// ----- + +// CHECK-LABEL: test_real_non_complex +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x8x9xf32> +// CHECK: %[[VAL_1:.*]] = tosa.identity %arg0 : (tensor<1x8x9xf32>) -> tensor<1x8x9xf32> +// CHECK: return %[[VAL_1]] +func.func @test_real_non_complex(%arg0: tensor<1x8x9xf32>) -> (tensor<1x8x9xf32>) { + %0 = "tfl.real"(%arg0) {} : (tensor<1x8x9xf32>) -> tensor<1x8x9xf32> + return %0 : tensor<1x8x9xf32> +} + +// ----- + +// CHECK-LABEL: test_imag +// CHECK-DAG: %[[VAL_1:.*]] = tosa.const_shape {values = dense<[1, 8, 9]> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK-DAG: %[[VAL_2:.*]] = tosa.const_shape {values = dense<[0, 0, 0, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_3:.*]] = tosa.const_shape {values = dense<[1, 8, 9, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_4:.*]] = tosa.slice %arg0, %[[VAL_2]], %[[VAL_3]] : (tensor<1x8x9x2xf32>, !tosa.shape<4>, !tosa.shape<4>) -> tensor<1x8x9x1xf32> +// CHECK: %[[VAL_5:.*]] = tosa.reshape %[[VAL_4]], %[[VAL_1]] : (tensor<1x8x9x1xf32>, !tosa.shape<3>) -> tensor<1x8x9xf32> +func.func @test_imag(%arg0: tensor<1x8x9xcomplex>) -> (tensor<1x8x9xf32>) { + %0 = "tfl.imag"(%arg0) {} : (tensor<1x8x9xcomplex>) -> tensor<1x8x9xf32> + return %0 : tensor<1x8x9xf32> +} + +// ----- + +// CHECK-LABEL: test_imag_non_complex +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x8x9xf32> +// CHECK-DAG: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1x8x9xf32>}> : () -> tensor<1x8x9xf32> +// CHECK: return %[[VAL_1]] : tensor<1x8x9xf32> +func.func @test_imag_non_complex(%arg0: tensor<1x8x9xf32>) -> (tensor<1x8x9xf32>) { + %0 = "tfl.imag"(%arg0) {} : (tensor<1x8x9xf32>) -> tensor<1x8x9xf32> + return %0 : tensor<1x8x9xf32> +} + +// ----- + +// CHECK-LABEL: test_squared_difference_qi8 +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = tosa.rescale %arg0 +// CHECK-DAG: %[[VAR1:.*]] = tosa.rescale %arg1 +// CHECK-DAG: %[[VAR2:.*]] = tosa.rescale %[[VAR0]] +// CHECK-DAG: %[[VAR3:.*]] = tosa.rescale %[[VAR1]] +// CHECK-DAG: %[[VAR4:.*]] = tosa.sub %[[VAR2]], %[[VAR3]] +// CHECK-DAG: %[[VAR5:.*]] = tosa.mul %[[VAR4]], %[[VAR4]], %[[SHIFT]] +// CHECK-DAG: %[[VAR6:.*]] = tosa.rescale %[[VAR5]] +// CHECK: return %[[VAR6]] +func.func @test_squared_difference_qi8(%arg0: tensor<1x197x768x!quant.uniform>, %arg1: tensor<1x197x1x!quant.uniform>) -> tensor<1x197x768x!quant.uniform> { + %0 = "tfl.squared_difference"(%arg0, %arg1) : (tensor<1x197x768x!quant.uniform>, tensor<1x197x1x!quant.uniform>) -> tensor<1x197x768x!quant.uniform> + func.return %0 : tensor<1x197x768x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_squared_difference_f32 +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK-DAG: %[[VAR0:.*]] = tosa.sub %arg0, %arg1 +// CHECK-DAG: %[[VAR1:.*]] = tosa.mul %[[VAR0]], %[[VAR0]], %[[SHIFT]] +// CHECK: return %[[VAR1]] +func.func @test_squared_difference_f32(%arg0: tensor<1x197x768xf32>, %arg1: tensor<1x197x1xf32>) -> tensor<1x197x768xf32> { + %0 = "tfl.squared_difference"(%arg0, %arg1) : (tensor<1x197x768xf32>, tensor<1x197x1xf32>) -> tensor<1x197x768xf32> + func.return %0 : tensor<1x197x768xf32> +} + +// ----- + +// CHECK-LABEL: test_squared_difference_with_unequal_ranks_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x304x1x44x!quant.uniform> +// CHECK-SAME: %[[VAL_1:.*]]: tensor<44x!quant.uniform> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<49> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<2132442608> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = tosa.const_shape {values = dense<[1, 1, 1, 44]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<38> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<1091903658> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<31> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_10:.*]] = "tosa.const"() <{values = dense<-16> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_11:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_12:.*]] = "tosa.const"() <{values = dense<23> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_13:.*]] = "tosa.const"() <{values = dense<-2> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_14:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_15:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_11]], %[[VAL_12]], %[[VAL_13]], %[[VAL_14]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x304x1x44x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<1x304x1x44xi32> +// CHECK: %[[VAL_16:.*]] = tosa.rescale %[[VAL_1]], %[[VAL_11]], %[[VAL_12]], %[[VAL_10]], %[[VAL_14]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<44x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<44xi32> +// CHECK: %[[VAL_17:.*]] = tosa.rescale %[[VAL_15]], %[[VAL_11]], %[[VAL_9]], %[[VAL_14]], %[[VAL_14]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x304x1x44xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<1x304x1x44xi32> +// CHECK: %[[VAL_18:.*]] = tosa.rescale %[[VAL_16]], %[[VAL_8]], %[[VAL_7]], %[[VAL_14]], %[[VAL_14]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<44xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi32>) -> tensor<44xi32> +// CHECK: %[[VAL_19:.*]] = tosa.reshape %[[VAL_18]], %[[VAL_6]] : (tensor<44xi32>, !tosa.shape<4>) -> tensor<1x1x1x44xi32> +// CHECK: %[[VAL_20:.*]] = tosa.sub %[[VAL_17]], %[[VAL_19]] : (tensor<1x304x1x44xi32>, tensor<1x1x1x44xi32>) -> tensor<1x304x1x44xi32> +// CHECK: %[[VAL_21:.*]] = tosa.mul %[[VAL_20]], %[[VAL_20]], %[[VAL_5]] : (tensor<1x304x1x44xi32>, tensor<1x304x1x44xi32>, tensor<1xi8>) -> tensor<1x304x1x44xi32> +// CHECK: %[[VAL_22:.*]] = tosa.rescale %[[VAL_21]], %[[VAL_4]], %[[VAL_3]], %[[VAL_14]], %[[VAL_2]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x304x1x44xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x304x1x44x!quant.uniform> +func.func @test_squared_difference_with_unequal_ranks_qi8(%arg0: tensor<1x304x1x44x!quant.uniform>, %arg1: tensor<44x!quant.uniform>) -> tensor<1x304x1x44x!quant.uniform> { + %0 = "tfl.squared_difference"(%arg0, %arg1) : (tensor<1x304x1x44x!quant.uniform>, tensor<44x!quant.uniform>) -> tensor<1x304x1x44x!quant.uniform> + func.return %0 : tensor<1x304x1x44x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_squared_difference_with_unequal_ranks_f32 +// CHECK: %[[C:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[CS:.*]] = tosa.const_shape {values = dense<[1, 1, 1, 44]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[RH:.*]] = tosa.reshape %arg1, %[[CS]] : (tensor<44xf32>, !tosa.shape<4>) -> tensor<1x1x1x44xf32> +// CHECK: %[[SUB:.*]] = tosa.sub %arg0, %[[RH]] +// CHECK: %[[MUL:.*]] = tosa.mul %[[SUB]], %[[SUB]], %[[C]] +// CHECK: return %[[MUL]] : tensor<1x304x1x44xf32> +func.func @test_squared_difference_with_unequal_ranks_f32(%arg0: tensor<1x304x1x44xf32>, %arg1: tensor<44xf32>) -> tensor<1x304x1x44xf32> { + %0 = "tfl.squared_difference"(%arg0, %arg1) : (tensor<1x304x1x44xf32>, tensor<44xf32>) -> tensor<1x304x1x44xf32> + func.return %0 : tensor<1x304x1x44xf32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_f32 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<-0.000000e+00> : tensor<3x3x13x7xf32>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xf32>, !tosa.shape<4>) +// CHECK: %[[VAL_2:.*]] = tosa.add %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xf32>, tensor<3x3x13x7xf32>) -> tensor<3x3x13x7xf32> +// CHECK: return %[[VAL_2]] : tensor<3x3x13x7xf32> +func.func @test_broadcast_to_f32(%arg0: tensor<13x1xf32>) -> (tensor<3x3x13x7xf32>) { + %shape = arith.constant dense<[3, 3, 1, 7]> : tensor<4xi32> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<13x1xf32>, tensor<4xi32>) -> tensor<3x3x13x7xf32> + return %1 : tensor<3x3x13x7xf32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_f16 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<-0.000000e+00> : tensor<3x3x13x7xf16>}> +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xf16>, !tosa.shape<4>) +// CHECK: %[[VAL_2:.*]] = tosa.add %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xf16>, tensor<3x3x13x7xf16>) -> tensor<3x3x13x7xf16> +// CHECK: return %[[VAL_2]] : tensor<3x3x13x7xf16> +func.func @test_broadcast_to_f16(%arg0: tensor<13x1xf16>) -> (tensor<3x3x13x7xf16>) { + %shape = arith.constant dense<[3, 3, 1, 7]> : tensor<4xi32> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<13x1xf16>, tensor<4xi32>) -> tensor<3x3x13x7xf16> + return %1 : tensor<3x3x13x7xf16> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_i32 +// CHECK-DAG: %[[VAL_10]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<0> : tensor<7x7x13x3xi32>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xi32>, !tosa.shape<4>) +// CHECK: %[[VAL_2:.*]] = tosa.add %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xi32>, tensor<7x7x13x3xi32>) -> tensor<7x7x13x3xi32> +// CHECK: return %[[VAL_2]] : tensor<7x7x13x3xi32> +func.func @test_broadcast_to_i32(%arg0: tensor<13x1xi32>) -> (tensor<3x3x13x3xi32>) { + %shape = arith.constant dense<[7, 7, 13, 3]> : tensor<4xi64> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<13x1xi32>, tensor<4xi64>) -> tensor<3x3x13x3xi32> + return %1 : tensor<3x3x13x3xi32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_i1 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense : tensor<7x7x13x7xi1>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] : (tensor<13x1xi1>, !tosa.shape<4>) +// CHECK: %[[VAL_2:.*]] = tosa.logical_or %[[VAL_1]], %[[VAL_0]] : (tensor<1x1x13x1xi1>, tensor<7x7x13x7xi1>) -> tensor<7x7x13x7xi1> +// CHECK: return %[[VAL_2]] : tensor<7x7x13x7xi1> +func.func @test_broadcast_to_i1(%arg0: tensor<13x1xi1>) -> (tensor<7x7x13x7xi1>) { + %shape = arith.constant dense<[7, 7, 13, 7]> : tensor<4xi64> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<13x1xi1>, tensor<4xi64>) -> tensor<7x7x13x7xi1> + return %1 : tensor<7x7x13x7xi1> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_qi8 +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 13, 1]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<0> : tensor<7x7x13x3xi32>} +// CHECK: %[[VAL_1:.*]] = tosa.reshape %arg0, %[[VAL_10]] +// CHECK: %[[VAL_2:.*]] = tosa.cast %2 : (tensor<1x1x13x1x!quant.uniform>) -> tensor<1x1x13x1xi32> +// CHECK: %[[VAL_3:.*]] = tosa.add %[[VAL_2]], %[[VAL_0]] : (tensor<1x1x13x1xi32>, tensor<7x7x13x3xi32>) -> tensor<7x7x13x3xi32> +// CHECK: %[[VAL_4:.*]] = tosa.cast %4 : (tensor<7x7x13x3xi32>) -> tensor<7x7x13x3x!quant.uniform> +// CHECK: return %[[VAL_4]] : tensor<7x7x13x3x!quant.uniform> +func.func @test_broadcast_to_qi8(%arg0: tensor<13x1x!quant.uniform>) -> (tensor<7x7x13x3x!quant.uniform>) { + %shape = arith.constant dense<[7, 7, 1, 3]> : tensor<4xi64> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<13x1x!quant.uniform>, tensor<4xi64>) -> tensor<7x7x13x3x!quant.uniform> + return %1 : tensor<7x7x13x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_smaller_rank +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<[13, 7]> : tensor<2xi64>} +// CHECK: %[[VAL_1:.*]] = "tfl.broadcast_to"(%arg0, %[[VAL_0]]) : (tensor<2x3x13x1xi32>, tensor<2xi64>) -> tensor<13x7xi32> +// CHECK: return %[[VAL_1]] : tensor<13x7xi32> +func.func @test_broadcast_to_smaller_rank(%arg0: tensor<2x3x13x1xi32>) -> (tensor<13x7xi32>) { + %shape = arith.constant dense<[13, 7]> : tensor<2xi64> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<2x3x13x1xi32>, tensor<2xi64>) -> tensor<13x7xi32> + return %1 : tensor<13x7xi32> +} + +// ----- + +// CHECK-LABEL: test_broadcast_to_i48 +// CHECK: %[[VAL_0:.*]] = "tosa.const"() <{values = dense<[7, 7, 1, 7]> : tensor<4xi64>} +// CHECK: %[[VAL_1:.*]] = "tfl.broadcast_to"(%arg0, %[[VAL_0]]) : (tensor<1x1x13x1xi48>, tensor<4xi64>) -> tensor<7x7x13x7xi48> +// CHECK: return %[[VAL_1]] : tensor<7x7x13x7xi48> +func.func @test_broadcast_to_i48(%arg0: tensor<1x1x13x1xi48>) -> (tensor<7x7x13x7xi48>) { + %shape = arith.constant dense<[7, 7, 1, 7]> : tensor<4xi64> + %1 = "tfl.broadcast_to"(%arg0, %shape) : (tensor<1x1x13x1xi48>, tensor<4xi64>) -> tensor<7x7x13x7xi48> + return %1 : tensor<7x7x13x7xi48> +} + +// ----- + +// CHECK-LABEL: test_transpose_conv2d_bias_f32 +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<128xf32>}> : () -> tensor<128xf32> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<-1.000000e+00> : tensor<128x2x2x256xf32>}> : () -> tensor<128x2x2x256xf32> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.transpose_conv2d %arg0, %[[VAR1]], %[[VAR0]], %[[VAR2]], %[[VAR2]] {acc_type = f32, out_pad = array, stride = array} +func.func @test_transpose_conv2d_bias_f32(%arg0: tensor<1x64x64x256xf32>) -> tensor<1x128x128x128xf32> { + %cst = arith.constant dense<[1, 128, 128, 128]> : tensor<4xi32> + %0 = arith.constant dense<-1.000000e+00> : tensor<128x2x2x256xf32> + %1 = arith.constant dense<1.000000e+00> : tensor<128xf32> + %2 = "tfl.transpose_conv"(%cst, %0, %arg0, %1) {padding = "VALID", stride_h = 2 : i32, stride_w = 2 : i32, fused_activation_function = "NONE"} : (tensor<4xi32>, tensor<128x2x2x256xf32>, tensor<1x64x64x256xf32>, tensor<128xf32>) -> tensor<1x128x128x128xf32> + return %2 : tensor<1x128x128x128xf32> +} + +// ----- + +// CHECK-LABEL: test_mul_with_unequal_ranks +// CHECK-DAG: %[[VAL_10:.*]] = tosa.const_shape {values = dense<[1, 1, 1, 384]> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK-DAG: %[[SHIFT:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> +// CHECK: %[[VAR0:.*]] = tosa.reshape %arg1, %[[VAL_10]] : (tensor<384xf32>, !tosa.shape<4>) -> tensor<1x1x1x384xf32> +// CHECK: %[[VAR1:.*]] = tosa.mul %arg0, %[[VAR0]], %[[SHIFT]] : (tensor, tensor<1x1x1x384xf32>, tensor<1xi8>) +func.func @test_mul_with_unequal_ranks(%arg0: tensor, %arg1: tensor<384xf32>) -> tensor { + %0 = "tfl.mul"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor, tensor<384xf32>) -> tensor + func.return %0 : tensor +} + +// ----- + +// CHECK-LABEL: test_mul_with_unequal_ranks_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1x192x192x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<38> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1077952640> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = tosa.const_shape {values = dense<1> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<127> : tensor}> : () -> tensor> +// CHECK: %[[VAL_6:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_7:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_8:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_9:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_10:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_6]], %[[VAL_7]], %[[VAL_8]], %[[VAL_9]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x192x192x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<1x192x192x3xi32> +// CHECK: %[[VAL_11:.*]] = tosa.rescale %[[VAL_5]], %[[VAL_6]], %[[VAL_7]], %[[VAL_8]], %[[VAL_9]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor +// CHECK: %[[VAL_12:.*]] = tosa.reshape %[[VAL_11]], %[[VAL_4]] : (tensor, !tosa.shape<4>) -> tensor<1x1x1x1xi32> +// CHECK: %[[VAL_13:.*]] = tosa.mul %[[VAL_10]], %[[VAL_12]], %[[VAL_3]] : (tensor<1x192x192x3xi32>, tensor<1x1x1x1xi32>, tensor<1xi8>) -> tensor<1x192x192x3xi32> +// CHECK: %[[VAL_14:.*]] = tosa.rescale %[[VAL_13]], %[[VAL_2]], %[[VAL_1]], %[[VAL_9]], %[[VAL_8]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<1x192x192x3xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<1x192x192x3x!quant.uniform> +func.func @test_mul_with_unequal_ranks_qi8(%arg0: tensor<1x192x192x3x!quant.uniform>) -> tensor<1x192x192x3x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor>, value = dense<127> : tensor} : () -> tensor> + %1 = tfl.mul(%arg0, %0) {fused_activation_function = "NONE"} : (tensor<1x192x192x3x!quant.uniform>, tensor>) -> tensor<1x192x192x3x!quant.uniform> + func.return %1 : tensor<1x192x192x3x!quant.uniform> +} + + +// ----- + +// CHECK-LABEL: test_sub_with_unequal_ranks_qi8 +// CHECK: %[[CS:.*]] = tosa.const_shape {values = dense<1> : tensor<4xindex>} : () -> !tosa.shape<4> +// CHECK: %[[C:.*]] = "tosa.const"() <{values = dense<127> : tensor}> : () -> tensor> +// CHECK: %[[RS1:.*]] = tosa.rescale %arg0 +// CHECK: %[[RS2:.*]] = tosa.rescale %[[C]] +// CHECK: %[[RS3:.*]] = tosa.rescale %[[RS2]] +// CHECK: %[[RH:.*]] = tosa.reshape %[[RS3]], %[[CS]] : (tensor, !tosa.shape<4>) -> tensor<1x1x1x1xi32> +// CHECK: %[[SUB:.*]] = tosa.sub %[[RS1]], %[[RH]] : (tensor<1x192x192x3xi32>, tensor<1x1x1x1xi32>) -> tensor<1x192x192x3xi32> +// CHECK: %[[RS4:.*]] = tosa.rescale %[[SUB]] +// CHECK: return %[[RS4]] : tensor<1x192x192x3x!quant.uniform> +func.func @test_sub_with_unequal_ranks_qi8(%arg0: tensor<1x192x192x3x!quant.uniform>) -> tensor<1x192x192x3x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor>, value = dense<127> : tensor} : () -> tensor> + %1 = tfl.sub(%arg0, %0) {fused_activation_function = "NONE"} : (tensor<1x192x192x3x!quant.uniform>, tensor>) -> tensor<1x192x192x3x!quant.uniform> + func.return %1 : tensor<1x192x192x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_add_with_unequal_ranks_qi8 +// CHECK: %[[CS:.*]] = tosa.const_shape {values = dense<1> : tensor<3xindex>} : () -> !tosa.shape<3> +// CHECK: %[[C:.*]] = "tosa.const"() <{values = dense<127> : tensor}> : () -> tensor> +// CHECK: %[[RS1:.*]] = tosa.rescale %arg0 +// CHECK: %[[RS2:.*]] = tosa.rescale %[[C]] +// CHECK: %[[RS3:.*]] = tosa.rescale %[[RS2]] +// CHECK: %[[RH:.*]] = tosa.reshape %[[RS3]], %[[CS]] : (tensor, !tosa.shape<3>) -> tensor<1x1x1xi32> +// CHECK: %[[ADD:.*]] = tosa.add %[[RS1]], %[[RH]] : (tensor<48x48x17xi32>, tensor<1x1x1xi32>) -> tensor<48x48x17xi32> +// CHECK: %[[RS4:.*]] = tosa.rescale %[[ADD]] +// CHECK: return %[[RS4]] : tensor<48x48x17x!quant.uniform> +func.func @test_add_with_unequal_ranks_qi8(%arg0: tensor<48x48x17x!quant.uniform>) -> tensor<48x48x17x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor>, value = dense<127> : tensor} : () -> tensor> + %1 = tfl.add(%arg0, %0) {fused_activation_function = "NONE"} : (tensor<48x48x17x!quant.uniform>, tensor>) -> tensor<48x48x17x!quant.uniform> + func.return %1 : tensor<48x48x17x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_cast_ui8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3xui8> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<-128> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_6:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_2]], %[[VAL_3]], %[[VAL_4]], %[[VAL_5]] {input_unsigned = true, output_unsigned = false, per_channel = false, rounding_mode = SINGLE_ROUND, scale32 = true} : (tensor<13x21x3xui8>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi8>) -> tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_7:.*]] = tosa.rescale %[[VAL_6]], %[[VAL_2]], %[[VAL_3]], %[[VAL_5]], %[[VAL_1]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_8:.*]] = tosa.cast %[[VAL_7]] : (tensor<13x21x3xi32>) -> tensor<13x21x3xf32> +// CHECK: return %[[VAL_8]] : tensor<13x21x3xf32> +func.func @test_cast_ui8(%arg0: tensor<13x21x3xui8>) -> (tensor<13x21x3xf32>) { + %0 = "tfl.cast"(%arg0) : (tensor<13x21x3xui8>) -> tensor<13x21x3xf32> + return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_cast_qi8 +// CHECK-SAME: %[[VAL_0:.*]]: tensor<13x21x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<30> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<-1> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_5:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]], %[[VAL_4]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<13x21x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<13x21x3xi32> +// CHECK: %[[VAL_6:.*]] = tosa.cast %[[VAL_5]] : (tensor<13x21x3xi32>) -> tensor<13x21x3xf32> +func.func @test_cast_qi8(%arg0: tensor<13x21x3x!quant.uniform>) -> (tensor<13x21x3xf32>) { + %0 = "tfl.cast"(%arg0) : (tensor<13x21x3x!quant.uniform>) -> tensor<13x21x3xf32> + return %0 : tensor<13x21x3xf32> +} + +// ----- + +// CHECK-LABEL: test_transpose_conv2d_bias_f32 +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<1.000000e+00> : tensor<128xf32>}> : () -> tensor<128xf32> +// CHECK-DAG: %[[VAR1:.*]] = "tosa.const"() <{values = dense<-1.000000e+00> : tensor<128x2x2x256xf32>}> : () -> tensor<128x2x2x256xf32> +// CHECK-DAG: %[[VAR2:.*]] = "tosa.const"() <{values = dense<0.000000e+00> : tensor<1xf32>}> +// CHECK-DAG: %[[VAR3:.*]] = tosa.transpose_conv2d %arg0, %[[VAR1]], %[[VAR0]], %[[VAR2]], %[[VAR2]] {acc_type = f32, out_pad = array, stride = array} +func.func @test_transpose_conv2d_bias_f32(%arg0: tensor<1x64x64x256xf32>) -> tensor<1x128x128x128xf32> { + %cst = arith.constant dense<[1, 128, 128, 128]> : tensor<4xi32> + %0 = arith.constant dense<-1.000000e+00> : tensor<128x2x2x256xf32> + %1 = arith.constant dense<1.000000e+00> : tensor<128xf32> + %2 = "tfl.transpose_conv"(%cst, %0, %arg0, %1) {padding = "VALID", stride_h = 2 : i32, stride_w = 2 : i32, fused_activation_function = "NONE"} : (tensor<4xi32>, tensor<128x2x2x256xf32>, tensor<1x64x64x256xf32>, tensor<128xf32>) -> tensor<1x128x128x128xf32> + return %2 : tensor<1x128x128x128xf32> +} + +// ----- + +// CHECK-LABEL: test_concat_qconst +// CHECK-DAG: %[[VAR0:.*]] = "tosa.const"() <{values = dense<42> : tensor<28x19xi8>}> : () -> tensor<28x19x!quant.uniform> +// CHECK-DAG: %[[VAR1:.*]] = tosa.concat %[[VAR0]], %arg0 {axis = 0 : i32} : (tensor<28x19x!quant.uniform>, tensor<1x19x!quant.uniform>) -> tensor<29x19x!quant.uniform> +func.func @test_concat_qconst(%arg0: tensor<1x19x!quant.uniform> ) -> tensor<29x19x!quant.uniform> { + %0 = "tfl.pseudo_qconst"() {qtype = tensor<28x19x!quant.uniform>, value = dense<42> : tensor<28x19xi8>} : () -> tensor<28x19x!quant.uniform> + %1 = "tfl.concatenation"(%0, %arg0) {axis = 0 : i32, fused_activation_function = "NONE"}: (tensor<28x19x!quant.uniform>, tensor<1x19x!quant.uniform>) -> tensor<29x19x!quant.uniform> + return %1 : tensor<29x19x!quant.uniform> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-stateful.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-stateful.mlir new file mode 100644 index 0000000000000000000000000000000000000000..b5de5ae30965d5a92e72bd4501168cc47adc7006 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-to-tosa-stateful.mlir @@ -0,0 +1,93 @@ +// RUN: tf-tosa-opt --split-input-file --tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + +// RUN: tf-tosa-opt --split-input-file --tf-tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + + +// Operations for testing tfl-to-tosa-pipeline + +// ----- + +// CHECK-LABEL: tosa.variable @var_x = dense<7.000000e+00> : tensor<1xf32> +// CHECK-LABEL: test_stateful_ops( +// CHECK-SAME: %[[VAL_0:.*]]: tensor<1xf32> +// CHECK: tosa.variable_write @var_x, %[[VAL_0]] : tensor<1xf32> +// CHECK: %[[VAL_1:.*]] = tosa.variable_read @var_x : tensor<1xf32> +// CHECK: return %[[VAL_1]] : tensor<1xf32> +module attributes {tf_saved_model.semantics, tfl.description = "Test.", tfl.schema_version = 3 : i32} { + func.func @test_stateful_ops(%arg0: tensor<1xf32> {tf_saved_model.index_path = ["placeholder_0"]}) + -> (tensor<1xf32> {tf_saved_model.index_path = ["output_0"]}) + attributes {tf_saved_model.exported_names = ["serving_default"]} { + "tfl.call_once"() {session_init_function = "InitializeX"} : () -> () + %0 = "tfl.var_handle"() {container = "", shared_name = "var_x"} : () -> tensor + "tfl.assign_variable"(%0, %arg0) : (tensor, tensor<1xf32>) -> () + %1 = "tfl.read_variable"(%0) : (tensor) -> tensor<1xf32> + return %1 : tensor<1xf32> + } + + // initialize variable var_x to 7.0 + func.func private @InitializeX() { + %0 = "tfl.var_handle"() {container = "", shared_name = "var_x"} : () -> tensor + %1 = "tfl.pseudo_const"() {value = dense<7.000000e+00> : tensor<1xf32>} : () -> tensor<1xf32> + "tfl.assign_variable"(%0, %1) : (tensor, tensor<1xf32>) -> () + return + } +} + +// ----- + +// CHECK-LABEL: tosa.variable @Variable = dense<42> : tensor<2x3xi8> +// CHECK-LABEL: readAssignQuant +// CHECK-SAME: %[[VAL_0:.*]]: tensor<2x3x!quant.uniform> +// CHECK: %[[VAL_1:.*]] = "tosa.const"() <{values = dense<49> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_2:.*]] = "tosa.const"() <{values = dense<0> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_3:.*]] = "tosa.const"() <{values = dense<2> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_4:.*]] = "tosa.const"() <{values = dense<11> : tensor<1xi8>}> : () -> tensor<1xi8> +// CHECK: %[[VAL_5:.*]] = "tosa.const"() <{values = dense<1073741824> : tensor<1xi32>}> : () -> tensor<1xi32> +// CHECK: %[[VAL_6:.*]] = tosa.variable_read @Variable : tensor<2x3xi8> +// CHECK: %[[VAL_7:.*]] = builtin.unrealized_conversion_cast %[[VAL_6]] : tensor<2x3xi8> to tensor<2x3x!quant.uniform> +// CHECK: %[[VAL_8:.*]] = tosa.rescale %[[VAL_7]], %[[VAL_5]], %[[VAL_4]], %[[VAL_3]], %[[VAL_2]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<2x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<2x3xi32> +// CHECK: %[[VAL_9:.*]] = tosa.rescale %[[VAL_0]], %[[VAL_5]], %[[VAL_4]], %[[VAL_3]], %[[VAL_2]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<2x3x!quant.uniform>, tensor<1xi32>, tensor<1xi8>, tensor<1xi8>, tensor<1xi32>) -> tensor<2x3xi32> +// CHECK: %[[VAL_10:.*]] = tosa.add %[[VAL_8]], %[[VAL_9]] : (tensor<2x3xi32>, tensor<2x3xi32>) -> tensor<2x3xi32> +// CHECK: %[[VAL_11:.*]] = tosa.rescale %[[VAL_10]], %[[VAL_5]], %[[VAL_1]], %[[VAL_2]], %[[VAL_3]] {input_unsigned = false, output_unsigned = false, per_channel = false, rounding_mode = DOUBLE_ROUND, scale32 = true} : (tensor<2x3xi32>, tensor<1xi32>, tensor<1xi8>, tensor<1xi32>, tensor<1xi8>) -> tensor<2x3x!quant.uniform> +// CHECK: %[[VAL_12:.*]] = builtin.unrealized_conversion_cast %[[VAL_11]] : tensor<2x3x!quant.uniform> to tensor<2x3xi8> +// CHECK: tosa.variable_write @Variable, %[[VAL_12]] : tensor<2x3xi8> +// CHECK: return %[[VAL_11]] : tensor<2x3x!quant.uniform> +module { + func.func @readAssignQuant(%arg0: tensor<2x3x!quant.uniform>) -> (tensor<2x3x!quant.uniform>) { + "tfl.call_once"() {session_init_function = "ReadAssignInit"} : () -> () + %0 = "tfl.var_handle"() {container = "", shared_name = "Variable"} : () -> tensor<*x!tf_type.resource> + %1 = "tfl.read_variable"(%0) : (tensor<*x!tf_type.resource>) -> tensor<2x3x!quant.uniform> + %2 = tfl.add %1, %arg0 {fused_activation_function = "NONE"} : tensor<2x3x!quant.uniform> + "tfl.assign_variable"(%0, %2) : (tensor<*x!tf_type.resource>, tensor<2x3x!quant.uniform>) -> () + return %2 : tensor<2x3x!quant.uniform> + } + func.func private @ReadAssignInit() { + %0 = "tfl.var_handle"() {container = "", shared_name = "Variable"} : () -> tensor<*x!tf_type.resource> + %1 = "tfl.pseudo_const"() {qtype = tensor<2x3x!quant.uniform>, value = dense<42> : tensor<2x3xi8>} : () -> tensor<2x3x!quant.uniform> + "tfl.assign_variable"(%0, %1) : (tensor<*x!tf_type.resource>, tensor<2x3x!quant.uniform>) -> () + return + } +} + +// ----- + +module { + // CHECK-LABEL: @nostate + // CHECK: %[[VAL_0:.*]]: tensor<16x16xf32>) -> tensor<16x16xf32> { + // CHECK: %[[VAL_1:.*]] = "tfl.var_handle"() <{container = "", shared_name = "Variable"}> : () -> tensor<*x!tf_type.resource> + // CHECK: %[[VAL_2:.*]] = "tfl.read_variable"(%[[VAL_1]]) : (tensor<*x!tf_type.resource>) -> tensor<16x16xf32> + // CHECK: %[[VAL_3:.*]] = tosa.add %[[VAL_2]], %[[VAL_0]] : (tensor<16x16xf32>, tensor<16x16xf32>) -> tensor<16x16xf32> + // CHECK: "tfl.assign_variable"(%[[VAL_1]], %[[VAL_3]]) : (tensor<*x!tf_type.resource>, tensor<16x16xf32>) -> () + // CHECK: return %[[VAL_3]] : tensor<16x16xf32> + func.func @nostate(%arg0: tensor<16x16xf32>) -> (tensor<16x16xf32>) { + "tfl.call_once"() {session_init_function = "NoStateInit"} : () -> () + %0 = "tfl.var_handle"() {container = "", shared_name = "Variable"} : () -> tensor<*x!tf_type.resource> + %1 = "tfl.read_variable"(%0) : (tensor<*x!tf_type.resource>) -> tensor<16x16xf32> + %2 = tfl.add %1, %arg0 {fused_activation_function = "NONE"} : tensor<16x16xf32> + "tfl.assign_variable"(%0, %2) : (tensor<*x!tf_type.resource>, tensor<16x16xf32>) -> () + return %2 : tensor<16x16xf32> + } + func.func private @NoStateInit() { + return + } +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-unequal-ranks.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-unequal-ranks.mlir new file mode 100644 index 0000000000000000000000000000000000000000..5164993758bd54175a75054ac8bf514198d9c510 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tfl-unequal-ranks.mlir @@ -0,0 +1,192 @@ +// RUN: tf-tosa-opt --split-input-file --tfl-to-tosa-pipeline --verify-each %s | FileCheck %s + +// Test tf legalization that produce TOSA ResultsBroadcastableShape operators with unequal ranks + +// ----- + +// CHECK-LABEL: test_add +func.func @test_add(%arg0: tensor<192x192x3xf32>, %arg1: tensor<16x192x192x3xf32>) -> tensor<16x192x192x3xf32> { + // CHECK: tosa.add + %1 = tfl.add(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<192x192x3xf32>, tensor<16x192x192x3xf32>) -> tensor<16x192x192x3xf32> + func.return %1 : tensor<16x192x192x3xf32> +} + +// ----- + +// CHECK-LABEL: test_add_dynamic +func.func @test_add_dynamic(%arg0: tensor, %arg1: tensor<5xf32>) -> tensor { + // CHECK: tosa.add + %1 = tfl.add(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor, tensor<5xf32>) -> tensor + func.return %1 : tensor +} + +// ----- + +// CHECK-LABEL: test_add_qi8 +func.func @test_add_qi8(%arg0: tensor<13x21x1x!quant.uniform>, %arg1: tensor<1x13x21x3x!quant.uniform>) -> tensor<1x13x21x3x!quant.uniform> { + // CHECK: tosa.add + %0 = tfl.add(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x1x!quant.uniform>, tensor<1x13x21x3x!quant.uniform>) -> tensor<1x13x21x3x!quant.uniform> + func.return %0 : tensor<1x13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_sub +func.func @test_sub(%arg0: tensor<192x192x3xf32>, %arg1: tensor<16x192x192x3xf32>) -> tensor<16x192x192x3xf32> { + // CHECK: tosa.sub + %1 = tfl.sub(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<192x192x3xf32>, tensor<16x192x192x3xf32>) -> tensor<16x192x192x3xf32> + func.return %1 : tensor<16x192x192x3xf32> +} + +// ----- + +// CHECK-LABEL: test_sub_qi8 +func.func @test_sub_qi8(%arg0: tensor<13x21x1x!quant.uniform>, %arg1: tensor<1x13x21x3x!quant.uniform>) -> tensor<1x13x21x3x!quant.uniform> { + // CHECK: tosa.sub + %0 = tfl.sub(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x1x!quant.uniform>, tensor<1x13x21x3x!quant.uniform>) -> tensor<1x13x21x3x!quant.uniform> + func.return %0 : tensor<1x13x21x3x!quant.uniform> +} + +// ----- + +// CHECK-LABEL: test_equal +// CHECK: tosa.equal +func.func @test_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x1x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tfl.equal"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x13x1x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_not_equal +// CHECK: tosa.equal +// CHECK: tosa.logical_not +func.func @test_not_equal(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x1x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tfl.not_equal"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x13x1x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_greater_equal +// CHECK: tosa.greater_equal +func.func @test_greater_equal(%arg0: tensor<13x1x3xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tfl.greater_equal"(%arg0, %arg1) : (tensor<13x1x3xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_greater +// CHECK: tosa.greater +func.func @test_greater(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tfl.greater"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_less +// CHECK: tosa.greater +func.func @test_less(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tfl.less"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_less_equal +// CHECK: tosa.greater_equal +func.func @test_less_equal(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> { + %2 = "tfl.less_equal"(%arg0, %arg1) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xi1> + func.return %2 : tensor<1x13x21x3xi1> +} + +// ----- +// CHECK-LABEL: test_select +// CHECK: tosa.select +func.func @test_select(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x21x3xf32>, %arg2: tensor<1xi1>) -> tensor<1x13x21x3xf32> { + %2 = "tfl.select_v2"(%arg2, %arg0, %arg1) : (tensor<1xi1>, tensor<13x21x3xf32>, tensor<1x13x21x3xf32>) -> tensor<1x13x21x3xf32> + func.return %2 : tensor<1x13x21x3xf32> +} + +// ----- +// CHECK-LABEL: test_mul_qi8 +// CHECK: tosa.mul +func.func @test_mul_qi8(%arg0: tensor<13x21x3x!quant.uniform>, %arg1: tensor<1x13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> { + %0 = "tfl.mul"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3x!quant.uniform>, tensor<1x13x21x3x!quant.uniform>) -> tensor<*x!quant.uniform> + func.return %0 : tensor<*x!quant.uniform> +} + +// ----- +// CHECK-LABEL: test_floor_div +// CHECK: tosa.intdiv +// CHECK: tosa.select +func.func @test_floor_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor<1x13x1x3xi32>) -> tensor<1x13x21x3xi32> { + %0 = "tfl.floor_div"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3xi32>, tensor<1x13x1x3xi32>) -> tensor<1x13x21x3xi32> + func.return %0 : tensor<1x13x21x3xi32> +} + +// ----- +// CHECK-LABEL: test_div +// CHECK: tosa.intdiv +func.func @test_div(%arg0: tensor<13x21x3xi32>, %arg1: tensor) -> tensor<*xi32> { + %0 = "tfl.div"(%arg0, %arg1) {fused_activation_function = "NONE"} : (tensor<13x21x3xi32>, tensor) -> tensor<*xi32> + func.return %0 : tensor<*xi32> +} + +// ----- + +// CHECK-LABEL: test_max +// CHECK: tosa.maximum +func.func @test_max(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x21x1xf32>) -> tensor<*xf32> { + %0 = "tfl.maximum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x13x21x1xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_min +// CHECK: tosa.minimum +func.func @test_min(%arg0: tensor<13x21x3xf32>, %arg1: tensor<1x13x21x1xf32>) -> tensor<*xf32> { + %0 = "tfl.minimum"(%arg0, %arg1) : (tensor<13x21x3xf32>, tensor<1x13x21x1xf32>) -> tensor<*xf32> + func.return %0 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_add +func.func @test_addn(%arg0: tensor<13x21x1xf32>, %arg1: tensor<1x13x21x3xf32>, %arg2: tensor<21x3xf32>, %arg3: tensor<3xf32>) -> tensor<*xf32> { + // CHECK: tosa.add + // CHECK: tosa.add + // CHECK: tosa.add + %2 = "tfl.add_n"(%arg0, %arg1, %arg2, %arg3) : (tensor<13x21x1xf32>, tensor<1x13x21x3xf32>, tensor<21x3xf32>, tensor<3xf32>) -> tensor<*xf32> + func.return %2 : tensor<*xf32> +} + +// ----- + +// CHECK-LABEL: test_logical_and +func.func @test_logical_and(%arg0: tensor<8x13x21x3xi1>, %arg1: tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> { + // CHECK: tosa.logical_and + %2 = "tfl.logical_and"(%arg0, %arg1) : (tensor<8x13x21x3xi1>, tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> + func.return %2 : tensor<8x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_logical_or +func.func @test_logical_or(%arg0: tensor<8x13x21x3xi1>, %arg1: tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> { + // CHECK: tosa.logical_or + %2 = "tfl.logical_or"(%arg0, %arg1) : (tensor<8x13x21x3xi1>, tensor<13x21x1xi1>) -> tensor<8x13x21x3xi1> + func.return %2 : tensor<8x13x21x3xi1> +} + +// ----- + +// CHECK-LABEL: test_power +func.func @test_power(%arg0: tensor<8x13x21x3xi32>, %arg1: tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> { + // CHECK: tosa.pow + %2 = "tfl.pow"(%arg0, %arg1) : (tensor<8x13x21x3xi32>, tensor<13x21x1xi32>) -> tensor<8x13x21x3xi32> + func.return %2 : tensor<8x13x21x3xi32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tosa-legalize-tfl-negative.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tosa-legalize-tfl-negative.mlir new file mode 100644 index 0000000000000000000000000000000000000000..a4d80a95254a5e4620b9b3de0665b032a42bdfca --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/tosa-legalize-tfl-negative.mlir @@ -0,0 +1,42 @@ +// RUN: tf-tosa-opt --split-input-file --tosa-legalize-tfl --verify-diagnostics %s | FileCheck %s + +// ----- +// CHECK-LABEL: max_pool_same_padding_dyn +// CHECK: tfl.max_pool_2d +func.func @max_pool_same_padding_dyn(%arg0: tensor) -> (tensor) { +%0 = "tfl.max_pool_2d"(%arg0) <{filter_height = 1 : i32, filter_width = 4 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 4 : i32}> : (tensor) -> tensor +return %0 : tensor +} + +// ----- +// CHECK-LABEL: avg_pool_same_padding_dyn +// CHECK: tfl.average_pool_2d +func.func @avg_pool_same_padding_dyn(%arg0: tensor) -> (tensor) { +%0 = "tfl.average_pool_2d"(%arg0) <{filter_height = 1 : i32, filter_width = 4 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 4 : i32}> : (tensor) -> tensor +return %0 : tensor +} + +// ----- +// CHECK-LABEL: conv2d_same_padding_dyn +// CHECK: tfl.conv_2d +func.func @conv2d_same_padding_dyn(%input: tensor<1x?x32x8xf32>, %filter: tensor<5x3x3x8xf32>, %bias: tensor<5xf32>) -> tensor<1x32x32x5xf32> { + %0 = "tfl.conv_2d"(%input, %filter, %bias) {dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 4 : i32, stride_w = 1 : i32} : (tensor<1x?x32x8xf32>, tensor<5x3x3x8xf32>, tensor<5xf32>) -> tensor<1x32x32x5xf32> + return %0 : tensor<1x32x32x5xf32> +} + +// ----- +// CHECK-LABEL: conv3d_same_padding_dyn +// CHECK: tfl.conv_3d +func.func @conv3d_same_padding_dyn(%arg0: tensor<2x2x7x?x2xf32>, %arg1: tensor<2x3x3x2x4xf32>) -> tensor<2x2x7x7x4xf32> { + %cst = "tfl.no_value"() {value} : () -> none + %0 = "tfl.conv_3d"(%arg0, %arg1, %cst) {dilation_d_factor = 1 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_d = 1 : i32, stride_h = 1 : i32, stride_w = 4 : i32} : (tensor<2x2x7x?x2xf32>, tensor<2x3x3x2x4xf32>, none) -> tensor<2x2x7x7x4xf32> + func.return %0 : tensor<2x2x7x7x4xf32> +} + +// ----- +// CHECK-LABEL: depthwise_conv2d_same_padding_dyn +// CHECK: tfl.depthwise_conv_2d +func.func @depthwise_conv2d_same_padding_dyn(%arg0: tensor, %arg1 : tensor<1x1x1x16xf32>, %arg2 : tensor<16xf32>) -> tensor { + %2 = "tfl.depthwise_conv_2d"(%arg0, %arg1, %arg2) {depth_multiplier = 2 : i32, dilation_h_factor = 1 : i32, dilation_w_factor = 1 : i32, fused_activation_function = "NONE", padding = "SAME", stride_h = 1 : i32, stride_w = 3 : i32} : (tensor, tensor<1x1x1x16xf32>, tensor<16xf32>) -> tensor + func.return %2 : tensor +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/verify_fully_converted.mlir b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/verify_fully_converted.mlir new file mode 100644 index 0000000000000000000000000000000000000000..74145fa2d0e2d4cf3c407562873dc0b546936c86 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tests/verify_fully_converted.mlir @@ -0,0 +1,20 @@ +// RUN: tf-tosa-opt %s --tosa-tflite-verify-fully-converted --split-input-file -verify-diagnostics + + +// CHECK-LABEL: func.func @main +func.func @main(%arg0: tensor<2xf32>) -> (tensor<2xf32>) { + // CHECK: "tosa.add" + %0 = "tosa.add"(%arg0, %arg0) : (tensor<2xf32>, tensor<2xf32>) -> tensor<2xf32> + return %0 : tensor<2xf32> +} + +// ----- + +// expected-error@below {{The following illegal operations still remain}} +func.func @main(%arg0: tensor<1x8x8x3xf32>) -> tensor<1x8x8x3xf32> attributes {tf.entry_function = {inputs = "input", outputs = "output"}} { + // expected-error@+1 {{'tfl.add' op : illegal op still exists}} + %0 = tfl.add %arg0, %arg0 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + // expected-error@+1 {{'tfl.sub' op : illegal op still exists}} + %1 = tfl.sub %0, %arg0 {fused_activation_function = "NONE"} : tensor<1x8x8x3xf32> + return %1 : tensor<1x8x8x3xf32> +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_passes.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_passes.cc new file mode 100644 index 0000000000000000000000000000000000000000..88bc3ff2d2c692c7ff056fa8b2710bb10e27aa37 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_passes.cc @@ -0,0 +1,67 @@ +/* Copyright 2020 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/mlir/tosa/tf_passes.h" + +#include "mlir/Dialect/Affine/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Transforms/Passes.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project +#include "mlir/Transforms/Passes.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +namespace mlir { +namespace tosa { + +void createTFtoTOSALegalizationPipeline( + OpPassManager& pm, const TOSATFLegalizationPipelineOptions& opts) { + //---------------------------------------------------------------------------- + // Prepare TFL module for conversion + //---------------------------------------------------------------------------- + // Inline all functions into main and then delete the functions themselves. + pm.addPass(mlir::createInlinerPass()); + + // Now that there is only one function, run some MLIR passes on it. + pm.addPass(mlir::createCanonicalizerPass()); + pm.addPass(mlir::createCSEPass()); + + pm.addPass(mlir::affine::createLoopFusionPass()); + pm.addPass(mlir::affine::createAffineScalarReplacementPass()); + + //---------------------------------------------------------------------------- + // Perform main conversion. + // Now that there is only one function, run some MLIR passes on it. + //---------------------------------------------------------------------------- + pm.addPass(mlir::tosa::createFuseBiasTFPass()); + pm.addPass(mlir::tosa::createLegalizeTFPass()); + + //---------------------------------------------------------------------------- + // Post conversion cleanup. + //---------------------------------------------------------------------------- + pm.addPass(mlir::tosa::createTosaInferShapesPass()); + pm.addPass(mlir::tosa::createTosaMakeBroadcastablePass()); + // Inline the call/return basic blocks within TOSA control flow ops. + pm.addPass(mlir::createInlinerPass()); + // Clean up with DCE. + pm.addPass(mlir::createSymbolDCEPass()); +} + +void registerTFtoTOSALegalizationPipeline() { + mlir::PassPipelineRegistration( + "tf-to-tosa-pipeline", "TensorFlow to TOSA legalization pipeline", + createTFtoTOSALegalizationPipeline); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_passes.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_passes.h new file mode 100644 index 0000000000000000000000000000000000000000..cd16d006029941b799358c66740194a02701fa0f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_passes.h @@ -0,0 +1,35 @@ +/* Copyright 2020 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_MLIR_TOSA_TF_PASSES_H_ +#define TENSORFLOW_COMPILER_MLIR_TOSA_TF_PASSES_H_ + +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Pass/PassOptions.h" // from @llvm-project + +namespace mlir::tosa { + +struct TOSATFLegalizationPipelineOptions + : public PassPipelineOptions {}; + +// Legalizes TF dialect(s) to Tosa. +void createTFtoTOSALegalizationPipeline( + OpPassManager& pm, const TOSATFLegalizationPipelineOptions& opts); + +void registerTFtoTOSALegalizationPipeline(); + +} // namespace mlir::mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TF_PASSES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tfl_passes.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tfl_passes.cc new file mode 100644 index 0000000000000000000000000000000000000000..c87a2f7f99fac25c790e20d7d5cc4236c7a7c21c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tfl_passes.cc @@ -0,0 +1,83 @@ +/* Copyright 2021 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/mlir/tosa/tf_tfl_passes.h" + +#include "mlir/Dialect/Affine/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Transforms/Passes.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project +#include "mlir/Transforms/Passes.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/transforms/lift_tflite_flex_ops.h" +#include "tensorflow/compiler/mlir/lite/transforms/passes.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +namespace mlir { +namespace tosa { + +void createTFTFLtoTOSALegalizationPipeline( + OpPassManager& pm, const TOSATFTFLLegalizationPipelineOptions& opts) { + //---------------------------------------------------------------------------- + // Prepare TFL module for conversion + //---------------------------------------------------------------------------- + // For stateful ops + pm.addPass(createRetainCallOnceFuncsPass()); + + // Inline all functions into main and then delete the functions themselves. + pm.addPass(mlir::createInlinerPass()); + + // Add pass to decompose TFLite mixed quantization to non-quantized variants. + pm.addPass(TFL::CreateDecomposeHybridQuantizationPass()); + + // Now that there is only one function, run some MLIR passes on it. + pm.addPass(mlir::createCanonicalizerPass()); + pm.addPass(mlir::createCSEPass()); + + pm.addPass(mlir::affine::createLoopFusionPass()); + pm.addPass(mlir::affine::createAffineScalarReplacementPass()); + + //---------------------------------------------------------------------------- + // Perform main conversion. + //---------------------------------------------------------------------------- + pm.addPass(mlir::TFL::CreateLiftTfliteFlexOpsPass()); + pm.addPass(mlir::tosa::createFuseBiasTFPass()); + pm.addPass(mlir::tosa::createConvertTFLUnsignedIntToSignedPass()); + if (opts.dequantize_tfl_softmax) { + pm.addPass(mlir::tosa::createDequantizeTFLSoftmaxPass()); + } + pm.addPass(mlir::tosa::createLegalizeTFLStatefulPass()); + pm.addPass(mlir::tosa::createLegalizeTFTFLPass()); + + //---------------------------------------------------------------------------- + // Post conversion cleanup. + //---------------------------------------------------------------------------- + pm.addPass(mlir::tosa::createLowerComplexTypesPass()); + pm.addPass(mlir::tosa::createTosaInferShapesPass()); + pm.addPass(mlir::tosa::createTosaMakeBroadcastablePass()); + // Inline the call/return basic blocks within TOSA control flow ops. + pm.addPass(mlir::createInlinerPass()); + // Clean up with DCE. + pm.addPass(mlir::createSymbolDCEPass()); +} + +void registerTFTFLtoTOSALegalizationPipeline() { + mlir::PassPipelineRegistration( + "tf-tfl-to-tosa-pipeline", + "TensorFlow / TensorFlow Lite to TOSA legalization pipeline", + createTFTFLtoTOSALegalizationPipeline); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tfl_passes.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tfl_passes.h new file mode 100644 index 0000000000000000000000000000000000000000..17395e552c5fa8180c8b0416ce532f9a6ef49d4d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tfl_passes.h @@ -0,0 +1,39 @@ +/* Copyright 2021 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_MLIR_TOSA_TF_TFL_PASSES_H_ +#define TENSORFLOW_COMPILER_MLIR_TOSA_TF_TFL_PASSES_H_ + +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Pass/PassOptions.h" // from @llvm-project + +namespace mlir { +namespace tosa { + +struct TOSATFTFLLegalizationPipelineOptions + : public PassPipelineOptions { + bool dequantize_tfl_softmax = false; +}; + +// Legalizes TF dialect(s) to Tosa. +void createTFTFLtoTOSALegalizationPipeline( + OpPassManager& pm, const TOSATFTFLLegalizationPipelineOptions& opts); + +void registerTFTFLtoTOSALegalizationPipeline(); + +} // namespace tosa +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TF_TFL_PASSES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tosa_opt.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tosa_opt.cc new file mode 100644 index 0000000000000000000000000000000000000000..87517c34c467f467671766f2d521153eef7d5a3f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tf_tosa_opt.cc @@ -0,0 +1,81 @@ +/* Copyright 2019 Google Inc. 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 "mlir/InitAllPasses.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Tools/mlir-opt/MlirOptMain.h" // from @llvm-project +#include "mlir/Transforms/Passes.h" // from @llvm-project +#include "tensorflow//compiler/mlir/tensorflow/transforms/tf_saved_model_passes.h" +#include "tensorflow/compiler/mlir/init_mlir.h" +#include "tensorflow/compiler/mlir/lite/transforms/passes.h" +#include "tensorflow/compiler/mlir/quantization/stablehlo/passes/bridge/passes.h" +#include "tensorflow/compiler/mlir/register_common_dialects.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/host_runtime/lower_cluster_to_runtime_ops.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/host_runtime/runtime_passes.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/passes.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/sparsecore/sparsecore_passes.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/test_passes.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/tf_graph_optimization_pass.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/mlprogram_util.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/compile_mlir_util.h" +#include "tensorflow/compiler/mlir/tf2xla/internal/passes/clustering_passes.h" +#include "tensorflow/compiler/mlir/tf2xla/internal/passes/mlir_to_graph_passes.h" +#include "tensorflow/compiler/mlir/tf2xla/transforms/passes.h" +#include "tensorflow/compiler/mlir/tosa/tf_passes.h" +#include "tensorflow/compiler/mlir/tosa/tf_tfl_passes.h" +#include "tensorflow/compiler/mlir/tosa/tfl_passes.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" +#include "xla/mlir_hlo/mhlo/transforms/passes.h" + +int main(int argc, char** argv) { + tensorflow::InitMlir y(&argc, &argv); + + mlir::registerAllPasses(); + mlir::registerTransformsPasses(); + mlir::registerTensorFlowPasses(); + mlir::TFDevice::registerTensorFlowDevicePasses(); + mlir::tf_saved_model::registerTensorFlowSavedModelPasses(); + mlir::TFL::registerTensorFlowLitePasses(); + mlir::mhlo::registerAllMhloPasses(); + + // These are in compiler/mlir/tf2xla and not part of the above MHLO passes. + mlir::mhlo::registerLegalizeTfPasses(); + mlir::mhlo::registerTfXlaPasses(); + mlir::quant::stablehlo::registerBridgePasses(); + tensorflow::tf2xla::internal::registerTFXLABridgeClusteringPasses(); + tensorflow::tf2xla::internal::registerTFXLABridgeMlirToGraphPasses(); + mlir::tf_test::registerTensorFlowTestPasses(); + tensorflow::RegisterConvertMlirToXlaHloPipelineWithDefaults(); + tensorflow::RegisterGraphOptimizationPasses(); + tensorflow::RegisterMlProgramPasses(); + mlir::TFTPU::registerRuntimeLoweringPasses(); + mlir::TFDevice::registerSparseCorePasses(); + mlir::tosa::registerLegalizeTosaPasses(); + mlir::tosa::registerTFtoTOSALegalizationPipeline(); + mlir::tosa::registerTFLtoTOSALegalizationPipeline(); + mlir::tosa::registerTFTFLtoTOSALegalizationPipeline(); + + tensorflow::tfrt_compiler::RegisterTPULowerClusterToRuntimeOpsPassPipeline(); + tensorflow::tfrt_compiler:: + RegisterNonTPULowerClusterToRuntimeOpsPassPipeline(); + + mlir::DialectRegistry registry; + mlir::RegisterCommonToolingDialects(registry); + registry.insert(); + registry.insert(); + + return failed( + mlir::MlirOptMain(argc, argv, "TensorFlow pass driver\n", registry)); +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tfl_passes.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tfl_passes.cc new file mode 100644 index 0000000000000000000000000000000000000000..b4248d6006c3555dff6e271431844acf233cb897 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tfl_passes.cc @@ -0,0 +1,94 @@ +/* Copyright 2020 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/mlir/tosa/tfl_passes.h" + +#include "mlir/Conversion/ReconcileUnrealizedCasts/ReconcileUnrealizedCasts.h" // from @llvm-project +#include "mlir/Dialect/Affine/Transforms/Passes.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Transforms/Passes.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project +#include "mlir/Transforms/Passes.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/transforms/passes.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +namespace mlir { +namespace tosa { + +void createTFLtoTOSALegalizationPipeline( + OpPassManager& pm, const TOSATFLLegalizationPipelineOptions& opts) { + //---------------------------------------------------------------------------- + // Prepare TFL module for conversion + //---------------------------------------------------------------------------- + pm.addPass(createRetainCallOnceFuncsPass()); + + // Inline all functions into main and then delete the functions themselves. + pm.addPass(mlir::createInlinerPass()); + pm.addPass(createCanonicalizerPass()); + pm.addPass(createSymbolDCEPass()); + if (opts.target_compilation_backend) { + pm.nest().addPass(createConvertFunctionMetadataPass()); + } + + // Add pass to decompose TFLite mixed quantization to non-quantized variants. + pm.addPass(TFL::CreateDecomposeHybridQuantizationPass()); + + // Now that there is only one function, run some MLIR passes on it. + pm.addPass(mlir::createCanonicalizerPass()); + pm.addPass(mlir::createCSEPass()); + + pm.addPass(mlir::affine::createLoopFusionPass()); + pm.addPass(mlir::affine::createAffineScalarReplacementPass()); + + //---------------------------------------------------------------------------- + // Perform main conversion. + //---------------------------------------------------------------------------- + pm.addPass(mlir::tosa::createConvertTFLUnsignedIntToSignedPass()); + if (opts.dequantize_tfl_softmax) { + pm.addPass(mlir::tosa::createDequantizeTFLSoftmaxPass()); + } + pm.addPass(mlir::tosa::createLegalizeTFLStatefulPass()); + pm.addPass(mlir::tosa::createLegalizeTFLPass(opts.disabled_patterns, + opts.enabled_patterns)); + + //---------------------------------------------------------------------------- + // Post conversion cleanup. + //---------------------------------------------------------------------------- + pm.addPass(mlir::tosa::createLowerComplexTypesPass()); + pm.addPass(mlir::tosa::createTosaInferShapesPass()); + pm.addPass(mlir::tosa::createTosaMakeBroadcastablePass()); + // Inline the call/return basic blocks within TOSA control flow ops. + pm.addPass(mlir::createInlinerPass()); + // Clean up with DCE. + pm.addPass(mlir::createSymbolDCEPass()); + + if (opts.target_compilation_backend) { + pm.nest().addPass(mlir::tosa::createStripQuantTypesPass()); + pm.addPass(createCanonicalizerPass()); + pm.addPass(createReconcileUnrealizedCastsPass()); + pm.nest().addPass(createStripFunctionMetadataPass()); + pm.addPass(createStripModuleMetadataPass()); + pm.addPass(createVerifyFullyConvertedPass()); + } +} + +void registerTFLtoTOSALegalizationPipeline() { + mlir::PassPipelineRegistration( + "tfl-to-tosa-pipeline", "TensorFlow Lite to TOSA legalization pipeline", + createTFLtoTOSALegalizationPipeline); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tfl_passes.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tfl_passes.h new file mode 100644 index 0000000000000000000000000000000000000000..5a158f17919033ee734244c22a51943612ed4567 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/tfl_passes.h @@ -0,0 +1,59 @@ +/* Copyright 2020 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_MLIR_TOSA_TFL_PASSES_H_ +#define TENSORFLOW_COMPILER_MLIR_TOSA_TFL_PASSES_H_ + +#include +#include + +#include "llvm/Support/CommandLine.h" +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Pass/PassOptions.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project + +namespace mlir { +namespace tosa { + +struct TOSATFLLegalizationPipelineOptions + : public PassPipelineOptions { + ArrayRef disabled_patterns; + ArrayRef enabled_patterns; + + PassOptions::Option target_compilation_backend{ + *this, "target-compilation-backend", + llvm::cl::desc("Whether targetting compilation backend"), + llvm::cl::init(false)}; + + PassOptions::Option dequantize_tfl_softmax{ + *this, "dequantize-tfl-softmax", + llvm::cl::desc("Dequantize the TFLite softmax"), llvm::cl::init(false)}; + + TOSATFLLegalizationPipelineOptions() { + disabled_patterns = {}; + enabled_patterns = {}; + } +}; + +// Legalizes TFL (TensorFlow lite) dialect(s) to Tosa. +void createTFLtoTOSALegalizationPipeline( + OpPassManager& pm, const TOSATFLLegalizationPipelineOptions& opts); + +void registerTFLtoTOSALegalizationPipeline(); + +} // namespace tosa +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TFL_PASSES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/convert_metadata.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/convert_metadata.cc new file mode 100644 index 0000000000000000000000000000000000000000..329ed1803ccacaf9c02807f26a1f1684324d641f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/convert_metadata.cc @@ -0,0 +1,114 @@ +/* Copyright 2023 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 +#include + +#include "llvm/ADT/StringExtras.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project + +namespace mlir::tosa { + +#define GEN_PASS_DEF_CONVERTFUNCTIONMETADATA +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +namespace { + +// Extract the input and output names +static void splitFunctionIONames(StringAttr namesAttr, + llvm::SmallVectorImpl &names) { + SmallVector namesRef; + llvm::SplitString(namesAttr.getValue(), namesRef, ","); + for (auto nameRef : namesRef) { + names.push_back(nameRef.str()); + } +} + +class ConvertFunctionMetadataPass + : public impl::ConvertFunctionMetadataBase { + public: + void runOnOperation() override { + auto funcOp = getOperation(); + + // Setup entry functions for compilation and preserve the + // associated metadata. Note that TFLite uses `tf.entry_function`. + auto entryFunctionAttr = + funcOp->getAttrOfType("tf.entry_function"); + if (entryFunctionAttr) { + setupEntryPointAttrs(funcOp, entryFunctionAttr); + } + } + + private: + // TF/TFL pack their I/O names in a dictionary, convert into arg attributes. + void setupEntryPointAttrs(func::FuncOp funcOp, + DictionaryAttr entryFunctionAttr) { + funcOp.setPublic(); + + if (funcOp.getNumArguments() > 0) { + auto inputsAttr = + dyn_cast_or_null(entryFunctionAttr.get("inputs")); + if (!inputsAttr) { + funcOp.emitError() << "functions with tf.entry_function must have " + "input names to be handled by backend"; + return signalPassFailure(); + } + SmallVector inputNames; + splitFunctionIONames(inputsAttr, inputNames); + if (inputNames.size() != funcOp.getNumArguments()) { + funcOp.emitError() + << "tf.entry_function attribute malformed: inputs don't " + "match the function signature"; + return signalPassFailure(); + } + for (auto [i, name] : llvm::enumerate(inputNames)) { + funcOp.setArgAttr(i, "ml_program.identifier", + StringAttr::get(&getContext(), name)); + } + } + if (funcOp.getNumResults() > 0) { + auto outputsAttr = + dyn_cast_or_null(entryFunctionAttr.get("outputs")); + if (!outputsAttr) { + funcOp.emitError() << "functions with tf.entry_function must have " + "output names to be handled by backend"; + return signalPassFailure(); + } + SmallVector outputNames; + splitFunctionIONames(outputsAttr, outputNames); + if (outputNames.size() != funcOp.getNumResults()) { + funcOp.emitError() + << "tf.entry_function attribute malformed: outputs don't " + "match the function signature"; + return signalPassFailure(); + } + for (auto [i, name] : llvm::enumerate(outputNames)) { + funcOp.setResultAttr(i, "ml_program.identifier", + StringAttr::get(&getContext(), name)); + } + } + } +}; +} // anonymous namespace + +std::unique_ptr> +createConvertFunctionMetadataPass() { + return std::make_unique(); +} + +} // namespace mlir::tosa diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/convert_tfl_uint.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/convert_tfl_uint.cc new file mode 100644 index 0000000000000000000000000000000000000000..19ba0013b46be6f2a5684cca5a78c0a7169412ee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/convert_tfl_uint.cc @@ -0,0 +1,547 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This pass converts a TFLite unsigned integer graph to the signed integer +// domain, with adaptors at input and output tensors. This is needed because +// TOSA precision is implemented in the signed integer domain. This pass: +// 1. Matches TFL::QConst with unsigned integers, generates TFL::QConst with +// signed integers with values remapped. +// 2. Inserts tosa.RESCALE unsigned -> signed at graph inputs +// 3. Inserts tosa.RESCALE signed -> unsigned at graph outputs + +#include +#include +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/QuantUtils.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-convert-tfl-uint-to-int" +#define DEBUG_TYPE PASS_NAME + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSACONVERTTFLUNSIGNEDINTTOSIGNEDPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +// Validate that zero point follows TOSA requirements: +// - int8/uint8 can have zero point within their valid range +// - uint16 zero point must be either 0 or 32768 +// - All other types must have zero point equal to 0 +// Ref: +// https://github.com/arm/tosa-specification/blob/9fe5e964e2193f0e345670f7f4098beecd7fd6eb/tosa.xml#L2479 +bool isValidTOSAZeroPoint(int32_t zp, unsigned bit_width, bool is_unsigned) { + if (bit_width == 8) { + // int8/uint8 can have any zero point in their valid range + if (is_unsigned) { + return zp >= 0 && zp <= 255; + } else { + return zp >= -128 && zp <= 127; + } + } else if (bit_width == 16 && is_unsigned) { + // uint16 must have zp of 0 or 32768 + return (zp == 0 || zp == 32768); + } else { + // All other types (int16, int32, uint32) must have zero point = 0 + return zp == 0; + } +} + +// Adjust zero points according to TOSA requirements +int32_t adjustZeroPointForTOSA(int32_t zp, unsigned bit_width, bool is_unsigned) { + if (bit_width == 16 && is_unsigned) { + // uint16 must have zp of 0 or 32768 + if (zp != 0 && zp != 32768) { + // TOSA doesn't support other zero points for uint16. Round to nearest + // valid value. This leads to precision loss in the rescaled type. + return (zp < 16384) ? 0 : 32768; + } + return zp; + } else if (bit_width == 8) { + // int8/uint8 can have any zero point in their valid range + return zp; + } else { + // All other types must have zero point = 0. This also leads to precision loss. + return 0; + } +} + +// Only support 8, 16, and 32-bit integers as tosa.rescale op only supports +// these bitWidths as both input and output types +bool isUnsupportedBitWidth(unsigned bit_width) { + return (bit_width != 8 && bit_width != 16 && bit_width != 32); +} + +// Create a signed quantized type from an unsigned one +// Returns the signed quantized type and the adjusted zero point +std::pair +createSignedQuantizedTypeFromUnsigned( + OpBuilder& builder, mlir::quant::UniformQuantizedType unsigned_quant_type) { + unsigned bit_width = unsigned_quant_type.getStorageTypeIntegralWidth(); + + int32_t unsigned_zp = unsigned_quant_type.getZeroPoint(); + + // Calculate real value range + double real_min = static_cast( + unsigned_quant_type.getStorageTypeMin() - unsigned_zp) * + unsigned_quant_type.getScale(); + double real_max = static_cast( + unsigned_quant_type.getStorageTypeMax() - unsigned_zp) * + unsigned_quant_type.getScale(); + + // Determine signed storage range + int64_t signed_min = quant::AnyQuantizedType::getDefaultMinimumForInteger( + /* isSignedInteger = */ true, bit_width); + int64_t signed_max = quant::AnyQuantizedType::getDefaultMaximumForInteger( + /* isSignedInteger = */ true, bit_width); + + // Adjust for narrow range + if (unsigned_quant_type.getStorageTypeMin() == 1) { + signed_min++; + } + + // Compute optimal scale and zero point + double real_range = real_max - real_min; + double storage_range = static_cast(signed_max - signed_min); + double new_scale = real_range / storage_range; + + // Compute zero point to align real_min with signed_min + int32_t signed_zp = + static_cast(std::round(signed_min - real_min / new_scale)); + + int32_t adjusted_zp = + adjustZeroPointForTOSA(signed_zp, bit_width, /*is_unsigned=*/false); + + // If zero point was changed by TOSA constraints, recompute scale + if (adjusted_zp != signed_zp) { + // With the adjusted zp, recompute scale to ensure coverage of real range + // real_min = new_scale * (signed_min - adjusted_zp) + // real_max = new_scale * (signed_max - adjusted_zp) + double scale_for_min = + real_min / static_cast(signed_min - adjusted_zp); + double scale_for_max = + real_max / static_cast(signed_max - adjusted_zp); + new_scale = std::max(scale_for_min, scale_for_max); + } + + signed_zp = adjusted_zp; + + auto signed_quant_type = quant::UniformQuantizedType::getChecked( + builder.getUnknownLoc(), quant::QuantizationFlags::Signed, + builder.getIntegerType(bit_width), unsigned_quant_type.getExpressedType(), + new_scale, signed_zp, signed_min, signed_max); + + return {signed_quant_type, signed_zp}; +} + +// Pattern for converting unsigned QConst ops +struct ConvertUnsignedQConstOp : public RewritePattern { + explicit ConvertUnsignedQConstOp(MLIRContext* context) + : RewritePattern(TFL::QConstOp::getOperationName(), 1, context) {} + + LogicalResult matchAndRewrite(Operation* op, + PatternRewriter& builder) const override { + auto tfl_qconst_op = cast(op); + + // Skip if it's not ranked tensor type. + auto output_type = + dyn_cast(tfl_qconst_op.getResult().getType()); + if (!output_type) + return builder.notifyMatchFailure(op, "not ranked tensor"); + + // Skip if output is not per-tensor quantized type. + auto output_element_type = dyn_cast( + output_type.getElementType()); + if (!output_element_type) + return builder.notifyMatchFailure( + op, "not per-tensor quantized tfl.qconst op"); + + // Skip if output is already signed. + if (output_element_type.isSigned()) { + return builder.notifyMatchFailure( + op, "expected output type to be unsigned quantized type"); + } + + // Get the bit_width from the quantized type itself + unsigned bit_width = output_element_type.getStorageTypeIntegralWidth(); + + if (isUnsupportedBitWidth(bit_width)) { + return builder.notifyMatchFailure( + op, "only 8, 16, and 32-bit integers are supported"); + } + + int32_t unsigned_zp = output_element_type.getZeroPoint(); + if (!isValidTOSAZeroPoint(unsigned_zp, bit_width, /*is_unsigned=*/true)) { + return builder.notifyMatchFailure(op, + "Zeropoint is not supported by TOSA."); + } + + // Calculate the zero-point offset for this bit_width + auto [signed_quant_type, signed_zp] = + createSignedQuantizedTypeFromUnsigned(builder, output_element_type); + + auto dst_qconst_type = TypeAttr::get( + RankedTensorType::get(output_type.getShape(), signed_quant_type)); + + Type dst_dense_element_type = builder.getIntegerType(bit_width); + + mlir::DenseElementsAttr src_dense_attr = + mlir::cast(tfl_qconst_op.getValue()); + + int64_t value_offset = unsigned_zp - signed_zp; + auto dst_dense_attr = src_dense_attr.mapValues( + dst_dense_element_type, + [bit_width, value_offset](const APInt& in) -> APInt { + int64_t in_i64 = in.getLimitedValue(); + int64_t out_i64 = in_i64 - value_offset; + return APInt(bit_width, out_i64, true); + }); + + builder.replaceOpWithNewOp(op, dst_qconst_type, + dst_dense_attr); + + return success(); + } +}; + +// returns true iff @a type is a shaped type with element type that is unsigned +// integer. If it is, then update the rescaled type, input_zp, and output_zp to +// use to rescale type to signed type with adjusted zero point. +bool ConvertUnsignedToSignedRescale(OpBuilder& builder, const Type type, + Type& rescaled_type, int32_t& unsigned_zp, + int32_t& output_zp, unsigned& bit_width) { + auto shaped_type = dyn_cast(type); + if (!shaped_type) return false; + + auto element_type = shaped_type.getElementType(); + auto unsigned_element_quant_type = + dyn_cast(element_type); + + // Check if it's unsigned quantized type + if (unsigned_element_quant_type && !unsigned_element_quant_type.isSigned()) { + bit_width = unsigned_element_quant_type.getStorageTypeIntegralWidth(); + if (isUnsupportedBitWidth(bit_width)) { + return false; + } + + unsigned_zp = unsigned_element_quant_type.getZeroPoint(); + // Use helper function to create signed quantized type + auto [signed_quant_type, signed_zp] = createSignedQuantizedTypeFromUnsigned( + builder, unsigned_element_quant_type); + + output_zp = signed_zp; + rescaled_type = shaped_type.clone(signed_quant_type); + return true; + } + + // Check for plain unsigned integer types + if (element_type.isUnsignedInteger()) { + bit_width = element_type.getIntOrFloatBitWidth(); + if (isUnsupportedBitWidth(bit_width)) { + return false; + } + + int64_t zp_offset = 1LL << (bit_width - 1); + unsigned_zp = 0; + output_zp = adjustZeroPointForTOSA(unsigned_zp - zp_offset, bit_width, + /*is_unsigned=*/false); + // Determine signed storage range + int64_t signed_min = quant::AnyQuantizedType::getDefaultMinimumForInteger( + /* isSignedInteger = */ true, bit_width); + int64_t signed_max = quant::AnyQuantizedType::getDefaultMaximumForInteger( + /* isSignedInteger = */ true, bit_width); + + rescaled_type = shaped_type.clone(quant::UniformQuantizedType::getChecked( + builder.getUnknownLoc(), quant::QuantizationFlags::Signed, + builder.getIntegerType(bit_width), builder.getF32Type(), + /* scale = */ 1.0, + /* zeroPoint = */ output_zp, + /* storageTypeMin = */ signed_min, + /* storageTypeMax = */ signed_max)); + + return true; + } + + return false; +} + +LogicalResult convert_graph_unsigned_tensor(mlir::MLIRContext& context, + mlir::func::FuncOp& function) { + size_t num_blocks_in_main = 0; + mlir::Region* region = function.getCallableRegion(); + OpBuilder builder(&context); + auto loc = function.getLoc(); + + for (mlir::Block& bb : region->getBlocks()) { + // Always have one block for each region right now + num_blocks_in_main++; + if (num_blocks_in_main > 1) { + return function.emitError("Invalid MLIR: multiple blocks in a region"); + } + + if (!bb.isEntryBlock()) { + return function.emitError("Invalid MLIR: block must be entry block"); + } + + // Create multiplier and shift tensors (these are always i32 and i8 + // respectively) + auto multiplier = tosa::getConstTensorInt(builder, loc, {1 << 30}); + auto shift = tosa::getConstTensorInt(builder, loc, {30}); + + // Insert rescale unsigned->signed for input arguments + for (Value arg : bb.getArguments()) { + auto shaped_type = dyn_cast(arg.getType()); + if (!shaped_type) continue; + + // Check if zeropoint is supported by TOSA if quantized unsigned type + auto element_type = shaped_type.getElementType(); + auto unsigned_element_quant_type = + dyn_cast(element_type); + + if (unsigned_element_quant_type && + !unsigned_element_quant_type.isSigned()) { + unsigned bit_width = + unsigned_element_quant_type.getStorageTypeIntegralWidth(); + int32_t unsigned_zp = unsigned_element_quant_type.getZeroPoint(); + + if (!isValidTOSAZeroPoint(unsigned_zp, bit_width, /*is_unsigned=*/true)) { + return function.emitError() + << "Input argument has unsigned quantized type with zero " + "point " + << unsigned_zp + << " which is not supported by TOSA for bitwidth " << bit_width + << "."; + } + } + + Type rescaled_type; + int32_t rescale_input_zp_val, rescale_output_zp_val; + unsigned bit_width; + + if (!ConvertUnsignedToSignedRescale(builder, arg.getType(), rescaled_type, + rescale_input_zp_val, rescale_output_zp_val, + bit_width)) + continue; + + // Keep original input_val use with tmp_val. + auto tmp_const_type = + RankedTensorType::get({1}, builder.getIntegerType(bit_width)); + auto tmp_const_attr = + DenseElementsAttr::get(tmp_const_type, {APInt(bit_width, 0)}); + Value tmp_val = + builder.create(loc, tmp_const_type, tmp_const_attr); + arg.replaceAllUsesWith(tmp_val); + + // Create zero point constants with appropriate bit_width + // input_zp must match input bit_width, output_zp must match + // output bit_width + auto rescale_input_zp = createZeroPointTensor( + builder, loc, tmp_const_type, rescale_input_zp_val); + auto rescale_output_zp = createZeroPointTensor( + builder, loc, tmp_const_type, rescale_output_zp_val); + + if (!rescale_input_zp || !rescale_output_zp) { + return function.emitError("Failed to create input zero point tensors."); + } + + const auto rounding_mode_attr = tosa::RoundingModeAttr::get( + builder.getContext(), tosa::RoundingMode::SINGLE_ROUND); + auto rescale_op = builder.create( + loc, rescaled_type, arg, multiplier, shift, rescale_input_zp.value(), + rescale_output_zp.value(), + /* scale32 = */ builder.getBoolAttr(true), + /* rounding_mode = */ rounding_mode_attr, + /* per_channel = */ builder.getBoolAttr(false), + /* input_unsigned = */ builder.getBoolAttr(true), // unsigned -> + /* output_unsigned = */ builder.getBoolAttr(false)); // signed + + Operation* op_rescale_op = static_cast(rescale_op); + bb.push_front(op_rescale_op); + tmp_val.replaceAllUsesWith(rescale_op.getResult()); + tmp_val.getDefiningOp()->erase(); + bb.push_front(rescale_output_zp.value().getDefiningOp()); + bb.push_front(rescale_input_zp.value().getDefiningOp()); + } + + bb.push_front(shift.getDefiningOp()); + bb.push_front(multiplier.getDefiningOp()); + + // Record types of original graph output before we convert intermediate + // tensors. + auto terminator = bb.getTerminator(); + SmallVector output_types; + for (Value val : terminator->getOperands()) { + output_types.push_back(val.getType()); + } + + // Convert intermediate tensors. + for (auto& op : bb) { + if (llvm::dyn_cast(&op)) { + // Skip tosa const ops created during rescaling. + continue; + } + + for (Value output_val : op.getResults()) { + auto shaped_type = dyn_cast(output_val.getType()); + if (!shaped_type) continue; + Type new_type; + int32_t unused_input_zp, unused_output_zp; + unsigned bit_width; + + if (ConvertUnsignedToSignedRescale(builder, output_val.getType(), new_type, + unused_input_zp, unused_output_zp, bit_width)) { + output_val.setType(new_type); + } + } + } + + if (terminator->getNumOperands() != output_types.size()) { + return function.emitError( + "Terminator's operand mismatch with number of outputs in graph"); + } + + // Insert signed->unsigned rescale before all terminator's operands + for (int32_t i = 0; i < terminator->getNumOperands(); i++) { + auto defining_op = terminator->getOperand(i).getDefiningOp(); + // Skip if operand of terminator is block arg (nullptr in this case) + if (!defining_op) continue; + Value input_val = defining_op->getResult(0); + + // Check if graph output is unsigned type. + auto unsigned_output_type = dyn_cast(output_types[i]); + if (!unsigned_output_type) continue; + + // Check if graph output is unsigned type. + Type rescaled_type; + int32_t unsigned_zp_val, unused_output_zp_val; + unsigned bit_width; + + if (!ConvertUnsignedToSignedRescale(builder, output_types[i], rescaled_type, + unsigned_zp_val, unused_output_zp_val, + bit_width)) + continue; + + // convert terminator operand type back to original output_type. + auto terminator_operand_type = + dyn_cast(terminator->getOperand(i).getType()); + if (!terminator_operand_type) continue; + int operand_zp_val = 0; + auto quantized_type = dyn_cast( + terminator_operand_type.getElementType()); + if (quantized_type) { + operand_zp_val = adjustZeroPointForTOSA(quantized_type.getZeroPoint(), + bit_width, /*is_unsigned=*/true); + } + + // Keep original input_val use with tmp_val. + auto tmp_const_type = + RankedTensorType::get({1}, builder.getIntegerType(bit_width)); + auto tmp_const_attr = + DenseElementsAttr::get(tmp_const_type, {APInt(bit_width, 0)}); + Value tmp_val = + builder.create(loc, tmp_const_type, tmp_const_attr); + input_val.replaceUsesWithIf(tmp_val, [&terminator](OpOperand& use) { + return use.getOwner() == terminator; + }); + + // Create zero point constants with appropriate bit_width + // input_zp must match input bit_width (signed), output_zp must match + // output bit_width (unsigned) + auto rescale_input_zp = + createZeroPointTensor(builder, loc, tmp_const_type, operand_zp_val); + auto rescale_output_zp = + createZeroPointTensor(builder, loc, tmp_const_type, unsigned_zp_val); + + if (!rescale_input_zp || !rescale_output_zp) { + return function.emitError("Failed to create input zero point tensors."); + } + + const auto rounding_mode_attr = tosa::RoundingModeAttr::get( + builder.getContext(), tosa::RoundingMode::SINGLE_ROUND); + auto rescale_op = builder.create( + loc, unsigned_output_type, input_val, multiplier, shift, + rescale_input_zp.value(), rescale_output_zp.value(), + /* scale32 = */ builder.getBoolAttr(true), + /* rounding_mode = */ rounding_mode_attr, + /* per_channel = */ builder.getBoolAttr(false), + /* input_unsigned = */ builder.getBoolAttr(false), // signed -> + /* output_unsigned = */ builder.getBoolAttr(true)); // unsigned + + Operation* op_rescale_op = static_cast(rescale_op); + bb.push_back(op_rescale_op); + op_rescale_op->moveBefore(terminator); + tmp_val.replaceAllUsesWith(rescale_op.getResult()); + tmp_val.getDefiningOp()->erase(); + bb.push_front(rescale_output_zp.value().getDefiningOp()); + bb.push_front(rescale_input_zp.value().getDefiningOp()); + } + } + + return success(); +} + +class ConvertTFLUnsignedToSigned + : public impl::TosaConvertTFLUnsignedIntToSignedPassBase< + ConvertTFLUnsignedToSigned> { + public: + void runOnOperation() override { + RewritePatternSet patterns(&getContext()); + auto& ctx = getContext(); + mlir::func::FuncOp func = getOperation(); + + func.walk([&](Operation* op) { + if (isa(op)) { + // Run this before calling convert_graph_uint8_tensor as rescaling + // introduces tosa ops + op->emitError( + "tosa operations are not expected in this pass. Run " + "tosa-convert-tfl-uint-to-int before tosa-legalize-tfl"); + } + }); + + // Convert uint const tensor. const needs to be handled specifically. + patterns.add(&ctx); + (void)applyPatternsGreedily(func, std::move(patterns)); + + // Replace uint tensor in the graph and insert rescale as needed. + (void)convert_graph_unsigned_tensor(ctx, func); + } +}; + +} // anonymous namespace + +std::unique_ptr> +createConvertTFLUnsignedIntToSignedPass() { + return std::make_unique(); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/dequantize_tfl_softmax.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/dequantize_tfl_softmax.cc new file mode 100644 index 0000000000000000000000000000000000000000..4bd24b3c45f0bf083c8652b1f638b65083f11a94 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/dequantize_tfl_softmax.cc @@ -0,0 +1,90 @@ +/* Copyright 2022 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 +#include + +#include "mlir/Dialect/Quant/IR/QuantTypes.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-dequantize_tfl-softmax" +#define DEBUG_TYPE PASS_NAME + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSADEQUANTIZETFLSOFTMAXPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +class TosaDequantizeTFLSoftmax + : public impl::TosaDequantizeTFLSoftmaxPassBase { + public: + explicit TosaDequantizeTFLSoftmax() = default; + void runOnOperation() override; +}; + +struct TosaDequantizeTFLSoftmaxPattern : public RewritePattern { + explicit TosaDequantizeTFLSoftmaxPattern(MLIRContext* context) + : RewritePattern(TFL::SoftmaxOp::getOperationName(), 1, context) {} + LogicalResult matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const override; +}; + +LogicalResult TosaDequantizeTFLSoftmaxPattern::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + TFL::SoftmaxOp tfl_softmax_op = cast(op); + RankedTensorType input_type = + mlir::cast(tfl_softmax_op.getInput().getType()); + if (!mlir::isa(input_type.getElementType())) { + return failure(); + } + Location loc = tfl_softmax_op.getLoc(); + RankedTensorType dequantized_input_type = + RankedTensorType::get(input_type.getShape(), rewriter.getF32Type()); + Value dequantized_input = rewriter.create( + loc, dequantized_input_type, tfl_softmax_op.getInput()); + Value dequantized_softmax_output = rewriter.create( + loc, dequantized_input_type, dequantized_input, tfl_softmax_op.getBeta()); + Type qtype = tfl_softmax_op.getOutput().getType(); + rewriter.replaceOpWithNewOp(tfl_softmax_op, qtype, + dequantized_softmax_output, + mlir::TypeAttr::get(qtype)); + return success(); +} + +void TosaDequantizeTFLSoftmax::runOnOperation() { + RewritePatternSet patterns(&getContext()); + patterns.add(&getContext()); + if (failed(applyPatternsGreedily(getOperation(), std::move(patterns)))) { + signalPassFailure(); + } +} + +} // anonymous namespace + +std::unique_ptr> createDequantizeTFLSoftmaxPass() { + return std::make_unique(); +} + +} // namespace tosa + +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/fuse_bias_tf.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/fuse_bias_tf.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6fa11b45144daa1a3c930caaea1148f454de572 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/fuse_bias_tf.cc @@ -0,0 +1,157 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// Fuse tf.Op + tf.BiasAdd and legalized to TOSA + +#include +#include +#include + +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h" +#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-fuse-bias-tf" +#define DEBUG_TYPE PASS_NAME + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSAFUSEBIASTFPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +class FuseBiasTF : public impl::TosaFusebiasTFPassBase { + public: + explicit FuseBiasTF() = default; + void runOnOperation() override; +}; + +struct ConvertTFBiasAddOp : public RewritePattern { + explicit ConvertTFBiasAddOp(MLIRContext* context) + : RewritePattern(TF::BiasAddOp::getOperationName(), 1, context) {} + LogicalResult matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const override; +}; + +// Replaces the following pattern, take conv2d as an example: +// %1 = tf.Conv2D (%ifm, %filter) +// %2 = tf.BiasAdd(%1, %bias) +// with +// %1 = tosa.conv2d(%ifm, %filter, %bias) +// This can also be done using the pair ot Pat<> options in +// tf_optimize_patterns.td +// However, this explicit code can handle both when the LHS or RHS is the +// defining conv2d op. +// TODO: support other pattern. e.g. tf.DepthwiseConv2DNative + +LogicalResult ConvertTFBiasAddOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_biasadd_op = cast(op); + auto output_type = + dyn_cast(tf_biasadd_op.getResult().getType()); + + if (!output_type) { + return rewriter.notifyMatchFailure(op, "output not a ranked tensor"); + } + + auto value = tf_biasadd_op.getValue(); + auto bias = tf_biasadd_op.getBias(); + auto bias_shape = mlir::cast(bias.getType()).getShape(); + if (bias_shape.size() != 1) { + return rewriter.notifyMatchFailure(op, "bias tensor must be rank 1"); + } + + if (TF::Conv2DOp tf_conv2d_op = + llvm::dyn_cast_if_present(value.getDefiningOp())) { + // Sanity check to confirm rhs() has the expected shape of bias + auto filter_shape = + mlir::cast(tf_conv2d_op.getFilter().getType()) + .getShape(); + + // Assume the filter shape is [H, W, I, O] + if (filter_shape.back() != bias_shape.back()) { + return rewriter.notifyMatchFailure( + op, "bias dimension must match filter output channels"); + } + + auto result = convertTFConv2DCommon( + rewriter, op, output_type, tf_conv2d_op.getInput(), + tf_conv2d_op.getFilter(), bias, tf_conv2d_op.getStrides(), + tf_conv2d_op.getDilations(), tf_conv2d_op.getExplicitPaddings(), + tf_conv2d_op.getPadding(), tf_conv2d_op.getDataFormat()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); + } + + if (TF::Conv3DOp tf_conv3d_op = + llvm::dyn_cast_if_present(value.getDefiningOp())) { + // Sanity check to confirm rhs() has the expected shape of bias + auto filter_shape = + mlir::cast(tf_conv3d_op.getFilter().getType()) + .getShape(); + + // Assume the filter shape is [D, H, W, I, O] + if (filter_shape.back() != bias_shape.back()) { + return rewriter.notifyMatchFailure( + op, "bias dimension must match filter output channels"); + } + + std::optional result = convertTFConv3DCommon( + rewriter, op, output_type, tf_conv3d_op.getInput(), + tf_conv3d_op.getFilter(), bias, tf_conv3d_op.getStrides(), + tf_conv3d_op.getDilations(), tf_conv3d_op.getPadding(), + tf_conv3d_op.getDataFormat()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); + } + + return failure(); +} + +void FuseBiasTF::runOnOperation() { + RewritePatternSet patterns(&getContext()); + auto* ctx = &getContext(); + auto func = getOperation(); + + // Add the generated patterns to the list. + patterns.add(ctx); + (void)applyPatternsGreedily(func, std::move(patterns)); +} + +} // anonymous namespace + +std::unique_ptr> createFuseBiasTFPass() { + return std::make_unique(); +} + +} // namespace tosa + +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_common.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_common.cc new file mode 100644 index 0000000000000000000000000000000000000000..287063469ebc09d993ded6c0223942dd1042756e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_common.cc @@ -0,0 +1,5063 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// This file contains legalizations common to mapping both TensorFlow and +// TensorFlow Lite to TOSA. It operates generically on ops and does not have +// a hard reference on either dialect. +// +// Conversion functions return std::nullopt on a legalization failure or a +// legalized value on success. Callers must check for presence of an +// llvm::Optional value after each call. + +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/FormatVariadic.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Arith/Utils/Utils.h" // from @llvm-project +#include "mlir/Dialect/Quant/IR/QuantTypes.h" // from @llvm-project +#include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/QuantUtils.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h" // from @llvm-project +#include "mlir/Dialect/Utils/StaticValueUtils.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributeInterfaces.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project +#include "mlir/IR/Matchers.h" // from @llvm-project +#include "mlir/IR/OpDefinition.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/IR/TypeUtilities.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tensorflow/utils/dynamic_shape_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h" + +namespace mlir { +namespace tosa { + +static int64_t multiply_dims(int64_t a, int64_t b) { + if (a == ShapedType::kDynamic || b == ShapedType::kDynamic) { + return ShapedType::kDynamic; + } + return a * b; +} + +static int64_t multiply_dims(llvm::ArrayRef dims, int64_t res = 1) { + for (auto dim : dims) { + if (ShapedType::isDynamic(dim)) { + return ShapedType::kDynamic; + } + res = res * dim; + } + return res; +} + +static int64_t divide_dims(int64_t a, int64_t b) { + if (a == ShapedType::kDynamic || b == ShapedType::kDynamic) { + return ShapedType::kDynamic; + } + return a / b; +} + +static OpFoldResult multiplyDims(ImplicitLocOpBuilder& builder, + OpFoldResult lhs, OpFoldResult rhs) { + auto val_x = getValueOrCreateConstantIndexOp(builder, builder.getLoc(), lhs); + auto val_y = getValueOrCreateConstantIndexOp(builder, builder.getLoc(), rhs); + return getAsOpFoldResult(builder.createOrFold(val_x, val_y)); +} + +static OpFoldResult multiplyDims(ImplicitLocOpBuilder& builder, + ArrayRef dims) { + if (dims.empty()) { + return OpFoldResult{builder.getIndexAttr(1)}; + } + + // Use the first value as the initial value + auto init = dims.front(); + dims = dims.drop_front(); + + return std::accumulate( + dims.begin(), dims.end(), init, + [&](auto lhs, auto rhs) { return multiplyDims(builder, lhs, rhs); }); +} + +// Try to extract the known integer value for the given OpFoldResult +// with the intention of interpreting it as a tensor dimension. +// When the value is not statically known, produce ShapedType::kDynamic. +static int64_t extractStaticDimension(OpFoldResult value) { + return getConstantIntValue(value).value_or(ShapedType::kDynamic); +} + +// Reshape the given tensor value based the new shape described by the +// shape parameter. Attempts to use tosa.reshape when at most one value is +// dynamic, otherwise generates a full tensor.reshape operation using a runtime +// representation of the desired shape. +static Value buildReshape(ImplicitLocOpBuilder& builder, Value value, + ArrayRef shape) { + auto staticShape = llvm::map_to_vector(shape, extractStaticDimension); + auto elementType = getElementTypeOrSelf(value.getType()); + + if (llvm::count_if(staticShape, ShapedType::isDynamic) > 1) { + auto runtimeShape = builder.create( + getValueOrCreateConstantIndexOp(builder, builder.getLoc(), shape)); + + return builder.create( + tensorflow::GetTypeFromTFTensorShape(staticShape, elementType), value, + runtimeShape); + } + + auto staticShapeType = + mlir::tosa::shapeType::get(builder.getContext(), staticShape.size()); + auto staticShapeAttr = + builder.getIndexTensorAttr(tensorflow::ConvertMlirShapeToTF(staticShape)); + auto staticShapeValue = builder.create( + builder.getLoc(), staticShapeType, staticShapeAttr); + + return CreateOpAndInfer( + builder, tensorflow::GetTypeFromTFTensorShape(staticShape, elementType), + value, staticShapeValue); +} + +namespace { +// Given an axis that can be a positive or negative value and the tensor size, +// return the adjusted axis value wrapped around the tensor size. +int32_t adjust_axis(int32_t axis, int32_t tensor_size) { + return axis >= 0 ? axis % tensor_size : (axis + tensor_size) % tensor_size; +} + +template +int countLeadingZeros(T integer_input) { + if (integer_input == 0) { + return std::numeric_limits::digits; + } + + const T one_in_leading_positive = static_cast(1) + << (std::numeric_limits::digits - 1); + int leading_zeros = 0; + while (integer_input < one_in_leading_positive) { + integer_input <<= 1; + ++leading_zeros; + } + return leading_zeros; +} +}; // namespace + +// Copied Nudge implementation from +// tensorflow/core/kernels/fake_quant_ops_functor.h. +// Suggested approach to avoid significant TensorFlow +// build dependency. +void tensorflow_nudge(const float min, const float max, const int quant_min, + const int quant_max, float* nudged_min, float* nudged_max, + float* scale) { + const float quant_min_float = static_cast(quant_min); + const float quant_max_float = static_cast(quant_max); + *scale = (max - min) / (quant_max_float - quant_min_float); + const float zero_point_from_min = quant_min_float - min / *scale; + const uint16_t nudged_zero_point = [zero_point_from_min, quant_min, + quant_min_float, quant_max, + quant_max_float] { + if (zero_point_from_min < quant_min_float) { + return static_cast(quant_min); + } + if (zero_point_from_min > quant_max_float) { + return static_cast(quant_max); + } + return static_cast(std::round(zero_point_from_min)); + }(); + *nudged_min = (quant_min_float - nudged_zero_point) * (*scale); + *nudged_max = (quant_max_float - nudged_zero_point) * (*scale); +} + +// Lowers the Pack operator to TOSA. +std::optional convertPackOp(PatternRewriter& rewriter, Operation* op, + Value result_value, + SmallVectorImpl& inputs, + int32_t axis) { + ////////////////////////////////////////////////// + // Operator: output = Pack([values], axis) or output = Stack([values], axis) + // Lowering: + // + // This operator is lowered into a series of pairwise tosa.concat() + // operators and a reshape + // Depending on the inputs, a tranpose operator is also generated: + // + // Step 1: concatenate the tensors + // a1_concat = tosa.concat(input[0], input[1], axis) + // for (i = 2; i < len(input); i++) + // a1_concat = tosa.concat(a1_concat, input[i], axis) + // + // Step 2: reshape to N+1 dimensions + // a2_reshape = tosa.reshape(a1_concat, new_rank) + // + // Step 3: Transpose if a new dimension is being added: + // if (axis == rank(values[0]): + // // perm will be [1, 2, 3, 0] + // a3_transpose = tosa.transpose(a2_reshape, perm) + + auto getNormalizedAxis = [&](int output_tensor_rank) -> int32_t { + // Axis can be from [-rank(input)-1, rank(input)]. Negative values "wrap + // around" with -1 equating to position rank(input). + return (axis >= 0) ? axis : axis + output_tensor_rank; + }; + + RankedTensorType output_type = + dyn_cast(result_value.getType()); + + llvm::SmallVector input_shape; + + Type element_type; + int32_t normalized_axis; + + // If we know the shape of the output tensor, we can figure out the shapes of + // the inputs using the axis value + if (output_type) { + ArrayRef out_tensor_shape = output_type.getShape(); + const int32_t output_tensor_rank = out_tensor_shape.size(); + + + // Deal with the negative axis value + normalized_axis = getNormalizedAxis(output_tensor_rank); + + for (auto [i, dim] : llvm::enumerate(out_tensor_shape)) { + if (i != normalized_axis) input_shape.push_back(dim); + } + + element_type = output_type.getElementType(); + + } else { + // Rank 0 inputs need special treatment + bool is_rank_zero_input = false; + + // Check if any of the inputs are ranked tensors + for (int i = 0; i < inputs.size(); i++) { + const auto current_input_type = + dyn_cast(inputs[i].getType()); + + // If the input is ranked, we can extract the shape + if (current_input_type) { + ArrayRef current_input_shape = current_input_type.getShape(); + element_type = current_input_type.getElementType(); + + if (current_input_shape.size() == 0) is_rank_zero_input = true; + + for (auto [i, dim] : llvm::enumerate(current_input_shape)) { + input_shape.push_back(dim); + } + break; + } + } + + // At that point, if the shape is empty, the input tensor must be rank 0 or + // none of the input tensors have known shape + if (input_shape.empty() && !is_rank_zero_input) { + (void)rewriter.notifyMatchFailure( + op, "Could not derive the input and output shapes."); + return std::nullopt; + } + + // create a result type + const int32_t input_rank = input_shape.size(); + normalized_axis = getNormalizedAxis(input_rank + 1); + llvm::SmallVector output_shape; + + for (size_t i = 0; i <= input_rank; ++i) { + if (i == normalized_axis) output_shape.push_back(inputs.size()); + if (i < input_rank) output_shape.push_back(input_shape[i]); + } + + output_type = + tensorflow::GetTypeFromTFTensorShape(output_shape, element_type); + } + + // We have figured out all the shapes. Now assign input shape types to all + // input tensors that don't have it + for (auto [i, inp] : llvm::enumerate(inputs)) { + const auto current_input_type = dyn_cast(inp.getType()); + + if (current_input_type) { + // If input has shape, verify that it is of an expected shape + ArrayRef current_input_shape = current_input_type.getShape(); + for (int d = 0; d < current_input_shape.size(); d++) { + if (input_shape[d] != current_input_shape[d]) { + (void)rewriter.notifyMatchFailure(op, "Input tensor mismatch"); + return std::nullopt; + } + } + } else { + // If the input is not ranked tensor, reshape it into correct shape + RankedTensorType reshape_op_type = + tensorflow::GetTypeFromTFTensorShape(input_shape, element_type); + + auto const_shape = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(input_shape)); + + auto reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), reshape_op_type, inp, const_shape); + inp = reshape_op.getResult(); + } + } + + // If input tensors are rank 0, we should reshape them to rank 1 size 1 before + // performing concat. + int input_tensor_rank = input_shape.size(); + + if (input_tensor_rank == 0) { + SmallVector reshape_rank1_size1_shape({1}); + RankedTensorType reshape_rank1_size1_type = + tensorflow::GetTypeFromTFTensorShape(reshape_rank1_size1_shape, + element_type); + auto shape_rank1_size1_value = getTosaConstShape( + rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(reshape_rank1_size1_shape)); + for (int i = 0; i < inputs.size(); i++) { + auto a0_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), reshape_rank1_size1_type, inputs[i], + shape_rank1_size1_value); + inputs[i] = a0_reshape_op.getResult(); + } + } + + // Sanity check that output is rank(input) + 1 + SmallVector output_shape_vals(output_type.getShape().begin(), + output_type.getShape().end()); + if (output_shape_vals.size() != (input_tensor_rank + 1)) { + (void)rewriter.notifyMatchFailure(op, "output tensor rank mismatch"); + return std::nullopt; + } + // Sanity check that the elements in the packing axis match the number of + // inputs to the Pack op + if (output_shape_vals[normalized_axis] != inputs.size()) { + (void)rewriter.notifyMatchFailure(op, "output tensor shape mismatch"); + return std::nullopt; + } + + // Most of the cases when PackOp.axis() is within [0, rank(input) - 1]. + // We can directly concatenate along that axis and perform the reshape. + // For example, stack N [A, B, C] input tensor ranks along axis = 1 + // after concatenation, output will be [A, N * B, C] + // and then reshape it into [A, N, B, C] + // a special case would be PackOp.axis() equal to rank(input), in which case + // we can't directly concatenate along the PackOp.axis(), instead + // we concat along axis=0, and reshape into [N, A, B, C] + // and then we need an extra transpose to [A, B, C, N]. + int64_t concat_axis{0}; + SmallVector perm; + SmallVector reshape_output_shape; + + if (normalized_axis == input_tensor_rank) { + // A special case when stack axis is equal to input tensor rank: + // Output shape is [A, B, C, N] + // so reshape output will be [N, A, B, C] + // and perm will be [1, 2, 3, 0]. + reshape_output_shape.push_back(output_shape_vals[normalized_axis]); + for (int d = 0; d < input_tensor_rank; d++) { + perm.push_back(d + 1); + reshape_output_shape.push_back(output_shape_vals[d]); + } + perm.push_back(0); + } else { + // General case, doesn't need perm vector. + concat_axis = normalized_axis; + reshape_output_shape.assign(output_shape_vals.begin(), + output_shape_vals.end()); + } + + IntegerAttr concat_axis_attr = rewriter.getI32IntegerAttr(concat_axis); + + // Concat output shape will depend on concat_axis. E.g. [N * A, B, C] + SmallVector concat_output_shape; + if (input_tensor_rank == 0) { + concat_output_shape.push_back(1); + } else { + for (int i = 0; i < input_tensor_rank; i++) { + concat_output_shape.push_back(input_shape[i]); + } + } + + concat_output_shape[concat_axis] = + concat_output_shape[concat_axis] * inputs.size(); + + RankedTensorType concat_type = tensorflow::GetTypeFromTFTensorShape( + ArrayRef(concat_output_shape), element_type); + + auto a1_concat_op = CreateOpAndInfer( + rewriter, op->getLoc(), concat_type, + SmallVector(inputs.begin(), inputs.end()), concat_axis_attr); + + // Doesn't need reshape or transpose if input tensor is rank 0, since inputs + // are reshaped beforehand. + if (input_tensor_rank == 0) return a1_concat_op.getResult(); + + // Reshape [N * A, B, C] to [N, A, B, C]. + RankedTensorType reshape_output_type = + tensorflow::GetTypeFromTFTensorShape(reshape_output_shape, element_type); + auto shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(reshape_output_shape)); + + auto a2_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), reshape_output_type, a1_concat_op.getResult(), + shape_value); + + // If axis is equal to input tensor rank, then we need extra transpose + // [N, A, B, C] to [A, B, C, N] + if (normalized_axis == input_tensor_rank) { + return CreateOpAndInfer( + rewriter, op->getLoc(), output_type, a2_reshape_op.getResult(), + rewriter.getDenseI32ArrayAttr(perm)) + .getResult(); + } + + return a2_reshape_op.getResult(); +} + +// Lowers the Unpack operator to TOSA +std::optional> convertUnpackOp(PatternRewriter& rewriter, + Operation* op, + Value input_value, + int32_t axis) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + auto input_shape = input_type.getShape(); + int64_t input_rank = input_shape.size(); + + SmallVector results_vec; + + // Negative axis allowed as long as it's within [-input_rank, input_rank). + if (axis < 0) axis += input_rank; + if ((axis < 0) || (axis >= input_rank)) { + (void)rewriter.notifyMatchFailure(op, "axis out of valid range"); + return std::nullopt; + } + + // Step 1: transpose 'axis' to leftmost dimension. + Value transposed_input_value; + if (axis != 0) { + SmallVector perm; + SmallVector a1_transpose_shape(input_rank); + + perm.push_back(axis); + for (int i = 0; i < input_rank; i++) { + if (i == axis) continue; + perm.push_back(i); + } + + for (int i = 0; i < input_rank; i++) { + a1_transpose_shape[i] = input_shape[perm[i]]; + } + + auto a1_transpose_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a1_transpose_shape, + input_type.getElementType()), + input_value, rewriter.getDenseI32ArrayAttr(perm)); + + transposed_input_value = a1_transpose_op.getResult(); + } else { + // Do nothing if axis is already at leftmost dimension. + transposed_input_value = input_value; + } + + // Step 2: slice [N, A, B, C] into N [A, B, C]. + RankedTensorType transposed_input_type = + dyn_cast(transposed_input_value.getType()); + if (!transposed_input_type) return std::nullopt; + + auto transposed_input_shape = transposed_input_type.getShape(); + int64_t transposed_input_rank = transposed_input_shape.size(); + + for (int i = 0; i < transposed_input_shape[0]; i++) { + SmallVector begin_vals, size_vals, shape_vals; + + for (int j = 0; j < transposed_input_rank; j++) { + if (j == 0) { + begin_vals.push_back(i); + size_vals.push_back(1); + } else { + begin_vals.push_back(0); + size_vals.push_back(transposed_input_shape[j]); + shape_vals.push_back(transposed_input_shape[j]); + } + } + + auto a2_slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape( + size_vals, transposed_input_type.getElementType()), + transposed_input_value, + getTosaConstShape(rewriter, op->getLoc(), begin_vals), + getTosaConstShape(rewriter, op->getLoc(), size_vals)); + + auto shape_vals_value = getTosaConstShape( + rewriter, op->getLoc(), tensorflow::ConvertMlirShapeToTF(shape_vals)); + auto a3_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape( + shape_vals, transposed_input_type.getElementType()), + a2_slice_op.getResult(), shape_vals_value); + + results_vec.push_back(a3_reshape_op.getResult()); + } + + return results_vec; +} + +// Lowers the Select operator to TOSA. +std::optional convertSelectOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value condition_value, + Value x_value, Value y_value) { + RankedTensorType result_type = + dyn_cast(result_value.getType()); + RankedTensorType condition_type = + dyn_cast(condition_value.getType()); + RankedTensorType x_type = dyn_cast(x_value.getType()); + RankedTensorType y_type = dyn_cast(y_value.getType()); + + if (!x_type || !y_type || !condition_type) { + (void)rewriter.notifyMatchFailure(op, "failed ranked tensor type check"); + return std::nullopt; + } + + // First check whether we need to reshape the condition to match + // the same rank as the then/else clauses. + if (x_type == y_type && x_type.getShape() == condition_type.getShape()) { + // Nothing to reshape. + return CreateOpAndInfer(rewriter, op->getLoc(), x_type, + condition_value, x_value, y_value) + .getResult(); + } + + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "failed ranked tensor type check"); + return std::nullopt; + } + + return CreateOpAndInfer(rewriter, op->getLoc(), result_type, + condition_value, x_value, y_value) + .getResult(); +} + +// Lowers the ZerosLike operator to TOSA by creating a constant +// of the desired type and shape. +std::optional convertZerosLikeOp(PatternRewriter& rewriter, + Operation* op, Value result, + Value input) { + RankedTensorType result_type = dyn_cast(result.getType()); + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "result not ranked tensor type"); + return std::nullopt; + } + + RankedTensorType input_type = dyn_cast(input.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input not ranked tensor type"); + return std::nullopt; + } + + auto input_shape = input_type.getShape(); + + ShapedType zero_type = tensorflow::GetTypeFromTFTensorShape( + input_shape, input_type.getElementType()); + Attribute zero_attr = rewriter.getZeroAttr(zero_type); + + return CreateOpAndInfer(rewriter, op->getLoc(), zero_type, + mlir::cast(zero_attr)) + .getResult(); +} + +// Lowers the Mul operator to TOSA. For quantized types, this requires +// inserting rescale operators before and after the operation. +std::optional convertMultiplyOp(PatternRewriter& rewriter, Operation* op, + Value output_val, Value input_lhs_val, + Value input_rhs_val) { + ShapedType input_lhs_type = dyn_cast(input_lhs_val.getType()); + ShapedType input_rhs_type = dyn_cast(input_rhs_val.getType()); + ShapedType output_type = dyn_cast(output_val.getType()); + // Not a shaped tensor output + if (!input_lhs_type || !input_rhs_type || !output_type) return std::nullopt; + + bool input_lhs_is_qtype = mlir::isa( + input_lhs_type.getElementType()); + bool input_rhs_is_qtype = mlir::isa( + input_rhs_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_lhs_is_qtype != output_is_qtype || + input_rhs_is_qtype != output_is_qtype) { + (void)rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + return std::nullopt; + } + + input_lhs_type = dyn_cast(input_lhs_val.getType()); + input_rhs_type = dyn_cast(input_rhs_val.getType()); + + if (output_is_qtype) { + ShapedType rescale_type = output_type.clone(rewriter.getI32Type()); + auto input_lhs_qtype = mlir::cast( + input_lhs_type.getElementType()); + auto input_rhs_qtype = mlir::cast( + input_rhs_type.getElementType()); + auto output_qtype = mlir::cast( + output_type.getElementType()); + + // MLIR store scale as double, but TFLite store scale as float + // Downcasting from double to float to match TFLite behavior + float in_lhs_scale = input_lhs_qtype.getScale(); + float in_rhs_scale = input_rhs_qtype.getScale(); + float output_scale = output_qtype.getScale(); + + double output_rescale_scale = in_lhs_scale * in_rhs_scale / output_scale; + + // 16bits x 16bits -> 32bits + // 32bits can be rescaled with 32bits quantize multiplier back to 16bits + bool scale32 = true; + + Value op1_rescale_lhs = removeZeroPointAndCastToInt32( + rewriter, op, input_lhs_val, input_lhs_qtype.getZeroPoint()); + Value op2_rescale_rhs = removeZeroPointAndCastToInt32( + rewriter, op, input_rhs_val, input_rhs_qtype.getZeroPoint()); + + auto op3_mul_op1_op2 = CreateMulOpAndInfer( + rewriter, op, rescale_type, op1_rescale_lhs, op2_rescale_rhs); + return buildRescale(rewriter, op, output_type, op3_mul_op1_op2.getResult(), + output_rescale_scale, 0, output_qtype.getZeroPoint(), + tosa::RoundingMode::DOUBLE_ROUND, scale32); + } + + return CreateMulOpAndInfer(rewriter, op, output_type, input_lhs_val, + input_rhs_val) + .getResult(); +} + +// Lowers the SquaredDifference operator to TOSA. +std::optional convertSquaredDifferenceOp(PatternRewriter& rewriter, + Operation* op, Value result, + Value x, Value y) { + // Squared-difference is (x-y)*(x-y). + // This lowering calculates the difference and multiplies. + ShapedType result_type = dyn_cast(result.getType()); + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "result not ranked tensor type"); + return std::nullopt; + } + + ShapedType x_type = dyn_cast(x.getType()); + ShapedType y_type = dyn_cast(y.getType()); + if (!x_type || !y_type) { + (void)rewriter.notifyMatchFailure(op, "inputs not ranked tensor type"); + return std::nullopt; + } + + bool x_is_qtype = + mlir::isa(x_type.getElementType()); + bool y_is_qtype = + mlir::isa(y_type.getElementType()); + bool result_is_qtype = mlir::isa( + result_type.getElementType()); + + if (x_is_qtype != result_is_qtype || y_is_qtype != result_is_qtype) { + (void)rewriter.notifyMatchFailure( + op, + "input/output tensor should all be in FP32, INT32 or quantized INT8"); + return std::nullopt; + } + + // If the output is I8 then we need to rescale to I32 + // Then scale back to I8 + if (result_is_qtype) { + auto x_qtype = + mlir::cast(x_type.getElementType()); + auto y_qtype = + mlir::cast(y_type.getElementType()); + auto result_qtype = mlir::cast( + result_type.getElementType()); + + uint32_t result_bits = result_qtype.getStorageTypeIntegralWidth(); + + if (result_bits == 8) { + ShapedType rescale_type = result_type.clone(rewriter.getI32Type()); + + // We need to make sure the inputs are rescaled correctly + // Following the behaviour defined here lite/kernels/squared_difference.cc + double in_x_scale = x_qtype.getScale(); + double in_y_scale = y_qtype.getScale(); + double result_scale = result_qtype.getScale(); + + double twice_max_input_scale = 2.0 * std::max(in_x_scale, in_y_scale); + + const int32_t LEFT_SHIFT = 7; + + double x_rescale_scale = in_x_scale / twice_max_input_scale; + double y_rescale_scale = in_y_scale / twice_max_input_scale; + double output_rescale_scale = + (twice_max_input_scale * twice_max_input_scale) / + ((static_cast(1 << LEFT_SHIFT * 2)) * result_scale); + + Value x_shift = buildRescaleToInt32(rewriter, op, x, (1 << LEFT_SHIFT), + x_qtype.getZeroPoint()); + Value y_shift = buildRescaleToInt32(rewriter, op, y, (1 << LEFT_SHIFT), + y_qtype.getZeroPoint()); + + Value x_scaled = + buildRescaleToInt32(rewriter, op, x_shift, x_rescale_scale, 0); + Value y_scaled = + buildRescaleToInt32(rewriter, op, y_shift, y_rescale_scale, 0); + + auto sub_op = CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type, x_scaled, y_scaled); + auto mul_op = CreateMulOpAndInfer(rewriter, op, rescale_type, + sub_op.getResult(), sub_op.getResult()); + + // Convert the operator back to the original type + return buildRescaleFromInt32(rewriter, op, result_type, + mul_op.getResult(), output_rescale_scale, + result_qtype.getZeroPoint()); + } + + (void)rewriter.notifyMatchFailure( + op, "Only FP32, INT32 or quantized INT8 is supported"); + return std::nullopt; + } + + // This will cover FP32/FP16/INT32 legalization + auto sub_op = + CreateOpAndInfer(rewriter, op->getLoc(), result_type, x, y); + return CreateMulOpAndInfer(rewriter, op, result_type, sub_op.getResult(), + sub_op.getResult()) + .getResult(); +} + +// Lowers the Round operator to TOSA. +std::optional convertRoundOp(PatternRewriter& rewriter, Operation* op, + Value result, Value input) { + // Implements banker's rounding by calculating floor(input + 0.5). + ShapedType result_type = dyn_cast(result.getType()); + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "result not shaped tensor type"); + return std::nullopt; + } + + ShapedType input_type = dyn_cast(input.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input not shaped tensor type"); + return std::nullopt; + } + + auto rank = input_type.getRank(); + + auto add_op = CreateOpAndInfer( + rewriter, op->getLoc(), result_type, input, + getTosaConstTensorSingleF32(rewriter, op, 0.5, rank)); + + return CreateOpAndInfer(rewriter, op->getLoc(), result_type, + add_op.getResult()) + .getResult(); +} + +// Lowers ConcatV2 to TOSA Concat. +std::optional convertConcatV2Op(PatternRewriter& rewriter, Operation* op, + ShapedType result_type, + SmallVectorImpl& values, + int32_t axis) { + // Check all inputs are RankedTensorType + for (auto v : values) { + if (!dyn_cast(v.getType())) { + (void)rewriter.notifyMatchFailure(op, "value type not ranked tensor"); + return std::nullopt; + } + } + + mlir::quant::UniformQuantizedType result_quant_type = + mlir::dyn_cast_or_null( + result_type.getElementType()); + + SmallVector values_rescaled; + + for (auto v : values) { + RankedTensorType operand_type = dyn_cast(v.getType()); + mlir::quant::UniformQuantizedType operand_quant_type = + mlir::dyn_cast_or_null( + operand_type.getElementType()); + + // tfl.concat currently allows different scales for each input tensor, which + // TFlite team will fix in: + // https://github.com/tensorflow/tensorflow/issues/39658 + // For backward compatibility, we still need to support this artifact by + // scaling inputs to let them have the same scales. + if (result_quant_type && operand_quant_type) { + double operand_scale = static_cast(operand_quant_type.getScale()); + int32_t operand_zeropoint = operand_quant_type.getZeroPoint(); + + double result_scale = static_cast(result_quant_type.getScale()); + int32_t result_zeropoint = result_quant_type.getZeroPoint(); + + // Rescale input if scale is not equal to output tensor scale. + if (operand_scale != result_scale) { + RankedTensorType rescale_type = tensorflow::GetTypeFromTFTensorShape( + operand_type.getShape(), result_quant_type); + Value rescale_op = buildRescale( + rewriter, op, rescale_type, v, operand_scale / result_scale, + operand_zeropoint, result_zeropoint, tosa::RoundingMode::SINGLE_ROUND, true); + values_rescaled.push_back(rescale_op); + } else { + values_rescaled.push_back(v); + } + } else { + values_rescaled.push_back(v); + } + } + + int32_t tensor_rank = + mlir::cast(values[0].getType()).getRank(); + + if (axis < 0) axis += tensor_rank; + if ((axis < 0) || (axis > tensor_rank)) { + (void)rewriter.notifyMatchFailure(op, "axis out of valid range"); + return std::nullopt; + } + + auto concat_op = CreateOpAndInfer( + rewriter, op->getLoc(), result_type, values_rescaled, + rewriter.getI32IntegerAttr(axis)); + + return concat_op.getResult(); +} + +// Lowers SpaceToBatchND to TOSA. +std::optional convertSpaceToBatchNDOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + Value block_shape_value, + Value paddings_value) { + ///////////////////////////////////////////////// + // Operator: output = SpaceToBatchND(input, block_shape, paddings) + // Lowering: + // + // SpaceToBatch input tensors are broken into three pieces: + // (a) batch dimension (N in NHWC) + // (b) input being transformed to batch dimension (typically H, W in NHWC) + // (c) remainder of input (typically C in NHWC) + // + // Step 0. Generate padding constant for the first reshape. + // No padding on the batch dimension + // The input paddings array is addressed as [input_rank][2] + // No padding on the remaining dimensions + // + // a0_pad_const = tosa.const(input=Tensor) + // + // Step 1. Pad the input tensor + // + // a1_pad_input_op = tosa.pad(input=input, shape=a0_pad_const_op) + // + // Step 2. Reshape the padded structure of shape padded_shape to + // [batch + padded_shape[1] / block_shape[0], block_shape[0], ... + // padded_shape[M] / block_shape[M-1], block_shape[M-1]] + + // remaining_shape + // + // block_rank = M (number of elements in block_shape) + // New rank: input_rank + block_rank + // + // a2_reshape_a1_op = tosa.reshape(input=a1_pad_input_op, shape=a2_shape) + // + // Step 3. Transpose dimensions to: + // block-shape + + // [batch] + + // [padded_shape[1] / block_shape[0], + // ... + // [padded_shape[M] / block_shape[M-1]] + + // remaining_shape + // + // a3_transpose_a2_op = tosa.tranpose(input=a2_reshape_a1_op, + // perms=a3_perm) + // + // Step 4. Reshape the transposed tensor to flatten block_shape stuff + // into the batch dimension with the following shape: + // [ batch * prod(block_shape)] + + // [ padded_shape[1] / block_shape[0], + // ..., + // padded_shape[M] / block_shape[M-1]] + + // remaining_shape + // + // a4_reshape_a3_op = tosa.reshape(input=a3_tranpose_a2_op, + // shape=a3_shape) + // + + RankedTensorType result_type = + dyn_cast(result_value.getType()); + RankedTensorType input_type = + dyn_cast(input_value.getType()); + RankedTensorType block_shape_type = + dyn_cast(block_shape_value.getType()); + RankedTensorType paddings_type = + dyn_cast(paddings_value.getType()); + + // Not a ranked tensor output. + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "result type not ranked tensor"); + return std::nullopt; + } + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + if (!block_shape_type) { + (void)rewriter.notifyMatchFailure(op, "block shape type not ranked tensor"); + return std::nullopt; + } + if (!paddings_type) { + (void)rewriter.notifyMatchFailure(op, "paddings type not ranked tensor"); + return std::nullopt; + } + + // Follow implementation in + // tensorflow/compiler/tf2xla/kernels/spacetobatch_op.cc + + // So, to figure out the spatial_shape, remove the batch dimension and + // then use the next block_rank dimensions. The remaining dimensions are + // remaining_shape. + + auto block_shape = block_shape_type.getShape(); + auto input_shape = input_type.getShape(); + + int block_rank = block_shape[0]; + int64_t batch_size = input_shape[0]; + int input_rank = input_type.getRank(); + int remaining_shape_rank = input_rank - block_rank - 1; + int64_t block_num_elems = 1; + int64_t padding_sum = 0; + + ElementsAttr block_shape_elems; + ElementsAttr paddings_elems; + + if (!matchPattern(block_shape_value, m_Constant(&block_shape_elems))) + return std::nullopt; + + if (!matchPattern(paddings_value, m_Constant(&paddings_elems))) + return std::nullopt; + + ImplicitLocOpBuilder builder(op->getLoc(), rewriter); + auto rank_one_shape_type = tosa::shapeType::get(rewriter.getContext(), 1); + + SmallVector a0_pad_const(2 * (input_rank)); + SmallVector padded_shape(input_rank); + + // 1. Pad based on paddings operand. No padding on the batch dimension. + // The a0_pad_const array is addressed as [input_rank][2], but + // it is flattened to a 1D array because LLVM appears to only accept 1D. + // + // padded_shape[] is the shape of the padded output of step a1. + // The name is retained for consistency with the TF reference code. + padded_shape[0] = input_shape[0]; + + // Batch dimension padding + a0_pad_const[0] = 0; + a0_pad_const[1] = 0; + + // This iterator seems to be the only reliable way to get + // int values out of a multi-dimensional ElementsAttr. + int idx = 0; + + for (auto i : paddings_elems.getValues()) { + a0_pad_const[idx + 2] = i.getInt(); + padding_sum += i.getInt(); + idx++; + } + + // Insert padding on the spatial shape dimensions + for (int i = 0; i < block_rank; i++) { + padded_shape[i + 1] = input_shape[i + 1]; + if (!ShapedType::isDynamic(padded_shape[i + 1])) { + int32_t lo_pad = a0_pad_const[2 * (i + 1) + 0]; + int32_t hi_pad = a0_pad_const[2 * (i + 1) + 1]; + padded_shape[i + 1] += lo_pad + hi_pad; + } + } + + // No padding on the remaining_shape dimensions + for (int i = 0; i < remaining_shape_rank; i++) { + a0_pad_const[2 * (i + block_rank + 1) + 0] = 0; + a0_pad_const[2 * (i + block_rank + 1) + 1] = 0; + padded_shape[i + block_rank + 1] = input_shape[i + block_rank + 1]; + } + + Value a0_padding = mlir::tosa::getTosaConstShape(rewriter, op->getLoc(), a0_pad_const); + + auto a1_pad_input_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(padded_shape, + result_type.getElementType()), + input_value, a0_padding); + + // 2. Reshape the padded structure of shape padded_shape to + // [batch + padded_shape[1] / block_shape[0], block_shape[0], ... + // padded_shape[M] / block_shape[M-1], block_shape[M-1]] + + // remaining_shape + + // block_rank = M (number of elements in block_shape) + // New rank: input_rank + block_rank + SmallVector a2_shape(1 + block_rank * 2 + remaining_shape_rank); + + // First dimension is batch. + a2_shape[0] = input_type.getDimSize(0); + for (int i = 0; i < block_rank; i++) { + int32_t block_shape_val = + block_shape_elems.getValues()[i].getInt(); + a2_shape[1 + i * 2 + 0] = padded_shape[1 + i]; + if (a2_shape[1 + i * 2 + 0] != ShapedType::kDynamic) { + a2_shape[1 + i * 2 + 0] /= block_shape_val; + } + + a2_shape[1 + i * 2 + 1] = block_shape_val; + block_num_elems *= block_shape_val; + } + + // Copy in the remaining block shape. + for (int i = 0; i < remaining_shape_rank; i++) { + a2_shape[1 + block_rank * 2 + i] = input_shape[1 + block_rank + i]; + } + + auto a2_shape_reshape = a2_shape; // save 'kDynamicSize' value for ReshapeOp + auto a2_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a2_shape)); + auto a2_reshape_a1_op = CreateOpAndInfer( + rewriter, op->getLoc(), + RankedTensorType::get(a2_shape_reshape, result_type.getElementType()), + a1_pad_input_op.getResult(), a2_shape_value); + + // 3. Transpose dimensions to: + // block-shape + + // [batch] + + // [padded_shape[1] / block_shape[0], + // ... + // [padded_shape[M] / block_shape[M-1]] + + // remaining_shape + int32_t a2_reshape_a1_rank = + mlir::cast(a2_reshape_a1_op.getResult().getType()) + .getRank(); + SmallVector a3_perm(a2_reshape_a1_rank); + SmallVector a3_transpose_shape(a2_reshape_a1_rank); + + for (int i = 0; i < block_rank; i++) { + a3_perm[i] = 1 + 2 * i + 1; + a3_perm[block_rank + 1 + i] = 1 + 2 * i; + } + a3_perm[block_rank] = 0; + for (int i = 1 + block_rank * 2; i < a2_reshape_a1_rank; i++) { + a3_perm[i] = i; + } + + for (int i = 0; i < a3_transpose_shape.size(); i++) { + a3_transpose_shape[i] = a2_shape[a3_perm[i]]; + } + + auto a3_transpose_a2_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a3_transpose_shape, + result_type.getElementType()), + a2_reshape_a1_op.getResult(), rewriter.getDenseI32ArrayAttr(a3_perm)); + + // 4. Reshape the transposed tensor to flatten block_shape + // into the batch dimension with the following shape: + // [ batch * prod(block_shape)] + + // [ padded_shape[1] / block_shape[0], + // ..., + // padded_shape[M] / block_shape[M-1]] + + // remaining_shape + SmallVector a4_reshape_shape(input_rank); + + // Batch + a4_reshape_shape[0] = multiply_dims(batch_size, block_num_elems); + + // padded shape / block_shape. + for (int i = 0; i < block_rank; i++) { + int32_t block_shape_val = + block_shape_elems.getValues()[i].getInt(); + a4_reshape_shape[i + 1] = padded_shape[i + 1]; + if (a4_reshape_shape[i + 1] != ShapedType::kDynamic) { + a4_reshape_shape[i + 1] /= block_shape_val; + } + } + + // Copy in remainder shape. + for (int i = 0; i < remaining_shape_rank; i++) { + a4_reshape_shape[1 + block_rank + i] = input_shape[1 + block_rank + i]; + } + + auto a4_reshape_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a4_reshape_shape)); + return CreateOpAndInfer( + rewriter, op->getLoc(), result_type, + a3_transpose_a2_op.getResult(), + a4_reshape_shape_value) + .getResult(); +} + +// Lowers BatchToSpaceND to TOSA. +std::optional convertBatchToSpaceNDOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + Value block_shape_value, + Value crops_value) { + ///////////////////////////////////////////////// + // Operator: output = BatchToSpaceND(input, block_shape, clips) + // Lowering: + // + // BatchToSpace input tensors are broken into three pieces: + // (a) batch dimension (N in NHWC) + // (b) input being transformed from batch dimension (typically H, W in + // NHWC) + // (c) remainder of input (typically C in NHWC) + // + // Step 1. Reshape input to: + // [block_shape[0], + // ... + // [block_shape[M-1], + // [batch / prod(block_shape)] + // [input_shape[1], + // ... + // [input_shape[N-1] + // + // a1_reshape_input_op = tosa.reshape(input=input, shape=a1_shape) + // + // Step 2. Permute to shape + // [ batch / prod(block_shape) ], + // [ input_shape[1] ], [ block_shape[1] ] + // ... + // [ input_shape[M] ], [ block_shape[M-1] + // + remaining_input_shapes input_shape[M .. N-1] + // + // a2_transpose_a1 = tosa.transpose(input=a1_reshape_input_op, + // shape=a2_shape) + // + // Step 3. Reshape to: + // [ batch / prod(block_shape) ], + // [input_shape[1] * block_shape[0] ], + // .. + // [input_shape[M * block_shape[M-1], + // + remaining input shapes [input_shape[M+1.. N-1]] + // + // a3_reshape_a2 = tosa.reshape(input=a2_transpose_a1, shape=a3_shape) + // + // Step 4. Crop the start/end dimensions according to crops of the + // a3_reshape_a2 shape + // + // a4_slice_a3 = tosa.slice(input=a3_reshape_a2, start=a4_start, + // size=a4_size) + + RankedTensorType result_type = + dyn_cast(result_value.getType()); + RankedTensorType input_type = + dyn_cast(input_value.getType()); + RankedTensorType block_shape_type = + dyn_cast(block_shape_value.getType()); + RankedTensorType crops_type = + dyn_cast(crops_value.getType()); + + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "result type not ranked tensor"); + return std::nullopt; + } + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + if (!block_shape_type) { + (void)rewriter.notifyMatchFailure(op, "block shape type not ranked tensor"); + return std::nullopt; + } + if (!crops_type) { + (void)rewriter.notifyMatchFailure(op, "crops type not ranked tensor"); + return std::nullopt; + } + + // Another 4-step process + int block_rank = block_shape_type.getShape()[0]; + int input_rank = input_type.getRank(); + int64_t crops_dims = crops_type.getShape()[0]; + int remaining_shape_rank = input_rank - block_rank - 1; + auto input_shape = input_type.getShape(); + + ElementsAttr block_shape_elems; + ElementsAttr crops_elems; + + if (!matchPattern(block_shape_value, m_Constant(&block_shape_elems))) { + (void)rewriter.notifyMatchFailure(op, "block_shape not a constant"); + return std::nullopt; + } + + if (!matchPattern(crops_value, m_Constant(&crops_elems))) { + (void)rewriter.notifyMatchFailure(op, "crops not a constant"); + return std::nullopt; + } + + SmallVector block_shape(block_rank); + SmallVector> crops(crops_dims); + + // Extract values for block_shape and crops now. + int64_t block_num_elems = 1; + for (int i = 0; i < block_rank; i++) { + int64_t block_shape_val = + rewriter + .getI32IntegerAttr( + block_shape_elems.getValues()[i].getInt()) + .getInt(); + block_num_elems *= block_shape_val; + block_shape[i] = block_shape_val; + } + + // This iterator seems to be the only reliable way to get + // int values out of a multi-dimensional ElementsAttr + SmallVector crops_const(2 * (crops_dims)); + int idx = 0; + for (auto i : crops_elems.getValues()) { + crops_const[idx++] = i.getInt(); + } + + for (int i = 0; i < crops_dims; i++) { + int crops_lo = crops_const[i * crops_dims + 0]; + int crops_hi = crops_const[i * crops_dims + 1]; + crops[i] = std::make_pair(crops_lo, crops_hi); + } + + // Step 1. Reshape input to: + // [block_shape[0], + // ... + // [block_shape[M-1], + // [batch / prod(block_shape)] + // [input_shape[1], + // ... + // [input_shape[N-1] + SmallVector a1_shape(block_rank + input_rank); + + for (int i = 0; i < block_rank; i++) a1_shape[i] = block_shape[i]; + + a1_shape[block_rank] = (input_shape[0] == ShapedType::kDynamic) + ? ShapedType::kDynamic + : input_shape[0] / block_num_elems; + + for (int i = 0; i < input_rank - 1; i++) + a1_shape[i + block_rank + 1] = input_shape[i + 1]; + + auto a1_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a1_shape)); + auto a1_reshape_input_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a1_shape, + result_type.getElementType()), + input_value, + a1_shape_value); + + // 2. Permute to shape + // [ batch / prod(block_shape) ], + // [ input_shape[1] ], [ block_shape[0] ] + // ... + // [ input_shape[M] ], [ block_shape[M-1] + // + remaining_input_shapes input_shape[M+1 .. N-1] + + // 2a. calculate the permutation + SmallVector a2_perm(block_rank + input_rank); + SmallVector a2_transpose_shape(block_rank + input_rank); + + a2_perm[0] = block_rank; + for (int i = 0; i < block_rank; i++) { + a2_perm[1 + i * 2 + 0] = block_rank + 1 + i; + a2_perm[1 + i * 2 + 1] = i; + } + + for (int i = 0; i < remaining_shape_rank; i++) { + a2_perm[1 + 2 * block_rank + i] = 1 + 2 * block_rank + i; + } + + // 2b. calculate the a2_permuted shape + for (int i = 0; i < (block_rank + input_rank); i++) { + a2_transpose_shape[i] = a1_shape[a2_perm[i]]; + } + + auto a2_transpose_a1_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a2_transpose_shape, + result_type.getElementType()), + a1_reshape_input_op.getResult(), rewriter.getDenseI32ArrayAttr(a2_perm)); + + // Step 3. Reshape to: + // [ batch / prod(block_shape) ], + // [input_shape[1] * block_shape[0] ], + // .. + // [input_shape[M * block_shape[M-1], + // + remaining input shapes [input_shape[M+1.. N-1]] + SmallVector a4_shape(input_rank); + + a4_shape[0] = input_shape[0]; + if (a4_shape[0] != ShapedType::kDynamic) { + a4_shape[0] /= block_num_elems; + } + for (int i = 0; i < block_rank; i++) { + a4_shape[1 + i] = multiply_dims(input_shape[i + 1], block_shape[i]); + } + for (int i = 0; i < remaining_shape_rank; i++) { + a4_shape[1 + block_rank + i] = input_shape[block_rank + 1 + i]; + } + + auto a4_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a4_shape)); + auto a3_reshape_a2 = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a4_shape, + result_type.getElementType()), + a2_transpose_a1_op.getResult(), + a4_shape_value); + + // 4. Crop the start/end dimensions on 'spatial dimension' according to + // crops + // Use a slice operator to do the cropping. + // + // Calculate a beginning point and a size: + // - Begin is the origin, offset by the lo crop amount in each dimension + // - Size is the reshaped tensor size, minus the quantity (lo + hi) for each + // dimension + SmallVector a4_begin_vals(input_rank), a4_size_vals(input_rank); + + for (int i = 0; i < input_rank; i++) { + // Batch dimension and remaining dimensions. + if (i == 0 || i > crops_dims) { + a4_begin_vals[i] = 0; + a4_size_vals[i] = (result_type.getShape()[i] == ShapedType::kDynamic) + ? a4_shape[i] + : result_type.getShape()[i]; + } else { + // Spatial dimension. + assert(i - 1 >= 0 && i - 1 < crops_dims); + a4_begin_vals[i] = crops[i - 1].first; + a4_size_vals[i] = a4_shape[i] - crops[i - 1].first - crops[i - 1].second; + } + } + + return CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a4_size_vals, + result_type.getElementType()), + a3_reshape_a2.getResult(), + getTosaConstShape(rewriter, op->getLoc(), a4_begin_vals), + getTosaConstShape(rewriter, op->getLoc(), a4_size_vals)) + .getResult(); +} + +// Lowers ExpandDims to TOSA. +std::optional convertExpandDimsOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, Value dim_value) { + // Lowers to a reshape op with 1's inserted in the appropriate dimensions. + RankedTensorType output_type = + dyn_cast(result_value.getType()); + // Not a ranked tensor output + if (!output_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + auto input_shape = input_type.getShape(); + + ElementsAttr dim_elem; + if (!matchPattern(dim_value, m_Constant(&dim_elem))) return std::nullopt; + + if (dim_elem.getNumElements() > 1) { + (void)rewriter.notifyMatchFailure(op, + "expected single dimension to expand"); + return std::nullopt; + } + int32_t dim = dim_elem.getValues()[0].getInt(); + int32_t input_size = input_shape.size(); + + // check: -1-input_size <= dim <= input_size + if (dim < (-1 - input_size)) { + (void)rewriter.notifyMatchFailure( + op, "dimension to expand cannot be less than -1-input.dims()."); + return std::nullopt; + } + if (dim > input_size) { + (void)rewriter.notifyMatchFailure( + op, "dimension to expand cannot be greater than input.dims()."); + return std::nullopt; + } + + SmallVector reshape_dims; + if (dim == input_size || dim == -1) { // add dim at end of tensor + dim = input_size; + for (int i = 0; i < input_shape.size(); i++) { + reshape_dims.emplace_back(input_shape[i]); + } + reshape_dims.emplace_back(1); + } else { + if (dim < 0) { + dim += (input_size + 1); // dim=-2 => dim=input_size-1 + } + for (int i = 0; i < input_size; i++) { + if (i == dim) { + reshape_dims.emplace_back(1); + } + reshape_dims.emplace_back(input_shape[i]); + } + } + + auto shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(reshape_dims)); + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + input_value, shape_value) + .getResult(); +} + +// Lowers Squeeze to TOSA. +std::optional convertSqueezeOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value input_value, + SmallVectorImpl& squeeze_dims) { + // Lowers to a reshape op where dimensions in squeeze_dims with size=1 + // are removed. + RankedTensorType output_type = + dyn_cast(result_value.getType()); + // Not a ranked tensor output + if (!output_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + auto input_shape = input_type.getShape(); + + SmallVector reshape_dims; + + if (squeeze_dims.empty()) { // remove all 1-dims + for (int i = 0; i < input_shape.size(); i++) { + if (input_shape[i] != 1) { + reshape_dims.emplace_back(input_shape[i]); + } + } + } else { + for (auto& dim : squeeze_dims) { + dim = dim < 0 ? dim + input_shape.size() : dim; + } + + // Remove only specified dims. + // First sort the array so they can be picked off in sequence. + std::sort(squeeze_dims.begin(), squeeze_dims.end(), + [](const int32_t a, const int32_t b) { return a < b; }); + + int pos = 0; + auto dim = squeeze_dims[pos]; + for (int i = 0; i < input_shape.size(); i++) { + if (i == dim) { + pos = pos + 1; + if (pos < squeeze_dims.size()) + dim = squeeze_dims[pos]; + else + dim = -1; // Invalid + } else { + reshape_dims.emplace_back(input_shape[i]); + } + } + } + + auto shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(reshape_dims)); + + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + input_value, shape_value) + .getResult(); +} + +// Lowers ELU to a sequence of TOSA ops. +std::optional convertEluOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value features_value) { + // Lowers Elu using the following formula: + // elu(x) = x < 0 ? (exp(x) - 1) : x + // one = const({1}); + // zero = const({0}); + // one_bcast = reshape(one, [1, ..., rank(x) - 1]) + // zero_bcast = reshape(zero, [1, ..., rank(x) - 1]) + // a1 = exp(x); + // a2 = sub(a1, one_bcast) + // a3 = ge(x, zero_bcast) + // a4 = select(a3, x, a2) + RankedTensorType output_type = + dyn_cast(result_value.getType()); + // Not a ranked tensor output + if (!output_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + auto rank = output_type.getRank(); + + int32_t input_rank = output_type.getShape().size(); + SmallVector bcast_shape(input_rank, 1); + + // Can't directly create size=1, rank=rank(input) tensor because + // it will be optimized out. Instead, create rank0 tensor and reshape later. + Value one_const_op = getTosaConstTensorSingleF32(rewriter, op, 1.0, rank); + + Value zero_const_op = getTosaConstTensorSingleF32(rewriter, op, 0.0, rank); + + auto a1_exp_in_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, features_value); + + auto a2_sub_a1_one_op = + CreateOpAndInfer(rewriter, op->getLoc(), output_type, + a1_exp_in_op.getResult(), one_const_op); + + auto a3_ge_in_zero_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(output_type.getShape(), + rewriter.getIntegerType(1)), + features_value, zero_const_op); + + return CreateOpAndInfer( + rewriter, op->getLoc(), output_type, a3_ge_in_zero_op.getResult(), + features_value, a2_sub_a1_one_op.getResult()) + .getResult(); +} + +// Lowers Softmax to a sequence of TOSA ops. +std::optional convertSoftmaxOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value logits_value, + double beta) { + // softmax = exp(logits) / reduce_sum(exp(logits), -1) + // + // or equivalently multiply exp(-max(logits)) to both numerator and + // denominator we get: + // + // softmax = exp(logits - max(logits)) / reduce_sum(exp(logits - + // max(logits)), -1) + // + // Second equation is used for both quantized and fp lowering. + // For quantized case, we can restrict input to exp() be negative, + // and thus LUT can always be within [0.0, 1.0]. + // For fp case, the normalization in the equation is required to prevent + // float overflow in softmax's intermediate calculations. + RankedTensorType output_type = + dyn_cast(result_value.getType()); + RankedTensorType input_type = + dyn_cast(logits_value.getType()); + + // Not a ranked tensor input/output + if (!output_type || !input_type) { + (void)rewriter.notifyMatchFailure(op, + "input and result not ranked tensors"); + return std::nullopt; + } + + // beta is not exposed from the TF API, assume only beta=1.0 is supported + // For more details: https://github.com/tensorflow/tensorflow/issues/60435 + if (beta != 1.0) { + (void)rewriter.notifyMatchFailure( + op, "beta values other than 1.0 are not supported"); + return std::nullopt; + } + + // reduce_sum on last dimension + int32_t input_rank = input_type.getRank(); + ArrayRef logits_shape = output_type.getShape(); + + const auto propagate_attr = tosa::NanPropagationModeAttr::get( + rewriter.getContext(), tosa::NanPropagationMode::PROPAGATE); + + if (mlir::isa(input_type.getElementType()) && + mlir::isa(output_type.getElementType())) { + SmallVector rsum_shape_v(input_type.getShape().begin(), + input_type.getShape().end() - 1); + rsum_shape_v.push_back(1); + ArrayRef rsum_shape(rsum_shape_v); + // The if condition already checks if these are UQTs + mlir::quant::UniformQuantizedType in_quant_type = + mlir::cast( + input_type.getElementType()); + mlir::quant::UniformQuantizedType out_quant_type = + mlir::cast( + output_type.getElementType()); + + auto int16_element_qtype = mlir::quant::UniformQuantizedType::get( + true, rewriter.getIntegerType(16), rewriter.getF32Type(), 1.0f, 0, + -32768, 32767); + RankedTensorType int16_logits_type = + tensorflow::GetTypeFromTFTensorShape(logits_shape, int16_element_qtype); + RankedTensorType int32_logits_type = tensorflow::GetTypeFromTFTensorShape( + logits_shape, rewriter.getIntegerType(32)); + RankedTensorType int16_rsum_type = + tensorflow::GetTypeFromTFTensorShape(rsum_shape, int16_element_qtype); + RankedTensorType int32_rsum_type = tensorflow::GetTypeFromTFTensorShape( + rsum_shape, rewriter.getIntegerType(32)); + + if (in_quant_type.getStorageTypeIntegralWidth() == 8) { + // Step 1. get x - max(x) + Value op1_rescale_in = + buildRescale(rewriter, op, int32_logits_type, logits_value, 1.0f, + in_quant_type.getZeroPoint(), 0, tosa::RoundingMode::SINGLE_ROUND, true); + + auto op2_reducemax_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op1_rescale_in, + rewriter.getI32IntegerAttr(input_rank - 1), + propagate_attr); + + auto op3_sub_op1_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op1_rescale_in, + op2_reducemax_op1.getResult()); + + // Step 2. get exp() result + // Implemented with 4 16-bit table lookup + // We use a 16-bit table lookup, as the result of x - max(x) for + // 8-bit values is a 9-bit value. We only use the bottom 8 bits of each + // table to avoid having the slope between two 16-bit table entries be + // greater than 16 bits, causing potential interpolation errors + Value exp_table_const_01, exp_table_const_02, exp_table_const_03, + exp_table_const_04; + getTosaConst32bitSoftmaxExpTable( + rewriter, op, beta, in_quant_type.getScale(), exp_table_const_01, + exp_table_const_02, exp_table_const_03, exp_table_const_04); + + Value op4_rescale_op3 = + buildRescale(rewriter, op, int16_logits_type, + op3_sub_op1_op2.getResult(), 128.0, 0, 0, tosa::RoundingMode::SINGLE_ROUND, true); + + // Input is 9.7, where lower 7 bits are all zeros. + // Output is 23 bits, where lower 7 bits should be all zeros as well, + // since there's no interpolation here. + auto op5_table_op4_bits_31_24 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op4_rescale_op3, + exp_table_const_01); + + auto op6_table_op4_bits_23_16 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op4_rescale_op3, + exp_table_const_02); + + auto op7_table_op4_bits_15_8 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op4_rescale_op3, + exp_table_const_03); + + auto op8_table_op4_bits_7_0 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op4_rescale_op3, + exp_table_const_04); + + // To get 16 bits upper/lower value, we need to right shift 7 bits + // And then we reconstruct 32-bit value we need (upper << 24) + lower + // So effectively we left shift the 1st group of 8-bit with 17 bits + auto op7_lshift_op5 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op5_table_op4_bits_31_24.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 17, input_rank)); + + // For the 2nd group of 8-bit, we need to >> 7 AND << 16 ==> << 9 + auto op8_lshift_op6 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op6_table_op4_bits_23_16.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 9, input_rank)); + + // For the 3rd 8-bit, we need to >> 7 AND << 8 ==> << 1 + auto op9_lshift_op7 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op7_table_op4_bits_15_8.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 1, input_rank)); + + // For the last 8-bit, we only need to >> 7 + auto op10_rshift_op8 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op8_table_op4_bits_7_0.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 7, input_rank), true); + + // Add together all the 8-bit groups + // Add [1+2] + auto op11_add_op7_op8 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op7_lshift_op5.getResult(), + op8_lshift_op6.getResult()); + + // Add [1+2+3] + auto op12_add_op11_op9 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op11_add_op7_op8.getResult(), op9_lshift_op7.getResult()); + + // Add [1+2+3+4] + auto op13_add_op12_op10 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op12_add_op11_op9.getResult(), op10_rshift_op8.getResult()); + + // Step 3. get sum(exp()). output 12.19 + auto op14_rshift_op13_12 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op13_add_op12_op10.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 12, input_rank), true); + + auto op15_reducesum_op14 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + op14_rshift_op13_12.getResult(), + rewriter.getI32IntegerAttr(input_rank - 1)); + + // Step 4. calculate reciprocal(sum(exp())) + // CLZ returns the number of leading zeros which equals to headroom + 1 + auto op16_clz_op15 = + CreateOpAndInfer(rewriter, op->getLoc(), int32_rsum_type, + op15_reducesum_op14.getResult()); + + // minus one to get headroom + auto op17_sub_op16 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op16_clz_op15.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 1, input_rank)); + + // Left shift to get s1.30 format + auto op18_lshift_op15_op17 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + op15_reducesum_op14.getResult(), op17_sub_op16.getResult()); + + // Step 5. Calculate one_over_one_plus_x() with Newton-Raphson division + // with 3 iterations. + // Need two magic constants 48/17 and -32/17 from Newton-Raphson algorithm + // We need to operate in s2.29 since 48/17 is > 2.0 + // Reference: gemmlowp/fixedpoint/fixedpoint.h + Value half_denominator = op18_lshift_op15_op17.getResult(); + Value four = getTosaConstTensorSingleI32(rewriter, op, 4, input_rank); + Value F2_one = + getTosaConstTensorSingleI32(rewriter, op, (1U << 29), input_rank); + Value constant_48_over_17 = + getTosaConstTensorSingleI32(rewriter, op, 1515870810, input_rank); + Value constant_neg_32_over_17 = + getTosaConstTensorSingleI32(rewriter, op, -1010580540, input_rank); + + // F2 x = constant_48_over_17 + half_denominator * + // constant_neg_32_over_17; + auto op19_mul_half_denominator = + CreateMulOpAndInfer(rewriter, op, int32_rsum_type, half_denominator, + constant_neg_32_over_17, 31); + + auto op20_add_op19 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + op19_mul_half_denominator.getResult(), constant_48_over_17); + + // Newton-Raphson 3x iteration + Value nr_x = op20_add_op19.getResult(); + for (int i = 0; i < 3; i++) { + // half_denominator_times_x = + // SaturatingRoundingDoublingHighMul(half_denominator, x) + auto op21_mul_x_half_denominator = CreateMulOpAndInfer( + rewriter, op, int32_rsum_type, nr_x, half_denominator, 31); + + // F2 one_minus_half_denominator_times_x = F2::One() - + // half_denominator_times_x + auto op22_sub_one_op21 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, F2_one, + op21_mul_x_half_denominator.getResult()); + + // SaturatingRoundingDoublingHighMul(x, + // one_minus_half_denominator_times_x) + auto op23_mul_x_op22 = + CreateMulOpAndInfer(rewriter, op, int32_rsum_type, nr_x, + op22_sub_one_op21.getResult(), 31); + + // x + Rescale<2>(x * one_minus_half_denominator_times_x) + auto op24_mul_op23_four = CreateMulOpAndInfer( + rewriter, op, int32_rsum_type, op23_mul_x_op22.getResult(), four); + + auto op25_add_x_op24 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, nr_x, + op24_mul_op23_four.getResult()); + + nr_x = op25_add_x_op24.getResult(); + } + + // Step 6. multiply exp(x) with 1 / sum(exp(x)) + // combined with Rescale<0>(ExactMulByPot<-1>(x)) + // so shift 30 instead of 31 + auto op26_mul_op13_x = + CreateMulOpAndInfer(rewriter, op, int32_logits_type, + op13_add_op12_op10.getResult(), nr_x, 31 - 1); + + // Right shift amount is + // num_bits_over_unit + 31 - (sizeof(OutputT) * 8 = + // (12 - headroom_plus_one) + 31 - 8 = + // (12 + 31 - 8) - headroom_plus_one + auto op27_sub_op16 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + getTosaConstTensorSingleI32(rewriter, op, 12 + 31 - 8, input_rank), + op16_clz_op15.getResult()); + + auto op28_rshift_op26_op27 = + CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op26_mul_op13_x.getResult(), op27_sub_op16.getResult(), true); + + return buildRescale(rewriter, op, output_type, + op28_rshift_op26_op27.getResult(), 1.0, 0, + out_quant_type.getZeroPoint(), tosa::RoundingMode::SINGLE_ROUND, true); + + } else if (in_quant_type.getStorageTypeIntegralWidth() == 16) { + // Step 1. get x - max(x) + Value op1_rescale_in = + buildRescale(rewriter, op, int32_logits_type, logits_value, 1.0f, + in_quant_type.getZeroPoint(), 0, tosa::RoundingMode::SINGLE_ROUND, true); + + auto op2_reducemax_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op1_rescale_in, + rewriter.getI32IntegerAttr(input_rank - 1), + propagate_attr); + + // output range is [-65535, 0] + auto op3_sub_op1_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op1_rescale_in, + op2_reducemax_op1.getResult()); + + auto exp_func = [](double x) -> double { return std::exp(x); }; + + // Follow TFLite reference: tensorflow/lite/kernels/activations.cc + Value exp_table_const = getTosaConst16bitTable( + rewriter, op, 10.0 / 65535.0, 32767, 2.0 / 65535.0, 0, exp_func); + + double input_diff_scale = in_quant_type.getScale() / (10.0 / 65535.0); + + // Step 2. rescale input from [-65535, 0] to [-32768, 32767] for LUT input + Value op4_rescale_op3 = buildRescale( + rewriter, op, int32_logits_type, op3_sub_op1_op2.getResult(), + /*scale=*/input_diff_scale, /*input_zp=*/0, /*output_zp=*/0, + /*rounding_mode=*/tosa::RoundingMode::DOUBLE_ROUND, /*scale32=*/true); + auto op5_add_op4 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op4_rescale_op3, + getTosaConstTensorSingleI32(rewriter, op, 32767, input_rank)); + + auto op6_cast_op5 = CreateOpAndInfer( + rewriter, op->getLoc(), int16_logits_type, op5_add_op4.getResult()); + + // Step 3. get exp() result + // Output is 15.7. + // In 8-bit case, no interpolation here, since input should be right on + // table entry. + auto op7_table_op6 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op6_cast_op5, + exp_table_const); + + // Right shift 7 bits. output 15. Shouldn't lose any precision since last + // 7 bits should be all 0. + auto op8_rshift_op7 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, op7_table_op6.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 7, input_rank), true); + + // Step 4. get sum(exp()). output 16.15 + auto op9_reducesum_op8 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op8_rshift_op7.getResult(), + rewriter.getI32IntegerAttr(input_rank - 1)); + + // Step 5. calculate reciprocal(sum(exp())) + // CLZ returns 32 - first non zero bit + auto op10_clz_op9 = + CreateOpAndInfer(rewriter, op->getLoc(), int32_rsum_type, + op9_reducesum_op8.getResult()); + + auto op11_sub_op10 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op10_clz_op9.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 1, input_rank)); + + // Left shift to get 1.30 format + auto op12_lshift_op9_op11 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + op9_reducesum_op8.getResult(), op11_sub_op10.getResult()); + + // Subtract (1 << 30) to make 0 <= x <= 1 under 0.30 format + auto op13_sub_op12 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + op12_lshift_op9_op11.getResult(), + getTosaConstTensorSingleI32(rewriter, op, (1u << 30), input_rank)); + + // Right shift 14 bits to get output range [0, 65535] + auto op14_rshift_op13 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op13_sub_op12.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 14, input_rank), true); + + // Remap input to [-32768, 32767] for LUT input + auto op15_add_op14 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op14_rshift_op13.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 32768, input_rank)); + auto op16_cast_op15 = CreateOpAndInfer( + rewriter, op->getLoc(), int16_rsum_type, op15_add_op14.getResult()); + + // Generate table for 1 / (1 + x), for 0 <= x <= 1 + auto one_over_one_plus_x_func = [](double x) -> double { + return 1.0 / (1.0 + x); + }; + + Value one_over_one_plus_x_table_const = getTosaConst16bitTable( + rewriter, op, 1.0 / 65535.0, -32768, 2.0 / 65535.0, 0, + one_over_one_plus_x_func); + + // Get (1 / sum(exp(x))) result as 23 bits (including sign bit) + auto op17_table_op16 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op16_cast_op15, + one_over_one_plus_x_table_const); + + // Right shift 7 bits back to 0.15 + auto op18_rshift_op17 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, op17_table_op16.getResult(), + getTosaConstTensorSingleI32(rewriter, op, 7, input_rank), true); + + // Step 6. multiply exp(max-x) with 1 / sum(exp(max-x)) + // lhs: 0.15, rhs: 0.15, output: 0.30 + auto op19_mul_op18_op8 = CreateMulOpAndInfer( + rewriter, op, int32_logits_type, op18_rshift_op17, op8_rshift_op7); + + auto op20_sub_op10 = CreateOpAndInfer( + rewriter, op->getLoc(), int32_rsum_type, + getTosaConstTensorSingleI32(rewriter, op, 31, input_rank), + op10_clz_op9.getResult()); + + // Apply the clz back, we get 0.15 output + // [0, 32767] corresponding to [0.0, 1.0] + auto op21_rshift_op19_op20 = + CreateOpAndInfer( + rewriter, op->getLoc(), int32_logits_type, + op19_mul_op18_op8.getResult(), op20_sub_op10.getResult(), true); + + return buildRescale(rewriter, op, output_type, + op21_rshift_op19_op20.getResult(), + (1.0 / out_quant_type.getScale()) * (1.0 / 32768.0), + 0, out_quant_type.getZeroPoint(), tosa::RoundingMode::SINGLE_ROUND, true); + } else { + (void)rewriter.notifyMatchFailure(op, "unknown quantization bitwidth"); + return std::nullopt; + } + } else { + SmallVector rsum_shape_v(input_type.getShape().begin(), + input_type.getShape().end()); + rsum_shape_v[input_rank - 1] = 1; + ArrayRef rsum_shape(rsum_shape_v); + + // Floating-point lowering is more direct: + // + // op1 = reducemax(logits) + // op2 = sub(logits, op1) + // op3 = exp(op2) + // op4 = reduce_sum(op3, -1) + // op5 = reciprocal(op4) + // op6 = mul(op3, op5) + RankedTensorType rsum_type = tensorflow::GetTypeFromTFTensorShape( + rsum_shape, output_type.getElementType()); + RankedTensorType logits_type = tensorflow::GetTypeFromTFTensorShape( + logits_shape, output_type.getElementType()); + + // Step 1. get x - max(x) + auto max_logits = CreateOpAndInfer( + rewriter, op->getLoc(), rsum_type, logits_value, + rewriter.getI32IntegerAttr(input_rank - 1), + propagate_attr); + auto normalized_logits = + CreateOpAndInfer(rewriter, op->getLoc(), logits_type, + logits_value, max_logits.getResult()); + + // Step 2. get exp(x - max(x)) + auto exp_norm_logits = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, normalized_logits); + + // Step 3. reuse softmax numerator to obtain denominator + // Keep dims so we don't need to reshape later + auto reducesum = CreateOpAndInfer( + rewriter, op->getLoc(), rsum_type, exp_norm_logits.getResult(), + rewriter.getI32IntegerAttr(input_rank - 1)); + auto denominator = CreateOpAndInfer( + rewriter, op->getLoc(), reducesum.getType(), reducesum.getResult()); + + return CreateMulOpAndInfer(rewriter, op, output_type, + exp_norm_logits.getResult(), + denominator.getResult()) + .getResult(); + } +} + +// Lowers LogSoftmax to a sequence of TOSA ops. +std::optional convertLogSoftmaxOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value logits_value) { + // log_softmax = log(exp(logits) / reduce_sum(exp(logits), -1)) + // op1 = exp(logits) + // op2 = reduce_sum(op1, -1) + // op3 = reciprocal(op2) + // op4 = mul(op1, op3) + // op5 = log(op4) + + TensorType output_type = dyn_cast(result_value.getType()); + // Not a tensor output + if (!output_type) { + (void)rewriter.notifyMatchFailure(op, "output type not tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(op->getOperand(0).getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + mlir::quant::UniformQuantizedType in_quant_type = + mlir::dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType out_quant_type = + mlir::dyn_cast_or_null( + output_type.getElementType()); + if (in_quant_type || out_quant_type) { + (void)rewriter.notifyMatchFailure( + op, "quantized log_softmax lowering not implemented yet"); + return std::nullopt; + } + + auto op1_exp_in = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, logits_value); + + // reduce_sum on last dimension + int32_t input_rank = input_type.getShape().size(); + // Keep dims so we don't need to reshape later + auto op2_reducesum_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), + UnrankedTensorType::get(output_type.getElementType()), + op1_exp_in.getResult(), rewriter.getI32IntegerAttr(input_rank - 1)); + auto op3_reciprocal_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), op2_reducesum_op1.getType(), + op2_reducesum_op1.getResult()); + + auto op4_mul_op1_op3 = + CreateMulOpAndInfer(rewriter, op, output_type, op1_exp_in.getResult(), + op3_reciprocal_op2.getResult()); + + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + op4_mul_op1_op3.getResult()) + .getResult(); +} + +// Lowers SpaceToDepth to a sequence of TOSA ops. Supports NHWC. +std::optional convertSpaceToDepthOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + IntegerAttr block_size_attr, + StringAttr data_format) { + // NHWC lowering version: + // a2 = tf.reshape(a, [orig_shape[0], orig_shape[1]//b, b, orig_shape[2]//b, + // b, orig_shape[3]]) + // a3 = tf.transpose(a2, [0, 1, 3, 2, 4, 5]) + // a4 = tf.reshape(a3, [orig_shape[0], orig_shape[1]//b, orig_shape[2]//b, + // orig_shape[3]*b*b]) + // return a4 + RankedTensorType output_type = + dyn_cast(result_value.getType()); + + // Not a ranked tensor output. + if (!output_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + if (input_type.getRank() != 4) { + (void)rewriter.notifyMatchFailure(op, "input rank not 4"); + return std::nullopt; + } + + auto input_shape = input_type.getShape(); + + if (!block_size_attr) { // This is a required parameter + (void)rewriter.notifyMatchFailure(op, "block size attribute not set"); + return std::nullopt; + } + + SmallVector block_size; + block_size.assign(2, block_size_attr.getInt()); + + if (!data_format) data_format = rewriter.getStringAttr("NHWC"); + + if (data_format.getValue().str() != "NHWC") { + (void)rewriter.notifyMatchFailure(op, "data format not NHWC"); + return std::nullopt; + } + + assert(block_size[0] * block_size[1] != 0); + + SmallVector a_reshape_dims; + a_reshape_dims.push_back(input_shape[0]); + a_reshape_dims.push_back(input_shape[1] / block_size[0]); + a_reshape_dims.push_back(block_size[0]); + a_reshape_dims.push_back(input_shape[2] / block_size[1]); + a_reshape_dims.push_back(block_size[1]); + a_reshape_dims.push_back(input_shape[3]); + + RankedTensorType a_reshape_output_type = tensorflow::GetTypeFromTFTensorShape( + a_reshape_dims, output_type.getElementType()); + + auto a_reshape_dims_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a_reshape_dims)); + auto a2_reshape_a_op = CreateOpAndInfer( + rewriter, op->getLoc(), a_reshape_output_type, input_value, + a_reshape_dims_value); + + SmallVector a2_transpose_dims; + a2_transpose_dims.push_back(input_shape[0]); + a2_transpose_dims.push_back(divide_dims(input_shape[1], block_size[0])); + a2_transpose_dims.push_back(divide_dims(input_shape[2], block_size[1])); + a2_transpose_dims.push_back(block_size[0]); + a2_transpose_dims.push_back(block_size[1]); + a2_transpose_dims.push_back(input_shape[3]); + + auto a3_transpose_a2_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a2_transpose_dims, + output_type.getElementType()), + a2_reshape_a_op.getResult(), + rewriter.getDenseI32ArrayAttr({0, 1, 3, 2, 4, 5})); + + SmallVector a3_reshape_dims; + a3_reshape_dims.push_back(input_shape[0]); + a3_reshape_dims.push_back(input_shape[1] / block_size[0]); + a3_reshape_dims.push_back(input_shape[2] / block_size[1]); + a3_reshape_dims.push_back(input_shape[3] * block_size[0] * block_size[1]); + + RankedTensorType a3_reshape_output_type = + tensorflow::GetTypeFromTFTensorShape(a3_reshape_dims, + output_type.getElementType()); + + auto a3_reshape_dims_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a3_reshape_dims)); + + return CreateOpAndInfer( + rewriter, op->getLoc(), a3_reshape_output_type, + a3_transpose_a2_op.getResult(), + a3_reshape_dims_value) + .getResult(); +} + +// Lowers DepthToSpace to a sequence of TOSA ops. Supports NHWC. +std::optional convertDepthToSpaceOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + IntegerAttr block_size_attr, + StringAttr data_format) { + // NHWC version + // a2 = tf.reshape(a, [orig_shape[0], orig_shape[1], orig_shape[2], b, b, + // orig_shape[3] // (b*b)]) + // a3 = tf.transpose(a2, [0, 1, 3, 2, 4, 5]) + // a4 = tf.reshape(a3, [orig_shape[0], orig_shape[1] * b, orig_shape[2] * b, + // orig_shape[3] // (b*b)]) + // return a4 + + RankedTensorType output_type = + dyn_cast(result_value.getType()); + + // Not a ranked tensor output + if (!output_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + if (input_type.getRank() != 4) return std::nullopt; + auto input_shape = input_type.getShape(); + + if (!block_size_attr) { // This is a required parameter + (void)rewriter.notifyMatchFailure(op, "block size attribute not set"); + return std::nullopt; + } + + SmallVector block_size; + block_size.assign(2, block_size_attr.getInt()); + + if (!data_format) data_format = rewriter.getStringAttr("NHWC"); + if (data_format.getValue().str() != "NHWC") { + (void)rewriter.notifyMatchFailure(op, "data format not NHWC"); + return std::nullopt; + } + + assert(block_size[0] * block_size[1] != 0); + + SmallVector a_reshape_dims; + a_reshape_dims.push_back(input_shape[0]); + a_reshape_dims.push_back(input_shape[1]); + a_reshape_dims.push_back(input_shape[2]); + a_reshape_dims.push_back(block_size[0]); + a_reshape_dims.push_back(block_size[1]); + a_reshape_dims.push_back(input_shape[3] / (block_size[0] * block_size[1])); + + RankedTensorType a_reshape_output_type = tensorflow::GetTypeFromTFTensorShape( + a_reshape_dims, output_type.getElementType()); + + auto a_reshape_dims_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a_reshape_dims)); + auto a2_reshape_a_op = CreateOpAndInfer( + rewriter, op->getLoc(), a_reshape_output_type, input_value, + a_reshape_dims_value); + + auto a3_transpose_a2_op = CreateOpAndInfer( + rewriter, op->getLoc(), a_reshape_output_type, + a2_reshape_a_op.getResult(), + rewriter.getDenseI32ArrayAttr({0, 1, 3, 2, 4, 5})); + + SmallVector a3_reshape_dims; + a3_reshape_dims.push_back(input_shape[0]); + a3_reshape_dims.push_back(input_shape[1] * block_size[0]); + a3_reshape_dims.push_back(input_shape[2] * block_size[1]); + a3_reshape_dims.push_back(input_shape[3] / (block_size[0] * block_size[1])); + + RankedTensorType a3_reshape_output_type = + tensorflow::GetTypeFromTFTensorShape(a3_reshape_dims, + output_type.getElementType()); + + auto a3_reshape_dims_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a3_reshape_dims)); + + return CreateOpAndInfer( + rewriter, op->getLoc(), a3_reshape_output_type, + a3_transpose_a2_op.getResult(), + a3_reshape_dims_value) + .getResult(); +} + +// Lowers Split to a sequence of TOSA ops. +std::optional> convertSplitOp( + PatternRewriter& rewriter, Operation* op, Value result_value, + Value input_value, int32_t num_split, int32_t axis) { + // This lowering creates num_split slice ops and ties them together + // with IdentityN to get from an array of Operations to a single Operation + // with a list of result tensors. + RankedTensorType result_type = + dyn_cast(result_value.getType()); + // Not a ranked tensor output + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + Type etype = input_type.getElementType(); + + if (axis < 0) axis += input_type.getRank(); + assert(num_split > 0); + assert(axis >= 0 && axis < input_type.getRank()); + + Value slice_value = input_value; + bool is_dyn_split = input_type.isDynamicDim(axis); + if (is_dyn_split) { + SmallVector new_shape; + for (int i = 0, s = input_type.getRank(); i < s; i++) { + if (i != axis) { + new_shape.push_back(input_type.getDimSize(i)); + continue; + } + + new_shape.push_back(num_split); + new_shape.push_back(-1); + } + + auto new_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(new_shape)); + slice_value = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(new_shape, etype), input_value, + new_shape_value); + } + + RankedTensorType slice_type = + mlir::cast(slice_value.getType()); + assert((slice_type.getDimSize(axis) % num_split) == 0); + + // Each slice has a different beginning point. + // The slice size is actually the same each op. + SmallVector begin_vals, size_vals; + for (int j = 0, s = slice_type.getRank(); j < s; j++) { + begin_vals.push_back(0); + int64_t dim = slice_type.getDimSize(j); + size_vals.push_back(ShapedType::isDynamic(dim) ? tensorflow::kTFDynamicSize + : dim); + } + size_vals[axis] = size_vals[axis] / num_split; + + SmallVector results_vec; + for (int i = 0; i < num_split; i++) { + begin_vals[axis] = i * size_vals[axis]; + + Value result = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(size_vals, + result_type.getElementType()), + slice_value, getTosaConstShape(rewriter, op->getLoc(), begin_vals), + getTosaConstShape(rewriter, op->getLoc(), size_vals)); + + if (is_dyn_split) { + SmallVector out_reshape_shape; + for (int i = 0, s = size_vals.size(); i < s; i++) + if (i != axis) out_reshape_shape.push_back(size_vals[i]); + + auto out_reshape_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(out_reshape_shape)); + result = + CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(out_reshape_shape, etype), + result, + out_reshape_shape_value) + .getResult(); + } + + results_vec.push_back(result); + } + + return results_vec; +} + +// Lowers SplitV to a sequence of TOSA ops. +std::optional> convertSplitVOp( + PatternRewriter& rewriter, Operation* op, Value result_value, + Value input_value, SmallVectorImpl& size_split, int32_t axis) { + // This lowering creates num_split slice ops and ties them together + // with IdentityN to get from an array of Operations to a single Operation + // with a list of result tensors. + RankedTensorType result_type = + dyn_cast(result_value.getType()); + // Not a ranked tensor output + if (!result_type) { + (void)rewriter.notifyMatchFailure(op, "output type not ranked tensor"); + return std::nullopt; + } + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + auto input_shape = input_type.getShape(); + + SmallVector results_vec; + + if ((axis >= 0 && axis >= input_shape.size()) || + (axis < 0 && axis < -input_shape.size())) { + (void)rewriter.notifyMatchFailure(op, "invalid axis value"); + return std::nullopt; + } + axis = adjust_axis(axis, input_shape.size()); + int32_t size_split_sum = 0; + for (int i = 0; i < size_split.size(); i++) { + size_split_sum += size_split[i]; + } + + // The split sizes must sum up to the size of the axis being split + assert(size_split_sum == input_shape[axis]); + + int32_t curr_split_start = 0; + for (int i = 0; i < size_split.size(); i++) { + // Each slice has a different beginning point. + // The slice size is different for each op. + SmallVector begin_vals, size_vals; + + for (int j = 0; j < input_shape.size(); j++) { + if (j == axis) { + begin_vals.push_back(curr_split_start); + size_vals.push_back(size_split[i]); + } else { + begin_vals.push_back(0); + size_vals.push_back(input_shape[j]); + } + } + + auto slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(size_vals, + result_type.getElementType()), + input_value, getTosaConstShape(rewriter, op->getLoc(), begin_vals), + getTosaConstShape(rewriter, op->getLoc(), size_vals)); + + results_vec.push_back(slice_op.getResult()); + + // Next start position + curr_split_start += size_split[i]; + } + + return results_vec; +} + +// Helper function to reverse negative striding. Only checks for -1 as that is +// the only legal negative stride. +static Value reverseNegativeStride(PatternRewriter& rewriter, Operation* op, + Value input, ArrayRef strides) { + for (const auto& it : llvm::enumerate(strides)) { + auto axis = it.index(); + auto stride = it.value(); + if (stride != -1) continue; + + input = CreateOpAndInfer(rewriter, op->getLoc(), + input.getType(), input, + rewriter.getI32IntegerAttr(axis)) + .getResult(); + } + + return input; +} + +// Lowers StridedSlice to a sequence of TOSA ops. +std::optional convertStridedSliceOp( + PatternRewriter& rewriter, Operation* op, Value result_value, + Value input_value, Value begin_value, Value end_value, Value strides_value, + int32_t begin_mask, int32_t end_mask, int32_t ellipsis_mask, + int32_t new_axis_mask, int32_t shrink_axis_mask) { + // The mask arguments are bitmasks where bit [i] applies to + // dimension [i] of the input tensor. + // + // The rough algorithm for lowering strided slice is as follows: + // + // 0. Process begin/end masks, since they are basically syntactic sugar + // on top of the begin_value/end_value arrays + // + // 1. Slice1: Ignoring stride, slice the interesting range from the input + // tensor + // + // 2. Reshape2: Reshape the tensor from (1) such that each dimension with + // abs(stride) != 1 is split into two dimensions of size_i/stride_i, stride_i. + // + // 3. Slice3: Slice the tensor from (2) such that we select index [0] from + // each of the stride_i dimensions in (2) + // + // 4. Reshape4: Reshape the tensor to eliminate the stride_i dimensions, add + // any dimensions in new_axis_mask and remove any dimensions in the + // shrink_axis_mask + + // Limitations: + // * This implementation only supports ellipsis_mask=0 for now + auto input_type = dyn_cast(input_value.getType()); + ShapedType result_type = mlir::cast(result_value.getType()); + + if (ellipsis_mask != 0) { + (void)rewriter.notifyMatchFailure(op, "ellipses mask not supported yet"); + return std::nullopt; + } + + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type has unknown rank"); + return std::nullopt; + } + + int32_t input_rank = input_type.getRank(); + Type element_type = input_type.getElementType(); + + // Conditionally extract begin/end values if requied. + SmallVector begin, end, strides; + if (failed(getVectorFromValue32(strides_value, strides))) { + (void)rewriter.notifyMatchFailure(op, "strides isn't a constant"); + return std::nullopt; + } + + // Current configuration does not support negative strides greater than 1. + // Bail out for now (fix if this proves to be legal). + for (auto stride : strides) + if (stride < -1) return std::nullopt; + + bool all_strides_one = true; + int32_t strides_size = strides.size(); + for (auto stride : strides) all_strides_one &= abs(stride) == 1; + + // If all of the masks are set we can just bypass the entire thing. + const int32_t all_masks_one = (1 << strides_size) - 1; + + if (failed(getVectorFromValue32(begin_value, begin)) && + begin_mask != all_masks_one) { + (void)rewriter.notifyMatchFailure(op, "begin isn't a constant"); + return std::nullopt; + } + + if (end_mask != all_masks_one && + failed(getVectorFromValue32(end_value, end))) { + (void)rewriter.notifyMatchFailure(op, "end isn't a constant"); + return std::nullopt; + } + + if (llvm::any_of(strides, [](auto i) { return i < -1; })) { + (void)rewriter.notifyMatchFailure(op, "stride < -1 unsupported"); + return std::nullopt; + } + + // Set begin mask values if possible. + for (const auto& val : llvm::enumerate(begin)) + begin_mask |= (val.value() == 0) << val.index(); + + // If all begin/end masks are set and striding is one we can just return + // the matrix with reversed dims (for negative strides). + if (all_strides_one && begin_mask == all_masks_one && + end_mask == all_masks_one) { + return reverseNegativeStride(rewriter, op, input_value, strides); + } + + // Set the bits true for the remaining dimensions. + int32_t new_mask_bits = (1 << input_rank) - all_masks_one - 1; + begin_mask |= new_mask_bits; + end_mask |= new_mask_bits; + + // Negative values are exclusive from the opposite end while TOSA is + // inclusive, we offset to adjust for this. + for (auto& b : begin) + if (b < 0) b = b - 1; + for (auto& e : end) + if (e < 0) e = e - 1; + + // Fill the remaining stride and begin/end with default values. + strides.resize(input_rank, 1); + begin.resize(input_rank, 0); + end.resize(input_rank, -1); + + // Set masking-bit overrides. + for (int i = 0; i < input_rank; ++i) { + if (begin_mask & (1 << i)) begin[i] = 0; + if (end_mask & (1 << i)) end[i] = -1; + } + + // If we know the static end we can adjust by it. + for (int i = 0; i < input_rank; ++i) { + if (input_type.isDynamicDim(i)) continue; + if (begin[i] < 0) begin[i] += input_type.getDimSize(i) + 1; + if (end[i] < 0) end[i] += input_type.getDimSize(i) + 1; + } + + // Perform some final validation on the begin/end values. + for (int i = 0; i < input_rank; ++i) { + if (begin[i] < 0 && input_type.isDynamicDim(i)) { + (void)rewriter.notifyMatchFailure( + op, "begin offset is negative on dynamic size"); + return std::nullopt; + } + + if (end[i] < -1 && input_type.isDynamicDim(i)) { + (void)rewriter.notifyMatchFailure( + op, "end is exclusive of final entry on dynamic size"); + return std::nullopt; + } + } + + SmallVector input_pads( + input_rank * 2); // Stores pads on either side of a dimension + + // Step 0: Process the begin/end masks and build the begin/sizes for the + // first slice + SmallVector a1_begin(input_rank), a1_size(input_rank); + for (int i = 0; i < input_rank; ++i) { + // Wrap around index if begin and end is negative + a1_begin[i] = begin[i]; + + if (end[i] == -1 && input_type.isDynamicDim(i)) { + // Slice using -1 as TOSA's sentinal value. + a1_size[i] = -1; + } else if (end[i] < 0 && input_type.isDynamicDim(i)) { + // Other dynamic cases cannot be handled. + (void)rewriter.notifyMatchFailure( + op, "input dim is dynamic and slice end depends on the length"); + return std::nullopt; + } else { + a1_size[i] = end[i] - a1_begin[i]; + } + + // Shrink axis mask means we know the size and stride are 1. + if (shrink_axis_mask & (1 << i)) { + a1_size[i] = 1; + strides[i] = 1; + } + + // Note: no padding added to dynamic dimensions + auto stride_remainder = a1_size[i] % strides[i]; + if (a1_size[i] > 0 && stride_remainder != 0) { + input_pads[2 * i] = 0; // No padding at beginning of dimension + auto pad_up_value = strides[i] - stride_remainder; + input_pads[2 * i + 1] = pad_up_value; // Pad end of dimension up to the + // next multiple of strides[i] + a1_size[i] += pad_up_value; + } else { + input_pads[2 * i] = 0; + input_pads[2 * i + 1] = 0; + } + } + + // Step 0.5: Add tosa.Pad if required + const bool need_padding = + llvm::any_of(input_pads, [](int64_t i) { return i != 0; }); + if (need_padding) { + Value a0_padding = getTosaConstShape(rewriter, op->getLoc(), input_pads); + + auto a0_pad_input_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a1_size, + result_type.getElementType()), + input_value, a0_padding); + + input_value = + a0_pad_input_op.getResult(); // overwrite input_value parameter + } + + auto a1_slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a1_size, element_type), input_value, + getTosaConstShape(rewriter, op->getLoc(), a1_begin), + getTosaConstShape(rewriter, op->getLoc(), a1_size)); + + // If unary striding is used we can reverse, reshape, and return the result. + if (all_strides_one) { + auto reversed = + reverseNegativeStride(rewriter, op, a1_slice_op.getResult(), strides); + auto shape = mlir::cast(reversed.getType()).getShape(); + + SmallVector new_shape; + for (int i = 0; i < input_rank; ++i) { + if (!(shrink_axis_mask & (1 << i))) { + if (new_axis_mask & (1 << i)) new_shape.push_back(1); + new_shape.push_back((shape[i])); + } + } + + auto new_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(new_shape)); + + return CreateOpAndInfer( + rewriter, op->getLoc(), result_type, reversed, + new_shape_value) + .getResult(); + } + + // Step 2: reshape the sliced array + SmallVector a2_shape; + for (int i = 0; i < input_rank; ++i) { + int64_t abs_stride_i = abs(strides[i]); + a2_shape.push_back(a1_size[i] == -1 ? -1 : a1_size[i] / abs_stride_i); + if (abs_stride_i != 1) { + // only add a stride dimension if strides[i] != 1 + a2_shape.push_back(abs_stride_i); + } + } + + auto a2_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a2_shape)); + auto a2_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a2_shape, element_type), + a1_slice_op.getResult(), + a2_shape_value); + + // Step 3: take a slice along the strides + SmallVector a3_begin, a3_size; + for (int i = 0; i < input_rank; ++i) { + int64_t abs_stride_i = abs(strides[i]); + a3_begin.push_back(0); + + if (shrink_axis_mask & (1 << i)) { + a3_size.push_back(1); + } else { + a3_size.push_back((a1_size[i] == -1) ? -1 : (a1_size[i] / abs_stride_i)); + } + if (abs_stride_i != 1) { + // previous reshape only adds a stride dimension if strides[i] != 1 + a3_begin.push_back(0); + a3_size.push_back(1); + } + } + assert(a2_shape.size() == a3_begin.size()); + assert(a2_shape.size() == a3_size.size()); + + auto a3_slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a3_size, element_type), + a2_reshape_op.getResult(), + getTosaConstShape(rewriter, op->getLoc(), a3_begin), + getTosaConstShape(rewriter, op->getLoc(), a3_size)); + + // Step 4: reshape the now-strided tensor + SmallVector a4_shape; + for (int i = 0; i < input_rank; ++i) { + if (!(shrink_axis_mask & (1 << i))) { + if (new_axis_mask & (1 << i)) a4_shape.push_back(1); + a4_shape.push_back( + ((a1_size[i] == -1) ? -1 : (a1_size[i] / abs(strides[i])))); + } + } + + auto a4_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(a4_shape)); + auto a4_reshape_op = + CreateOpAndInfer( + rewriter, op->getLoc(), result_type, a3_slice_op.getResult(), + a4_shape_value) + .getResult(); + + return reverseNegativeStride(rewriter, op, a4_reshape_op, strides); +} + +// Helper function to perform division with floor rounding mode (rounding result +// down) for integer type inputs. +Value floorIntDiv(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value lhs_value, Value rhs_value) { + // To implement floor div int input, utilize tosa::IntDivOp (trunc div + // result - rounds towards zero) with the following formula elementwise: + // floor_value = trunc_value - ((trunc_value * rhs_value != lhs_value) + // && (sign(lhs_value) != sign(rhs_value))) + // + // a1 = intdiv(lhs_value, rhs_value); // IntDivOp return truncated result + // a2 = mul(lhs_value, rhs_value); + // a3 = mul(rhs_value, a1); + // a4 = eq(lhs_value, a3); + // a5 = not(a4); // (trunc_value * rhs_value != lhs_value) + // a6 = gt(zero, a2); // (sign(lhs_value) != sign(rhs_value)) + // a7 = sub(a1, one); + // a8 = and(a5, a6); // (trunc_value * rhs_value != lhs_value) && + // (sign(lhs_value) != sign(rhs_value)) + // a9 = select(a8, a7, a1); + // return a9; + + ShapedType lhs_type = dyn_cast(lhs_value.getType()); + ShapedType rhs_type = dyn_cast(rhs_value.getType()); + + ImplicitLocOpBuilder builder(op->getLoc(), rewriter); + + ShapedType output_i32_type = output_type.clone(rewriter.getIntegerType(32)); + ShapedType output_bool_type = output_type.clone(rewriter.getIntegerType(1)); + + Value zero = + getTosaConstTensorSingleI32(rewriter, op, 0, output_type.getRank()); + Value one = + getTosaConstTensorSingleI32(rewriter, op, 1, output_type.getRank()); + + auto output_shape_value = getTosaConstShape( + rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(output_type.getShape())); + + Value lhs_value_casted = CreateOpAndInfer( + rewriter, op->getLoc(), lhs_type.clone(rewriter.getIntegerType(32)), + lhs_value); + + Value lhs_value_reshaped = + CreateOpAndInfer(rewriter, op->getLoc(), output_i32_type, + lhs_value_casted, output_shape_value); + + Value rhs_value_casted = CreateOpAndInfer( + rewriter, op->getLoc(), rhs_type.clone(rewriter.getIntegerType(32)), + rhs_value); + + // TOSA IntDiv requires inputs to be i32 + auto a1_int_div_op = + CreateOpAndInfer(rewriter, op->getLoc(), output_i32_type, + lhs_value_casted, rhs_value_casted); + + auto a1_int_div_op_casted = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, a1_int_div_op.getResult()); + + auto a2_lhs_mul_rhs_op = + CreateMulOpAndInfer(rewriter, op, output_type, lhs_value, rhs_value); + + auto a3_rhs_mul_a1_op = CreateMulOpAndInfer( + rewriter, op, output_type, rhs_value, a1_int_div_op_casted.getResult()); + + auto a4_lhs_eq_a3_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_bool_type, lhs_value_reshaped, + a3_rhs_mul_a1_op.getResult()); + + // (trunc_value * rhs_value != lhs_value) + auto a5_not_a4_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_bool_type, a4_lhs_eq_a3_op.getResult()); + + // (sign(lhs_value) != sign(rhs_value)) + auto a6_zero_gt_a2_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_bool_type, zero, + a2_lhs_mul_rhs_op.getResult()); + + auto a7_a1_sub_one_op = + CreateOpAndInfer(rewriter, op->getLoc(), output_type, + a1_int_div_op_casted.getResult(), one); + + // (trunc_value * rhs_value != lhs_value) + // && (sign(lhs_value) != sign(rhs_value)) + auto a8_a5_and_a6_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_bool_type, a5_not_a4_op.getResult(), + a6_zero_gt_a2_op.getResult()); + + auto a9_select_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, a8_a5_and_a6_op.getResult(), + a7_a1_sub_one_op.getResult(), a1_int_div_op_casted.getResult()); + + return a9_select_op.getResult(); +} + +// Lowers FloorDiv to a sequence of TOSA operators. +std::optional convertFloorDivOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value lhs_value, + Value rhs_value) { + // FloorDiv lowering for float type: + // floor(1/rhs * lhs) + // + // a1 = reciprocal(rhs); + // a2 = mul(lhs, a1); + // a3 = floor(a2); + // return a3; + // + // FloorDiv lowering for integer type: + // See floorIntDiv() function for details + ShapedType output_type = dyn_cast(result_value.getType()); + // Not a shaped tensor output + if (!output_type) return std::nullopt; + + Type element_type = output_type.getElementType(); + + if (mlir::isa(element_type)) { + return floorIntDiv(rewriter, op, output_type, lhs_value, rhs_value); + } + + auto a1_reciprocal_rhs_op = CreateOpAndInfer( + rewriter, op->getLoc(), rhs_value.getType(), rhs_value); + auto a2_mul_lhs_a1_op = CreateMulOpAndInfer( + rewriter, op, output_type, lhs_value, a1_reciprocal_rhs_op.getResult()); + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + a2_mul_lhs_a1_op.getResult()) + .getResult(); +} + +// Lowers FloorMod to a sequence of TOSA operators. +std::optional convertFloorModOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value lhs_value, + Value rhs_value) { + // FloorMod lowering: + // (1/rhs * lhs) - floor(1/rhs * lhs) + // a1 = reciprocal(rhs); + // a2 = mul(lhs, a1); + // a3 = floor(a2); + // a4 = sub(a2, a3); + // return a4; + + RankedTensorType output_type = + dyn_cast(result_value.getType()); + // Not a ranked tensor output + if (!output_type) return std::nullopt; + + auto a1_reciprocal_rhs_op = CreateOpAndInfer( + rewriter, op->getLoc(), rhs_value.getType(), rhs_value); + auto a2_mul_lhs_a1_op = CreateMulOpAndInfer( + rewriter, op, output_type, lhs_value, a1_reciprocal_rhs_op.getResult()); + auto a3_floor_a2_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, a2_mul_lhs_a1_op.getResult()); + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + a2_mul_lhs_a1_op.getResult(), + a3_floor_a2_op.getResult()) + .getResult(); +} + +// Lowers FusedActivation to a sequence of TOSA ops. +std::optional convertFusedActivation(PatternRewriter& rewriter, + Operation* op, Value input_value, + StringAttr fused_activation_fn) { + ShapedType input_type = dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + + if (input_is_qtype) { + // We can always make output/input tensor's scale/zp always be the same + // when legalizing fused_activation_function, as it's generated during + // legalization. + auto input_qtype = mlir::cast( + input_type.getElementType()); + auto input_element_type = input_qtype.getStorageType(); + + if (fused_activation_fn.getValue() == "NONE") { + return input_value; + } else if (fused_activation_fn.getValue() == "RELU") { + int64_t quantized_0 = input_qtype.getZeroPoint(); + int64_t quantized_max = input_qtype.getStorageTypeMax(); + + auto clamp_op = CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input_value, + /* min_val = */ + rewriter.getIntegerAttr(input_element_type, quantized_0), + /* max_val = */ + rewriter.getIntegerAttr(input_element_type, quantized_max)); + + return clamp_op.getResult(); + } else if (fused_activation_fn.getValue() == "RELU6") { + int64_t quantized_0 = input_qtype.getZeroPoint(); + int64_t quantized_6 = std::llround((6.0f / input_qtype.getScale()) + + input_qtype.getZeroPoint()); + int64_t quantized_min = input_qtype.getStorageTypeMin(); + int64_t quantized_max = input_qtype.getStorageTypeMax(); + + int64_t clamp_min = std::max(quantized_0, quantized_min); + int64_t clamp_max = std::min(quantized_6, quantized_max); + + auto clamp_op = CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input_value, + /* min_val = */ + rewriter.getIntegerAttr(input_element_type, clamp_min), + /* max_val = */ + rewriter.getIntegerAttr(input_element_type, clamp_max)); + + return clamp_op.getResult(); + } else if (fused_activation_fn.getValue() == "RELU_N1_TO_1") { + int64_t quantized_max = input_qtype.getStorageTypeMax(); + int64_t quantized_min = input_qtype.getStorageTypeMin(); + int64_t quantized_n1 = std::llround((-1.0f / input_qtype.getScale()) + + input_qtype.getZeroPoint()); + int64_t quantized_1 = std::llround((1.0f / input_qtype.getScale()) + + input_qtype.getZeroPoint()); + + int64_t clamp_min = std::max(quantized_n1, quantized_min); + int64_t clamp_max = std::min(quantized_1, quantized_max); + + auto clamp_op = CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input_value, + /* min_val = */ + rewriter.getIntegerAttr(input_element_type, clamp_min), + /* max_val = */ + rewriter.getIntegerAttr(input_element_type, clamp_max)); + + return clamp_op.getResult(); + } else { + op->emitWarning("convertFusedActivation: Not implemented yet"); + return std::nullopt; + } + } else { + if (fused_activation_fn.getValue() == "NONE") { + return input_value; + } else { + // For non-quantized type, only support F32. + if (!input_type.getElementType().isF32()) { + (void)rewriter.notifyMatchFailure(op, "only support F32"); + return std::nullopt; + } + + if (fused_activation_fn.getValue() == "RELU") { + return CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input_value, + /* min_val = */ rewriter.getF32FloatAttr(0.0f), + /* max_val = */ + rewriter.getF32FloatAttr(std::numeric_limits::max())) + .getResult(); + } else if (fused_activation_fn.getValue() == "RELU6") { + return CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input_value, + /* min_val = */ rewriter.getF32FloatAttr(0.0f), + /* max_val = */ rewriter.getF32FloatAttr(6.0f)) + .getResult(); + } else if (fused_activation_fn.getValue() == "RELU_N1_TO_1") { + return CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input_value, + /* min_val = */ rewriter.getF32FloatAttr(-1.0), + /* max_val = */ rewriter.getF32FloatAttr(1.0)) + .getResult(); + } else if (fused_activation_fn.getValue() == "TANH") { + return CreateOpAndInfer(rewriter, op->getLoc(), + input_type, input_value) + .getResult(); + } else { + // Unsupported activation type. Bail out. + return std::nullopt; + } + } + } + + return std::nullopt; +} + +// Common function for lowering reduce operations to TOSA ops. +// Nan propagation mode is only applied to reduce_max and reduce_min. +template +std::optional convertReduceOpCommon( + PatternRewriter& rewriter, Operation* op, RankedTensorType output_type, + Value input_value, ElementsAttr axes_elems, Type reduce_element_type, + bool is_quantized, int32_t input_scale_multiplier, + int32_t input_scale_shift, int64_t input_zp, + int32_t output_scale_multiplier, int32_t output_scale_shift, + int64_t output_zp, bool keep_dims, std::optional nan_mode = std::nullopt) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + ArrayRef input_shape = input_type.getShape(); + auto input_rank = input_shape.size(); + Location loc = op->getLoc(); + + if (axes_elems.getNumElements() == 0) { + // No axes means return the original tensor. + auto identity_op = CreateOpAndInfer( + rewriter, loc, output_type, input_value); + return identity_op.getResult(); + } + + // Handle negative axis and guarantee in increasing order. + llvm::SmallVector axes; + for (auto axis : axes_elems.getValues()) { + auto axis_val = axis.getInt(); + if (axis_val < 0) axis_val += input_rank; + if (axis_val < 0 || axis_val >= input_rank) { + (void)rewriter.notifyMatchFailure( + op, "axis values not within range of input shape"); + + return std::nullopt; + } + axes.push_back(axis_val); + } + + Value val = input_value; + SmallVector shape_vec(input_shape.begin(), input_shape.end()); + + if (is_quantized) { + val = buildRescaleToInt32(rewriter, op, val, input_scale_multiplier, + input_scale_shift, input_zp); + } + + for (auto axis_val : axes) { + auto axis_attr = rewriter.getI32IntegerAttr(axis_val); + + shape_vec[axis_val] = 1; + RankedTensorType reduce_type = + tensorflow::GetTypeFromTFTensorShape(shape_vec, reduce_element_type); + + if constexpr (std::is_same_v || + std::is_same_v) { + if (!nan_mode) { + (void)rewriter.notifyMatchFailure( + op, "invalid NaN mode: must be either 'PROPAGATE' or 'IGNORE'"); + return std::nullopt; + } + const auto nan_mode_attr = tosa::NanPropagationModeAttr::get( + rewriter.getContext(), *nan_mode); + val = CreateOpAndInfer(rewriter, op->getLoc(), reduce_type, val, + axis_attr, nan_mode_attr) + .getResult(); + } else { + val = CreateOpAndInfer(rewriter, op->getLoc(), reduce_type, val, + axis_attr) + .getResult(); + } + } + + if (is_quantized) { + const tosa::RoundingMode rounding_mode = IsTFLDoubleRoundingMode() ? + tosa::RoundingMode::DOUBLE_ROUND : tosa::RoundingMode::SINGLE_ROUND; + UnrankedTensorType output_rescale_type = + UnrankedTensorType::get(output_type.getElementType()); + val = buildRescale(rewriter, op, output_rescale_type, val, + output_scale_multiplier, output_scale_shift, + /*input_zp=*/0, output_zp, rounding_mode, + /*scale32=*/true); + } + + // If keep dims, no reshaping of the output is required + if (keep_dims) { + return val; + } + + // Squeeze out the reduced axes. + const auto squeeze_axes = [](llvm::ArrayRef in, llvm::ArrayRef axes) { + llvm::SmallVector sorted_axes{axes}; + std::sort(sorted_axes.begin(), sorted_axes.end()); + auto current_axis = sorted_axes.begin(); + + llvm::SmallVector out; + out.reserve(in.size() - axes.size()); + for (const auto& [i, dim] : llvm::enumerate(in)) { + if (current_axis == sorted_axes.end() || i != *current_axis) + out.push_back(dim); + else + current_axis++; + } + return out; + }; + + const auto output_shape = squeeze_axes(input_shape, axes); + auto output_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(output_shape)); + auto reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, val, + output_shape_value); + return reshape_op.getResult(); +} + +// Common function for lowering reduce operations to TOSA ops. +template +std::optional convertReduceOpCommon( + PatternRewriter& rewriter, Operation* op, RankedTensorType output_type, + Value input_value, ElementsAttr axes_elems, Type reduce_element_type, + bool is_quantized, double input_scale, int64_t input_zp, + double output_scale, int64_t output_zp, bool keep_dims, std::optional nan_mode = std::nullopt) { + const int32_t scale_width = 32; + + int32_t input_scale_multiplier; + int32_t input_scale_shift; + computeMultiplierAndShift(input_scale, input_scale_multiplier, + input_scale_shift, scale_width); + + int32_t output_scale_multiplier; + int32_t output_scale_shift; + computeMultiplierAndShift(output_scale, output_scale_multiplier, + output_scale_shift, scale_width); + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, reduce_element_type, + is_quantized, input_scale_multiplier, input_scale_shift, input_zp, + output_scale_multiplier, output_scale_shift, output_zp, keep_dims, nan_mode); +} + +// Lowers ReduceAll to a sequence of TOSA ops. +std::optional convertReduceAllOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, + output_type.getElementType(), false, 1.0f, 0, 1.0f, 0, keep_dims); +} + +// Lowers ReduceAny to a sequence of TOSA ops. +std::optional convertReduceAnyOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, + output_type.getElementType(), false, 1.0f, 0, 1.0f, 0, keep_dims); +} + +// Lowers ReduceMin to a sequence of TOSA ops. +std::optional convertReduceMinOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims, + std::optional nan_mode) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, + output_type.getElementType(), false, 1.0f, 0, 1.0f, 0, keep_dims, nan_mode); +} + +// Lowers ReduceMax to a sequence of TOSA ops. +std::optional convertReduceMaxOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims, + std::optional nan_mode) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, + output_type.getElementType(), false, 1.0f, 0, 1.0f, 0, keep_dims, nan_mode); +} + +// Lowers ReduceProd to a sequence of TOSA ops. +std::optional convertReduceProdOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype || output_is_qtype) { + (void)rewriter.notifyMatchFailure( + op, "input/output tensor should be all floating-point"); + return std::nullopt; + } + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, + output_type.getElementType(), false, 1.0f, 0, 1.0f, 0, keep_dims); +} + +// Lowers ReduceSum to a sequence of TOSA ops. +std::optional convertReduceSumOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + (void)rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + return std::nullopt; + } + + double input_scale = 1.0f; + double output_scale = 1.0f; + int64_t input_zp = 0; + int64_t output_zp = 0; + Type reduce_element_type = input_type.getElementType(); + + if (input_is_qtype) { + auto input_qtype = mlir::cast( + input_type.getElementType()); + auto output_qtype = mlir::cast( + output_type.getElementType()); + + int32_t input_shift = 20; + + input_scale = + static_cast(1 << input_shift) * input_qtype.getScale(); + output_scale = + 1.0 / (output_qtype.getScale() * static_cast(1 << input_shift)); + + input_zp = input_qtype.getZeroPoint(); + output_zp = output_qtype.getZeroPoint(); + reduce_element_type = rewriter.getI32Type(); + } + + return convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, reduce_element_type, + input_is_qtype, input_scale, input_zp, output_scale, output_zp, keep_dims); +} + +// Lowers ReduceMean to a sequence of TOSA ops. +std::optional convertReduceMeanOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims) { + // reduce_mean is lowered as followed for quantized types: + // op1 = reduce_sum(input) with the 1.0/num_elements_on_reduced_axis + // integrated to the rescale layer, + // + // and for floating-point types: + // op1 = reduce_sum(input) + // op2 = mul(op1, 1.0 / num_elements_on_reduced_axis) + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + (void)rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + return std::nullopt; + } + + // Only supports float type mean() if it's non-quantized + if (!input_is_qtype && + !mlir::isa(output_type.getElementType())) { + op->emitWarning("input unquantized type but output element not FloatType"); + return std::nullopt; + } + + int64_t input_rank = input_type.getRank(); + int64_t num_elems_on_reduced_axis = 1; + for (int i = 0; i < axes_elems.getNumElements(); i++) { + int64_t axis_val = axes_elems.getValues()[i].getInt(); + if (axis_val < 0) axis_val += input_rank; + if (axis_val < 0 || axis_val >= input_rank) { + (void)rewriter.notifyMatchFailure( + op, "axis values not within range of input shape"); + + return std::nullopt; + } + num_elems_on_reduced_axis *= input_type.getShape()[axis_val]; + } + + int64_t input_zp = 0; + int64_t output_zp = 0; + Type reduce_element_type = input_type.getElementType(); + + int32_t input_scale_multiplier = 1; + int32_t input_scale_shift = 0; + + int32_t output_scale_multiplier = 1; + int32_t output_scale_shift = 0; + + if (input_is_qtype) { + auto input_qtype = mlir::cast( + input_type.getElementType()); + auto output_qtype = mlir::cast( + output_type.getElementType()); + + const int32_t scale_width = 32; + computeMultiplierAndShift(1.0f, input_scale_multiplier, input_scale_shift, + scale_width); + computeMultiplierAndShift(input_qtype.getScale() / output_qtype.getScale(), + output_scale_multiplier, output_scale_shift, + scale_width); + + input_zp = input_qtype.getZeroPoint(); + output_zp = output_qtype.getZeroPoint(); + reduce_element_type = rewriter.getI32Type(); + + // Match TFL REDUCE_MEAN reference kernel + // tensorflow/lite/kernels/internal/reference/reduce.h taking into account + // the shift difference between computeMultiplierAndShift and + // QuantizeMultiplier. + // + // Readapt output rescaling when calculating the mean to integrate a + // 1/num_elems_on_reduced_axis multiplier. + int shift = 63 - countLeadingZeros( + static_cast(num_elems_on_reduced_axis)); + shift = std::min(shift, 32); + shift = std::min(shift, 62 - output_scale_shift); + output_scale_multiplier = static_cast( + (static_cast(output_scale_multiplier) << shift) / + num_elems_on_reduced_axis); + output_scale_shift = output_scale_shift + shift; + } + + auto val = convertReduceOpCommon( + rewriter, op, output_type, input_value, axes_elems, reduce_element_type, + input_is_qtype, input_scale_multiplier, input_scale_shift, input_zp, + output_scale_multiplier, output_scale_shift, output_zp, keep_dims); + + if (!val.has_value()) return std::nullopt; + + if (!input_is_qtype) { + double div_scale = 1.0 / static_cast(num_elems_on_reduced_axis); + Value div_const = getTosaConstTensorSingleF32(rewriter, op, div_scale, + output_type.getRank()); + return CreateMulOpAndInfer(rewriter, op, output_type, val.value(), + div_const) + .getResult(); + } + + return val; +} + +// Lowers ResizeBilinear and ResizeNearestNeighbor to TOSA resize. +std::optional convertResizeOp(PatternRewriter& rewriter, Operation* op, + RankedTensorType output_type, + Value input_value, tosa::ResizeMode mode, + bool align_corners, + bool half_pixel_centers) { + const bool is_bilinear = mode == tosa::ResizeMode::BILINEAR; + const bool is_nearest = mode == tosa::ResizeMode::NEAREST_NEIGHBOR; + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + if (input_type.getRank() != 4 || output_type.getRank() != 4) { + (void)rewriter.notifyMatchFailure(op, "input/output must be rank 4"); + return std::nullopt; + } + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + (void)rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + return std::nullopt; + } + + if (!input_is_qtype) { + if (!mlir::isa(input_type.getElementType())) { + (void)rewriter.notifyMatchFailure( + op, "only quantized or float types supported"); + return std::nullopt; + } + } + + auto input_shape = input_type.getShape(); + auto output_shape = output_type.getShape(); + + if (input_type.isDynamicDim(1) || input_type.isDynamicDim(2)) { + (void)rewriter.notifyMatchFailure(op, "resize dynamic input not supported"); + return std::nullopt; + } + + if (output_type.isDynamicDim(1) || output_type.isDynamicDim(2)) { + (void)rewriter.notifyMatchFailure(op, + "resize dynamic output not supported"); + return std::nullopt; + } + + size_t input_height = input_shape[1]; + size_t input_width = input_shape[2]; + size_t output_height = output_shape[1]; + size_t output_width = output_shape[2]; + + // The ratio below is a non-zero positive value if this is a power-of-two + // upscaling. + int height_ratio = 0; + if (output_height % input_height == 0) { + int quotient = output_height / input_height; + if (llvm::isPowerOf2_64(quotient)) { + height_ratio = quotient; + } + } + + int width_ratio = 0; + if (output_width % input_width == 0) { + int quotient = output_width / input_width; + if (llvm::isPowerOf2_64(quotient)) { + width_ratio = quotient; + } + } + + // Align corners sets the scaling ratio to (OH - 1)/(IH - 1) + // rather than OH / IH. Similarly for width. + auto normalize = [&](int input, int output, int& n, int& d, int& offset, + int& border) { + // Dimension is length 1, we are just sampling from one value. + if (input == 1) { + n = output; + d = 1; + offset = 0; + border = output - 1; + return; + } + + // Apply if aligned and capable to be aligned. + bool apply_aligned = align_corners && (output > 1); + n = apply_aligned ? (output - 1) : output; + d = apply_aligned ? (input - 1) : input; + + // Simplify the scalers, make sure they are even values. + int gcd = std::gcd(n, d); + n = 2 * n / gcd; + d = 2 * d / gcd; + + // If half pixel centers we need to sample half a pixel inward. + offset = half_pixel_centers ? d / 2 : 0; + + // If nearest neighbours we need to guarantee we round up. + if (is_nearest && align_corners) { + offset += n / 2; + } + + if (is_bilinear && half_pixel_centers) { + offset -= n / 2; + } + + // We can compute this directly based on previous values. + border = d * (output - 1) - n * (input - 1) + offset; + }; + + int scale_y_n, scale_y_d, offset_y, border_y; + int scale_x_n, scale_x_d, offset_x, border_x; + normalize(input_height, output_height, scale_y_n, scale_y_d, offset_y, + border_y); + normalize(input_width, output_width, scale_x_n, scale_x_d, offset_x, + border_x); + + auto scale = getTosaConstShape(rewriter, op->getLoc(), {scale_y_n, scale_y_d, scale_x_n, scale_x_d}); + auto offset = getTosaConstShape(rewriter, op->getLoc(), {offset_y, offset_x}); + auto border = getTosaConstShape(rewriter, op->getLoc(), {border_y, border_x}); + + + const auto resize_mode_attr = tosa::ResizeModeAttr::get( + rewriter.getContext(), mode); + + auto isInt16Range = [](int x) { + return (x <= std::numeric_limits::max()) && + (x >= std::numeric_limits::min()); + }; + + if (input_is_qtype) { + // It isn't commonly seen these numbers aren't fit within 16 bits, and won't + // match TFLite reference. + if (!isInt16Range(scale_y_n) || !isInt16Range(scale_y_d) || + !isInt16Range(scale_x_n) || !isInt16Range(scale_x_d) || + !isInt16Range(offset_y) || !isInt16Range(offset_x) || + !isInt16Range(border_y) || !isInt16Range(border_x)) { + return (void)rewriter.notifyMatchFailure( + op, "stride or offset out of 16 bit range"), + std::nullopt; + } + + // If quantized bilinear mode, need to lower to RESIZE + RESCALE pair. + if (is_bilinear) { + RankedTensorType output_acc_type; + auto input_element_qtype = mlir::cast( + input_type.getElementType()); + + bool is_scale32; + + // TOSA RESIZE: 16 bit input -> 48 bit output, or 8 bit input -> 32 bit + // output. + if (input_element_qtype.getStorageTypeIntegralWidth() == 16) { + is_scale32 = false; + output_acc_type = tensorflow::GetTypeFromTFTensorShape( + output_type.getShape(), rewriter.getIntegerType(48)); + } else if (input_element_qtype.getStorageTypeIntegralWidth() == 8) { + is_scale32 = true; + output_acc_type = tensorflow::GetTypeFromTFTensorShape( + output_type.getShape(), rewriter.getI32Type()); + } else { + (void)rewriter.notifyMatchFailure( + op, "support 16-bit and 8-bit quantized input"); + return std::nullopt; + } + + auto resize_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_acc_type, input_value, scale, offset, + border, resize_mode_attr); + +#ifdef RESIZE_BILINEAR_LOWER_SYMMETRIC_ROUNDING + // TFLite resize_bilinear always assume input and output tensors have + // same scale That means we only need to arithmetic right shift with + // (2 * shift) + // TODO(suderman): Align TFLite rounding behavior + // TFLite also uses symmetric rounding by doing 'x / (1 << 20)' + // TOSA arithmetic right shift is doing standard rounding. + // Right now it's legalized using GreaterEqualOp + SelectOp to conform + // to TFLite reference. But this eventually should be fixed in TFLite + // reference + Value cst_zero = getTosaConstTensorSingleI32(rewriter, op, 0); + Value cst_twenty = getTosaConstTensorSingleI32( + rewriter, op, log2(scale_x_n * scale_y_n)); + auto output_bool_type = output_acc_type.clone(rewriter.getI1Type()); + + auto ge_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_bool_type, resize_op.getResult(), + cst_zero); + + auto abs_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_acc_type, resize_op.getResult()); + + auto rshift_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_acc_type, abs_op.getResult(), + cst_twenty, true); + + auto negate_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_acc_type, rshift_op.getResult()); + + auto select_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_acc_type, ge_op.getResult(), + rshift_op.getResult(), negate_op.getResult()); + + auto cast_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, select_op.getResult()); + + return cast_op.getResult(); +#else + // This should be the expected lowering, but is +-1 within compared to + // TFLite reference. + return buildRescale(rewriter, op, output_type, resize_op.getResult(), + 1.0 / (scale_y_n * scale_x_n), 0, 0, tosa::RoundingMode::SINGLE_ROUND, + is_scale32); +#endif + + } else if (is_nearest) { + auto resize_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, input_value, scale, offset, + border, resize_mode_attr); + return resize_op.getResult(); + } else { + (void)rewriter.notifyMatchFailure( + op, "only support BILINEAR or NEAREST_NEIGHBOR mode"); + return std::nullopt; + } + } else { + auto resize_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, input_value, scale, offset, border, + resize_mode_attr); + + return resize_op.getResult(); + } +} + +// Lowers Quantize to a sequence of TOSA quantization ops. +std::optional convertQuantizeOp(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, + Value input_value, double scale, + int64_t zeropoint) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + auto output_element_type = output_type.getElementType(); + + // output element type could only be quantized integer + if (!mlir::isa(output_element_type)) { + (void)rewriter.notifyMatchFailure( + op, "lowering quantizeOp but output element type not quantized"); + return std::nullopt; + } + + ShapedType output_fp_type = output_type.clone(rewriter.getF32Type()); + + auto rank = input_type.getRank(); + + Value result = + CreateMulOpAndInfer(rewriter, op, output_fp_type, input_value, + getTosaConstTensorSingleF32( + rewriter, op, static_cast(scale), rank)); + + if (zeropoint != 0) { + // cast to i32 to add zeropoint + ShapedType output_i32_type = output_type.clone(rewriter.getI32Type()); + Value cast_i32 = CreateOpAndInfer(rewriter, op->getLoc(), + output_i32_type, result); + + Value zp_val = getTosaConstTensorSingleI32(rewriter, op, zeropoint, rank); + + result = CreateOpAndInfer(rewriter, op->getLoc(), + output_i32_type, cast_i32, zp_val); + } + + Value final_result = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, result); + + return final_result; +} + +// Lowers Dequantize to a sequence of TOSA dequantization ops. +std::optional convertDequantizeOp(PatternRewriter& rewriter, + Operation* op, ShapedType output_type, + Value input_value, + ArrayRef scale, + ArrayRef zeropoint, + int64_t dim) { + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + // input element type could only be quantized integer + if (!mlir::isa(input_type.getElementType())) + return std::nullopt; + + auto input_rank = input_type.getRank(); + + std::optional zp_val; + if (zeropoint.size() == 1) { + zp_val = getTosaConstTensorSingleF32( + rewriter, op, static_cast(zeropoint[0]), input_rank); + } else { + SmallVector shape; + shape.resize(input_rank, 1); + shape[dim] = zeropoint.size(); + zp_val = getConstTensor(rewriter, op, zeropoint, shape); + } + + std::optional scale_val; + if (scale.size() == 1) { + scale_val = getTosaConstTensorSingleF32( + rewriter, op, static_cast(scale[0]), input_rank); + } else { + SmallVector shape; + shape.resize(input_rank, 1); + shape[dim] = scale.size(); + scale_val = getConstTensor(rewriter, op, scale, shape); + } + + if (!zp_val || !scale_val) return std::nullopt; + + auto op1_cast_in = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, input_value); + Value op1_cast_in_value = op1_cast_in.getResult(); + Value zp_value = zp_val.value(); + auto op2_sub_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op1_cast_in_value, zp_value); + + Value op2_sub_op1_value = op2_sub_op1.getResult(); + Value scale_value = scale_val.value(); + return CreateMulOpAndInfer(rewriter, op, output_type, op2_sub_op1_value, + scale_value) + .getResult(); +} + +// Lowers FakeQuant to a sequence of TOSA quantization ops. +std::optional convertFakeQuantOp(PatternRewriter& rewriter, + Operation* op, ShapedType output_type, + Value input_value, double min, + double max, int64_t num_bits, + bool narrow_range) { + // FakeQuant is lowered as follow: + // op1 = quantize(input) + // op2 = dequantize(op1) + + RankedTensorType input_type = + dyn_cast(input_value.getType()); + if (!input_type) return std::nullopt; + + // quantized as INT, where num_bits can only be 8, 16 + if (num_bits != 8 && num_bits != 16) { + op->emitWarning("FakeQuantOp lowering handles only 8 and 16 for num_bits!"); + return std::nullopt; + } + + // This code originates from + // tensorflow/core/kernels/fake_quant_ops_functor.h. + int32_t qmax = (1 << (num_bits)) - 1; + int32_t qmin = narrow_range ? 1 : 0; + + float nudged_min, nudged_max, nudged_scale; + tensorflow_nudge(min, max, qmin, qmax, &nudged_min, &nudged_max, + &nudged_scale); + auto rank = input_type.getRank(); + Value cst_min = getTosaConstTensorSingleF32(rewriter, op, nudged_min, rank); + Value cst_max = getTosaConstTensorSingleF32(rewriter, op, nudged_max, rank); + Value cst_scale = + getTosaConstTensorSingleF32(rewriter, op, nudged_scale, rank); + Value cst_inv_scale = + getTosaConstTensorSingleF32(rewriter, op, 1.0f / nudged_scale, rank); + Value cst_half = getTosaConstTensorSingleF32(rewriter, op, 0.5f, rank); + + // This code originates from + // tensorflow/core/kernels/fake_quant_ops_functor.h. + auto op1_min_in = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, input_value, cst_max); + + auto op2_max_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op1_min_in.getResult(), cst_min); + + auto op3_sub_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op2_max_op1.getResult(), cst_min); + + auto op4_mul_op3 = CreateMulOpAndInfer( + rewriter, op, output_type, op3_sub_op2.getResult(), cst_inv_scale); + + auto op5_add_op4 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op4_mul_op3.getResult(), cst_half); + + auto op6_floor_op5 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op5_add_op4.getResult()); + + auto op7_mul_op6 = CreateMulOpAndInfer(rewriter, op, output_type, + op6_floor_op5.getResult(), cst_scale); + + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + op7_mul_op6.getResult(), cst_min) + .getResult(); +} + +std::optional convertMirrorPadCommon(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input, Value pad, + TFTFLMirrorPaddingType mode) { + RankedTensorType input_type = dyn_cast(input.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type isn't a ranked tensor"); + return std::nullopt; + } + + if (mode != TFTFLMirrorPaddingType::SYMMETRIC && + mode != TFTFLMirrorPaddingType::REFLECT) { + return std::nullopt; + } + + ElementsAttr pad_elems; + if (!matchPattern(pad, m_Constant(&pad_elems))) { + (void)rewriter.notifyMatchFailure(op, "fail to retrieve padding values"); + return std::nullopt; + } + + // Split N-rank mirrorpad into N sequences of "slice, reverse, concat" + // operation. Take an example below. Perform mirrorpad on a 2D input tensor + // with paddings[] = ([[1, 1,], [2, 2]]) in `SYMMETRIC` mode. Original input + // tensor: + // | 1 2 3 | + // | 4 5 6 | + // + // First, fill in the padding value on the top and bottom. + // pad before | 1 2 3 | + // | 1 2 3 | + // | 4 5 6 | + // pad after | 4 5 6 | + // + // Second, fill in the padding value on the left and right. + // pad before pad after + // 2 1 | 1 2 3 | 3 2 + // 2 1 | 1 2 3 | 3 2 + // 5 4 | 4 5 6 | 6 5 + // 5 4 | 4 5 6 | 6 5 + + // Indicate the value and shape of the tensor being processed in that + // dimension. + Value current_tensor(input); + SmallVector current_dim_size = to_vector(input_type.getShape()); + + // Note that this also represents the intermediate padded tensors for each + // dimension. + std::optional result; + + const int rank = input_type.getRank(); + const int offset = (mode == TFTFLMirrorPaddingType::SYMMETRIC) ? 0 : 1; + + for (int axis = 0; axis < rank; ++axis) { + int pad_before = pad_elems.getValues()[2 * axis].getInt(); + int pad_after = pad_elems.getValues()[2 * axis + 1].getInt(); + + SmallVector slice_before_begin, slice_before_size; + SmallVector slice_after_begin, slice_after_size; + + for (int i = 0; i < rank; ++i) { + if (axis == i) { + // Calculate the padding area of slices that is going to be added to + // the core tensor in that axis. + slice_before_begin.push_back(offset); + slice_before_size.push_back(pad_before); + slice_after_begin.push_back(current_dim_size[i] - pad_after - offset); + slice_after_size.push_back(pad_after); + } else { + // Keep the whole length of other axes. + slice_before_begin.push_back(0); + slice_before_size.push_back(current_dim_size[i]); + slice_after_begin.push_back(0); + slice_after_size.push_back(current_dim_size[i]); + } + } + + SmallVector slices; + + if (pad_before != 0) { + // Construct a padding slice for adding values before the contents of + // tensor. + auto slice_before_op = CreateOpAndInfer( + rewriter, op->getLoc(), + RankedTensorType::get(slice_before_size, + output_type.getElementType()), + current_tensor, + getTosaConstShape(rewriter, op->getLoc(), slice_before_begin), + getTosaConstShape(rewriter, op->getLoc(), slice_before_size)); + + // Reverse op is superfluous when the padding value is 1. + if (pad_before == 1) { + slices.push_back(slice_before_op); + } else { + auto reverse_before_op = CreateOpAndInfer( + rewriter, op->getLoc(), slice_before_op.getType(), slice_before_op, + rewriter.getI32IntegerAttr(axis)); + slices.push_back(reverse_before_op); + } + } + + // Copy the core tensor + slices.push_back(current_tensor); + + if (pad_after != 0) { + // Construct a padding slice for adding values after the contents of + // tensor. + auto slice_after_op = CreateOpAndInfer( + rewriter, op->getLoc(), + RankedTensorType::get(slice_after_size, output_type.getElementType()), + current_tensor, + getTosaConstShape(rewriter, op->getLoc(), slice_after_begin), + getTosaConstShape(rewriter, op->getLoc(), slice_after_size)); + + if (pad_after == 1) { + slices.push_back(slice_after_op); + } else { + auto reverse_after_op = CreateOpAndInfer( + rewriter, op->getLoc(), slice_after_op.getType(), slice_after_op, + rewriter.getI32IntegerAttr(axis)); + slices.push_back(reverse_after_op); + } + } + + // The padded size of each dimension D of the output is: + // paddings[D, 0] + tensor.dim_size(D) + paddings[D, 1] + current_dim_size[axis] = + pad_before + input_type.getDimSize(axis) + pad_after; + + // Create the expected output shape and type, and initialize it with zero. + ShapedType result_type = + UnrankedTensorType::get(output_type.getElementType()); + + // Concatenate the old tensor with padding areas. + result = convertConcatV2Op(rewriter, op, result_type, slices, axis); + + if (!result) return std::nullopt; + + // Update to the padded tensor + current_tensor = result.value(); + } + + return result; +} + + +std::optional convertConv3DCommon( + PatternRewriter& rewriter, Operation* op, ShapedType output_type, + Value input, Value filter, Value bias, DenseI64ArrayAttr pads, + DenseI64ArrayAttr strides, DenseI64ArrayAttr dilations, TypeAttr acc_type, + StringRef data_format_ref) { + if (data_format_ref.str() != "NDHWC") { + (void)rewriter.notifyMatchFailure(op, "currently only supports NDHWC"); + return std::nullopt; + } + RankedTensorType filter_type = mlir::cast(filter.getType()); + // Note that the kernel shape of tfl.conv_3d isn't [O, D, H, W, I] but + // [D, H, W, I, O] which is the same as in TF. + // Transpose filter shape from [D, H, W, I, O] to [O, D, H, W, C] + auto filter_shape = filter_type.getShape(); + SmallVector a1_transpose_dims; + a1_transpose_dims.push_back(filter_shape[4]); + a1_transpose_dims.push_back(filter_shape[0]); + a1_transpose_dims.push_back(filter_shape[1]); + a1_transpose_dims.push_back(filter_shape[2]); + a1_transpose_dims.push_back(filter_shape[3]); + auto a1_filter_transpose_op = CreateOpAndInfer( + rewriter, op->getLoc(), + RankedTensorType::get(a1_transpose_dims, filter_type.getElementType()), + filter, rewriter.getDenseI32ArrayAttr({4, 0, 1, 2, 3})); + return CreateOpAndInfer( + rewriter, op->getLoc(), output_type, input, + a1_filter_transpose_op.getResult(), bias, pads, strides, dilations, + acc_type) + .getResult(); +} + + +// Lowers Gather operators to a sequence of TOSA ops. +std::optional convertGatherOp(PatternRewriter& rewriter, Operation* op, + Value params_value, Value indices_value, + int32_t batch_dims, int32_t axis, + bool tosaOnly) { + auto result_type = dyn_cast(op->getResult(0).getType()); + auto params_type = dyn_cast(params_value.getType()); + auto indices_type = dyn_cast(indices_value.getType()); + + if (!result_type || !params_type || !indices_type) return std::nullopt; + + // batch_dims indicates the number of batch dimensions in params and + // indices axis indicates the axis at which the gather indexing is + // applied. axis must be >= batch_dims. When axis is equal to + // batch_dims, the right-most batch dimension disappears. + // + // N: number of batches + // Computed as product of params.shape[0:batch_dims-1] + // + // W: number of indices in each batch + // Computed as product of indices.shape[batch_dims:] + // + // K: range of each index + // Computed as params.shape[axis:axis+rank(indices)-1] + // + // C: number of channels for each index + // Computed as: LeftChannels * RightChannels: + // product(params.shape[batch_dims:axis]) * product(params.shape[axis+1:]) + // + // The params tensor needs to be transposed, then reshaped to move the + // dimensions into [N, K, C] order. + // + // The dimensions of the input params[] tensor are grouped in the following + // order to begin with: + // + // [Batch, LeftChannels, Indices, RightChannels] + // |-----||------------||-------||-------------| + // N C_l K C_r + // + // Where Batch (N), Indices (K) can be one or more dimensions in size, + // while LeftChannels and RightChannels represent the group of data channels + // (C) to the left and right (C_l, C_r) of the indices; the sum of these two + // is one or more dimensions in size, but either one may be zero depending + // on how axis was specified by the caller. + // + // The resulting tensor will look like: + // + // [Batch, Indices, LeftChannels, RightChannels] + // |-----||-------||---------------------------| + // N K C + // + // The indices tensor simply needs a reshape to flatten all of the + // batch dimensions (N) together and flatten all of the indices (W) + // together. + // + // Then do the tosa.GATHER + // + // output[N,W,C] = tosa.GATHER(values[N,K,C], indices[N,W]) + // + // Finally, the resulting tensor will have shape [N, W, C], where C is a + // flattened version of [LeftChannels, RightChannels]. We need to reshape + // to unflatten to: + // + // [N, W, LeftChannels, RightChannels] + // + // and finally transpose back to the output shape + // + // [Batch, LeftChannels, Non-Batch-Indices, RightChannels] + + int params_rank = params_type.getRank(); + int indices_rank = indices_type.getRank(); + + if (axis < 0 || axis >= params_rank) { + (void)rewriter.notifyMatchFailure( + op, llvm::formatv("axis {} must be within range of params rank", axis)); + return std::nullopt; + } + + if (!(batch_dims <= indices_rank)) { + (void)rewriter.notifyMatchFailure( + op, "batch_dims must be <= indices_rank for a valid gather op"); + return std::nullopt; + } + + if (!(axis >= batch_dims)) { + (void)rewriter.notifyMatchFailure( + op, "axis must be >= batch_dims for a valid gather op"); + return std::nullopt; + } + + // tf/tfl allow i64 indices, but tosa does not. + if (indices_type.getElementType().isInteger(64)) { + indices_type = + dyn_cast(indices_type.clone(rewriter.getI32Type())); + indices_value = CreateOpAndInfer(rewriter, op->getLoc(), + indices_type, indices_value) + .getResult(); + } + + // Sizes for each of these fields. + SmallVector params_batch, params_indices, params_left_channels, + params_right_channels; + + // Dimension indices for each of these fields. + SmallVector params_idx_batch, params_idx_indices, + params_idx_left_channels, params_idx_right_channels; + + auto params_shape = + tensor::getMixedSizes(rewriter, op->getLoc(), params_value); + auto indices_shape = + tensor::getMixedSizes(rewriter, op->getLoc(), indices_value); + + // Read through the params tensor dimensions left-to-right and extract the + // different fields. + for (int i = 0; i < params_rank; i++) { + // When batch_dims == axis, the batch dimension gets replaced. + if (i < batch_dims && i < axis) { + params_batch.push_back(params_shape[i]); + params_idx_batch.push_back(i); + } else if (i < axis) { + params_left_channels.push_back(params_shape[i]); + params_idx_left_channels.push_back(i); + } else if (i < (axis + 1)) { + params_indices.push_back(params_shape[i]); + params_idx_indices.push_back(i); + } else { + params_right_channels.push_back(params_shape[i]); + params_idx_right_channels.push_back(i); + } + } + + // Calculate N, K, W, C + auto paramsLow = llvm::ArrayRef(params_shape).take_front(batch_dims); + + auto paramsMid = + llvm::ArrayRef(params_shape).slice(batch_dims, axis - batch_dims); + + auto paramsHigh = + llvm::ArrayRef(params_shape).slice(axis + 1, params_rank - axis - 1); + + auto indicesMid = llvm::ArrayRef(indices_shape) + .slice(batch_dims, indices_rank - batch_dims); + + ImplicitLocOpBuilder builder(op->getLoc(), rewriter); + OpFoldResult lowProduct = multiplyDims(builder, paramsMid); + OpFoldResult highProduct = multiplyDims(builder, paramsHigh); + + OpFoldResult N = multiplyDims(builder, paramsLow); + OpFoldResult W = multiplyDims(builder, indicesMid); + OpFoldResult K = params_shape[axis]; + OpFoldResult C = multiplyDims(builder, lowProduct, highProduct); + + ///////////////////////////////////////////// + // Build up the params transpose operator + SmallVector params_transpose_perm; + SmallVector params_transpose_shape; + + // Batch + for (int i = 0; i < params_batch.size(); i++) { + params_transpose_perm.push_back(params_idx_batch[i]); + params_transpose_shape.push_back(extractStaticDimension(params_batch[i])); + } + + // Indices + for (int i = 0; i < params_indices.size(); i++) { + params_transpose_perm.push_back(params_idx_indices[i]); + params_transpose_shape.push_back(extractStaticDimension(params_indices[i])); + } + + // LeftChannels + for (int i = 0; i < params_left_channels.size(); i++) { + params_transpose_perm.push_back(params_idx_left_channels[i]); + params_transpose_shape.push_back( + extractStaticDimension(params_left_channels[i])); + } + + // RightChannels + for (int i = 0; i < params_right_channels.size(); i++) { + params_transpose_perm.push_back(params_idx_right_channels[i]); + params_transpose_shape.push_back( + extractStaticDimension(params_right_channels[i])); + } + + ///////////////////////////////////////////// + // Build up the result reshape, in prepration for transpose + // [N, W, C] -> [ Batch, Indices, LeftChannels, RightChannels ] + SmallVector result_reshape_shape; + + // Indices + result_reshape_shape.append(indices_shape); + + // Left channels + result_reshape_shape.append(params_left_channels); + + // Right channels + result_reshape_shape.append(params_right_channels); + + ///////////////////////////////////////////// + // Build up the result transpose operator. + SmallVector result_transpose_perm; + + // Batch dimensions + for (int i = 0; i < batch_dims; i++) { + result_transpose_perm.push_back(i); + } + + // LeftChannels + for (int i = 0; i < params_left_channels.size(); i++) { + result_transpose_perm.push_back(i + indices_type.getShape().size()); + } + + // Indices (remainder of dimensions after batch). + for (int i = batch_dims; i < (indices_type.getShape().size()); i++) { + result_transpose_perm.push_back(i); + } + + // RightChannels, coming from after both the Indices and LeftChannels. + for (int i = 0; i < params_right_channels.size(); i++) { + result_transpose_perm.push_back(i + indices_type.getShape().size() + + params_left_channels.size()); + } + + SmallVector tosa_values_shape = {N, K, C}; + SmallVector tosa_indices_shape = {N, W}; + SmallVector tosa_gather_result_shape = {N, W, C}; + + auto params_transpose_op = CreateOpAndInfer( + builder, + tensorflow::GetTypeFromTFTensorShape(params_transpose_shape, + params_type.getElementType()), + params_value, rewriter.getDenseI32ArrayAttr(params_transpose_perm)); + + Value tosa_values_reshape_op = + buildReshape(builder, params_transpose_op, {N, K, C}); + + Value tosa_indices_reshape_op = buildReshape(builder, indices_value, {N, W}); + + auto tosa_gather_static_shape = + llvm::map_to_vector(tosa_gather_result_shape, extractStaticDimension); + + auto tosa_gather_op = CreateOpAndInfer( + builder, + tensorflow::GetTypeFromTFTensorShape(tosa_gather_static_shape, + result_type.getElementType()), + tosa_values_reshape_op, tosa_indices_reshape_op); + + Value tosa_result_reshape_op = + buildReshape(builder, tosa_gather_op, result_reshape_shape); + + return CreateOpAndInfer( + builder, result_type, tosa_result_reshape_op, + rewriter.getDenseI32ArrayAttr(result_transpose_perm)) + .getResult(); +} + +// Lowers Gather operators to a sequence of TOSA ops. +std::optional convertGatherNdOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value params_value, + Value indices_value) + +{ + auto result_type = dyn_cast(result_value.getType()); + auto params_type = dyn_cast(params_value.getType()); + auto indices_type = dyn_cast(indices_value.getType()); + + if (!result_type || !params_type || !indices_type) return std::nullopt; + + // N: number of batches + // Always 1 for GatherND + // + // Because TOSA's GATHER operator already uses the symbol 'N' for + // the number of batches, we will use the symbol 'ND' to specify the + // number of dimensions that are sliced from params instead of'N' in + // the TF MLIR documentation. + // + // ND: indices.shape[-1] + // + // W: number of indices in each batch + // Computed as: + // product(indices.shape[0:-1]) (all but the last dimension) + // + // K: range of each index + // Computed as: + // product(params.shape[0:ND-1]) + // + // C: number of channels for each index + // Computed as: + // product(params.shape[ND:]) + // + // The params tensor needs to be reshaped, but not transposed, to move the + // dimensions into [N, K, C] order. + // + // The dimensions of the input params[] tensor are grouped in the following + // order to begin with: + // + // [ParamIndices, ParamChannels] + // |------------||-------------| + // K C + // + // The reshape simply flattens the params tensor into a 2D [K, C] shape. + // + // Indices needs to be put in the form of [N, W], but a simple flattening + // will not suffice, because the indices need to index into a [W]-shape + // vector instead of the params.shape[0:ND-1] tensor that we had before. + // + // To flatten the coordinates, first reshape indices to a [W, ND] matrix, + // where the matrix now represents W ND-dimensional coordinates into the + // params tensor. + // + // From here, we take each of the ND dimensions and multiply it with + // the size of the next params dimension (or 1 for the last + // dimension), then sum all these together with a reduce_sum + // operator. This is exactly the same mathematics as one would use + // flatten the indices of an N-dimensional row-major array into a + // 1-D array in C. + // + // More precisely, do an element-wise multiply with [params.shape[1 + // .. ND], 1] in axis 1, then reduce_sum in axis 1 to flatten to a + // [W]-shaped tensor, then trivially reshape to [N=1, W] to be + // compatible with the GATHER operator's shape. + // + // Then perform the tosa.GATHER() operation. + // + // Now we have result = [N, K, C]. + // + // Reshape with a single, simple reshape to the final output shape of: + // [Indices, ParamChannels] + // + // Where, Indices is indices.shape[0:ND-1] + + int N = 1, W = 1, K = 1, C = 1, ND = 1; + + int params_rank = params_type.getShape().size(); + int indices_rank = indices_type.getShape().size(); + + ND = indices_type.getShape()[indices_rank - 1]; + + if (ND > params_rank) { + (void)rewriter.notifyMatchFailure( + op, "size of last dimension of indices must be <= params rank"); + return std::nullopt; + } + + // Calculate N, K, W, C. (N is always 1) + for (int i = 0; i < (indices_rank - 1); i++) { + W *= indices_type.getShape()[i]; + } + + for (int i = 0; i < ND; i++) { + K *= params_type.getShape()[i]; + } + + for (int i = ND; i < params_rank; i++) { + C *= params_type.getShape()[i]; + } + + SmallVector tosa_values_shape({N, K, C}); + SmallVector tosa_indices_shape({N, W}); + SmallVector indices_matrix_shape({W, ND}); + SmallVector tosa_gather_result_shape({N, W, C}); + + auto tosa_values_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(tosa_values_shape)); + auto tosa_values_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_values_shape, + params_type.getElementType()), + params_value, + tosa_values_shape_value); + + // Flatten the input indices tensor to an [W, ND] matrix. + auto indices_matrix_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(indices_matrix_shape)); + auto indices_matrix_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(indices_matrix_shape, + indices_type.getElementType()), + indices_value, + indices_matrix_shape_value); + + SmallVector flattened_coeff_vec; + for (int i = 1; i < ND; i++) { + flattened_coeff_vec.push_back(params_type.getShape()[i]); + } + flattened_coeff_vec.push_back(1); + + for (int i = ND - 1; i > 0; i--) { + flattened_coeff_vec[i - 1] *= flattened_coeff_vec[i]; + } + + std::optional flattened_coeff_value = getConstTensor( + rewriter, op, flattened_coeff_vec, + {static_cast(flattened_coeff_vec.size())}); + + if (!flattened_coeff_value) return std::nullopt; + + // Multiply the coefficients by the coordinates + Value mul_x = indices_matrix_reshape_op.getResult(); + Value mul_y = flattened_coeff_value.value(); + RankedTensorType mul_type = tensorflow::GetTypeFromTFTensorShape( + indices_matrix_shape, indices_type.getElementType()); + auto flattened_indices_mul_op = CreateMulOpAndInfer( + rewriter, op, mul_type, mul_x, mul_y); + + // Sum up the products of the coefficients and coordinates + auto flattened_indices_reduce_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_indices_shape, + indices_type.getElementType()), + flattened_indices_mul_op.getResult(), rewriter.getI32IntegerAttr(1)); + + // And reshape to [N, W] + auto tosa_indices_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(tosa_indices_shape)); + auto tosa_indices_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_indices_shape, + indices_type.getElementType()), + flattened_indices_reduce_op.getResult(), + tosa_indices_shape_value); + + // Now the gather op itself + auto tosa_gather_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_gather_result_shape, + result_type.getElementType()), + tosa_values_reshape_op.getResult(), tosa_indices_reshape_op.getResult()); + + // Finally, reshape back to the original output shape of [Indices, + // ParamChannels]. + auto result_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(result_type.getShape())); + + return CreateOpAndInfer( + rewriter, op->getLoc(), result_type, tosa_gather_op.getResult(), + result_shape_value) + .getResult(); +} + +std::optional convertScatterNdOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value indices_value, + Value updates_value, + Value shape_value) { + auto const result_type = dyn_cast(result_value.getType()); + auto const indices_type = dyn_cast(indices_value.getType()); + auto const updates_type = dyn_cast(updates_value.getType()); + auto const shape_type = dyn_cast(shape_value.getType()); + + if (!result_type || !indices_type || !updates_type || !shape_type) { + (void)rewriter.notifyMatchFailure( + op, "input/output types must be ranked tensor type"); + return std::nullopt; + } + + // Don't support variable indices yet since we cannot check uniqueness + // of indices in this case + Operation* indices_op = indices_value.getDefiningOp(); + if (!indices_op || !llvm::isa(indices_op)) { + (void)rewriter.notifyMatchFailure(op, "indices must be a constant tensor"); + return std::nullopt; + } + + Type indices_elmt_type = indices_type.getElementType(); + if (!indices_elmt_type.isInteger(32)) { + (void)rewriter.notifyMatchFailure(op, "indices expected to be int32"); + return std::nullopt; + } + + // The tosa scatter operation only supports unique indices, so if there + // are duplicates, we cannot legalize + tosa::ConstOp const_indices = cast(indices_op); + ElementsAttr const_data = const_indices.getValues(); + if (!checkUniqueConstantScatterIndices(indices_type, result_type, + const_data)) { + (void)rewriter.notifyMatchFailure(op, "index values must be unique"); + return std::nullopt; + } + + // N: number of batches + // Always 1 for ScatterND + // + // Because TOSA's SCATTER operator already uses the symbol 'N' for + // the number of batches, we will use the symbol 'ND' to specify the + // number of dimensions that are sliced from input instead of'N' in + // the TF MLIR documentation. + // + // ND: indices.shape[-1] + // + // W: number of indices in each batch + // Computed as: + // product(indices.shape[0:-1]) (all but the last dimension) + // + // K: range of each index + // Computed as: + // product(result.shape[0:ND-1]) + // + // C: number of channels for each index + // Computed as: + // product(result.shape[ND:]) + // + // The updates tensor needs to be reshaped, but not transposed, to move + // the dimensions into [N, W, C] order. + // + // Indices needs to be put in the form of [N, W], but a simple flattening + // will not suffice, because the indices need to index into the [W]-shape + // updates vector instead. + // + // To flatten the coordinates, first reshape indices to a [W, ND] matrix, + // where the matrix now represents W ND-dimensional coordinates into the + // updates tensor. + // + // From here, we take each of the ND dimensions and multiply it with + // the size of the next updates dimension (or 1 for the last + // dimension), then sum all these together with a reduce_sum + // operator. This is exactly the same mathematics as one would use + // flatten the indices of an N-dimensional row-major array into a + // 1-D array in C. + // + // More precisely, do an element-wise multiply with [updates.shape[1 + // .. ND], 1] in axis 1, then reduce_sum in axis 1 to flatten to a + // [W]-shaped tensor, then trivially reshape to [N=1, W] to be + // compatible with the SCATTER operator's shape. + // + // Then perform the tosa.SCATTER() operation. + // + // Now we have result = [N, K, C]. + // + // Reshape with a single, simple reshape to the final output shape + // provided by shape_value. + + const unsigned int input_output_rank = result_type.getShape().size(); + const unsigned int indices_rank = indices_type.getShape().size(); + + const unsigned int ND = indices_type.getShape()[indices_rank - 1]; + + if (ND > input_output_rank) { + (void)rewriter.notifyMatchFailure( + op, "size of last dimension of indices must be <= input/output rank"); + return std::nullopt; + } + + // Calculate N, K, W, C. (N is always 1) + auto const indices_shape_begin{indices_type.getShape().begin()}; + auto const result_shape_begin{result_type.getShape().begin()}; + auto const accumulate_func = [](auto const& a_, auto const& b_) { + return a_ * b_; + }; + + const unsigned int N = 1; + const unsigned int W = std::accumulate(indices_shape_begin, + indices_shape_begin + indices_rank - 1, + 1, accumulate_func); + const unsigned int K = std::accumulate( + result_shape_begin, result_shape_begin + ND, 1, accumulate_func); + const unsigned int C = std::accumulate(result_shape_begin + ND, + result_shape_begin + input_output_rank, + 1, accumulate_func); + + SmallVector tosa_indices_shape({N, W}); + SmallVector indices_matrix_shape({W, ND}); + SmallVector tosa_input_shape({N, W, C}); + SmallVector tosa_values_in_out_shape({N, K, C}); + + // Flatten the updates tensor to an [N, W] matrix. + auto input_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(tosa_input_shape)); + auto tosa_input_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_input_shape, + result_type.getElementType()), + updates_value, input_shape_value); + + // Flatten the indices tensor to an [W, ND] matrix. + auto indices_matrix_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(indices_matrix_shape)); + auto indices_matrix_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(indices_matrix_shape, + indices_elmt_type), + indices_value, indices_matrix_shape_value); + + SmallVector flattened_coeff_vec; + for (int i = 1; i < ND; i++) { + flattened_coeff_vec.push_back(result_type.getShape()[i]); + } + flattened_coeff_vec.push_back(1); + for (int i = ND - 1; i > 0; i--) { + flattened_coeff_vec[i - 1] *= flattened_coeff_vec[i]; + } + std::optional flattened_coeff_value = getConstTensor( + rewriter, op, flattened_coeff_vec, + {static_cast(flattened_coeff_vec.size())}); + + if (!flattened_coeff_value) { + (void)rewriter.notifyMatchFailure( + op, "failed to calculate flattened coeff value"); + return std::nullopt; + } + + // Multiply the coefficients by the coordinates + Value mul_x = indices_matrix_reshape_op.getResult(); + Value mul_y = flattened_coeff_value.value(); + RankedTensorType mul_type = tensorflow::GetTypeFromTFTensorShape( + indices_matrix_shape, indices_type.getElementType()); + if (EqualizeRanks(rewriter, op->getLoc(), mul_x, mul_y).failed()) { + (void)rewriter.notifyMatchFailure( + op, "failed to broadcast coefficients over the coordinates"); + return std::nullopt; + } + auto flattened_indices_mul_op = CreateMulOpAndInfer( + rewriter, op, mul_type, mul_x, mul_y); + + // Sum up the products of the coefficients and coordinates + auto flattened_indices_reduce_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_indices_shape, + indices_type.getElementType()), + flattened_indices_mul_op.getResult(), rewriter.getI32IntegerAttr(1)); + + // And reshape to [N, W] + auto tosa_indices_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(tosa_indices_shape)); + auto tosa_indices_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(tosa_indices_shape, + indices_type.getElementType()), + flattened_indices_reduce_op.getResult(), tosa_indices_shape_value); + + // Scatter_nd has no input tensor, use a zero tensor + Type const_element_type = updates_type.getElementType(); + auto const_type = + RankedTensorType::get(tosa_values_in_out_shape, const_element_type); + if (mlir::isa(const_element_type)) { + auto quant_type = dyn_cast(const_element_type); + const_element_type = quant_type.getStorageType(); + } + auto const_storage_type = + RankedTensorType::get(tosa_values_in_out_shape, const_element_type); + auto const_attr = DenseElementsAttr::get( + const_storage_type, rewriter.getZeroAttr(const_element_type)); + Value tosa_values_in = + rewriter.create(op->getLoc(), const_type, const_attr); + + // Now the scatter op itself + auto tosa_scatter_op = CreateOpAndInfer( + rewriter, op->getLoc(), result_type, tosa_values_in, + tosa_indices_reshape_op.getResult(), tosa_input_reshape_op.getResult()); + + // Finally, reshape back to the expected output shape. + auto reshape_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(result_type.getShape())); + return CreateOpAndInfer(rewriter, op->getLoc(), result_type, + tosa_scatter_op.getResult(), + reshape_shape_value) + .getResult(); +} + +// Lowers OneHot operator to a sequence of TOSA ops. +std::optional convertOneHotOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value indices_value, + Value on_value, Value off_value, + int32_t depth, int32_t axis) { + auto result_type = dyn_cast(result_value.getType()); + auto indices_type = dyn_cast(indices_value.getType()); + auto on_value_type = dyn_cast(on_value.getType()); + auto off_value_type = dyn_cast(off_value.getType()); + + if (!result_type || !indices_type || !on_value_type || !off_value_type) + return std::nullopt; + + // OneHot operator creates a new tensor with shape indices.shape[:axis] + + // [depth] + indices.shape[axis:] For each index in 'indices', it needs to + // be within range of [0, depth - 1] and the [..., k, ...] = on_value (if k + // = index), or [..., k, ...] = off_value (if k != index) + // + // The lowering below assumes depth is always known at compile time. + // TBD for depth resolved in run time. + // + // OneHot can be lowered as TOSA Scatter, where off_value being mapped to + // 'values_in', on_value being mapped to 'input', and indices naturally + // mapped to 'indices'. Also the dimensions of TOSA scatter (N, W, K, C) + // need to be picked. + // + // N: number of elements of input indices + // Computed as: + // product(indices.shape[:]) + // + // K: newly added dimension + // K = depth + // + // W, C: dummy dimension now + // W = C = 1 + // + // High level description of lowering looks like: + // 1. off_value is reshaped/tiled into [N, K, C] + // 2. on_value is reshaped/tiled into [N, W, C] + // 3. indices is reshaped into [N, W] + // 4. scatter into [N, K, C] + // 5. reshaped into [LeftDims, RightDims, K] + // 6. transpose into [LeftDims, K, RightDims] + // 7. reshaped to result.shape + + if (on_value_type.getRank() != 0 || off_value_type.getRank() != 0) { + (void)rewriter.notifyMatchFailure(op, + "on_value/off_value needs to be scalar"); + return std::nullopt; + } + + if (axis < -1 || axis > indices_type.getRank()) { + (void)rewriter.notifyMatchFailure( + op, "axis out of valid range [-1, indices.rank]"); + return std::nullopt; + } + + // axis = -1 is equivalent to axis = indices.rank + if (axis == -1) { + axis = indices_type.getRank(); + } + + int N = 1, W = 1, C = 1; + int K = depth; + int left_dim = 1, right_dim = 1; + + for (int32_t i = 0; i < indices_type.getRank(); i++) { + int32_t dim = indices_type.getShape()[i]; + N *= dim; + if (i >= axis) { + right_dim *= dim; + } else { + left_dim *= dim; + } + } + + // Reshape on_value to [1, 1, 1] + auto shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF({ 1, 1, 1 })); + auto op1_reshape_on_value = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({1, 1, 1}, + on_value_type.getElementType()), + on_value, shape_value); + + // And tile to [N, W, C] + auto op2_tile_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({N, W, C}, + on_value_type.getElementType()), + op1_reshape_on_value.getResult(), + getTosaConstShape(rewriter, op->getLoc(), {N, W, C})); + + // Reshape off_value to [1, 1, 1] + auto op3_reshape_off_value = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({1, 1, 1}, + off_value_type.getElementType()), + off_value, shape_value); + + // And tile to [N, K, C] + auto op4_tile_op3 = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({N, K, C}, + on_value_type.getElementType()), + op3_reshape_off_value.getResult(), + getTosaConstShape(rewriter, op->getLoc(), {N, K, C})); + + // Reshape indices to [N, W] + shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF({ N, W })); + auto op5_reshape_indices = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({N, W}, + indices_type.getElementType()), + indices_value, + shape_value); + + // Scatter to [N, K, C] + auto op6_scatter_op4_op5_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({N, K, C}, + result_type.getElementType()), + op4_tile_op3.getResult(), op5_reshape_indices.getResult(), + op2_tile_op1.getResult()); + + // Reshaped to [LeftDims, RightDims, K]. C being squeezed out since it's 1. + shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF({left_dim, right_dim, K})); + auto op7_reshape_op6 = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({left_dim, right_dim, K}, + result_type.getElementType()), + op6_scatter_op4_op5_op2.getResult(), + shape_value); + + // Transposed to [LeftDims, K, RightDims]. + auto op8_transpose_op7 = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape({left_dim, K, right_dim}, + result_type.getElementType()), + op7_reshape_op6.getResult(), rewriter.getDenseI32ArrayAttr({0, 2, 1})); + + // Reshaped to result.shape. + auto result_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(result_type.getShape())); + return CreateOpAndInfer( + rewriter, op->getLoc(), result_type, op8_transpose_op7.getResult(), + result_shape_value) + .getResult(); +} + +// Lowers Sign operator to a sequence of TOSA ops. +std::optional convertSignOp(PatternRewriter& rewriter, Operation* op, + Value input, RankedTensorType output_type) { + auto output_elem_type = output_type.getElementType(); + if (mlir::isa(output_elem_type)) { + (void)rewriter.notifyMatchFailure(op, "tfl quantization not yet supported"); + return std::nullopt; + } + + // TOSA greater and select can both broadcast, so simply create a tensor with + // one element. + auto rank = output_type.getRank(); + Value pos_one, neg_one, zero; + ImplicitLocOpBuilder builder(op->getLoc(), rewriter); + if (mlir::isa(output_elem_type)) { + pos_one = getTosaConstTensorSingleF32(rewriter, op, 1.0f, rank); + neg_one = getTosaConstTensorSingleF32(rewriter, op, -1.0f, rank); + zero = getTosaConstTensorSingleF32(rewriter, op, 0.0f, rank); + } else { + pos_one = getTosaConstTensorScalarInt(builder, output_elem_type, 1, rank); + neg_one = getTosaConstTensorScalarInt(builder, output_elem_type, -1, rank); + zero = getTosaConstTensorScalarInt(builder, output_elem_type, 0, rank); + } + + ShapedType const_type = output_type.clone(rewriter.getIntegerType(1)); + + auto gt_zero_op = + CreateOpAndInfer(builder, const_type, input, zero); + + auto lt_zero_op = + CreateOpAndInfer(builder, const_type, zero, input); + + auto select_neg_op = CreateOpAndInfer( + builder, output_type, lt_zero_op, neg_one, zero); + + // Select positive one based on the condition tensor. + return CreateOpAndInfer(builder, output_type, gt_zero_op, + pos_one, select_neg_op) + .getResult(); +} + +// Lowers BroadcastTo operator to a sequence of TOSA ops. +std::optional convertBroadcastToOp(PatternRewriter& rewriter, + Operation* op, Value input, + Value shape) { + RankedTensorType input_type = dyn_cast(input.getType()); + if (!input_type) { + (void)rewriter.notifyMatchFailure(op, "input type not ranked tensor"); + return std::nullopt; + } + + Type element_type = input_type.getElementType(); + if (mlir::isa(element_type)) { + (void)rewriter.notifyMatchFailure(op, "input element type is complex"); + return std::nullopt; + } + + if (isa(element_type)) { + auto bitwidth = element_type.getIntOrFloatBitWidth(); + if (bitwidth > 32) { + (void)rewriter.notifyMatchFailure( + op, "input element type has greater than 32 bits"); + return std::nullopt; + } + } + + ElementsAttr shape_elems; + if (!matchPattern(shape, m_Constant(&shape_elems))) { + (void)rewriter.notifyMatchFailure(op, "shape is not constant"); + return std::nullopt; + } + int input_rank = input_type.getRank(); + int shape_rank = shape_elems.getNumElements(); + + if (auto shape_type = dyn_cast(shape.getType())) { + if (shape_type.hasStaticShape()) { + assert(shape_type.getRank() == 1); + if (!shape_type.isDynamicDim(0) && + shape_rank != shape_type.getDimSize(0)) { + // shape_elems and shape's type's 'are different + // this is not supported for now + (void)rewriter.notifyMatchFailure( + op, + "shape's constant value has different elements than its static " + "dimension"); + return std::nullopt; + } + } + } + + if (input_rank > shape_rank) { + // not clear what to do in this case, bail for now + (void)rewriter.notifyMatchFailure(op, "shape has less rank than input"); + return std::nullopt; + } + + // equalize new_rank and input_rank + if (input_rank < shape_rank) { + // reshape input to shape_rank + SmallVector reshaped_shape((shape_rank - input_rank), 1); + for (auto dim : input_type.getShape()) { + reshaped_shape.push_back(dim); + } + input_type = + tensorflow::GetTypeFromTFTensorShape(reshaped_shape, element_type); + + auto reshaped_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(reshaped_shape)); + input = CreateOpAndInfer( + rewriter, op->getLoc(), input_type, input, + reshaped_shape_value); + } + + auto input_shape = input_type.getShape(); + assert(input_shape.size() == shape_rank); // should be equal ranks by now + + // construct new_shape as broadcasted shape of input_shape and shape_elems + int32_t num_elements = 1; + SmallVector new_shape; + for (int i = 0; i < shape_rank; i++) { + auto shape_dim = shape_elems.getValues()[i].getInt(); + auto input_dim = input_shape[i]; + if (shape_dim != input_dim && std::min(shape_dim, input_dim) != 1) { + // shape_dim and input_dim are different, but the lower value is not 1 + // this is not broadcastable + (void)rewriter.notifyMatchFailure( + op, "input and shape are not broadcastable"); + return std::nullopt; + } + auto dim = std::max(shape_dim, input_dim); + new_shape.push_back(dim); + num_elements *= dim; + } + + RankedTensorType output_type = + tensorflow::GetTypeFromTFTensorShape(new_shape, element_type); + + if (mlir::isa(element_type)) { + // F32: legalize to broadcastable Add with (-0.f), instead of 0.f. + // This is to preserve original values: + // for corner case where x = -0.f + // x + -0.f => -0.f (ie, equals x), whereas, + // x + 0.f => 0.f (ie, not equals x) + auto const_attr = + DenseElementsAttr::get(output_type, FloatAttr::get(element_type, -0.0)); + Value f32_const_zero = + rewriter.create(op->getLoc(), output_type, const_attr); + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + input, f32_const_zero) + .getResult(); + } + + if (element_type.isInteger(1)) { + // I1: legalize to broadcastable LogicalOr with false + auto const_attr = + DenseElementsAttr::get(output_type, rewriter.getZeroAttr(element_type)); + Value i1_const_zero = + rewriter.create(op->getLoc(), output_type, const_attr); + return CreateOpAndInfer( + rewriter, op->getLoc(), output_type, input, i1_const_zero) + .getResult(); + } + + // cast type is always I32 type + // const_zero is always output shape with cast type + auto cast_type = rewriter.getI32Type(); + RankedTensorType cast_shaped_type = output_type.clone(cast_type); + auto const_attr = + DenseElementsAttr::get(cast_shaped_type, rewriter.getZeroAttr(cast_type)); + Value const_zero = rewriter.create( + op->getLoc(), cast_shaped_type, const_attr); + + if (element_type.isInteger(32)) { + // I32: legalize to broadcastable Add with 0 + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + input, const_zero) + .getResult(); + } + + if (isa(element_type) || + isa(element_type)) { + // for any other non-float element type: + // cast input to the input_shape with cast type, perform an add 0 (with + // const_zero), then cast to output type. + Value input_cast = CreateOpAndInfer( + rewriter, op->getLoc(), + /* I32 input type */ input_type.clone(cast_type), input); + Value add_const = CreateOpAndInfer( + rewriter, op->getLoc(), cast_shaped_type, input_cast, const_zero); + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + add_const) + .getResult(); + } + + (void)rewriter.notifyMatchFailure(op, "Unsupported element type"); + return std::nullopt; +} + +// Lowers cast operator to a sequence of TOSA ops. +std::optional convertCastOp(PatternRewriter& rewriter, Operation* op, + Value input, RankedTensorType output_type) { + auto input_type = mlir::cast(input.getType()); + auto input_element_type = input_type.getElementType(); + Value cast_input = input; + + if (auto input_element_qtype = + dyn_cast(input_element_type)) { + auto zero_point = input_element_qtype.getZeroPoint(); + if (zero_point != 0) { + cast_input = + removeZeroPointAndCastToInt32(rewriter, op, input, zero_point); + } + } + + auto cast_op = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, cast_input); + + return cast_op.getResult(); +} + +}; // namespace tosa +}; // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_common.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_common.h new file mode 100644 index 0000000000000000000000000000000000000000..5e38b09a6a8b06e4846c2644a21a2aea9d0d9702 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_common.h @@ -0,0 +1,337 @@ +/* Copyright 2020 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_MLIR_TOSA_TRANSFORMS_LEGALIZE_COMMON_H_ +#define TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_COMMON_H_ + +#include +#include + +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project + +// This file contains legalizations common to mapping both TensorFlow and +// TensorFlow Lite to TOSA. +// +// Conversion functions return None on a failure or result value on success. +// Callers must check and return a LogicalResult failure on nullptr. +// +// For these functions, the framework-specific operands/attributes/defaults +// are already extracted and placed in a common form for lowering. + +namespace mlir { +namespace tosa { + +// Lowers the Pack operator to TOSA. +std::optional convertPackOp(PatternRewriter& rewriter, Operation* op, + Value result_value, + SmallVectorImpl& inputs, + int32_t axis); + +// Lowers the Unpack operator to TOSA. +std::optional> convertUnpackOp(PatternRewriter& rewriter, + Operation* op, + Value input_value, + int32_t axis); + +// Lowers the Select operator to TOSA. +std::optional convertSelectOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value condition_value, + Value x_value, Value y_value); + +// Lowers the ZerosLike operator to TOSA by creating a constant +// of the desired type and shape. +std::optional convertZerosLikeOp(PatternRewriter& rewriter, + Operation* op, Value result, + Value input); + +// Lowers the Mul operator to TOSA. For quantized types, this requires +// inserting rescale operators before and after the operation. +std::optional convertMultiplyOp(PatternRewriter& rewriter, Operation* op, + Value output_val, Value input_lhs_val, + Value input_rhs_val); + +// Lowers the SquaredDifference operator to TOSA. +std::optional convertSquaredDifferenceOp(PatternRewriter& rewriter, + Operation* op, Value result, + Value x, Value y); + +// Lowers the Round operator to TOSA. +std::optional convertRoundOp(PatternRewriter& rewriter, Operation* op, + Value result, Value input); + +// Lowers ConcatV2 to TOSA. +std::optional convertConcatV2Op(PatternRewriter& rewriter, Operation* op, + ShapedType result_type, + SmallVectorImpl& values, + int32_t axis); + +// Lowers SpaceToBatchND to TOSA. +std::optional convertSpaceToBatchNDOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + Value block_shape_value, + Value paddings_value); + +// Lowers BatchToSpaceND to TOSA. +std::optional convertBatchToSpaceNDOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + Value block_shape_value, + Value crops_value); + +// Lowers ExpandDims to TOSA. +std::optional convertExpandDimsOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, Value dim_value); + +// Lowers Squeeze to TOSA. +std::optional convertSqueezeOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value input_value, + SmallVectorImpl& squeeze_dims); + +// Lowers ELU to a sequence of TOSA ops. +std::optional convertEluOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value features_value); + +// Lowers Softmax to a sequence of TOSA ops. +std::optional convertSoftmaxOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value logits_value, + double beta); + +// Lowers LogSoftmax to a sequence of TOSA ops. +std::optional convertLogSoftmaxOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value logits_value); + +// Lowers SpaceToDepth to a sequence of TOSA ops. Supports NHWC. +std::optional convertSpaceToDepthOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + IntegerAttr block_size_attr, + StringAttr data_format); + +// Lowers DepthToSpace to a sequence of TOSA ops. Supports NHWC. +std::optional convertDepthToSpaceOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value input_value, + IntegerAttr block_size_attr, + StringAttr data_format); + +// Lowers Split to a sequence of TOSA ops. +std::optional> convertSplitOp( + PatternRewriter& rewriter, Operation* op, Value result_value, + Value input_value, int32_t num_split, int32_t axis); + +// Lowers SplitV to a sequence of TOSA ops. +std::optional> convertSplitVOp( + PatternRewriter& rewriter, Operation* op, Value result_value, + Value input_value, SmallVectorImpl& size_split, int32_t axis); + +// Lowers StridedSlice to a sequence of TOSA ops. +std::optional convertStridedSliceOp( + PatternRewriter& rewriter, Operation* op, Value result_value, + Value input_value, Value begin_value, Value end_value, Value strides_value, + int32_t begin_mask, int32_t end_mask, int32_t ellipsis_mask, + int32_t new_axis_mask, int32_t shrink_axis_mask); + +// Helper function to perform division with floor rounding mode (rounding result +// down) for integer type inputs. +Value floorIntDiv(PatternRewriter& rewriter, Operation* op, ShapedType outType, + Value lhs, Value rhs); + +// Lowers FloorDiv to a sequence of TOSA operators. +std::optional convertFloorDivOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value lhs_value, + Value rhs_value); + +// Lowers FloorMod to a sequence of TOSA operators. +std::optional convertFloorModOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value lhs_value, + Value rhs_value); + +// Lowers FusedActivation to a sequence of TOSA ops. +std::optional convertFusedActivation(PatternRewriter& rewriter, + Operation* op, Value input_value, + StringAttr fused_activation_fn); + +// Helper function for implementing quantized divide by power-of-two in TOSA +// ops. +std::optional convertRoundingDivideByPOT(PatternRewriter& rewriter, + Operation* op, + Value input_value, + Value rshift_value); + +// Lowers ReduceAll to a sequence of TOSA ops. +std::optional convertReduceAllOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims); + +// Lowers ReduceAny to a sequence of TOSA ops. +std::optional convertReduceAnyOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims); + +// Lowers ReduceMin to a sequence of TOSA ops. +std::optional convertReduceMinOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims, + std::optional nan_mode = tosa::NanPropagationMode::PROPAGATE); + +// Lowers ReduceMax to a sequence of TOSA ops. +std::optional convertReduceMaxOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims, + std::optional nan_mode = tosa::NanPropagationMode::PROPAGATE); + +// Lowers ReduceProd to a sequence of TOSA ops. +std::optional convertReduceProdOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims); + +// Lowers ReduceSum to a sequence of TOSA ops. +std::optional convertReduceSumOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elems, + bool keep_dims); + +// Lowers ReduceMean to a sequence of TOSA ops. +std::optional convertReduceMeanOp(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input_value, + ElementsAttr axes_elem, + bool keep_dims); + +// Lowers ResizeBilinear and ResizeNearestNeighbor to TOSA resize. +std::optional convertResizeOp(PatternRewriter& rewriter, Operation* op, + RankedTensorType output_type, + Value input_value, tosa::ResizeMode mode, + bool align_corners, + bool half_pixel_centers); + +// Lowers Quantize to a sequence of TOSA quantization ops. +std::optional convertQuantizeOp(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, + Value input_value, double scale, + int64_t zeropoint); + +// Lowers Dequantize to a sequence of TOSA dequantization ops. +std::optional convertDequantizeOp(PatternRewriter& rewriter, + Operation* op, ShapedType output_type, + Value input_value, + ArrayRef scale, + ArrayRef zeropoint, + int64_t dim); + +// Lowers FakeQuant to a sequence of TOSA quantization ops. +std::optional convertFakeQuantOp(PatternRewriter& rewriter, + Operation* op, ShapedType output_type, + Value input_value, double min, + double max, int64_t num_bits, + bool narrow_range); + +// Align to TF_MirrorPadOp::mode and TFL_MirrorPadOp::mode +enum class TFTFLMirrorPaddingType : uint32_t { + REFLECT = 0, + SYMMETRIC = 1, +}; + +std::optional convertMirrorPadCommon(PatternRewriter& rewriter, + Operation* op, + RankedTensorType output_type, + Value input, Value pad, + TFTFLMirrorPaddingType mode); + +// Lowers TensorFlow Conv2D to a sequence of TOSA quantization ops. +std::optional convertTFConv2DCommon( + PatternRewriter& rewriter, Operation* op, RankedTensorType output_type, + Value input, Value filter, Value bias, ArrayAttr strides_attr, + ArrayAttr dilations_attr, ArrayAttr explicit_padding_attr, + StringRef padding_ref, StringRef data_format_ref); + +// Lowers TensorFlow and TensorFlow Lite Conv3D to a sequence of TOSA +// quantization ops. +std::optional convertConv3DCommon( + PatternRewriter& rewriter, Operation* op, ShapedType output_type, + Value input, Value filter, Value bias, DenseI64ArrayAttr pads, + DenseI64ArrayAttr strides, DenseI64ArrayAttr dilations, TypeAttr acc_type, + StringRef data_format_ref); + +// Preprocess TensorFlow Conv3D attributes prior to calling +// `convertConv3DCommon` +std::optional convertTFConv3DCommon( + PatternRewriter& rewriter, Operation* op, ShapedType output_type, + Value input, Value filter, Value bias, ArrayAttr strides_attr, + ArrayAttr dilations_attr, StringRef padding_ref, StringRef data_format_ref); + +// Lowers Gather operator to a sequence of TOSA ops. +std::optional convertGatherOp(PatternRewriter& rewriter, Operation* op, + Value params_value, Value indices_value, + int32_t batch_dims, int32_t axis, + bool tosaOnly = true); + +// Lowers GatherNd operator to a sequence of TOSA ops. +std::optional convertGatherNdOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value params_value, + Value indices_value); + +// Lowers ScatterNd operator to a sequence of TOSA ops. +std::optional convertScatterNdOp(PatternRewriter& rewriter, + Operation* op, Value result_value, + Value indices_value, + Value updates_value, Value shape_value); + +// Lowers OneHot operator to a sequence of TOSA ops. +std::optional convertOneHotOp(PatternRewriter& rewriter, Operation* op, + Value result_value, Value indices_value, + Value on_value, Value off_value, + int32_t depth, int32_t axis); + +// Lowers cast operator to a sequence of TOSA ops. +std::optional convertCastOp(PatternRewriter& rewriter, Operation* op, + Value input, RankedTensorType output_type); + +// Lowers Sign operator to a sequence of TOSA ops. +std::optional convertSignOp(PatternRewriter& rewriter, Operation* op, + Value input, RankedTensorType output_type); + +// Lowers BroadcastTo operator to a sequence of TOSA ops. +std::optional convertBroadcastToOp(PatternRewriter& rewriter, + Operation* op, Value input, + Value shape); + +}; // namespace tosa +}; // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_COMMON_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tf.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tf.cc new file mode 100644 index 0000000000000000000000000000000000000000..92ae34535512c1106678ad954a1f9579dcd2b339 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tf.cc @@ -0,0 +1,2679 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// Legalize TensorFlow to TOSA + +#include +#include +#include +#include +#include +#include +#include + +#include "mlir/Dialect/Quant/IR/Quant.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h" +#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/dynamic_shape_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-legalize-tf" +#define DEBUG_TYPE PASS_NAME + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSALEGALIZETFPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +// Performs lowering to TOSA dialect +class LegalizeTF : public impl::TosaLegalizeTFPassBase { + public: + explicit LegalizeTF() = default; + void runOnOperation() override; +}; + +// All the Pat<> lowering mappings. +#include "tensorflow/compiler/mlir/tosa/transforms/tf_legalize_patterns.inc" + +#define DECL_CONVERT_OP(tf_op) \ + struct ConvertTF##tf_op##Op : public RewritePattern { \ + explicit ConvertTF##tf_op##Op(MLIRContext* context) \ + : RewritePattern(TF::tf_op##Op::getOperationName(), 1, context) {} \ + LogicalResult matchAndRewrite(Operation* op, \ + PatternRewriter& rewriter) const override; \ + } + +// All the explcitly implemented complex lowerings. +DECL_CONVERT_OP(MatMul); +DECL_CONVERT_OP(Relu); +DECL_CONVERT_OP(Relu6); +DECL_CONVERT_OP(Equal); +DECL_CONVERT_OP(NotEqual); +DECL_CONVERT_OP(Greater); +DECL_CONVERT_OP(GreaterEqual); +DECL_CONVERT_OP(Add); +DECL_CONVERT_OP(AddV2); +DECL_CONVERT_OP(AddN); +DECL_CONVERT_OP(Sub); +DECL_CONVERT_OP(Mul); +DECL_CONVERT_OP(Square); +DECL_CONVERT_OP(SquaredDifference); +DECL_CONVERT_OP(Sign); +DECL_CONVERT_OP(Round); +DECL_CONVERT_OP(FloorDiv); +DECL_CONVERT_OP(FloorMod); +DECL_CONVERT_OP(Assert); +DECL_CONVERT_OP(Maximum); +DECL_CONVERT_OP(Minimum); +DECL_CONVERT_OP(RealDiv); +DECL_CONVERT_OP(ArgMax); +DECL_CONVERT_OP(AvgPool); +DECL_CONVERT_OP(MaxPool); +DECL_CONVERT_OP(ConcatV2); +DECL_CONVERT_OP(Reshape); +DECL_CONVERT_OP(Rank); +DECL_CONVERT_OP(Shape); +DECL_CONVERT_OP(ExpandDims); +DECL_CONVERT_OP(Squeeze); +DECL_CONVERT_OP(Fill); +DECL_CONVERT_OP(Conv2D); +DECL_CONVERT_OP(Conv3D); +DECL_CONVERT_OP(DepthwiseConv2dNative); +DECL_CONVERT_OP(Conv2DBackpropInput); +DECL_CONVERT_OP(Elu); +DECL_CONVERT_OP(Softmax); +DECL_CONVERT_OP(LogSoftmax); +DECL_CONVERT_OP(All); +DECL_CONVERT_OP(Any); +DECL_CONVERT_OP(Max); +DECL_CONVERT_OP(Min); +DECL_CONVERT_OP(Mean); +DECL_CONVERT_OP(Prod); +DECL_CONVERT_OP(Sum); +DECL_CONVERT_OP(FusedBatchNorm); +DECL_CONVERT_OP(FusedBatchNormV3); +DECL_CONVERT_OP(BiasAdd); +DECL_CONVERT_OP(Split); +DECL_CONVERT_OP(SplitV); +DECL_CONVERT_OP(Pack); +DECL_CONVERT_OP(Unpack); +DECL_CONVERT_OP(Transpose); +DECL_CONVERT_OP(Tile); +DECL_CONVERT_OP(Slice); +DECL_CONVERT_OP(StridedSlice); +DECL_CONVERT_OP(Less); +DECL_CONVERT_OP(LessEqual); +DECL_CONVERT_OP(Pad); +DECL_CONVERT_OP(PadV2); +DECL_CONVERT_OP(MirrorPad); +DECL_CONVERT_OP(ResizeBilinear); +DECL_CONVERT_OP(ResizeNearestNeighbor); +DECL_CONVERT_OP(Gather); +DECL_CONVERT_OP(GatherV2); +DECL_CONVERT_OP(GatherNd); +DECL_CONVERT_OP(ScatterNd); +DECL_CONVERT_OP(SelectV2); +DECL_CONVERT_OP(SpaceToDepth); +DECL_CONVERT_OP(DepthToSpace); +DECL_CONVERT_OP(Sin); +DECL_CONVERT_OP(Cos); +DECL_CONVERT_OP(SpaceToBatchND); +DECL_CONVERT_OP(BatchToSpaceND); +DECL_CONVERT_OP(ZerosLike); +DECL_CONVERT_OP(Sigmoid); +DECL_CONVERT_OP(Tanh); +DECL_CONVERT_OP(LeakyRelu); +DECL_CONVERT_OP(Neg); +DECL_CONVERT_OP(StopGradient); +DECL_CONVERT_OP(ReverseV2); +DECL_CONVERT_OP(FakeQuantWithMinMaxArgs); +DECL_CONVERT_OP(FakeQuantWithMinMaxVars); +DECL_CONVERT_OP(LeftShift); +DECL_CONVERT_OP(RightShift); +DECL_CONVERT_OP(OneHot); +DECL_CONVERT_OP(BatchMatMulV2); +DECL_CONVERT_OP(BroadcastTo); +DECL_CONVERT_OP(BitwiseOr); +DECL_CONVERT_OP(BitwiseXor); +DECL_CONVERT_OP(BitwiseAnd); +DECL_CONVERT_OP(LogicalAnd); +DECL_CONVERT_OP(LogicalOr); +DECL_CONVERT_OP(Pow); +#undef DECL_CONVERT_OP + +LogicalResult ConvertTFReluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_relu_op = cast(op); + + TensorType output_type = + dyn_cast(tf_relu_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + auto element_type = output_type.getElementType(); + if (auto quant_type = + dyn_cast(element_type)) { + element_type = quant_type.getStorageType(); + } + + mlir::Attribute min_val, max_val; + if (mlir::isa(element_type)) { + min_val = rewriter.getFloatAttr(element_type, 0.0f); + max_val = + rewriter.getFloatAttr(element_type, std::numeric_limits::max()); + } else { + min_val = rewriter.getIntegerAttr(element_type, 0); + max_val = rewriter.getIntegerAttr(element_type, + std::numeric_limits::max()); + } + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_relu_op.getFeatures(), min_val, max_val); + return success(); +} + +LogicalResult ConvertTFRelu6Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_relu6_op = cast(op); + + TensorType output_type = + dyn_cast(tf_relu6_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + auto element_type = output_type.getElementType(); + if (auto quant_type = + dyn_cast(element_type)) { + element_type = quant_type.getStorageType(); + } + + mlir::Attribute min_val, max_val; + if (mlir::isa(element_type)) { + min_val = rewriter.getFloatAttr(element_type, 0.0f); + max_val = rewriter.getFloatAttr(element_type, 6.0f); + } else { + min_val = rewriter.getIntegerAttr(element_type, 0); + max_val = rewriter.getIntegerAttr(element_type, 6); + } + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_relu6_op.getFeatures(), min_val, max_val); + return success(); +} + +LogicalResult ConvertTFNotEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_not_equal_op = cast(op); + + TensorType output_type = + dyn_cast(tf_not_equal_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + Value x = tf_not_equal_op.getX(); + Value y = tf_not_equal_op.getY(); + + auto op1_equal_in = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, x, y); + + auto op2_not_op1 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op1_equal_in.getResult()); + + rewriter.replaceOp(op, {op2_not_op1.getResult()}); + + return success(); +} + +LogicalResult ConvertTFSignOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_sign_op = cast(op); + + RankedTensorType output_type = + mlir::cast(tf_sign_op.getResult().getType()); + + std::optional result = + convertSignOp(rewriter, op, tf_sign_op.getX(), output_type); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFSinOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_sin_op = cast(op); + + ShapedType output_type = + dyn_cast(tf_sin_op.getResult().getType()); + if (!output_type) + return rewriter.notifyMatchFailure(op, "output_type required"); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_sin_op.getX()); + + return success(); +} + +LogicalResult ConvertTFCosOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_cos_op = cast(op); + + ShapedType output_type = + dyn_cast(tf_cos_op.getResult().getType()); + if (!output_type) + return rewriter.notifyMatchFailure(op, "output_type required"); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_cos_op.getX()); + + return success(); +} + +LogicalResult ConvertTFAddOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_add_op = cast(op); + + TensorType output_type = + dyn_cast(tf_add_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + Value x = tf_add_op.getX(); + Value y = tf_add_op.getY(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, x, y); + return success(); +} + +LogicalResult ConvertTFAddV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_addv2_op = cast(op); + + TensorType output_type = + dyn_cast(tf_addv2_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + Value x = tf_addv2_op.getX(); + Value y = tf_addv2_op.getY(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, x, y); + return success(); +} + +// AddN is commutative +LogicalResult ConvertTFAddNOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_addn_op = cast(op); + + TensorType output_type = + dyn_cast(tf_addn_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + SmallVector inputs(tf_addn_op.getInputs()); + + assert(inputs.size() >= 2); + + Value lhs = inputs[0]; + Value rhs = inputs[1]; + auto newOp = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, lhs, rhs); + for (int i = 2; i < inputs.size(); i++) { + Value lhs = inputs[i]; + Value rhs = newOp.getResult(); + newOp = CreateOpAndInfer(rewriter, op->getLoc(), output_type, + lhs, rhs); + } + + rewriter.replaceOp(op, {newOp.getResult()}); + + return success(); +} + +LogicalResult ConvertTFSubOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_sub_op = cast(op); + + TensorType output_type = + dyn_cast(tf_sub_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + Value lhs = tf_sub_op.getX(); + Value rhs = tf_sub_op.getY(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, lhs, rhs); + return success(); +} + +LogicalResult ConvertTFMulOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_mul_op = cast(op); + + std::optional result = convertMultiplyOp( + rewriter, op, tf_mul_op.getResult(), tf_mul_op.getX(), tf_mul_op.getY()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFSquareOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_square_op = cast(op); + + std::optional result = + convertMultiplyOp(rewriter, op, tf_square_op.getResult(), + tf_square_op.getX(), tf_square_op.getX()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFSquaredDifferenceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_squared_op = cast(op); + + std::optional result = + convertSquaredDifferenceOp(rewriter, op, tf_squared_op.getResult(), + tf_squared_op.getX(), tf_squared_op.getY()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFRoundOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_round_op = cast(op); + + TensorType input_type = dyn_cast(tf_round_op.getX().getType()); + if (!input_type) { + return rewriter.notifyMatchFailure(op, "input not tensor type"); + } + + if (mlir::isa(input_type.getElementType())) { + std::optional result = convertRoundOp( + rewriter, op, tf_round_op.getResult(), tf_round_op.getX()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); + + } else { + tf_round_op.replaceAllUsesWith(tf_round_op.getX()); + return success(); + } +} + +LogicalResult ConvertTFFloorDivOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_floordiv_op = cast(op); + + std::optional result = + convertFloorDivOp(rewriter, op, tf_floordiv_op.getResult(), + tf_floordiv_op.getX(), tf_floordiv_op.getY()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFFloorModOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_floormod_op = cast(op); + + std::optional result = + convertFloorModOp(rewriter, op, tf_floormod_op.getResult(), + tf_floormod_op.getX(), tf_floormod_op.getY()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFAssertOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + op->dropAllReferences(); + op->erase(); + return success(); +} + +LogicalResult ConvertTFRealDivOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_div_op = cast(op); + + TensorType y_type = dyn_cast(tf_div_op.getY().getType()); + TensorType output_type = + dyn_cast(tf_div_op.getResult().getType()); + // Not a tensor output + if (!output_type || !y_type) return failure(); + + Type element_type = output_type.getElementType(); + + Value x = tf_div_op.getX(); + Value y = tf_div_op.getY(); + + if (mlir::isa(element_type)) { + CreateReplaceOpAndInfer(rewriter, op, output_type, x, y); + return success(); + } + + auto reciprocal_op = CreateOpAndInfer( + rewriter, op->getLoc(), y.getType(), y); + + auto mul_op = CreateMulOpAndInfer( + rewriter, op, output_type, tf_div_op.getX(), + reciprocal_op.getResult()); + rewriter.replaceOp(op, {mul_op.getResult()}); + + return success(); +} + +LogicalResult ConvertTFArgMaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_argmax_op = cast(op); + + TensorType input_type = + dyn_cast(tf_argmax_op.getInput().getType()); + TensorType output_type = + dyn_cast(tf_argmax_op.getResult().getType()); + // Not a tensor output + if (!output_type || !input_type) return failure(); + + ElementsAttr axis_elems; + if (!matchPattern(tf_argmax_op.getDimension(), m_Constant(&axis_elems))) + return failure(); + + int32_t axis = axis_elems.getValues()[0].getInt(); + if (axis < 0) { + axis += input_type.getRank(); + } + + if (axis < 0 || axis >= input_type.getRank()) { + return rewriter.notifyMatchFailure(op, "invalid axis value"); + } + + IntegerAttr axis_attr = rewriter.getI32IntegerAttr(axis); + const auto nan_propagate_attr = tosa::NanPropagationModeAttr::get( + rewriter.getContext(), tosa::NanPropagationMode::PROPAGATE); + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_argmax_op.getInput(), axis_attr, + nan_propagate_attr); + + return success(); +} + +LogicalResult ConvertTFAvgPoolOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_avgpool_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tf_avgpool_op.getValue().getType()); + RankedTensorType output_type = + dyn_cast(tf_avgpool_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type || !output_type) return failure(); + + auto tmpAttr = tf_avgpool_op.getDataFormatAttr(); + if (tmpAttr && tmpAttr.getValue().str() != "NHWC") return failure(); + + DenseI64ArrayAttr pad; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr kernel; + { + auto tmpAttr = tf_avgpool_op.getStrides(); + if (!tmpAttr) { + stride = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t stride_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t stride_w = dyn_cast(tmpAttr[2]).getInt(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + } + { + auto tmpAttr = tf_avgpool_op.getKsize(); + if (!tmpAttr) { + kernel = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t kernel_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t kernel_w = dyn_cast(tmpAttr[2]).getInt(); + kernel = rewriter.getDenseI64ArrayAttr({kernel_h, kernel_w}); + } + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tf_avgpool_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + DenseI64ArrayAttr dilation = rewriter.getDenseI64ArrayAttr( + {1, 1}); // Pooling has no non-unit dilation + + SmallVector i64array; + + for (auto& elem : tf_avgpool_op.getKsize()) { + int64_t value = dyn_cast(elem).getInt(); + i64array.emplace_back(value); + } + + RankedTensorType filter_type = tensorflow::GetTypeFromTFTensorShape( + llvm::ArrayRef(i64array), rewriter.getIntegerType(64)); + + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, stride, dilation, rewriter, pad)) + return failure(); + } + + // Tosa supports FP16 and FP32 accumulator type for FP16 input. When the time + // FP16 is supported, the accumulator type can be selected based on trade-off + // between performance and accuracy. Set to FP32 by default. + auto acc_attr = mlir::TypeAttr::get(rewriter.getF32Type()); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_avgpool_op.getValue(), kernel, + stride, pad, acc_attr); + return success(); +} + +LogicalResult ConvertTFMaxPoolOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_maxpool_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tf_maxpool_op.getInput().getType()); + RankedTensorType output_type = + dyn_cast(tf_maxpool_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type || !output_type) return failure(); + + auto tmpAttr = tf_maxpool_op.getDataFormatAttr(); + if (tmpAttr && tmpAttr.getValue().str() != "NHWC") return failure(); + + DenseI64ArrayAttr pad; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr kernel; + { + auto tmpAttr = tf_maxpool_op.getStrides(); + if (!tmpAttr) { + stride = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t stride_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t stride_w = dyn_cast(tmpAttr[2]).getInt(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + } + { + auto tmpAttr = tf_maxpool_op.getKsize(); + if (!tmpAttr) { + kernel = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t kernel_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t kernel_w = dyn_cast(tmpAttr[2]).getInt(); + kernel = rewriter.getDenseI64ArrayAttr({kernel_h, kernel_w}); + } + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tf_maxpool_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + // Pooling has no non-unit dilation + DenseI64ArrayAttr dilation = rewriter.getDenseI64ArrayAttr({1, 1}); + + SmallVector i64array; + + for (auto& elem : tf_maxpool_op.getKsize()) { + int64_t value = dyn_cast(elem).getInt(); + i64array.emplace_back(value); + } + + RankedTensorType filter_type = tensorflow::GetTypeFromTFTensorShape( + llvm::ArrayRef(i64array), rewriter.getIntegerType(64)); + + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, stride, dilation, rewriter, pad)) + return failure(); + } + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_maxpool_op.getInput(), kernel, stride, pad); + return success(); +} + +LogicalResult ConvertTFConcatV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_concatv2_op = cast(op); + auto result_type = + mlir::cast(tf_concatv2_op.getResult().getType()); + SmallVector values(tf_concatv2_op.getValues()); + + ElementsAttr axis_elems; + if (!matchPattern(tf_concatv2_op.getAxis(), m_Constant(&axis_elems))) + return failure(); + + int32_t axis = axis_elems.getValues()[0].getInt(); + + std::optional result = + convertConcatV2Op(rewriter, op, result_type, values, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFReshapeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_reshape_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_reshape_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + // Regular way to match tensor as element attribute doesn't always work + // use output_type.getShape() which is more stable + SmallVector shape_vals; + for (int i = 0; i < output_type.getShape().size(); i++) { + shape_vals.push_back(output_type.getShape()[i]); + } + DenseI64ArrayAttr shape_attr = rewriter.getDenseI64ArrayAttr(shape_vals); + + auto shape_value = getTosaConstShape(rewriter, op->getLoc(), shape_vals); + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_reshape_op.getTensor(), shape_value); + return success(); +} + +LogicalResult ConvertTFRankOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_rank_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tf_rank_op.getInput().getType()); + if (!input_type) return failure(); + + int32_t rank = input_type.getRank(); + + RankedTensorType rank_type = + tensorflow::GetTypeFromTFTensorShape({1}, rewriter.getIntegerType(32)); + auto rank_attr = DenseI32ArrayAttr::get(rewriter.getContext(), {rank}); + auto rank_const = CreateOpAndInfer( + rewriter, op->getLoc(), rank_type, cast(rank_attr)); + + rewriter.replaceOp(op, {rank_const.getResult()}); + + return success(); +} + +LogicalResult ConvertTFShapeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_shape_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_shape_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + RankedTensorType input_type = + dyn_cast(tf_shape_op.getInput().getType()); + if (!input_type) return failure(); + + auto input_shape = input_type.getShape(); + + SmallVector shape_arr; + for (int i = 0; i < input_shape.size(); i++) { + shape_arr.emplace_back(input_shape[i]); + } + + RankedTensorType shape_type = tensorflow::GetTypeFromTFTensorShape( + {static_cast(shape_arr.size())}, rewriter.getIntegerType(32)); + auto shape_attr = + DenseI32ArrayAttr::get(rewriter.getContext(), llvm::ArrayRef(shape_arr)); + auto shape_const = CreateOpAndInfer( + rewriter, op->getLoc(), shape_type, cast(shape_attr)); + + rewriter.replaceOp(op, {shape_const.getResult()}); + + return success(); +} + +LogicalResult ConvertTFExpandDimsOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_expanddims_op = cast(op); + + std::optional result = convertExpandDimsOp( + rewriter, op, tf_expanddims_op.getResult(), tf_expanddims_op.getInput(), + tf_expanddims_op.getDim()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSqueezeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_squeeze_op = cast(op); + + // Copy squeeze_dims into int32_t array + auto squeeze_dims_attr = tf_squeeze_op.getSqueezeDimsAttr(); + SmallVector squeeze_dims; + for (auto& squeeze_dim : squeeze_dims_attr) { + squeeze_dims.emplace_back(dyn_cast(squeeze_dim).getInt()); + } + + std::optional result = + convertSqueezeOp(rewriter, op, tf_squeeze_op.getResult(), + tf_squeeze_op.getInput(), squeeze_dims); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFFillOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_fill_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_fill_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + ElementsAttr dims_elems; + if (!matchPattern(tf_fill_op.getDims(), m_Constant(&dims_elems))) + return failure(); + SmallVector dims_vals; + uint32_t total_size = 1; + for (int i = 0; i < dims_elems.getNumElements(); i++) { + dims_vals.push_back(dims_elems.getValues()[i].getInt()); + total_size *= dims_vals[i]; + } + + ElementsAttr value_elem; + if (!matchPattern(tf_fill_op.getValue(), m_Constant(&value_elem))) + return failure(); + + RankedTensorType fill_type = tensorflow::GetTypeFromTFTensorShape( + ArrayRef(dims_vals), + value_elem.getShapedType().getElementType()); + DenseArrayAttr fill_attr; + + // Convert to a compatible zero type + if (mlir::isa(value_elem.getShapedType().getElementType())) { + SmallVector fill_arr( + total_size, + value_elem.getValues()[0].getValue().convertToFloat()); + fill_attr = + DenseF32ArrayAttr::get(rewriter.getContext(), llvm::ArrayRef(fill_arr)); + } else { + SmallVector fill_arr( + total_size, + value_elem.getValues()[0].getValue().getLimitedValue()); + fill_attr = + DenseI32ArrayAttr::get(rewriter.getContext(), llvm::ArrayRef(fill_arr)); + } + auto fill_const_op = CreateOpAndInfer( + rewriter, op->getLoc(), fill_type, mlir::cast(fill_attr)); + rewriter.replaceOp(op, {fill_const_op.getResult()}); + + return success(); +} + +LogicalResult ConvertTFConv2DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_conv2d_op = cast(op); + + RankedTensorType filter_type = + dyn_cast(tf_conv2d_op.getFilter().getType()); + RankedTensorType output_type = + dyn_cast(tf_conv2d_op.getResult().getType()); + + // Set up a zero attr for subsequent pattern replacement if required + auto bias_dim = filter_type.getShape().back(); + RankedTensorType bias_type = tensorflow::GetTypeFromTFTensorShape( + {bias_dim}, filter_type.getElementType()); + auto bias_attr = rewriter.getZeroAttr(bias_type); + auto bias = CreateOpAndInfer( + rewriter, op->getLoc(), bias_type, mlir::cast(bias_attr)); + + std::optional result = convertTFConv2DCommon( + rewriter, op, output_type, tf_conv2d_op.getInput(), + tf_conv2d_op.getFilter(), bias, tf_conv2d_op.getStrides(), + tf_conv2d_op.getDilations(), tf_conv2d_op.getExplicitPaddings(), + tf_conv2d_op.getPadding(), tf_conv2d_op.getDataFormat()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFConv3DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_conv3d_op = cast(op); + + RankedTensorType filter_type = + dyn_cast(tf_conv3d_op.getFilter().getType()); + RankedTensorType output_type = + dyn_cast(tf_conv3d_op.getResult().getType()); + + if (!filter_type || !output_type) { + return rewriter.notifyMatchFailure( + op, "filter/output are not all a ranked tensor"); + } + + // Set up a zero attr for subsequent pattern replacement if required + auto bias_dim = filter_type.getShape().back(); + RankedTensorType bias_type = + RankedTensorType::get({bias_dim}, filter_type.getElementType()); + auto bias_attr = rewriter.getZeroAttr(bias_type); + auto bias = CreateOpAndInfer( + rewriter, op->getLoc(), bias_type, mlir::cast(bias_attr)); + + std::optional result = convertTFConv3DCommon( + rewriter, op, output_type, tf_conv3d_op.getInput(), + tf_conv3d_op.getFilter(), bias, tf_conv3d_op.getStrides(), + tf_conv3d_op.getDilations(), tf_conv3d_op.getPadding(), + tf_conv3d_op.getDataFormat()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFDepthwiseConv2dNativeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_dwconv2d_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tf_dwconv2d_op.getInput().getType()); + RankedTensorType filter_type = + dyn_cast(tf_dwconv2d_op.getFilter().getType()); + RankedTensorType output_type = + dyn_cast(tf_dwconv2d_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type) return failure(); + if (!output_type) return failure(); + + // Set up a zero attr for subsequent pattern replacement if required + if (!filter_type) { + return rewriter.notifyMatchFailure(op, "filter type unranked tensor"); + } + + auto tmpAttr = tf_dwconv2d_op.getDataFormatAttr(); + if (tmpAttr && tmpAttr.getValue().str() != "NHWC") return failure(); + + DenseI64ArrayAttr stride; + DenseI64ArrayAttr dilation; + DenseI64ArrayAttr pad; + { + auto tmpAttr = tf_dwconv2d_op.getStrides(); + if (!tmpAttr) { + stride = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t stride_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t stride_w = dyn_cast(tmpAttr[2]).getInt(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + } + { + auto tmpAttr = tf_dwconv2d_op.getDilations(); + if (!tmpAttr) { + dilation = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t dilation_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t dilation_w = dyn_cast(tmpAttr[2]).getInt(); + dilation = rewriter.getDenseI64ArrayAttr({dilation_h, dilation_w}); + } + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tf_dwconv2d_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + tensorflow::TensorFormat data_format_tf; + if (!FormatFromString(tf_dwconv2d_op.getDataFormat().str(), + &data_format_tf)) + return failure(); + + if (tf_pad == tensorflow::Padding::EXPLICIT) { + pad = getPaddingValuesFromExplicitPadAttr( + tf_dwconv2d_op.getExplicitPaddings(), data_format_tf, rewriter); + } else { + if (!getPaddingValuesFromPadType(tf_pad, data_format_tf, + 0, // tensorflow::FORMAT_HWIO + input_type, filter_type, stride, + dilation, rewriter, pad)) + return failure(); + } + } + + auto filter_shape = filter_type.getShape(); + auto bias_dim = filter_shape[2] * filter_shape[3]; + RankedTensorType bias_type = tensorflow::GetTypeFromTFTensorShape( + {bias_dim}, filter_type.getElementType()); + auto bias_attr = rewriter.getZeroAttr(bias_type); + auto bias = CreateOpAndInfer( + rewriter, op->getLoc(), bias_type, mlir::cast(bias_attr)); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ output_type.getElementType()); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_dwconv2d_op.getInput(), + tf_dwconv2d_op.getFilter(), bias, pad, stride, dilation, acc_type); + return success(); +} + +LogicalResult ConvertTFConv2DBackpropInputOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_conv_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tf_conv_op.getOutBackprop().getType()); + RankedTensorType filter_type = + dyn_cast(tf_conv_op.getFilter().getType()); + RankedTensorType output_type = + dyn_cast(tf_conv_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type) return failure(); + if (!filter_type) return failure(); + if (!output_type) return failure(); + + // Transpose [H, W, I, O] to [O, H, W, I] + auto filter_shape = filter_type.getShape(); + SmallVector a1_transpose_dims; + a1_transpose_dims.push_back(filter_shape[2]); + a1_transpose_dims.push_back(filter_shape[0]); + a1_transpose_dims.push_back(filter_shape[1]); + a1_transpose_dims.push_back(filter_shape[3]); + + auto a1_filter_transpose_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(ArrayRef(a1_transpose_dims), + filter_type.getElementType()), + tf_conv_op.getFilter(), rewriter.getDenseI32ArrayAttr({2, 0, 1, 3})); + + DenseI64ArrayAttr stride; + DenseI64ArrayAttr outpad; + { + auto tmpAttr = tf_conv_op.getStrides(); + if (!tmpAttr) { + stride = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t stride_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t stride_w = dyn_cast(tmpAttr[2]).getInt(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + } + { + auto tmpAttr = tf_conv_op.getDilations(); + if (tmpAttr) { + // Note: hardcoded to NHWC for now + int64_t dilation_h = dyn_cast(tmpAttr[1]).getInt(); + int64_t dilation_w = dyn_cast(tmpAttr[2]).getInt(); + // TOSA transpose_conv2d does not support non-unit dilation + if (dilation_h != 1 || dilation_w != 1) return failure(); + } + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tf_conv_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + tensorflow::TensorFormat data_format_tf; + if (!FormatFromString(tf_conv_op.getDataFormat().str(), &data_format_tf)) + return failure(); + + if (tf_pad == tensorflow::Padding::EXPLICIT) { + outpad = getPaddingValuesFromExplicitPadAttr( + tf_conv_op.getExplicitPaddings(), data_format_tf, rewriter); + } else { + if (!getTransposeConv2dPaddingValues(tf_pad, data_format_tf, + 0, // tensorflow::FORMAT_HWIO, + input_type, filter_type, output_type, + stride, rewriter, outpad)) + return failure(); + } + } + + int output_channel = output_type.getShape()[3]; + SmallVector vec(output_channel, 0.0f); + std::optional zero_bias = + getConstTensor(rewriter, op, vec, {output_channel}); + + if (!zero_bias) return failure(); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ output_type.getElementType()); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_conv_op.getOutBackprop(), + a1_filter_transpose_op.getResult(), zero_bias.value(), outpad, stride, + acc_type); + + return success(); +} + +LogicalResult ConvertTFAllOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_all_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_all_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_all_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceAllOp( + rewriter, op, output_type, tf_all_op.getInput(), axes_elems, tf_all_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFAnyOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_any_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_any_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_any_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceAnyOp( + rewriter, op, output_type, tf_any_op.getInput(), axes_elems, tf_any_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFMaxOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_max_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_max_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_max_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceMaxOp( + rewriter, op, output_type, tf_max_op.getInput(), axes_elems, tf_max_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFMinOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_min_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_min_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_min_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceMinOp( + rewriter, op, output_type, tf_min_op.getInput(), axes_elems, tf_min_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFMeanOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_mean_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_mean_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_mean_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceMeanOp( + rewriter, op, output_type, tf_mean_op.getInput(), axes_elems, tf_mean_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFProdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_prod_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_prod_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_prod_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceProdOp( + rewriter, op, output_type, tf_prod_op.getInput(), axes_elems, tf_prod_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSumOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_sum_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_sum_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tf_sum_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceSumOp( + rewriter, op, output_type, tf_sum_op.getInput(), axes_elems, tf_sum_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFEluOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_elu_op = cast(op); + + std::optional result = convertEluOp( + rewriter, op, tf_elu_op.getResult(), tf_elu_op.getFeatures()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSoftmaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_softmax_op = cast(op); + + std::optional result = + convertSoftmaxOp(rewriter, op, tf_softmax_op.getResult(), + tf_softmax_op.getLogits(), /*beta=*/1.0); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLogSoftmaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_logsoftmax_op = cast(op); + + std::optional result = convertLogSoftmaxOp( + rewriter, op, tf_logsoftmax_op.getResult(), tf_logsoftmax_op.getLogits()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFFusedBatchNormOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_batchnorm_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_batchnorm_op.getResult(0).getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + // Lowering: + // fused batchnorm = (input-mean) * scale * rsqrt(var+epsilon)) + offset + // + // shape_0 = ones(input.rank) + // shape_0[input.rank-1] = input.shape[input.rank-1] + // shape_1 = ones(1) + // + // bmean = reshape(mean, shape_0) + // bscale = reshape(scale, shape_0) + // boffset= reshape(offset, shape_0) + // beps = reshape(epsilon, shape_1) + // + // op1 = sub(input, bmean) + // op2 = add(var, beps) + // op3 = rsqrt(op2) + // bvar = reshape(op3, shape_0) + // op4 = mul(op1, bvar) + // op5 = mul(op4, bscale) + // op6 = add(op5, boffset) + + Value mean = tf_batchnorm_op.getMean(); + Value variance = tf_batchnorm_op.getVariance(); + Value x = tf_batchnorm_op.getX(); + Value scale = tf_batchnorm_op.getScale(); + Value offset = tf_batchnorm_op.getOffset(); + + RankedTensorType mean_type = dyn_cast(mean.getType()); + RankedTensorType variance_type = + dyn_cast(variance.getType()); + RankedTensorType x_type = dyn_cast(x.getType()); + RankedTensorType scale_type = dyn_cast(scale.getType()); + RankedTensorType offset_type = dyn_cast(offset.getType()); + if (!variance_type || !mean_type || !x_type || !scale_type || !offset_type) + return failure(); + + auto rank = x_type.getRank(); + + Value mean_val, variance_val; + + if (mean_type.getNumElements() == 0) { + mean_val = getTosaConstTensorSingleF32(rewriter, tf_batchnorm_op, 0, rank); + } else { + mean_val = tf_batchnorm_op.getMean(); + } + + if (variance_type.getNumElements() == 0) { + variance_val = + getTosaConstTensorSingleF32(rewriter, tf_batchnorm_op, 1.0, 1); + } else { + variance_val = tf_batchnorm_op.getVariance(); + } + + RankedTensorType epsilon_type = + tensorflow::GetTypeFromTFTensorShape({1}, variance_type.getElementType()); + auto epsilon_attr = + DenseFPElementsAttr::get(epsilon_type, {tf_batchnorm_op.getEpsilon()}); + Value epsilon_const = CreateOpAndInfer( + rewriter, op->getLoc(), epsilon_type, epsilon_attr); + + Value op1_sub_input_mean = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, x, mean_val); + + Value op2_add_var_epsilon = CreateOpAndInfer( + rewriter, op->getLoc(), variance_val.getType(), variance_val, + epsilon_const); + + Value op3_rsqrt_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), variance_val.getType(), op2_add_var_epsilon); + + Value op4_mul_op1_op3 = CreateMulOpAndInfer( + rewriter, op, output_type, op1_sub_input_mean, op3_rsqrt_op2); + + Value op5_mul_op4_scale = CreateMulOpAndInfer( + rewriter, op, output_type, op4_mul_op1_op3, scale); + + Value op6_add_op5_offset = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op5_mul_op4_scale, offset); + + rewriter.replaceOp(op, {op6_add_op5_offset}); + return success(); +} + +LogicalResult ConvertTFFusedBatchNormV3Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_batchnorm_op = cast(op); + + if (tf_batchnorm_op.getIsTraining()) + return rewriter.notifyMatchFailure( + op, "unable to lower when is_training is set"); + + for (auto value : tf_batchnorm_op.getResults().drop_front(1)) { + if (!value.use_empty()) { + // Really we should compute this still and let it DCE but I can't find + // the math. + return rewriter.notifyMatchFailure( + op, "lowering does not support aggregate statistics"); + } + } + + RankedTensorType output_type = + dyn_cast(tf_batchnorm_op.getResult(0).getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + // Lowering: + // fused batchnorm = (input-mean) * scale * rsqrt(var+epsilon)) + offset + // op1 = sub(input, mean) + // op2 = add(var, epsilon) + // op3 = rsqrt(op2) + // op4 = mul(op1, op3) + // op5 = mul(op4, scale) + // op6 = add(op5, offset) + + Value x = tf_batchnorm_op.getX(); + Value mean = tf_batchnorm_op.getMean(); + + Value op1_sub_input_mean = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, x, mean); + + Value variance = tf_batchnorm_op.getVariance(); + RankedTensorType variance_type = + dyn_cast(variance.getType()); + if (!variance_type) return failure(); + + auto epsilon_type = + tensorflow::GetTypeFromTFTensorShape({1}, variance_type.getElementType()); + auto epsilon_attr = + DenseFPElementsAttr::get(epsilon_type, {tf_batchnorm_op.getEpsilon()}); + auto epsilon_const = CreateOpAndInfer( + rewriter, op->getLoc(), epsilon_type, epsilon_attr); + + variance_type = mlir::cast(variance.getType()); + Value op2_add_var_epsilon = CreateOpAndInfer( + rewriter, op->getLoc(), variance_type, variance, epsilon_const); + + Value op3_rsqrt_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), variance_type, op2_add_var_epsilon); + + Value op4_mul_op1_op3 = CreateMulOpAndInfer( + rewriter, op, tf_batchnorm_op.getResult(0).getType(), + op1_sub_input_mean, op3_rsqrt_op2); + + Value scale = tf_batchnorm_op.getScale(); + Value op5_mul_op4_scale = CreateMulOpAndInfer( + rewriter, op, output_type, op4_mul_op1_op3, scale); + + Value offset = tf_batchnorm_op.getOffset(); + Value op6_add_op5_offset = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op5_mul_op4_scale, offset); + + llvm::SmallVector replacements = { + op6_add_op5_offset, tf_batchnorm_op.getMean(), + tf_batchnorm_op.getVariance(), + // The last three are reserved spaces and have no purpose currently. + tf_batchnorm_op.getMean(), tf_batchnorm_op.getVariance(), + tf_batchnorm_op.getVariance()}; + rewriter.replaceOp(op, replacements); + return success(); +} + +LogicalResult ConvertTFBiasAddOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_biasadd_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_biasadd_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + Value x = tf_biasadd_op.getValue(); + Value bias = tf_biasadd_op.getBias(); + + RankedTensorType x_type = dyn_cast(x.getType()); + RankedTensorType bias_type = dyn_cast(bias.getType()); + if (!x_type || !bias_type) return failure(); + + auto add_op = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, x, bias); + + rewriter.replaceOp(op, {add_op.getResult()}); + return success(); +} + +LogicalResult ConvertTFSliceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_slice_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_slice_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + ElementsAttr begin_elems, size_elems; + + SmallVector begin_vals, size_vals; + + // Assuming begin is always compile-time constant + if (!matchPattern(tf_slice_op.getBegin(), m_Constant(&begin_elems))) { + return rewriter.notifyMatchFailure(op, "begin is not constant"); + } + + for (int i = 0; i < begin_elems.getNumElements(); i++) + begin_vals.push_back(begin_elems.getValues()[i].getInt()); + + // Try to match size as compile-time constant first, + // if this fails, use the output tensor shape instead. + if (matchPattern(tf_slice_op.getSize(), m_Constant(&size_elems))) { + for (int i = 0; i < size_elems.getNumElements(); i++) + size_vals.push_back(size_elems.getValues()[i].getInt()); + } else { + size_vals.assign(output_type.getShape().begin(), + output_type.getShape().end()); + } + + DenseI64ArrayAttr begin = rewriter.getDenseI64ArrayAttr(begin_vals); + DenseI64ArrayAttr size = rewriter.getDenseI64ArrayAttr(size_vals); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_slice_op.getInput(), + getTosaConstShape(rewriter, op->getLoc(), begin_vals), + getTosaConstShape(rewriter, op->getLoc(), size_vals)); + return success(); +} + +LogicalResult ConvertTFTileOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_tile_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_tile_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + ElementsAttr multiples_elems; + if (!matchPattern(tf_tile_op.getMultiples(), m_Constant(&multiples_elems))) + return failure(); + SmallVector multiples_vals; + for (int i = 0; i < multiples_elems.getNumElements(); i++) + multiples_vals.push_back( + multiples_elems.getValues()[i].getInt()); + + auto multiples = getTosaConstShape(rewriter, op->getLoc(), multiples_vals); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_tile_op.getInput(), multiples); + + return success(); +} + +LogicalResult ConvertTFTransposeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_transpose_op = cast(op); + + TensorType output_type = + dyn_cast(tf_transpose_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) { + return failure(); + } + + // Get the constant values for perm input + ElementsAttr permsAttrElems; + if (!matchPattern(tf_transpose_op.getPerm(), m_Constant(&permsAttrElems))) { + return rewriter.notifyMatchFailure(op, "perm value is not constant"); + } + + SmallVector perms; + for (auto v : permsAttrElems.getValues()) { + perms.push_back(v.getSExtValue()); + } + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tf_transpose_op.getX(), + rewriter.getDenseI32ArrayAttr(perms)); + + return success(); +} + +LogicalResult ConvertTFPackOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_pack_op = cast(op); + + SmallVector inputs(tf_pack_op.getValues()); + + assert(inputs.size() >= 2); + + IntegerAttr axis_attr = tf_pack_op.getAxisAttr(); + if (!axis_attr) axis_attr = rewriter.getI32IntegerAttr(0); + + int32_t axis_i32 = axis_attr.getInt(); + + std::optional result = + convertPackOp(rewriter, op, tf_pack_op.getResult(), inputs, axis_i32); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFUnpackOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_unpack_op = cast(op); + + IntegerAttr axis_attr; + { + auto tmpAttr = tf_unpack_op.getAxisAttr(); + if (!tmpAttr) tmpAttr = rewriter.getI32IntegerAttr(0); + axis_attr = tmpAttr; + } + int32_t axis_i32 = axis_attr.getInt(); + + std::optional> results = + convertUnpackOp(rewriter, op, tf_unpack_op.getValue(), axis_i32); + + if (!results) return failure(); + + rewriter.replaceOp(op, results.value()); + + return success(); +} + +// Splits in num_split parts along split_dim +LogicalResult ConvertTFSplitOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_split_op = cast(op); + + // Get the number of splits + int32_t num_split = -1; + + auto range = tf_split_op.getODSResults(0); + num_split = std::distance(range.begin(), range.end()); + + // Get the axis + int32_t axis = 0; + ElementsAttr axisAttrElems; + if (matchPattern(tf_split_op.getSplitDim(), m_Constant(&axisAttrElems))) { + axis = axisAttrElems.getValues()[0].getInt(); + } + + std::optional> results = + convertSplitOp(rewriter, op, tf_split_op.getResult(0), + tf_split_op.getValue(), num_split, axis); + + if (!results) return failure(); + + rewriter.replaceOp(op, results.value()); + + return success(); +} + +// TFSplitV op splits based on a vector of sizes +LogicalResult ConvertTFSplitVOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_splitv_op = cast(op); + + // Get the size_splits array + SmallVector size_split; + ElementsAttr size_split_elems; + if (!matchPattern(tf_splitv_op.getSizeSplits(), + m_Constant(&size_split_elems))) { + return failure(); + } + + for (int i = 0; i < size_split_elems.getNumElements(); i++) { + size_split.push_back(size_split_elems.getValues()[i].getInt()); + } + + // Get the axis + ElementsAttr axisAttrElems; + if (!matchPattern(tf_splitv_op.getSplitDim(), m_Constant(&axisAttrElems))) { + return rewriter.notifyMatchFailure(op, "cannot read split_dim elems"); + } + + int32_t axis = axisAttrElems.getValues()[0].getInt(); + + std::optional> results = + convertSplitVOp(rewriter, op, tf_splitv_op.getResult(0), + tf_splitv_op.getValue(), size_split, axis); + + if (!results) return failure(); + + rewriter.replaceOp(op, results.value()); + + return success(); +} + +LogicalResult ConvertTFLessOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_less_op = cast(op); + + TensorType output_type = + dyn_cast(tf_less_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + Value x = tf_less_op.getX(); + Value y = tf_less_op.getY(); + + // less(x, y) is not(greater_equal(x, y)) + auto greater_equal_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, x, y); + + auto not_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, greater_equal_op.getResult()); + + rewriter.replaceOp(op, {not_op.getResult()}); + return success(); +} + +LogicalResult ConvertTFLessEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_less_equal_op = cast(op); + + TensorType output_type = + dyn_cast(tf_less_equal_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + Value x = tf_less_equal_op.getX(); + Value y = tf_less_equal_op.getY(); + + // less_equal(x, y) is not(greater(x, y)) + auto greater_op = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, x, y); + + auto not_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, greater_op.getResult()); + + rewriter.replaceOp(op, {not_op.getResult()}); + return success(); +} + +LogicalResult ConvertTFPadOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_pad_op = cast(op); + + TensorType output_type = + dyn_cast(tf_pad_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + SmallVector padding_vals; + if (failed(getVectorFromValue64(tf_pad_op.getPaddings(), padding_vals))) { + return rewriter.notifyMatchFailure(op, "paddings is not a constant value"); + } + + Value padding = mlir::tosa::getTosaConstShape(rewriter, op->getLoc(), padding_vals); + + auto pad_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, tf_pad_op.getInput(), padding); + + rewriter.replaceOp(op, {pad_op.getResult()}); + return success(); +} + +LogicalResult ConvertTFPadV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_pad_op = cast(op); + + RankedTensorType output_type = + mlir::dyn_cast(tf_pad_op.getResult().getType()); + if (!output_type) { + return rewriter.notifyMatchFailure(op, "output type not a ranked tensor"); + } + + Value input = tf_pad_op.getInput(); + Value constant_value = tf_pad_op.getConstantValues(); + + Value rank1_scalar_value = + reshapeScalarTo1D(rewriter, op->getLoc(), constant_value); + if (!rank1_scalar_value) { + return rewriter.notifyMatchFailure( + op, "cannot reshape constant_value input to rank 1"); + } + + SmallVector padding_vals; + if (failed(getVectorFromValue64(tf_pad_op.getPaddings(), padding_vals))) { + return rewriter.notifyMatchFailure(op, "paddings is not a constant value"); + } + + Value padding = mlir::tosa::getTosaConstShape(rewriter, op->getLoc(), padding_vals); + + CreateReplaceOpAndInfer(rewriter, op, tf_pad_op.getType(), input, + padding, rank1_scalar_value); + + return success(); +} + +LogicalResult ConvertTFMirrorPadOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_mirrorpad_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_mirrorpad_op.getResult().getType()); + if (!output_type) { + return rewriter.notifyMatchFailure(op, "output type isn't a ranked tensor"); + } + + TFTFLMirrorPaddingType mode; + StringRef tf_mode = tf_mirrorpad_op.getMode(); + if (tf_mode == "REFLECT") { + mode = TFTFLMirrorPaddingType::REFLECT; + } else if (tf_mode == "SYMMETRIC") { + mode = TFTFLMirrorPaddingType::SYMMETRIC; + } else { + return rewriter.notifyMatchFailure( + op, "mode isn't one of REFLECT or SYMMETRIC"); + } + + std::optional result = convertMirrorPadCommon( + rewriter, op, output_type, tf_mirrorpad_op.getInput(), + tf_mirrorpad_op.getPaddings(), mode); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFResizeBilinearOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_resize_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_resize_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + std::optional result = convertResizeOp( + rewriter, op, output_type, tf_resize_op.getImages(), + tosa::ResizeMode::BILINEAR, + tf_resize_op.getAlignCornersAttr().getValue(), + tf_resize_op.getHalfPixelCentersAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFResizeNearestNeighborOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_resize_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tf_resize_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + std::optional result = + convertResizeOp(rewriter, op, output_type, tf_resize_op.getImages(), + tosa::ResizeMode::NEAREST_NEIGHBOR, + tf_resize_op.getAlignCornersAttr().getValue(), + tf_resize_op.getHalfPixelCentersAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFMatMulOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_matmul_op = cast(op); + + RankedTensorType a_type = + dyn_cast(tf_matmul_op.getA().getType()); + RankedTensorType b_type = + dyn_cast(tf_matmul_op.getB().getType()); + RankedTensorType output_type = + dyn_cast(tf_matmul_op.getResult().getType()); + + if (!(a_type && b_type && output_type)) { + return rewriter.notifyMatchFailure(op, "a/b/output not ranked tensors"); + } + + if (a_type.getRank() != b_type.getRank() || + a_type.getRank() != output_type.getRank()) { + return rewriter.notifyMatchFailure(op, "a/b/output rank must match"); + } + + // Can only handle rank 2 tensors for tf.MatMul. + // Cases with rank > 2 tensors should be handled by tf.BatchMatMul or + // tf.BatchMatMulV2 + if (a_type.getRank() != 2) { + return rewriter.notifyMatchFailure(op, "a/b/output rank must be 2"); + } + + SmallVector batch_a_shape( + {1, a_type.getShape()[0], a_type.getShape()[1]}); + SmallVector batch_b_shape( + {1, b_type.getShape()[0], b_type.getShape()[1]}); + SmallVector batch_output_shape( + {1, output_type.getShape()[0], output_type.getShape()[1]}); + + RankedTensorType batch_a_type = tensorflow::GetTypeFromTFTensorShape( + batch_a_shape, a_type.getElementType()); + RankedTensorType batch_b_type = tensorflow::GetTypeFromTFTensorShape( + batch_b_shape, b_type.getElementType()); + RankedTensorType batch_output_type = tensorflow::GetTypeFromTFTensorShape( + batch_output_shape, output_type.getElementType()); + + // Need to reshape input and output since TOSA matmul only supports + // [N, H, C] * [N, C, W] -> [N, H, W]. + auto batch_a_shape_value = getTosaConstShape(rewriter, op->getLoc(), batch_a_shape); + auto op1_reshape_a = CreateOpAndInfer( + rewriter, op->getLoc(), batch_a_type, tf_matmul_op.getA(), + batch_a_shape_value); + + auto batch_b_shape_value = getTosaConstShape(rewriter, op->getLoc(), batch_b_shape); + auto op2_reshape_b = CreateOpAndInfer( + rewriter, op->getLoc(), batch_b_type, tf_matmul_op.getB(), + batch_b_shape_value); + + auto op3_matmul_op1_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), batch_output_type, op1_reshape_a.getResult(), + op2_reshape_b.getResult()); + + auto output_shape_value = getTosaConstShape(rewriter, op->getLoc(), output_type.getShape()); + CreateReplaceOpAndInfer( + rewriter, op, output_type, op3_matmul_op1_op2.getResult(), + output_shape_value); + + return success(); +} + +LogicalResult ConvertTFGatherOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_gather_op = cast(op); + + // tf.Gather is equivalent to tf.GatherV2 with batch_dims = 0, axis = 0 + int32_t batch_dims = 0; + int32_t axis = 0; + + std::optional result = + convertGatherOp(rewriter, op, tf_gather_op.getParams(), + tf_gather_op.getIndices(), batch_dims, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFGatherV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_gather_op = cast(op); + + // Axis is a tensor. Pull out the one integer value. + ElementsAttr axis_elem; + if (!matchPattern(tf_gather_op.getAxis(), m_Constant(&axis_elem))) + return failure(); + assert(axis_elem.getNumElements() == 1); + + int32_t axis = axis_elem.getValues()[0].getInt(); + int32_t batch_dims = tf_gather_op.getBatchDimsAttr().getInt(); + + std::optional result = + convertGatherOp(rewriter, op, tf_gather_op.getParams(), + tf_gather_op.getIndices(), batch_dims, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFGatherNdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_gathernd_op = cast(op); + + std::optional result = convertGatherNdOp( + rewriter, op, tf_gathernd_op.getResult(), tf_gathernd_op.getParams(), + tf_gathernd_op.getIndices()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFScatterNdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_scatternd_op = cast(op); + + const std::optional result = convertScatterNdOp( + rewriter, op, tfl_scatternd_op.getResult(), tfl_scatternd_op.getIndices(), + tfl_scatternd_op.getUpdates(), tfl_scatternd_op.getShape()); + + if (!result) { + return failure(); + } + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSelectV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_sel_op = cast(op); + + std::optional result = convertSelectOp( + rewriter, op, tf_sel_op.getResult(), tf_sel_op.getCondition(), + tf_sel_op.getThenValue(), tf_sel_op.getElseValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSpaceToDepthOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_s2d_op = cast(op); + + std::optional result = convertSpaceToDepthOp( + rewriter, op, tf_s2d_op.getResult(), tf_s2d_op.getInput(), + tf_s2d_op.getBlockSizeAttr(), tf_s2d_op.getDataFormatAttr()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFDepthToSpaceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_d2s_op = cast(op); + + std::optional result = convertDepthToSpaceOp( + rewriter, op, tf_d2s_op.getResult(), tf_d2s_op.getInput(), + tf_d2s_op.getBlockSizeAttr(), tf_d2s_op.getDataFormatAttr()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSpaceToBatchNDOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_s2b_op = cast(op); + + std::optional result = convertSpaceToBatchNDOp( + rewriter, op, tf_s2b_op.getResult(), tf_s2b_op.getInput(), + tf_s2b_op.getBlockShape(), tf_s2b_op.getPaddings()); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFBatchToSpaceNDOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_b2s_op = cast(op); + + std::optional result = convertBatchToSpaceNDOp( + rewriter, op, tf_b2s_op.getResult(), tf_b2s_op.getInput(), + tf_b2s_op.getBlockShape(), tf_b2s_op.getCrops()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFStridedSliceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_ss_op = cast(op); + + std::optional result = convertStridedSliceOp( + rewriter, op, tf_ss_op.getResult(), tf_ss_op.getInput(), + tf_ss_op.getBegin(), tf_ss_op.getEnd(), tf_ss_op.getStrides(), + tf_ss_op.getBeginMaskAttr().getInt(), tf_ss_op.getEndMaskAttr().getInt(), + tf_ss_op.getEllipsisMaskAttr().getInt(), + tf_ss_op.getNewAxisMaskAttr().getInt(), + tf_ss_op.getShrinkAxisMaskAttr().getInt()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFZerosLikeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_zeroslike_op = cast(op); + + std::optional result = convertZerosLikeOp( + rewriter, op, tf_zeroslike_op.getResult(), tf_zeroslike_op.getX()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFSigmoidOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_sigmoid_op = cast(op); + TensorType output_type = + dyn_cast(tf_sigmoid_op.getResult().getType()); + if (!output_type) return failure(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_sigmoid_op.getX()); + + return success(); +} + +LogicalResult ConvertTFTanhOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_tanh_op = cast(op); + TensorType output_type = + dyn_cast(tf_tanh_op.getResult().getType()); + if (!output_type) return failure(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_tanh_op.getX()); + + return success(); +} + +LogicalResult ConvertTFLeakyReluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_leakyrelu_op = cast(op); + TensorType output_type = + dyn_cast(tf_leakyrelu_op.getResult().getType()); + if (!output_type) return failure(); + + // Implement LeakyRelu as element-wise: + // out = x > 0 ? x : alpha * x + // + // In TOSA ops: + // + // const_zero = constant(0) + // a1 = mul(x, alpha) + // a2 = greater_equal(x, const_zero) + // out = select(a2, x, a1) + // + // If alpha can be constrained to 0.0 <= alpha <= 1.0, then + // an alternative simpler lowering could be implemented with: + // + // max(mul(x, alapha), x) + // + // But this alternative is not robust unless alpha meets those constraints. + + if (!output_type.getElementType().isF32()) { + return rewriter.notifyMatchFailure(op, "only support F32"); + } + + FloatAttr tmpAttr = tf_leakyrelu_op.getAlphaAttr(); + // There is disagreement between the MLIR .td defaults and TF + // documentation on 0.2 vs 0.3, but 0.2 will be used here. + double alpha = 0.2; + + if (tmpAttr) { + alpha = tmpAttr.getValueAsDouble(); + } + + int rank = output_type.getRank(); + Value const_zero = getTosaConstTensorSingleF32(rewriter, op, 0.0, rank); + + auto a1_mul = CreateMulOpAndInfer( + rewriter, op, output_type, tf_leakyrelu_op.getFeatures(), + getTosaConstTensorSingleF32(rewriter, op, alpha, rank)); + + auto a2_ge = CreateOpAndInfer( + rewriter, op->getLoc(), UnrankedTensorType::get(rewriter.getI1Type()), + tf_leakyrelu_op.getFeatures(), const_zero); + + auto a3_select = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, a2_ge, tf_leakyrelu_op.getFeatures(), + a1_mul.getResult()); + + rewriter.replaceOp(op, {a3_select.getResult()}); + + return success(); +} + +LogicalResult ConvertTFNegOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + auto tf_neg_op = cast(op); + TensorType output_type = + dyn_cast(tf_neg_op.getResult().getType()); + if (!output_type) return failure(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_neg_op.getX()); + + return success(); +} + +LogicalResult ConvertTFStopGradientOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_stopgrad_op = cast(op); + TensorType output_type = + dyn_cast(tf_stopgrad_op.getResult().getType()); + if (!output_type) return failure(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_stopgrad_op.getInput()); + + return success(); +} + +LogicalResult ConvertTFReverseV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_reverse_op = cast(op); + RankedTensorType input_type = + dyn_cast(tf_reverse_op.getTensor().getType()); + TensorType output_type = + dyn_cast(tf_reverse_op.getResult().getType()); + if (!input_type || !output_type) return failure(); + + ElementsAttr axis_elems; + if (!matchPattern(tf_reverse_op.getAxis(), m_Constant(&axis_elems))) + return failure(); + + auto input_rank = input_type.getShape().size(); + Value val = tf_reverse_op.getTensor(); + if (axis_elems.getNumElements() == 0) { + auto identity_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, val); + val = identity_op.getResult(); + } else { + for (int i = 0; i < axis_elems.getNumElements(); i++) { + int64_t axis_val = axis_elems.getValues()[i].getInt(); + if (axis_val < 0) axis_val += input_rank; + auto axis_attr = rewriter.getI32IntegerAttr(axis_val); + auto reverse_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, val, axis_attr); + + val = reverse_op.getResult(); + } + } + + rewriter.replaceOp(op, {val}); + + return success(); +} + +LogicalResult ConvertTFFakeQuantWithMinMaxArgsOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_fakequant_op = cast(op); + + TensorType output_type = + dyn_cast(tf_fakequant_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + std::optional result = + convertFakeQuantOp(rewriter, op, output_type, tf_fakequant_op.getInputs(), + tf_fakequant_op.getMinAttr().getValueAsDouble(), + tf_fakequant_op.getMaxAttr().getValueAsDouble(), + tf_fakequant_op.getNumBitsAttr().getInt(), + tf_fakequant_op.getNarrowRangeAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFFakeQuantWithMinMaxVarsOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_fakequant_op = cast(op); + + TensorType output_type = + dyn_cast(tf_fakequant_op.getResult().getType()); + // Not a tensor output + if (!output_type) return failure(); + + // Only support min/max that can be matched at compile time + ElementsAttr min_elems, max_elems; + if (!matchPattern(tf_fakequant_op.getMin(), m_Constant(&min_elems))) + return failure(); + + if (!matchPattern(tf_fakequant_op.getMax(), m_Constant(&max_elems))) + return failure(); + + if (min_elems.getNumElements() != 1 && max_elems.getNumElements() != 1) + return failure(); + + int64_t min_val = min_elems.getValues()[0].getInt(); + int64_t max_val = max_elems.getValues()[0].getInt(); + + std::optional result = convertFakeQuantOp( + rewriter, op, output_type, tf_fakequant_op.getInputs(), min_val, max_val, + tf_fakequant_op.getNumBitsAttr().getInt(), + tf_fakequant_op.getNarrowRangeAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLeftShiftOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_left_shift_op = cast(op); + + TensorType output_type = + dyn_cast(tf_left_shift_op.getResult().getType()); + if (!output_type) return failure(); + + Value x = tf_left_shift_op.getX(); + Value y = tf_left_shift_op.getY(); + + RankedTensorType x_type = dyn_cast(x.getType()); + RankedTensorType y_type = dyn_cast(y.getType()); + if (!x_type || !y_type) return failure(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + x, y); + + return success(); +} + +LogicalResult ConvertTFRightShiftOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + // Performs a logical shift for unsigned integer types, and an arithmetic + // shift for signed integer types. + auto tf_right_shift_op = cast(op); + + TensorType output_type = + dyn_cast(tf_right_shift_op.getResult().getType()); + if (!output_type) return failure(); + + Value x = tf_right_shift_op.getX(); + Value y = tf_right_shift_op.getY(); + + RankedTensorType x_type = dyn_cast(x.getType()); + RankedTensorType y_type = dyn_cast(y.getType()); + if (!x_type || !y_type) return failure(); + + Type output_element_type = output_type.getElementType(); + + bool is_signed = false; + if (!output_element_type.isUnsignedInteger()) is_signed = true; + + if (is_signed) { + CreateReplaceOpAndInfer( + rewriter, op, output_type, x, y, false); + } else { + CreateReplaceOpAndInfer(rewriter, op, + output_type, x, y); + } + + return success(); +} + +LogicalResult ConvertTFOneHotOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_one_hot_op = cast(op); + + ElementsAttr depth_elems; + if (!matchPattern(tf_one_hot_op.getDepth(), m_Constant(&depth_elems))) + return failure(); + int32_t depth = depth_elems.getValues()[0].getInt(); + + IntegerAttr axisAttr = tf_one_hot_op.getAxisAttr(); + int32_t axis = axisAttr.getInt(); + + std::optional result = convertOneHotOp( + rewriter, op, tf_one_hot_op.getResult(), tf_one_hot_op.getIndices(), + tf_one_hot_op.getOnValue(), tf_one_hot_op.getOffValue(), depth, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFBatchMatMulV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_batch_matmul_op = cast(op); + + RankedTensorType x_type = + dyn_cast(tf_batch_matmul_op.getX().getType()); + RankedTensorType y_type = + dyn_cast(tf_batch_matmul_op.getY().getType()); + RankedTensorType output_type = + dyn_cast(tf_batch_matmul_op.getResult().getType()); + + if (!(x_type && y_type && output_type)) { + return rewriter.notifyMatchFailure(op, "x/y/output not ranked tensors"); + } + + if (x_type.getRank() != y_type.getRank() || + x_type.getRank() != output_type.getRank()) { + return rewriter.notifyMatchFailure(op, "x/y/output rank must match"); + } + + if (x_type.getRank() <= 2) { + return rewriter.notifyMatchFailure(op, "x/y/output rank must > 2"); + } + + // Rank 3 batch matmul can be directly mapped to tosa.matmul trivially. + if (x_type.getRank() == 3) { + CreateReplaceOpAndInfer(rewriter, op, output_type, + tf_batch_matmul_op.getX(), + tf_batch_matmul_op.getY()); + } else { + // 1. Reshape x from: (similar for y) + // [a0, a1, ... an, H, C] to [N, H, C]. + // where N = a0 * a1 * ... * an. + // 2. tosa.MatMul + // [N, H, C] * [N, C, W] -> [N, H, W]. + // 3. Reshape output from: + // [N, H, W] to [a0, a1, ... , an, H, W] + int64_t rank = x_type.getRank(); + int64_t N = 1; + for (int i = 0; i < (rank - 2); i++) { + N *= x_type.getShape()[i]; + } + int64_t H = x_type.getShape()[rank - 2]; + int64_t C = x_type.getShape()[rank - 1]; + int64_t W = y_type.getShape()[rank - 1]; + + SmallVector rank3_x_shape({N, H, C}); + SmallVector rank3_y_shape({N, C, W}); + SmallVector rank3_output_shape({N, H, W}); + + RankedTensorType rank3_x_type = tensorflow::GetTypeFromTFTensorShape( + rank3_x_shape, x_type.getElementType()); + RankedTensorType rank3_y_type = tensorflow::GetTypeFromTFTensorShape( + rank3_y_shape, y_type.getElementType()); + RankedTensorType rank3_output_type = tensorflow::GetTypeFromTFTensorShape( + rank3_output_shape, output_type.getElementType()); + + auto rank3_x_shape_value = getTosaConstShape(rewriter, op->getLoc(), rank3_x_shape); + auto op1_reshape_x = CreateOpAndInfer( + rewriter, op->getLoc(), rank3_x_type, tf_batch_matmul_op.getX(), + rank3_x_shape_value); + + auto rank3_y_shape_value = getTosaConstShape(rewriter, op->getLoc(), rank3_y_shape); + auto op2_reshape_y = CreateOpAndInfer( + rewriter, op->getLoc(), rank3_y_type, tf_batch_matmul_op.getY(), + rank3_y_shape_value); + + auto op3_matmul_op1_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), rank3_output_type, op1_reshape_x.getResult(), + op2_reshape_y.getResult()); + + auto output_shape_value = getTosaConstShape(rewriter, op->getLoc(), output_type.getShape()); + CreateReplaceOpAndInfer( + rewriter, op, output_type, op3_matmul_op1_op2.getResult(), + output_shape_value); + } + return success(); +} + +LogicalResult ConvertTFBroadcastToOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tf_broadcast_to_op = cast(op); + + std::optional result = + convertBroadcastToOp(rewriter, op, tf_broadcast_to_op.getInput(), + tf_broadcast_to_op.getShape()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFGreaterOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFGreaterEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFMaximumOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFMinimumOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFBitwiseOrOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFBitwiseXorOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFBitwiseAndOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFLogicalAndOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFLogicalOrOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFPowOp::matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +void LegalizeTF::runOnOperation() { + auto* ctx = &getContext(); + RewritePatternSet patterns(ctx); + auto func = getOperation(); + populateLegalizeTFPatterns(ctx, patterns); + + if (ApplyPatternsWithShapeResolution(func, std::move(patterns)).failed()) { + signalPassFailure(); + } +} + +} // anonymous namespace + +void populateLegalizeTFPatterns(MLIRContext* ctx, RewritePatternSet& patterns) { + // Add the generated patterns to the list. + populateWithGenerated(patterns); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); + patterns.add(ctx); +} + +// Creates an instance of the TensorFlow dialect LegalizeTF pass. +std::unique_ptr> createLegalizeTFPass() { + return std::make_unique(); +} + +} // namespace tosa + +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tf_tfl.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tf_tfl.cc new file mode 100644 index 0000000000000000000000000000000000000000..937bdf26ea0e5fd899ab2340e34b1c0e667598bc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tf_tfl.cc @@ -0,0 +1,68 @@ +/* Copyright 2021 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. +==============================================================================*/ + +// Legalize TensorFlow and TensorFlow Lite to TOSA + +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +namespace mlir { +namespace tosa { + +namespace { + +#define GEN_PASS_DEF_TOSALEGALIZETFTFLPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +// Performs lowering to TOSA dialect +class LegalizeTFTFL : public impl::TosaLegalizeTFTFLPassBase { + public: + explicit LegalizeTFTFL() = default; + void runOnOperation() override; +}; + +void LegalizeTFTFL::runOnOperation() { + MLIRContext* ctx = &getContext(); + RewritePatternSet patterns(ctx); + populateLegalizeTFPatterns(ctx, patterns); + populateLegalizeTFLPatterns(ctx, patterns); + + func::FuncOp func = getOperation(); + if (ApplyPatternsWithShapeResolution(func, std::move(patterns)).failed()) { + signalPassFailure(); + } +} + +} // anonymous namespace + +// Creates an instance of the TensorFlow Lite dialect LegalizeTFL pass. +std::unique_ptr> createLegalizeTFTFLPass() { + return std::make_unique(); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tfl.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tfl.cc new file mode 100644 index 0000000000000000000000000000000000000000..4af3663e16a816de947a36684b7a9bd3fd472b1b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tfl.cc @@ -0,0 +1,5173 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// Legalize TensorFlow Lite to TOSA + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "llvm/ADT/ArrayRef.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Quant/IR/QuantTypes.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/QuantUtils.h" +#include "mlir/IR/Block.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributeInterfaces.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/Matchers.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/IR/Region.h" // from @llvm-project +#include "mlir/IR/TypeUtilities.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/IR/ValueRange.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/dynamic_shape_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" +#include "tensorflow/lite/kernels/internal/reference/gelu.h" + +#define PASS_NAME "tosa-legalize-tfl" +#define DEBUG_TYPE PASS_NAME +#define HARDSWISH_EXPLICIT_RESCALING false + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSALEGALIZETFLPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +// Performs lowering to TOSA dialect. +class LegalizeTFL : public impl::TosaLegalizeTFLPassBase { + public: + LegalizeTFL() = default; + explicit LegalizeTFL(ArrayRef disabled_patterns, + ArrayRef enabled_patterns) { + this->disabled_patterns_ = disabled_patterns; + this->enabled_patterns_ = enabled_patterns; + } + void runOnOperation() override; + LogicalResult initialize(MLIRContext* context) override; + + private: + FrozenRewritePatternSet frozen_patterns_; +}; + +#include "tensorflow/compiler/mlir/tosa/transforms/tfl_legalize_patterns.inc" + +// Input from tfl.conv2d takes 64 bits a bias, while tosa.conv2d expects 48 +// bits. Need to do a customized truncate here instead of tablegen to handle +// attribute with negative value. +struct ConvertConstantOp : public RewritePattern { + explicit ConvertConstantOp(MLIRContext* context) + : RewritePattern(arith::ConstantOp::getOperationName(), 1, context) {} + LogicalResult matchAndRewrite(Operation* op, + PatternRewriter& rewriter) const override; +}; + +#define DECL_CONVERT_OP(tfl_op) \ + struct ConvertTFL##tfl_op##Op : public RewritePattern { \ + explicit ConvertTFL##tfl_op##Op(MLIRContext* context) \ + : RewritePattern(TFL::tfl_op##Op::getOperationName(), 1, context) {} \ + LogicalResult matchAndRewrite(Operation* op, \ + PatternRewriter& rewriter) const override; \ + } +DECL_CONVERT_OP(Gelu); +DECL_CONVERT_OP(Relu); +DECL_CONVERT_OP(Relu1); +DECL_CONVERT_OP(Relu0To1); +DECL_CONVERT_OP(Relu6); +DECL_CONVERT_OP(Equal); +DECL_CONVERT_OP(NotEqual); +DECL_CONVERT_OP(Greater); +DECL_CONVERT_OP(GreaterEqual); +DECL_CONVERT_OP(Add); +DECL_CONVERT_OP(Sub); +DECL_CONVERT_OP(Mul); +DECL_CONVERT_OP(Square); +DECL_CONVERT_OP(SquaredDifference); +DECL_CONVERT_OP(Cast); +DECL_CONVERT_OP(Sign); +DECL_CONVERT_OP(Round); +DECL_CONVERT_OP(Div); +DECL_CONVERT_OP(Maximum); +DECL_CONVERT_OP(Minimum); +DECL_CONVERT_OP(FloorMod); +DECL_CONVERT_OP(FloorDiv); +DECL_CONVERT_OP(AddN); +DECL_CONVERT_OP(AveragePool2D); +DECL_CONVERT_OP(MaxPool2D); +DECL_CONVERT_OP(Concatenation); +DECL_CONVERT_OP(Reshape); +DECL_CONVERT_OP(Rank); +DECL_CONVERT_OP(Shape); +DECL_CONVERT_OP(ExpandDims); +DECL_CONVERT_OP(Squeeze); +DECL_CONVERT_OP(Fill); +DECL_CONVERT_OP(Elu); +DECL_CONVERT_OP(Softmax); +DECL_CONVERT_OP(LogSoftmax); +DECL_CONVERT_OP(Rsqrt); +DECL_CONVERT_OP(Sqrt); +DECL_CONVERT_OP(L2Normalization); +DECL_CONVERT_OP(ReduceAll); +DECL_CONVERT_OP(ReduceAny); +DECL_CONVERT_OP(ReduceMax); +DECL_CONVERT_OP(ReduceMin); +DECL_CONVERT_OP(Mean); +DECL_CONVERT_OP(ReduceProd); +DECL_CONVERT_OP(Sum); +DECL_CONVERT_OP(Conv2D); +DECL_CONVERT_OP(Conv3D); +DECL_CONVERT_OP(TransposeConv); +DECL_CONVERT_OP(DepthwiseConv2D); +DECL_CONVERT_OP(FullyConnected); +DECL_CONVERT_OP(BatchMatMul); +DECL_CONVERT_OP(Split); +DECL_CONVERT_OP(SplitV); +DECL_CONVERT_OP(Pack); +DECL_CONVERT_OP(Unpack); +DECL_CONVERT_OP(Transpose); +DECL_CONVERT_OP(Tile); +DECL_CONVERT_OP(Slice); +DECL_CONVERT_OP(StridedSlice); +DECL_CONVERT_OP(HardSwish); +DECL_CONVERT_OP(ZerosLike); +DECL_CONVERT_OP(Less); +DECL_CONVERT_OP(LessEqual); +DECL_CONVERT_OP(Pad); +DECL_CONVERT_OP(MirrorPad); +DECL_CONVERT_OP(PadV2); +DECL_CONVERT_OP(ResizeBilinear); +DECL_CONVERT_OP(ResizeNearestNeighbor); +DECL_CONVERT_OP(Select); +DECL_CONVERT_OP(SelectV2); +DECL_CONVERT_OP(SpaceToBatchNd); +DECL_CONVERT_OP(BatchToSpaceNd); +DECL_CONVERT_OP(SpaceToDepth); +DECL_CONVERT_OP(DepthToSpace); +DECL_CONVERT_OP(Bucketize); +DECL_CONVERT_OP(Sin); +DECL_CONVERT_OP(Cos); +DECL_CONVERT_OP(Atan2); +DECL_CONVERT_OP(Logistic); +DECL_CONVERT_OP(Tanh); +DECL_CONVERT_OP(PRelu); +DECL_CONVERT_OP(LeakyRelu); +DECL_CONVERT_OP(Neg); +DECL_CONVERT_OP(Yield); +DECL_CONVERT_OP(Custom); +DECL_CONVERT_OP(ReverseV2); +DECL_CONVERT_OP(Quantize); +DECL_CONVERT_OP(Dequantize); +DECL_CONVERT_OP(Const); +DECL_CONVERT_OP(QConst); +DECL_CONVERT_OP(Gather); +DECL_CONVERT_OP(GatherNd); +DECL_CONVERT_OP(ScatterNd); +DECL_CONVERT_OP(SparseToDense); +DECL_CONVERT_OP(OneHot); +DECL_CONVERT_OP(ArgMax); +DECL_CONVERT_OP(ArgMin); +DECL_CONVERT_OP(FakeQuant); +DECL_CONVERT_OP(While); +DECL_CONVERT_OP(Real); +DECL_CONVERT_OP(Imag); +DECL_CONVERT_OP(RFFT2d); +DECL_CONVERT_OP(LogicalAnd); +DECL_CONVERT_OP(LogicalOr); +DECL_CONVERT_OP(BitwiseXor); +DECL_CONVERT_OP(Pow); +DECL_CONVERT_OP(BroadcastTo); +DECL_CONVERT_OP(Exp); +DECL_CONVERT_OP(Log); + +#undef DECL_CONVERT_OP + +LogicalResult ConvertTFLGeluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_gelu_op = cast(op); + Location loc = op->getLoc(); + + auto approximate = tfl_gelu_op.getApproximateAttr().getValue(); + + Value input = tfl_gelu_op.getInput(); + RankedTensorType input_type = dyn_cast(input.getType()); + RankedTensorType output_type = + dyn_cast(tfl_gelu_op.getResult().getType()); + if (!input_type || !output_type) { + return rewriter.notifyMatchFailure( + op, "input/output are not all a ranked tensor"); + } + + UniformQuantizedType in_quant_type = + dyn_cast(input_type.getElementType()); + UniformQuantizedType out_quant_type = + dyn_cast(output_type.getElementType()); + + if ((in_quant_type == nullptr) != (out_quant_type == nullptr)) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + if (out_quant_type) { + if (in_quant_type.getStorageTypeIntegralWidth() != 8) { + return rewriter.notifyMatchFailure( + op, "current tfl.gelu only support 8-bit quantized type"); + } + + Value table_const = getTosaConst8bitTable( + rewriter, op, in_quant_type.getScale(), in_quant_type.getZeroPoint(), + out_quant_type.getScale(), out_quant_type.getZeroPoint(), + approximate ? tflite::reference_ops::GeluTransformApproximate + : tflite::reference_ops::GeluTransform); + + CreateReplaceOpAndInfer(rewriter, op, output_type, input, + table_const); + return success(); + } + + // Following approximated implemention described in + // tensorflow/lite/kernels/internal/reference/gelu.h + // + // gelu(x) = 0.5 * x * (1 + tanh(sqrt(2/pi) * (x + 0.044715 * x^3))) + // + // Lower the formula to the sequence of operators below: + // op0 = pow(x, 3) + // op1 = mul(op0, 0.044715) + // op2 = add(x, op1) + // op3 = mul(op2, sqrt(2/pi)) + // op4 = tanh(op3) + // op5 = add(op4 ,1) + // op6 = mul(x, 0.5) + // op7 = mul(op6, op5) + + auto rank = input_type.getRank(); + Value cst_3 = getTosaConstTensorSingleF32(rewriter, op, 3.0f, rank); + auto op0_pow_3 = + CreateOpAndInfer(rewriter, loc, output_type, input, cst_3); + + Value cst_004 = + getTosaConstTensorSingleF32(rewriter, op, 4.471500e-02f, rank); + auto op1_mul_op0_004 = + CreateMulOpAndInfer(rewriter, op, output_type, op0_pow_3, cst_004); + + auto op2_add_x_op1 = CreateOpAndInfer(rewriter, loc, output_type, + input, op1_mul_op0_004); + + Value cst_sqrt2pi = + getTosaConstTensorSingleF32(rewriter, op, 0.797884583f, rank); + auto op3_mul_op2_sqrt2pi = CreateMulOpAndInfer(rewriter, op, output_type, + op2_add_x_op1, cst_sqrt2pi); + + auto op4_tanh_op3 = CreateOpAndInfer(rewriter, loc, output_type, + op3_mul_op2_sqrt2pi); + + Value cst_1 = getTosaConstTensorSingleF32(rewriter, op, 1.0f, rank); + auto op5_add_op4_1 = CreateOpAndInfer(rewriter, loc, output_type, + op4_tanh_op3, cst_1); + + Value cst_05 = getTosaConstTensorSingleF32(rewriter, op, 0.5f, rank); + auto op6_mul_x_05 = + CreateMulOpAndInfer(rewriter, op, output_type, input, cst_05); + + auto op7_mul_op6_op5 = CreateMulOpAndInfer(rewriter, op, output_type, + op6_mul_x_05, op5_add_op4_1); + + rewriter.replaceOp(op, {op7_mul_op6_op5.getResult()}); + + return success(); +} + +LogicalResult ConvertTFLReluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_relu_op = cast(op); + + ShapedType input_type = dyn_cast(tfl_relu_op.getX().getType()); + ShapedType output_type = + dyn_cast(tfl_relu_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type || !output_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + int64_t clamp_min = 0; + int64_t clamp_max = std::numeric_limits::max(); + Value clamp_in = tfl_relu_op.getX(); + + if (output_is_qtype) { + UniformQuantizedType input_qtype = + dyn_cast( + input_type.getElementType()); + UniformQuantizedType output_qtype = + dyn_cast( + output_type.getElementType()); + + clamp_min = output_qtype.getZeroPoint(); + TrimQuantizedIntegerRangeMin(input_qtype, clamp_min); + TrimQuantizedIntegerRangeMax(input_qtype, clamp_max); + + clamp_in = + buildRescale(rewriter, op, output_type, tfl_relu_op.getX(), + input_qtype.getScale() / output_qtype.getScale(), + input_qtype.getZeroPoint(), output_qtype.getZeroPoint(), + /*double_round=*/tosa::RoundingMode::SINGLE_ROUND, /*scale32=*/true); + } + + auto element_type = input_type.getElementType(); + if (auto quant_type = + dyn_cast(element_type)) { + element_type = + tosa::getStorageElementTypeFromQuantized(quant_type); + } + + mlir::Attribute min_val, max_val; + if (mlir::isa(element_type)) { + min_val = rewriter.getFloatAttr(element_type, 0.0f); + max_val = + rewriter.getFloatAttr(element_type, std::numeric_limits::max()); + } else { + min_val = rewriter.getIntegerAttr(element_type, clamp_min); + max_val = rewriter.getIntegerAttr(element_type, clamp_max); + } + + CreateReplaceOpAndInfer(rewriter, op, output_type, clamp_in, + min_val, max_val); + + return success(); +} + +LogicalResult ConvertTFLRelu1Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_relu1_op = cast(op); + + ShapedType input_type = dyn_cast(tfl_relu1_op.getX().getType()); + ShapedType output_type = + dyn_cast(tfl_relu1_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type || !output_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + int64_t clamp_min = -1; + int64_t clamp_max = 1; + Value clamp_in = tfl_relu1_op.getX(); + + if (output_is_qtype && input_is_qtype) { + UniformQuantizedType input_qtype = + dyn_cast( + input_type.getElementType()); + UniformQuantizedType output_qtype = + dyn_cast( + output_type.getElementType()); + + clamp_min = output_qtype.getZeroPoint() - + std::llround(1.0f / output_qtype.getScale()); + + clamp_max = std::llround(1.0f / output_qtype.getScale()) + + output_qtype.getZeroPoint(); + + TrimQuantizedIntegerRange(input_qtype, clamp_min, clamp_max); + + clamp_in = + buildRescale(rewriter, op, output_type, tfl_relu1_op.getX(), + input_qtype.getScale() / output_qtype.getScale(), + input_qtype.getZeroPoint(), output_qtype.getZeroPoint(), + /*double_round=*/tosa::RoundingMode::SINGLE_ROUND, /*scale32=*/true); + } + + auto element_type = input_type.getElementType(); + if (auto quant_type = + dyn_cast(element_type)) { + element_type = tosa::getStorageElementTypeFromQuantized(quant_type); + } + + mlir::Attribute min_val, max_val; + if (mlir::isa(element_type)) { + min_val = rewriter.getFloatAttr(element_type, -1.0f); + max_val = rewriter.getFloatAttr(element_type, 1.0f); + } else { + min_val = rewriter.getIntegerAttr(element_type, clamp_min); + max_val = rewriter.getIntegerAttr(element_type, clamp_max); + } + + CreateReplaceOpAndInfer(rewriter, op, output_type, clamp_in, + min_val, max_val); + + return success(); +} + +LogicalResult ConvertTFLRelu0To1Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_relu0to1_op = cast(op); + + ShapedType input_type = + mlir::cast(tfl_relu0to1_op.getX().getType()); + ShapedType output_type = + mlir::cast(tfl_relu0to1_op.getResult().getType()); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + int64_t clamp_min = 0; + int64_t clamp_max = 1; + Value clamp_in = tfl_relu0to1_op.getX(); + + if (output_is_qtype && input_is_qtype) { + UniformQuantizedType input_qtype = + mlir::cast( + input_type.getElementType()); + UniformQuantizedType output_qtype = + mlir::cast( + output_type.getElementType()); + + clamp_min = output_qtype.getZeroPoint(); + + clamp_max = std::llround(1.0f / output_qtype.getScale()) + + output_qtype.getZeroPoint(); + + TrimQuantizedIntegerRange(input_qtype, clamp_min, clamp_max); + + clamp_in = + buildRescale(rewriter, op, output_type, tfl_relu0to1_op.getX(), + input_qtype.getScale() / output_qtype.getScale(), + input_qtype.getZeroPoint(), output_qtype.getZeroPoint(), + /*double_round=*/tosa::RoundingMode::SINGLE_ROUND, /*scale32=*/true); + } + + auto element_type = input_type.getElementType(); + if (auto quant_type = + dyn_cast(element_type)) { + element_type = tosa::getStorageElementTypeFromQuantized(quant_type); + } + + mlir::Attribute min_val, max_val; + if (mlir::isa(element_type)) { + min_val = rewriter.getFloatAttr(element_type, 0.0f); + max_val = rewriter.getFloatAttr(element_type, 1.0f); + } else { + min_val = rewriter.getIntegerAttr(element_type, clamp_min); + max_val = rewriter.getIntegerAttr(element_type, clamp_max); + } + + CreateReplaceOpAndInfer(rewriter, op, output_type, clamp_in, + min_val, max_val); + + return success(); +} + +LogicalResult ConvertTFLRelu6Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_relu6_op = cast(op); + + ShapedType input_type = dyn_cast(tfl_relu6_op.getX().getType()); + ShapedType output_type = + dyn_cast(tfl_relu6_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type || !output_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + int64_t clamp_min = 0; + int64_t clamp_max = 6; + Value clamp_in = tfl_relu6_op.getX(); + + if (output_is_qtype && input_is_qtype) { + UniformQuantizedType input_qtype = + dyn_cast( + input_type.getElementType()); + UniformQuantizedType output_qtype = + dyn_cast( + output_type.getElementType()); + + clamp_min = output_qtype.getZeroPoint(); + clamp_max = std::llround(6.0f / output_qtype.getScale()) + + output_qtype.getZeroPoint(); + + TrimQuantizedIntegerRange(input_qtype, clamp_min, clamp_max); + + clamp_in = + buildRescale(rewriter, op, output_type, tfl_relu6_op.getX(), + input_qtype.getScale() / output_qtype.getScale(), + input_qtype.getZeroPoint(), output_qtype.getZeroPoint(), + /*double_round=*/tosa::RoundingMode::SINGLE_ROUND, /*scale32=*/true); + } + + auto element_type = input_type.getElementType(); + if (auto quant_type = + dyn_cast(element_type)) { + element_type = tosa::getStorageElementTypeFromQuantized(quant_type); + } + + mlir::Attribute min_val, max_val; + if (mlir::isa(element_type)) { + min_val = rewriter.getFloatAttr(element_type, 0.0f); + max_val = rewriter.getFloatAttr(element_type, 6.0f); + } else { + min_val = rewriter.getIntegerAttr(element_type, clamp_min); + max_val = rewriter.getIntegerAttr(element_type, clamp_max); + } + + CreateReplaceOpAndInfer(rewriter, op, output_type, clamp_in, + min_val, max_val); + + return success(); +} + +static LogicalResult prepareMatchAndRewriteComparison( + Operation* op, mlir::OperandRange operands, PatternRewriter& rewriter, + llvm::SmallVectorImpl& newOperands) { + Value x = operands[0]; + Value y = operands[1]; + Value result = op->getResult(0); + + ShapedType input_x_type = dyn_cast(x.getType()); + ShapedType input_y_type = dyn_cast(y.getType()); + ShapedType output_type = dyn_cast(result.getType()); + // Not a shaped tensor output + if (!input_x_type || !input_y_type || !output_type) return failure(); + + bool input_x_is_qtype = mlir::isa( + input_x_type.getElementType()); + bool input_y_is_qtype = mlir::isa( + input_y_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_x_is_qtype != input_y_is_qtype || + input_y_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + if (!output_is_qtype && !input_x_is_qtype && !input_y_is_qtype) { + newOperands.push_back(x); + newOperands.push_back(y); + return success(); + } + + UniformQuantizedType input_x_qtype = + dyn_cast( + input_x_type.getElementType()); + UniformQuantizedType input_y_qtype = + dyn_cast( + input_y_type.getElementType()); + + if (input_x_qtype.getScale() != input_y_qtype.getScale() || + input_x_qtype.getZeroPoint() != input_y_qtype.getZeroPoint()) { + return rewriter.notifyMatchFailure( + op, "input_x and input_y scale/zp must be the same"); + } + + x = removeZeroPointAndCastToInt32(rewriter, op, x, + input_x_qtype.getZeroPoint()); + y = removeZeroPointAndCastToInt32(rewriter, op, y, + input_y_qtype.getZeroPoint()); + + newOperands.push_back(x); + newOperands.push_back(y); + return success(); +} + +LogicalResult ConvertTFLEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + llvm::SmallVector newOperands; + LogicalResult status = prepareMatchAndRewriteComparison( + op, op->getOperands(), rewriter, newOperands); + if (status.failed()) return failure(); + + CreateReplaceOpAndInfer( + rewriter, op, op->getResult(0).getType(), newOperands[0], newOperands[1]); + + return success(); +} + +LogicalResult ConvertTFLNotEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + llvm::SmallVector newOperands; + LogicalResult status = prepareMatchAndRewriteComparison( + op, op->getOperands(), rewriter, newOperands); + if (status.failed()) return failure(); + + auto equal_op = CreateOpAndInfer( + rewriter, op->getLoc(), op->getResult(0).getType(), newOperands[0], + newOperands[1]); + + CreateReplaceOpAndInfer( + rewriter, op, op->getResult(0).getType(), equal_op); + + return success(); +} + +LogicalResult ConvertTFLGreaterOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + llvm::SmallVector newOperands; + LogicalResult status = prepareMatchAndRewriteComparison( + op, op->getOperands(), rewriter, newOperands); + if (status.failed()) return failure(); + + CreateReplaceOpAndInfer( + rewriter, op, op->getResult(0).getType(), newOperands[0], newOperands[1]); + + return success(); +} + +LogicalResult ConvertTFLGreaterEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + llvm::SmallVector newOperands; + LogicalResult status = prepareMatchAndRewriteComparison( + op, op->getOperands(), rewriter, newOperands); + if (status.failed()) return failure(); + + CreateReplaceOpAndInfer( + rewriter, op, op->getResult(0).getType(), newOperands[0], newOperands[1]); + + return success(); +} + +LogicalResult ConvertTFLLessOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + llvm::SmallVector newOperands; + LogicalResult status = prepareMatchAndRewriteComparison( + op, op->getOperands(), rewriter, newOperands); + if (status.failed()) return failure(); + + CreateReplaceOpAndInfer( + rewriter, op, op->getResult(0).getType(), newOperands[1], newOperands[0]); + return success(); +} + +LogicalResult ConvertTFLLessEqualOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + llvm::SmallVector newOperands; + LogicalResult status = prepareMatchAndRewriteComparison( + op, op->getOperands(), rewriter, newOperands); + if (status.failed()) return failure(); + + // Swapping the args handles the greater/less difference. + CreateReplaceOpAndInfer( + rewriter, op, op->getResult(0).getType(), newOperands[1], newOperands[0]); + + return success(); +} + +template +static LogicalResult matchAndRewriteAddSub(Operation* op, + mlir::OperandRange operands, + PatternRewriter& rewriter) { + auto tfl_add_op = cast(op); + + Value lhs = tfl_add_op.getLhs(); + Value rhs = tfl_add_op.getRhs(); + + ShapedType input_lhs_type = mlir::dyn_cast(lhs.getType()); + ShapedType input_rhs_type = mlir::dyn_cast(rhs.getType()); + ShapedType output_type = + mlir::dyn_cast(tfl_add_op.getResult().getType()); + if (!input_lhs_type || !input_rhs_type || !output_type) return failure(); + + bool input_lhs_is_qtype = mlir::isa( + input_lhs_type.getElementType()); + bool input_rhs_is_qtype = mlir::isa( + input_rhs_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_lhs_is_qtype != output_is_qtype || + input_rhs_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + Value output; + if (output_is_qtype && input_lhs_is_qtype && input_rhs_is_qtype) { + ShapedType rescale_type_output = output_type.clone(rewriter.getI32Type()); + ShapedType rescale_type_input_left = + input_lhs_type.clone(rewriter.getI32Type()); + ShapedType rescale_type_input_right = + input_rhs_type.clone(rewriter.getI32Type()); + + UniformQuantizedType input_lhs_qtype = + dyn_cast( + input_lhs_type.getElementType()); + UniformQuantizedType input_rhs_qtype = + dyn_cast( + input_rhs_type.getElementType()); + UniformQuantizedType output_qtype = + dyn_cast( + output_type.getElementType()); + + // Following quantization described in tensorflow/lite/kernels/add.cc + // In details it does: + // 1. Rescale inputs to scale = 2.0 x max(lhs.scale, rhs.scale) + // 2. Extra left shift to input to increase precision + // Where input_shift = 20 if input is 8-bit + // input_shift = 15 if input is 16-bit + double in_lhs_scale = input_lhs_qtype.getScale(); + double in_rhs_scale = input_rhs_qtype.getScale(); + double output_scale = output_qtype.getScale(); + double max_scale_2x = 2.0 * std::max(in_lhs_scale, in_rhs_scale); + + const int32_t SHIFT_8_BIT = 20; + const int32_t SHIFT_16_BIT = 15; + + int32_t input_shift = (output_qtype.getStorageTypeIntegralWidth() == 16) + ? SHIFT_16_BIT + : SHIFT_8_BIT; + + double lhs_rescale_scale = in_lhs_scale / max_scale_2x; + double rhs_rescale_scale = in_rhs_scale / max_scale_2x; + double output_rescale_scale = + max_scale_2x / (output_scale * static_cast(1 << input_shift)); + +#if TFLITE_SINGLE_ROUNDING + Value op1_rescale_lhs = buildRescaleToInt32( + rewriter, op, lhs, + lhs_rescale_scale * static_cast(1 << input_shift), + input_lhs_qtype.getZeroPoint()); + Value op2_rescale_rhs = buildRescaleToInt32( + rewriter, op, rhs, + rhs_rescale_scale * static_cast(1 << input_shift), + input_rhs_qtype.getZeroPoint()); +#else // TFLITE_DOUBLE_ROUNDING + Value op1_rescale_lhs; + Value op2_rescale_rhs; + + // Left side + // Handle only 16-bit none_exact_half_rescale_scale as a special case here: + // 1. The double rescale implementation will break the TOSA reference model + // because for 16-bit values, the minimum shift must be 16 which + // leaves a left shift of 15 impossible. Using a Cast + Shift instead. + // 2. In other cases, we are scaling by lhs_rescale_scale*(1<( + rewriter, op->getLoc(), rescale_type_input_left, lhs); + op1_none_half_scale_intermediate = + CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type_input_left, + tfl_add_lhs_casted.getResult(), + getTosaConstTensorSingleI32(rewriter, op, input_shift, + input_lhs_type.getRank())); + } else { + op1_none_half_scale_intermediate = + buildRescaleToInt32(rewriter, op, lhs, (1 << input_shift), + input_lhs_qtype.getZeroPoint()); + } + op1_rescale_lhs = buildRescaleToInt32( + rewriter, op, op1_none_half_scale_intermediate, lhs_rescale_scale, 0); + } + + // Right side + // Handle only 16-bit none_exact_half_rescale_scale as a special case here: + // 1. The double rescale implementation will break the TOSA reference model + // because for 16-bit values, the minimum shift must be 16 which + // leaves a left shift of 15 impossible. Using a Cast + Shift instead. + // 2. In other cases, we are scaling by rhs_rescale_scale*(1<( + rewriter, op->getLoc(), rescale_type_input_right, rhs); + op2_none_half_scale_intermediate = + CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type_input_right, + tfl_add_rhs_casted.getResult(), + getTosaConstTensorSingleI32(rewriter, op, input_shift, + input_rhs_type.getRank())); + } else { + op2_none_half_scale_intermediate = + buildRescaleToInt32(rewriter, op, rhs, (1 << input_shift), + input_rhs_qtype.getZeroPoint()); + } + op2_rescale_rhs = buildRescaleToInt32( + rewriter, op, op2_none_half_scale_intermediate, rhs_rescale_scale, 0); + } + +#endif // TFLITE_DOUBLE_ROUNDING + auto op3_add_op1_op2 = + CreateOpAndInfer(rewriter, op->getLoc(), rescale_type_output, + op1_rescale_lhs, op2_rescale_rhs); + Value op4_rescale_op3 = buildRescaleFromInt32( + rewriter, op, output_type, op3_add_op1_op2.getResult(), + output_rescale_scale, output_qtype.getZeroPoint()); + + output = op4_rescale_op3; + } else { + auto op1_add_in = + CreateOpAndInfer(rewriter, op->getLoc(), output_type, lhs, rhs); + + output = op1_add_in.getResult(); + } + + auto fused_activation_fn = tfl_add_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = + convertFusedActivation(rewriter, op, output, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {output}); + return success(); +} + +LogicalResult ConvertTFLSignOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_sign_op = cast(op); + + RankedTensorType output_type = + mlir::cast(tfl_sign_op.getResult().getType()); + + std::optional result = + convertSignOp(rewriter, op, tfl_sign_op.getX(), output_type); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFLCastOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_cast_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_cast_op.getInput().getType()); + RankedTensorType output_type = + dyn_cast(tfl_cast_op.getOutput().getType()); + // Not a ranked tensor input or output + if (!input_type || !output_type) + return rewriter.notifyMatchFailure( + op, "both operand and result must be ranked tensor type."); + + std::optional result = + convertCastOp(rewriter, op, tfl_cast_op.getInput(), output_type); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFLAddOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return matchAndRewriteAddSub(op, op->getOperands(), + rewriter); +} + +LogicalResult ConvertTFLSubOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return matchAndRewriteAddSub(op, op->getOperands(), + rewriter); +} + +LogicalResult ConvertTFLMulOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_mul_op = cast(op); + + std::optional result = + convertMultiplyOp(rewriter, op, tfl_mul_op.getResult(), + tfl_mul_op.getLhs(), tfl_mul_op.getRhs()); + + if (!result) return failure(); + + auto fused_activation_fn = tfl_mul_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = convertFusedActivation( + rewriter, op, result.value(), fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFLSquareOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_square_op = cast(op); + + std::optional result = + convertMultiplyOp(rewriter, op, tfl_square_op.getResult(), + tfl_square_op.getX(), tfl_square_op.getX()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFLSquaredDifferenceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_squared_op = cast(op); + + std::optional result = convertSquaredDifferenceOp( + rewriter, op, tfl_squared_op.getResult(), tfl_squared_op.getLhs(), + tfl_squared_op.getRhs()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFLRoundOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_round_op = cast(op); + + ShapedType input_type = dyn_cast(tfl_round_op.getX().getType()); + if (!input_type) { + return rewriter.notifyMatchFailure(op, "input not shaped tensor type"); + } + + if (mlir::isa(input_type.getElementType())) { + std::optional result = convertRoundOp( + rewriter, op, tfl_round_op.getResult(), tfl_round_op.getX()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); + + } else { + // Round on int is nonsensical. Instead, replace uses of result with the + // input. + tfl_round_op.replaceAllUsesWith(tfl_round_op.getX()); + return success(); + } +} + +LogicalResult ConvertTFLDivOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_div_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_div_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + auto fused_activation_fn = tfl_div_op.getFusedActivationFunctionAttr(); + + Type element_type = output_type.getElementType(); + Value lhs = tfl_div_op.getLhs(); + Value rhs = tfl_div_op.getRhs(); + Value div_op; + if (mlir::isa(element_type)) { + div_op = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, lhs, rhs) + .getResult(); + } else { + auto reciprocal_op = CreateOpAndInfer( + rewriter, op->getLoc(), rhs.getType(), rhs); + div_op = CreateMulOpAndInfer(rewriter, op, output_type, lhs, + reciprocal_op.getResult()) + .getResult(); + } + + if (fused_activation_fn) { + std::optional fused_activation_val = + convertFusedActivation(rewriter, op, div_op, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {div_op}); + + return success(); +} + +LogicalResult ConvertTFLMaximumOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_max_op = cast(op); + + Value lhs = tfl_max_op.getLhs(); + Value rhs = tfl_max_op.getRhs(); + + ShapedType input_lhs_type = dyn_cast(lhs.getType()); + ShapedType input_rhs_type = dyn_cast(rhs.getType()); + ShapedType output_type = + dyn_cast(tfl_max_op.getResult().getType()); + + // Not a shaped tensor output + if (!input_lhs_type || !input_rhs_type || !output_type) return failure(); + + bool input_lhs_is_qtype = mlir::isa( + input_lhs_type.getElementType()); + bool input_rhs_is_qtype = mlir::isa( + input_rhs_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_lhs_is_qtype != output_is_qtype || + input_rhs_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + Value output; + if (output_is_qtype) { + ShapedType rescale_type = output_type.clone(rewriter.getI32Type()); + + Value op1_rescale_lhs = removeZeroPointAndCastToInt32(rewriter, op, lhs, 0); + Value op2_rescale_rhs = removeZeroPointAndCastToInt32(rewriter, op, rhs, 0); + + auto op3_max_op1_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type, op1_rescale_lhs, op2_rescale_rhs); + + Value op4_rescale_op3 = buildRescaleFromInt32( + rewriter, op, output_type, op3_max_op1_op2.getResult(), 1.0f, 0); + + output = op4_rescale_op3; + } else { + auto op1_max_in = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, lhs, rhs); + + output = op1_max_in.getResult(); + } + + rewriter.replaceOp(op, {output}); + + return success(); +} + +LogicalResult ConvertTFLMinimumOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_min_op = cast(op); + + Value lhs = tfl_min_op.getLhs(); + Value rhs = tfl_min_op.getRhs(); + + ShapedType input_lhs_type = dyn_cast(lhs.getType()); + ShapedType input_rhs_type = dyn_cast(rhs.getType()); + ShapedType output_type = + dyn_cast(tfl_min_op.getResult().getType()); + // Not a shaped tensor output + if (!input_lhs_type || !input_rhs_type || !output_type) return failure(); + + bool input_lhs_is_qtype = mlir::isa( + input_lhs_type.getElementType()); + bool input_rhs_is_qtype = mlir::isa( + input_rhs_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_lhs_is_qtype != output_is_qtype || + input_rhs_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + Value output; + if (output_is_qtype) { + ShapedType rescale_type = output_type.clone(rewriter.getI32Type()); + + Value op1_rescale_lhs = removeZeroPointAndCastToInt32(rewriter, op, lhs, 0); + Value op2_rescale_rhs = removeZeroPointAndCastToInt32(rewriter, op, rhs, 0); + auto op3_min_op1_op2 = CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type, op1_rescale_lhs, op2_rescale_rhs); + + Value op4_rescale_op3 = buildRescaleFromInt32( + rewriter, op, output_type, op3_min_op1_op2.getResult(), 1.0f, 0); + + output = op4_rescale_op3; + } else { + auto op1_min_in = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, lhs, rhs); + + output = op1_min_in.getResult(); + } + + rewriter.replaceOp(op, {output}); + + return success(); +} + +LogicalResult ConvertTFLFloorDivOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_floordiv_op = cast(op); + + std::optional result = + convertFloorDivOp(rewriter, op, tfl_floordiv_op.getResult(), + tfl_floordiv_op.getLhs(), tfl_floordiv_op.getRhs()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLFloorModOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_floormod_op = cast(op); + + std::optional result = + convertFloorModOp(rewriter, op, tfl_floormod_op.getResult(), + tfl_floormod_op.getLhs(), tfl_floormod_op.getRhs()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLAddNOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_addn_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_addn_op.getResult().getType()); + // Not a shaped output + if (!output_type) return failure(); + + SmallVector inputs(tfl_addn_op.getInputs()); + + assert(inputs.size() >= 2); + + Value x = inputs[0]; + Value y = inputs[1]; + Value newValue = + CreateOpAndInfer(rewriter, op->getLoc(), output_type, x, y); + for (int i = 2; i < inputs.size(); i++) { + Value next = inputs[i]; + newValue = CreateOpAndInfer(rewriter, op->getLoc(), + output_type, next, newValue); + } + + rewriter.replaceOp(op, {newValue}); + + return success(); +} + +LogicalResult ConvertTFLAveragePool2DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_avgpool_op = cast(op); + + ShapedType input_type = + dyn_cast(tfl_avgpool_op.getInput().getType()); + ShapedType output_type = + dyn_cast(tfl_avgpool_op.getResult().getType()); + // Not a shaped output + if (!output_type) return failure(); + + // Kernels and strides are dimensionally ordered + SmallVector i64array({1, 1, 1, 1}); + DenseI64ArrayAttr kernel_size; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr pad; + // Pooling has no non-unit dilation + DenseI64ArrayAttr dilation = rewriter.getDenseI64ArrayAttr({1, 1}); + { + int64_t kernel_h = tfl_avgpool_op.getFilterHeight(); + int64_t kernel_w = tfl_avgpool_op.getFilterWidth(); + kernel_size = rewriter.getDenseI64ArrayAttr({kernel_h, kernel_w}); + // i64array is formatted as NHWC now + i64array[1] = kernel_h; + i64array[2] = kernel_w; + } + { + int64_t stride_h = tfl_avgpool_op.getStrideH(); + int64_t stride_w = tfl_avgpool_op.getStrideW(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tfl_avgpool_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + // Pooling has no non-unit dilation + DenseI64ArrayAttr dilation = rewriter.getDenseI64ArrayAttr({1, 1}); + + RankedTensorType filter_type = RankedTensorType::get( + llvm::ArrayRef(i64array), rewriter.getIntegerType(64)); + + // TFLite doesn't support explicit padding + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, stride, dilation, rewriter, pad)) + return failure(); + } + + Value avg_pool_input = getInputSlicedToItsUsedSize( + rewriter, op, tensorflow::FORMAT_NHWC, input_type, + tfl_avgpool_op.getInput(), kernel_size, pad, stride, dilation); + + auto average_etype = input_type.getElementType(); + auto average_type = output_type.clone(average_etype); + + // Tosa supports FP16 and FP32 accumulator type for FP16 input. When the time + // FP16 is supported, the accumulator type can be selected based on trade-off + // between performance and accuracy. Set to FP32 by default. + TypeAttr acc_attr = mlir::isa(average_etype) + ? mlir::TypeAttr::get(rewriter.getF32Type()) + : mlir::TypeAttr::get(rewriter.getIntegerType(32)); + + Value result; + if (mlir::isa(average_etype)) { + // TensorFlow Lite doesn't use the zero point when calculating + // quantized average pool, while TOSA does. Force the TOSA + // zero_points to zero to ensure that the calculations match + Location loc = op->getLoc(); + const std::optional input_zp = + tosa::createZeroPointTensor(rewriter, loc, avg_pool_input.getType(), 0); + if (!input_zp.has_value()) + return op->emitError("Failed to create input zero-point tensor for AvgPool2D op."); + + const Value empty_output_val = rewriter.create(loc, + average_type.getShape(), average_type.getElementType()); + const std::optional output_zp = + tosa::createZeroPointTensor(rewriter, loc, empty_output_val.getType(), 0); + if (!output_zp.has_value()) + return op->emitError("Failed to create output zero-point tensor for AvgPool2D op."); + + result = CreateOpAndInfer( + rewriter, op->getLoc(), average_type, avg_pool_input, input_zp.value(), + output_zp.value(), kernel_size, stride, pad, acc_attr); + } else { + result = CreateOpAndInfer( + rewriter, op->getLoc(), average_type, avg_pool_input, kernel_size, + stride, pad, acc_attr); + } + + if (average_type != output_type) { + result = CreateOpAndInfer(rewriter, op->getLoc(), output_type, + result); + } + + rewriter.replaceOp(op, result); + return success(); +} + +LogicalResult ConvertTFLMaxPool2DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_maxpool_op = cast(op); + + ShapedType input_type = + dyn_cast(tfl_maxpool_op.getInput().getType()); + ShapedType output_type = + dyn_cast(tfl_maxpool_op.getResult().getType()); + // Not a shaped type + if (!output_type) return failure(); + + // Kernels and strides are dimensionally ordered + SmallVector i64array({1, 1, 1, 1}); + DenseI64ArrayAttr kernel_size; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr pad; + // Pooling has no non-unit dilation + DenseI64ArrayAttr dilation = rewriter.getDenseI64ArrayAttr({1, 1}); + { + int64_t kernel_h = tfl_maxpool_op.getFilterHeight(); + int64_t kernel_w = tfl_maxpool_op.getFilterWidth(); + kernel_size = rewriter.getDenseI64ArrayAttr({kernel_h, kernel_w}); + // i64array is formatted as NHWC now + i64array[1] = kernel_h; + i64array[2] = kernel_w; + } + { + int64_t stride_h = tfl_maxpool_op.getStrideH(); + int64_t stride_w = tfl_maxpool_op.getStrideW(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tfl_maxpool_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + RankedTensorType filter_type = + RankedTensorType::get(i64array, rewriter.getIntegerType(64)); + + // TFLite doesn't support explicit padding + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, stride, dilation, rewriter, pad)) + return failure(); + } + + // TFLite only supports NHWC format + const Value max_pool_input = getInputSlicedToItsUsedSize( + rewriter, op, tensorflow::FORMAT_NHWC, input_type, + tfl_maxpool_op.getInput(), kernel_size, pad, stride, dilation); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + max_pool_input, + kernel_size, stride, pad); + return success(); +} + +// Returns a new type based on an input type and slicing information. +// If the input is quantized per axis, slices the scale and zp arrays. +// In any other case, returns the original type. +RankedTensorType getTypeForSlice(RankedTensorType type, int64_t slice_dim, + int64_t slice_size, int64_t offset) { + if (auto per_channel_qtype = + dyn_cast(type.getElementType())) { + if (per_channel_qtype.getQuantizedDimension() != slice_dim) return type; + SmallVector output_scale_arr( + per_channel_qtype.getScales().begin() + offset, + per_channel_qtype.getScales().begin() + offset + slice_size); + SmallVector output_zp_arr( + per_channel_qtype.getZeroPoints().begin() + offset, + per_channel_qtype.getZeroPoints().begin() + offset + slice_size); + auto output_per_channel_qtype = quant::UniformQuantizedPerAxisType::get( + per_channel_qtype.getFlags(), + tosa::getStorageElementTypeFromQuantized(per_channel_qtype), + per_channel_qtype.getExpressedType(), output_scale_arr, output_zp_arr, + per_channel_qtype.getQuantizedDimension(), + per_channel_qtype.getStorageTypeMin(), + per_channel_qtype.getStorageTypeMax()); + return RankedTensorType::get(type.getShape(), output_per_channel_qtype); + } + return type; +} + +Value lowerGroupedConvolution(TFL::Conv2DOp op, PatternRewriter& rewriter) { + auto input_type = dyn_cast(op.getInput().getType()); + auto filter_type = dyn_cast(op.getFilter().getType()); + auto bias_type = dyn_cast(op.getBias().getType()); + auto output_type = dyn_cast(op.getResult().getType()); + + // The slicing on the input/output is done on dim 3, while on the filter/bias + // it's done on dim 0. + int64_t input_slice_dim = 3; + int64_t filter_slice_dim = 0; + int64_t bias_slice_dim = 0; + int64_t output_slice_dim = 3; + int64_t input_channels = input_type.getDimSize(input_slice_dim); + int64_t ic_slice_size = filter_type.getDimSize(input_slice_dim); + int64_t num_groups = input_channels / ic_slice_size; + + // When slicing the filter/bias, the slice size is determined by the number of + // slices on the input. + int64_t oc_slice_size = filter_type.getDimSize(filter_slice_dim) / num_groups; + + SmallVector convolutions; + convolutions.reserve(num_groups); + auto rank = input_type.getRank(); + + // Input size vector + SmallVector input_size_vals(input_type.getShape().begin(), + input_type.getShape().end()); + input_size_vals.back() = ic_slice_size; + auto input_slice_ty = + RankedTensorType::get(input_size_vals, input_type.getElementType()); + + // Filter size vector + SmallVector filter_size_vals(filter_type.getShape().begin(), + filter_type.getShape().end()); + filter_size_vals.front() = + filter_type.getDimSize(filter_slice_dim) / num_groups; + DenseI64ArrayAttr filter_size = + rewriter.getDenseI64ArrayAttr(filter_size_vals); + auto filter_slice_ty = + RankedTensorType::get(filter_size_vals, filter_type.getElementType()); + + // Bias size vector + int64_t bias_size_val = bias_type.getDimSize(bias_slice_dim) / num_groups; + auto bias_slice_ty = + RankedTensorType::get(bias_size_val, bias_type.getElementType()); + + auto per_conv_out_ty = RankedTensorType::get( + {output_type.getDimSize(0), output_type.getDimSize(1), + output_type.getDimSize(2), oc_slice_size}, + output_type.getElementType()); + + // Create a separate convolution for each group + for (int i = 0; i < num_groups; ++i) { + auto verified_input_slice_ty = getTypeForSlice( + input_slice_ty, input_slice_dim, ic_slice_size, i * ic_slice_size); + auto verified_filter_slice_ty = getTypeForSlice( + filter_slice_ty, filter_slice_dim, oc_slice_size, i * oc_slice_size); + auto verified_bias_slice_ty = getTypeForSlice( + bias_slice_ty, bias_slice_dim, oc_slice_size, i * oc_slice_size); + auto verified_per_conv_out_ty = getTypeForSlice( + per_conv_out_ty, output_slice_dim, oc_slice_size, i * oc_slice_size); + + // Slice the input + SmallVector input_start_vals(rank, 0); + input_start_vals.back() = i * ic_slice_size; + + auto slice_input = rewriter.createOrFold( + op->getLoc(), verified_input_slice_ty, op.getInput(), + getTosaConstShape(rewriter, op->getLoc(), input_start_vals), + getTosaConstShape(rewriter, op->getLoc(), input_size_vals)); + + // Slice the filter + SmallVector filter_start_vals(rank, 0); + filter_start_vals.front() = i * oc_slice_size; + DenseI64ArrayAttr filter_start = + rewriter.getDenseI64ArrayAttr(filter_start_vals); + + auto slice_filter = rewriter.createOrFold( + op->getLoc(), verified_filter_slice_ty, op.getFilter(), + getTosaConstShape(rewriter, op->getLoc(), filter_start_vals), + getTosaConstShape(rewriter, op->getLoc(), filter_size_vals)); + + // Slice the bias + int64_t bias_start_val = i * oc_slice_size; + + auto slice_bias = rewriter.createOrFold( + op->getLoc(), verified_bias_slice_ty, op.getBias(), + getTosaConstShape(rewriter, op->getLoc(), bias_start_val), + getTosaConstShape(rewriter, op->getLoc(), bias_size_val)); + + // Create a convolution for each set of slices + auto conv = rewriter.create( + op->getLoc(), verified_per_conv_out_ty, slice_input, slice_filter, + slice_bias, op.getDilationHFactor(), op.getDilationWFactor(), + op.getFusedActivationFunction(), op.getPadding(), op.getStrideH(), + op.getStrideW()); + + convolutions.push_back(conv.getResult()); + } + + return rewriter.createOrFold(op->getLoc(), output_type, + convolutions, output_slice_dim); +} + +bool isInt16InputAndVariableBias(mlir::ShapedType input_type, Value orig_bias) { + auto input_qtype = llvm::dyn_cast( + input_type.getElementType()); + if (!input_qtype) return false; + + int input_bits = input_qtype.getStorageTypeIntegralWidth(); + auto const_bias = orig_bias.getDefiningOp(); + auto no_value_bias = orig_bias.getDefiningOp(); + + return (input_bits == 16 && !const_bias && !no_value_bias); +} + +/* Ensure bias is of the correct type. +TOSA requires that bias must be of the same type as the output, and that +output type must be of a certain type depending on the input type. +*/ +static FailureOr> getTosaBias( + Operation* op, PatternRewriter& rewriter, ShapedType input_type, + ShapedType output_type, bool output_is_qtype, Value bias) { + Type bias_ety; + + int bias_bits; + if (output_is_qtype) { + auto input_qtype = + dyn_cast(input_type.getElementType()); + if (!input_qtype) { + return rewriter.notifyMatchFailure(op, + "output is qtype but input is not"); + } + int input_bits = input_qtype.getStorageTypeIntegralWidth(); + // For signed int8/int16 input tensor, int32/int48 bias and output + // tensor are generated. + bias_bits = input_bits == 16 ? 48 : 32; + bias_ety = rewriter.getIntegerType(bias_bits); + } else { + bias_ety = output_type.getElementType(); + bias_bits = bias_ety.getIntOrFloatBitWidth(); + } + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + + bool special_case_16bit_input = + input_is_qtype ? isInt16InputAndVariableBias(input_type, bias) : false; + + if (!bias || !dyn_cast(bias.getType()) || + special_case_16bit_input) { + // Create a bias with values of all zeros. This is needed in two situations: + // 1. The bias may actually be typed "None" which has no value. TOSA + // requires bias to be an array of output_channel_count values, so create a + // constant of the appropriate number and type of zeros. + // 2. Conv output is of type int48 and bias is of type int32 but TOSA + // insists on dtype(output) == dtype(bias). So we need to create zero bias + // of type 48 now and later add the int32 bias explicitly + RankedTensorType bias_type = RankedTensorType::get({1}, bias_ety); + auto bias_attr = rewriter.getZeroAttr(bias_type); + + bias = CreateOpAndInfer(rewriter, op->getLoc(), bias_type, + mlir::cast(bias_attr)); + } + + auto prev_bias_type = dyn_cast(bias.getType()); + if (!prev_bias_type) { + return rewriter.notifyMatchFailure(op, "bias not a ranked tensor"); + } + + auto prev_bias_etype = prev_bias_type.getElementType(); + + int prev_bias_bits; + if (auto prev_bias_eqtype = + dyn_cast(prev_bias_etype)) { + prev_bias_bits = prev_bias_eqtype.getStorageTypeIntegralWidth(); + } else { + prev_bias_bits = prev_bias_etype.getIntOrFloatBitWidth(); + } + + if (prev_bias_bits == bias_bits || special_case_16bit_input) { + return std::pair(bias_ety, bias); + } + + auto const_op = bias.getDefiningOp(); + if (!const_op) { + return rewriter.notifyMatchFailure(op, "bias not a ConstOp"); + } + + DenseElementsAttr bias_attr; + { + auto prev_bias_attr = + dyn_cast(const_op.getValuesAttr()); + if (!prev_bias_attr) { + return rewriter.notifyMatchFailure( + op, "bias values not DenseIntElementsAttr"); + } + // Promote to int32/int48 if necessary. + bias_attr = prev_bias_attr.mapValues( + bias_ety, + [bias_bits = bias_ety.getIntOrFloatBitWidth()]( + const APInt& x) -> APInt { return x.sext(bias_bits); }); + } + + ShapedType bias_output_type; + if (auto bias_attr_type = dyn_cast(bias_attr.getType())) { + bias_output_type = bias_attr_type.clone(bias_ety); + } else { + bias_output_type = dyn_cast(const_op.getResult().getType()); + if (!bias_output_type) { + return rewriter.notifyMatchFailure( + op, "bias defining op result not ShapedType"); + } + bias_output_type = bias_output_type.clone(bias_ety); + } + + auto new_const_op = + rewriter.create(op->getLoc(), bias_output_type, bias_attr); + Value new_bias = new_const_op.getResult(); + rewriter.replaceOp(const_op, new_bias); + + return std::make_pair(bias_ety, new_bias); +} + +Value handleConvRescaleAndBias(Operation* op, PatternRewriter& rewriter, + Value conv_val, Value bias, + ShapedType input_type, ShapedType filter_type, + ShapedType output_type) { + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + + if (!input_is_qtype) { + return conv_val; + } + + bool special_case_16bit_input = + input_is_qtype ? isInt16InputAndVariableBias(input_type, bias) : false; + + Value conv_output = conv_val; + + // Special case - if input tensor is int16, we have to add the bias + // manually after rescale + if (special_case_16bit_input) { + conv_output = buildRescaleToInt32(rewriter, op, conv_output, 1.0, 0); + + // Rescale the actual bias to 32 bit to be able to do the bias add + auto bias_scaled = buildRescaleToInt32(rewriter, op, bias, 1.0, 0); + conv_output = CreateOpAndInfer(rewriter, op->getLoc(), + conv_output.getType(), + conv_output, bias_scaled) + .getResult(); + } + conv_output = buildRescaleOpConvOutput(rewriter, op, conv_output, input_type, + filter_type, output_type); + return conv_output; +} + +LogicalResult ConvertTFLConv2DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_conv2d_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_conv2d_op.getInput().getType()); + RankedTensorType filter_type = + dyn_cast(tfl_conv2d_op.getFilter().getType()); + ShapedType output_type = + dyn_cast(tfl_conv2d_op.getResult().getType()); + // Not a ranked tensor output + if (!input_type) return failure(); + if (!output_type) return failure(); + if (!filter_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool filter_is_qtype = + mlir::isa(filter_type.getElementType()); + bool output_is_qtype = + mlir::isa(output_type.getElementType()); + + if ((input_is_qtype != filter_is_qtype) || + (input_is_qtype != output_is_qtype)) { + return rewriter.notifyMatchFailure( + op, + "input/filter/output tensor should " + "be all quantized or all floating-point"); + } + + int64_t input_channels = input_type.getDimSize(3); + int64_t filter_channels = filter_type.getDimSize(3); + if (input_channels != filter_channels && + input_channels % filter_channels == 0) { + rewriter.replaceOp(op, lowerGroupedConvolution(tfl_conv2d_op, rewriter)); + return success(); + } + + DenseI64ArrayAttr kernel_size; + DenseI64ArrayAttr pad; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr dilation; + { + // TFLite filter format is tensorflow::FORMAT_OHWI + int64_t kernel_h = filter_type.getDimSize(1); + int64_t kernel_w = filter_type.getDimSize(2); + kernel_size = rewriter.getDenseI64ArrayAttr({kernel_h, kernel_w}); + } + { + int64_t stride_h = tfl_conv2d_op.getStrideH(); + int64_t stride_w = tfl_conv2d_op.getStrideW(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + { + int64_t dilation_h = tfl_conv2d_op.getDilationHFactor(); + int64_t dilation_w = tfl_conv2d_op.getDilationWFactor(); + dilation = rewriter.getDenseI64ArrayAttr({dilation_h, dilation_w}); + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tfl_conv2d_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + // TFLite doesn't support explicit padding + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, stride, dilation, rewriter, pad)) + return failure(); + } + + auto bias_result = getTosaBias(op, rewriter, input_type, output_type, + output_is_qtype, tfl_conv2d_op.getBias()); + if (failed(bias_result)) return failure(); + auto [bias_ety, bias_val] = bias_result.value(); + + // TFLite only supports NHWC format + Value conv2d_input = getInputSlicedToItsUsedSize( + rewriter, op, tensorflow::FORMAT_NHWC, input_type, + tfl_conv2d_op.getInput(), kernel_size, pad, stride, dilation); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ bias_ety); + + auto a1_conv2d_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type.clone(bias_ety), conv2d_input, + tfl_conv2d_op.getFilter(), bias_val, pad, stride, dilation, acc_type); + + // Sometimes we need to rescale the op to the output quantization space or + // expliciyly add variable bias + Value conv2d_output = handleConvRescaleAndBias( + op, rewriter, a1_conv2d_op.getResult(), tfl_conv2d_op.getBias(), + input_type, filter_type, output_type); + + auto fused_activation_fn = tfl_conv2d_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = convertFusedActivation( + rewriter, op, conv2d_output, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {conv2d_output}); + + return success(); +} + +LogicalResult ConvertTFLConv3DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_conv3d_op = cast(op); + RankedTensorType input_type = + dyn_cast(tfl_conv3d_op.getInput().getType()); + RankedTensorType filter_type = + dyn_cast(tfl_conv3d_op.getFilter().getType()); + ShapedType output_type = + dyn_cast(tfl_conv3d_op.getResult().getType()); + + if (!input_type | !filter_type || !output_type) { + return rewriter.notifyMatchFailure( + op, "input/filter/output are not all a ranked tensor"); + } + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool filter_is_qtype = + mlir::isa(filter_type.getElementType()); + bool output_is_qtype = + mlir::isa(output_type.getElementType()); + + if ((input_is_qtype != filter_is_qtype) || + (input_is_qtype != output_is_qtype)) { + return rewriter.notifyMatchFailure( + op, + "ConvertTFLConv3DOp: input/filter/output tensor should " + "be all quantized or all floating-point."); + } + + DenseI64ArrayAttr kernel_size; + DenseI64ArrayAttr pad; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr dilation; + { + // TFLite filter format is DHWIO + int64_t kernel_d = filter_type.getDimSize(0); + int64_t kernel_h = filter_type.getDimSize(1); + int64_t kernel_w = filter_type.getDimSize(2); + kernel_size = rewriter.getDenseI64ArrayAttr({kernel_d, kernel_h, kernel_w}); + } + { + int64_t stride_d = tfl_conv3d_op.getStrideD(); + int64_t stride_h = tfl_conv3d_op.getStrideH(); + int64_t stride_w = tfl_conv3d_op.getStrideW(); + stride = rewriter.getDenseI64ArrayAttr({stride_d, stride_h, stride_w}); + } + { + int64_t dilation_d = tfl_conv3d_op.getDilationDFactor(); + int64_t dilation_h = tfl_conv3d_op.getDilationHFactor(); + int64_t dilation_w = tfl_conv3d_op.getDilationWFactor(); + dilation = + rewriter.getDenseI64ArrayAttr({dilation_d, dilation_h, dilation_w}); + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tfl_conv3d_op.getPadding().str(), &tf_pad).ok()) { + return failure(); + } + + // TFLite doesn't support explicit padding + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports NDHWC format, + // tensorflow::FORMAT_NHWC is used for + // both rank 4 and rank 5 tensors + 0, // TFLite filter is DHWIO + input_type, filter_type, stride, dilation, rewriter, pad)) { + return failure(); + } + } + + // TFLite only supports NDHWC format, tensorflow::FORMAT_NHWC is used for both + // rank 4 and rank 5 tensors + Value conv3d_input = getInputSlicedToItsUsedSize( + rewriter, op, tensorflow::FORMAT_NHWC, input_type, + tfl_conv3d_op.getInput(), kernel_size, pad, stride, dilation); + + auto bias_result = getTosaBias(op, rewriter, input_type, output_type, + output_is_qtype, tfl_conv3d_op.getBias()); + if (failed(bias_result)) return failure(); + auto [bias_ety, bias_val] = bias_result.value(); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ bias_ety); + + std::optional a1_conv3d_op = + convertConv3DCommon(rewriter, op, output_type.clone(bias_ety), + conv3d_input, tfl_conv3d_op.getFilter(), bias_val, + pad, stride, dilation, acc_type, StringRef("NDHWC")); + + if (!a1_conv3d_op) return failure(); + + // Sometimes we need to rescale the op to the output quantization space or + // expliciyly add variable bias + Value conv3d_output = handleConvRescaleAndBias( + op, rewriter, a1_conv3d_op.value(), tfl_conv3d_op.getBias(), input_type, + filter_type, output_type); + + if (auto fused_activation_fn = + tfl_conv3d_op.getFusedActivationFunctionAttr()) { + std::optional fused_activation_val = convertFusedActivation( + rewriter, op, conv3d_output, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {conv3d_output}); + + return success(); +} + +LogicalResult ConvertTFLTransposeConvOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_conv_op = cast(op); + + ShapedType input_type = + dyn_cast(tfl_conv_op.getInput().getType()); + ShapedType filter_type = + dyn_cast(tfl_conv_op.getWeights().getType()); + ShapedType output_type = + dyn_cast(tfl_conv_op.getResult().getType()); + + // Not a ranked tensor output + if (!input_type) return failure(); + if (!output_type) return failure(); + if (!filter_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool filter_is_qtype = + mlir::isa(filter_type.getElementType()); + bool output_is_qtype = + mlir::isa(output_type.getElementType()); + + if ((input_is_qtype != filter_is_qtype) || + (input_is_qtype != output_is_qtype)) { + return rewriter.notifyMatchFailure( + op, + "input/filter/output tensor should " + "be all quantized or all floating-point"); + } + + DenseI64ArrayAttr stride; + DenseI64ArrayAttr outpad; + { + int64_t stride_h = tfl_conv_op.getStrideH(); + int64_t stride_w = tfl_conv_op.getStrideW(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tfl_conv_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + if (!getTransposeConv2dPaddingValues( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, output_type, stride, rewriter, outpad)) + return failure(); + } + + auto bias_result = getTosaBias(op, rewriter, input_type, output_type, + output_is_qtype, tfl_conv_op.getBias()); + if (failed(bias_result)) return failure(); + auto [bias_ety, bias_val] = bias_result.value(); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ bias_ety); + + auto a1_conv2d_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type.clone(bias_ety), + tfl_conv_op.getInput(), tfl_conv_op.getWeights(), bias_val, outpad, + stride, acc_type); + + // Sometimes we need to rescale the op to the output quantization space or + // expliciyly add variable bias + Value conv2d_output = handleConvRescaleAndBias( + op, rewriter, a1_conv2d_op.getResult(), tfl_conv_op.getBias(), input_type, + filter_type, output_type); + + auto fused_activation_fn = tfl_conv_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = convertFusedActivation( + rewriter, op, conv2d_output, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {conv2d_output}); + + return success(); +} + +LogicalResult ConvertTFLDepthwiseConv2DOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_conv2d_op = cast(op); + + ShapedType input_type = + dyn_cast(tfl_conv2d_op.getInput().getType()); + ShapedType filter_type = + dyn_cast(tfl_conv2d_op.getFilter().getType()); + ShapedType output_type = + dyn_cast(tfl_conv2d_op.getResult().getType()); + // Not a shaped output + if (!input_type) return failure(); + if (!output_type) return failure(); + if (!filter_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool filter_is_qtype = + mlir::isa(filter_type.getElementType()); + bool output_is_qtype = + mlir::isa(output_type.getElementType()); + + if ((input_is_qtype != filter_is_qtype) || + (input_is_qtype != output_is_qtype)) { + return rewriter.notifyMatchFailure( + op, + "input/filter/output tensor should " + "be all quantized or all floating-point"); + } + + // We need the filter shape to compute the transpose. + if (!filter_type.hasRank()) return failure(); + auto filter_shape = filter_type.getShape(); + // Operator depthwiseConv2D + // TFLite orders the depthwiseConv2D filter in IHWO, while TOSA orders + // filter in HWIO + // + // The lowering reorders the filter. + // + // a1_transpose = tosa.transpose(filter, {1, 2, 3, 0}) // HWIO + // a2_reshape = tosa.reshape(filter, H, W, depth_multiplier, I / + // depth_multiplier) + // a3_transpose_conv2d = tosa.transpose_conv2d(input, a2_reshape, padding, + // stride, dilation) + + DenseI64ArrayAttr kernel_size; + DenseI64ArrayAttr pad; + DenseI64ArrayAttr stride; + DenseI64ArrayAttr dilation; + auto depth_multiplier = tfl_conv2d_op.getDepthMultiplierAttr(); + + { + // DepthwiseConv2D TFLite filter format is tensorflow::FORMAT_IHWO + int64_t kernel_h = filter_type.getDimSize(1); + int64_t kernel_w = filter_type.getDimSize(2); + kernel_size = rewriter.getDenseI64ArrayAttr({kernel_h, kernel_w}); + } + { + int64_t stride_h = tfl_conv2d_op.getStrideH(); + int64_t stride_w = tfl_conv2d_op.getStrideW(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + { + int64_t dilation_h = tfl_conv2d_op.getDilationHFactor(); + int64_t dilation_w = tfl_conv2d_op.getDilationWFactor(); + dilation = rewriter.getDenseI64ArrayAttr({dilation_h, dilation_w}); + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(tfl_conv2d_op.getPadding().str(), &tf_pad).ok()) + return failure(); + + if (!getPaddingValuesFromPadType( + tf_pad, + tensorflow::FORMAT_NHWC, // TFLite only supports this + 1, // tensorflow::FORMAT_OHWI, + input_type, filter_type, stride, dilation, rewriter, pad)) + return failure(); + } + + SmallVector a1_transpose_dims; + a1_transpose_dims.push_back(filter_shape[1]); + a1_transpose_dims.push_back(filter_shape[2]); + a1_transpose_dims.push_back(filter_shape[3]); + a1_transpose_dims.push_back(filter_shape[0]); + + SmallVector a2_reshape_dims; + a2_reshape_dims.push_back(a1_transpose_dims[0]); + a2_reshape_dims.push_back(a1_transpose_dims[1]); + a2_reshape_dims.push_back(a1_transpose_dims[2] / depth_multiplier.getInt()); + a2_reshape_dims.push_back(depth_multiplier.getInt()); + + auto a1_filter_transpose_op = CreateOpAndInfer( + rewriter, op->getLoc(), + RankedTensorType::get(ArrayRef(a1_transpose_dims), + filter_type.getElementType()), + tfl_conv2d_op.getFilter(), rewriter.getDenseI32ArrayAttr({1, 2, 3, 0})); + + auto a2_reshape_dims_value = getTosaConstShape(rewriter, op->getLoc(), a2_reshape_dims); + auto a2_filter_reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), + RankedTensorType::get(ArrayRef(a2_reshape_dims), + filter_type.getElementType()), + a1_filter_transpose_op.getResult(), a2_reshape_dims_value); + + auto input_type_ranked = + dyn_cast(tfl_conv2d_op.getInput().getType()); + + if (!input_type_ranked) { + return failure(); + } + + auto bias_result = getTosaBias(op, rewriter, input_type, output_type, + output_is_qtype, tfl_conv2d_op.getBias()); + if (failed(bias_result)) return failure(); + auto [bias_ety, bias_val] = bias_result.value(); + + // TFLite only supports NHWC format + Value conv2d_input = getInputSlicedToItsUsedSize( + rewriter, op, tensorflow::FORMAT_NHWC, input_type, + tfl_conv2d_op.getInput(), kernel_size, pad, stride, dilation); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ bias_ety); + + auto a3_depthwise_conv2d_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type.clone(bias_ety), conv2d_input, + a2_filter_reshape_op.getResult(), bias_val, pad, stride, dilation, + acc_type); + + // Sometimes we need to rescale the op to the output quantization space or + // expliciyly add variable bias + Value depthwise_conv2d_output = handleConvRescaleAndBias( + op, rewriter, a3_depthwise_conv2d_op.getResult(), tfl_conv2d_op.getBias(), + input_type, filter_type, output_type); + + auto fused_activation_fn = tfl_conv2d_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = convertFusedActivation( + rewriter, op, depthwise_conv2d_output, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {depthwise_conv2d_output}); + + return success(); +} + +LogicalResult ConvertTFLBatchMatMulOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_mm_op = cast(op); + auto result_ty = mlir::cast(tfl_mm_op.getType()); + Value lhs = tfl_mm_op.getX(); + Value rhs = tfl_mm_op.getY(); + + if (broadcastLowRankTensor(rewriter, op, lhs, rhs).failed()) { + return rewriter.notifyMatchFailure( + op, "failed to broadcast low rank input tensor"); + } + + RankedTensorType lhs_ty = dyn_cast(lhs.getType()); + RankedTensorType rhs_ty = dyn_cast(rhs.getType()); + bool transpose_lhs = tfl_mm_op.getAdjX(); + bool transpose_rhs = tfl_mm_op.getAdjY(); + + if (!lhs_ty || !rhs_ty) { + return rewriter.notifyMatchFailure(op, + "lhs/rhs tensor should be all ranked"); + } + + bool lhs_is_qtype = + mlir::isa(lhs_ty.getElementType()); + bool rhs_is_qtype = + mlir::isa(rhs_ty.getElementType()); + bool result_is_qtype = + mlir::isa(result_ty.getElementType()); + + if ((lhs_is_qtype != rhs_is_qtype) || (lhs_is_qtype != result_is_qtype)) { + return rewriter.notifyMatchFailure( + op, + "lhs/rhs/output tensor should " + "be all quantized or all floating-point"); + } + + auto batch_dims = lhs_ty.getShape().drop_back(2); + if (batch_dims.size() != 1) { + int64_t N = 1; + for (auto d : batch_dims) { + N = N < 0 || d < 0 ? -1 : N * d; + } + + llvm::SmallVector new_lhs_shape{N}; + llvm::SmallVector new_rhs_shape{N}; + auto lhs_shape_end = lhs_ty.getShape().take_back(2); + auto rhs_shape_end = rhs_ty.getShape().take_back(2); + + new_lhs_shape.append(lhs_shape_end.begin(), lhs_shape_end.end()); + new_rhs_shape.append(rhs_shape_end.begin(), rhs_shape_end.end()); + + auto new_lhs_shape_value = getTosaConstShape(rewriter, op->getLoc(), new_lhs_shape); + lhs = CreateOpAndInfer( + rewriter, op->getLoc(), + UnrankedTensorType::get(lhs_ty.getElementType()), lhs, + new_lhs_shape_value); + + auto new_rhs_shape_value = getTosaConstShape(rewriter, op->getLoc(), new_rhs_shape); + rhs = CreateOpAndInfer( + rewriter, op->getLoc(), + UnrankedTensorType::get(rhs_ty.getElementType()), rhs, + new_rhs_shape_value); + lhs_ty = mlir::cast(lhs.getType()); + rhs_ty = mlir::cast(rhs.getType()); + } + + if (transpose_lhs) { + Type output_type = UnrankedTensorType::get(lhs_ty.getElementType()); + lhs = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, lhs, + rewriter.getDenseI32ArrayAttr({0, 2, 1})) + .getResult(); + } + + if (transpose_rhs) { + Type output_type = UnrankedTensorType::get(rhs_ty.getElementType()); + rhs = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, rhs, + rewriter.getDenseI32ArrayAttr({0, 2, 1})) + .getResult(); + } + + Type output_ety; + if (result_is_qtype) { + auto lhs_qty_width = + mlir::cast(lhs_ty.getElementType()) + .getStorageTypeIntegralWidth(); + auto rhs_qty_width = + mlir::cast(rhs_ty.getElementType()) + .getStorageTypeIntegralWidth(); + + if (lhs_qty_width != rhs_qty_width) { + return rewriter.notifyMatchFailure( + op, "input tensors should have same qtype storage width"); + } + + if (lhs_qty_width == 8) { + output_ety = rewriter.getI32Type(); + } else if (lhs_qty_width == 16) { + output_ety = rewriter.getIntegerType(48); + } else { + return rewriter.notifyMatchFailure( + op, "only support 8-bit or 16-bit quantized type"); + } + } else { + output_ety = result_ty.getElementType(); + } + + Value matmul = + CreateOpAndInfer( + rewriter, op->getLoc(), UnrankedTensorType::get(output_ety), lhs, rhs) + .getResult(); + + // Conditionally reshape rank back to expected rank. + auto matmul_ty = mlir::cast(matmul.getType()); + if (batch_dims.size() != 1) { + llvm::SmallVector new_shape{}; + for (auto d : batch_dims) { + new_shape.push_back(d); + } + + for (auto d : matmul_ty.getShape().take_back(2)) { + new_shape.push_back(d); + } + + auto new_shape_value = getTosaConstShape(rewriter, op->getLoc(), new_shape); + matmul = CreateOpAndInfer( + rewriter, op->getLoc(), + UnrankedTensorType::get(matmul_ty.getElementType()), matmul, + new_shape_value); + } + + if (lhs_is_qtype) { + matmul = buildRescaleOpConvOutput(rewriter, op, matmul, lhs_ty, rhs_ty, + result_ty); + } + + rewriter.replaceOp(op, matmul); + + return success(); +} + +LogicalResult ConvertTFLFullyConnectedOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_fc_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_fc_op.getResult(0).getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + RankedTensorType input_type = + dyn_cast(tfl_fc_op.getInput().getType()); + RankedTensorType filter_type = + dyn_cast(tfl_fc_op.getFilter().getType()); + if (!input_type || !filter_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool filter_is_qtype = + mlir::isa(filter_type.getElementType()); + bool output_is_qtype = + mlir::isa(output_type.getElementType()); + + if ((input_is_qtype != filter_is_qtype) || + (input_is_qtype != output_is_qtype)) { + return rewriter.notifyMatchFailure( + op, + "input/filter/output tensor should " + "be all quantized or all floating-point"); + } + + Value input_val = tfl_fc_op.getInput(); + Value filter_val = tfl_fc_op.getFilter(); + + // tfl.fully_connected() can takes various dimension tensor as input + // need to reshape it to rank 2 tensor, which tosa.fully_connected only + // supports if input tensor is rank 4. It's not always reshaping to (dim[0] * + // dim[1], dim[2] * dim[3]). + + // In some networks it's reshaping to (dim[0], dim[1] * dim[2] * dim[3]) so a + // more general way to determine the reshape's shape is by looking at filter's + // shape[1]. + if (input_type.getRank() != 2) { + int64_t num_elems = filter_type.getShape()[1]; + int64_t num_batch = ShapedType::kDynamic; + if (input_type.hasStaticShape()) { + num_batch = input_type.getNumElements() / num_elems; + } + SmallVector shape_vals({num_batch, num_elems}); + + RankedTensorType reshape_type = + RankedTensorType::get(shape_vals, input_type.getElementType()); + auto shape_vals_value = + getTosaConstShape(rewriter, op->getLoc(), shape_vals); + auto reshape_op = CreateOpAndInfer( + rewriter, op->getLoc(), reshape_type, input_val, shape_vals_value); + + input_val = reshape_op.getResult(); + input_type = reshape_type; + } + + // reshape input_val from [N, IC] to [N, 1, 1, IC] to use conv2d + // reshape filter_val from [OC, IC] to [OC, 1, 1, IC] to use conv2d + const int64_t N = input_type.getShape()[0]; + const int64_t IC = input_type.getShape()[1]; + const int64_t OC = filter_type.getShape()[0]; + + SmallVector new_input_shape({N, 1, 1, IC}); + SmallVector new_filter_shape({OC, 1, 1, IC}); + + auto new_input_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertTFShapeToMlir(new_input_shape)); + input_val = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(new_input_shape, + input_type.getElementType()), + input_val, new_input_shape_value); + input_type = cast(input_val.getType()); + + auto new_filter_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertTFShapeToMlir(new_filter_shape)); + filter_val = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(new_filter_shape, + filter_type.getElementType()), + filter_val, new_filter_shape_value); + filter_type = cast(filter_val.getType()); + + auto bias_result = getTosaBias(op, rewriter, input_type, output_type, + output_is_qtype, tfl_fc_op.getBias()); + if (failed(bias_result)) return failure(); + auto [bias_ety, bias_val] = bias_result.value(); + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ bias_ety); + + auto fc_op = CreateOpAndInfer( + rewriter, op->getLoc(), UnrankedTensorType::get(bias_ety), input_val, + filter_val, bias_val, + /* pad = */ rewriter.getDenseI64ArrayAttr({0, 0, 0, 0}), + /* stride = */ rewriter.getDenseI64ArrayAttr({1, 1}), + /* dilation = */ rewriter.getDenseI64ArrayAttr({1, 1}), acc_type); + + // Sometimes we need to rescale the op to the output quantization space or + // expliciyly add variable bias + Value fc_output = handleConvRescaleAndBias(op, rewriter, fc_op.getResult(), + tfl_fc_op.getBias(), input_type, + filter_type, output_type); + + // If we know the output rank, we need to ensure the output shape is correct. + ShapedType fc_type = mlir::cast(fc_output.getType()); + + llvm::SmallVector output_shape; + if (tfl_fc_op.getKeepNumDims()) { + const llvm::ArrayRef orig_input_shape = tfl_fc_op.getInput().getType().getShape(); + output_shape.append(orig_input_shape.begin(), orig_input_shape.end() - 1); + output_shape.push_back(OC); + } else { + output_shape.append({N, OC}); + } + + auto output_shape_value = getTosaConstShape(rewriter, op->getLoc(), output_shape); + fc_output = CreateOpAndInfer( + rewriter, op->getLoc(), UnrankedTensorType::get(fc_type.getElementType()), + fc_output, output_shape_value); + + auto fused_activation_fn = tfl_fc_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = + convertFusedActivation(rewriter, op, fc_output, fused_activation_fn); + + if (!fused_activation_val) return failure(); + + rewriter.replaceOp(op, {fused_activation_val.value()}); + return success(); + } + + rewriter.replaceOp(op, {fc_output}); + + return success(); +} + +LogicalResult ConvertTFLConcatenationOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_concat_op = cast(op); + auto result_type = dyn_cast(tfl_concat_op.getResult().getType()); + + SmallVector values(tfl_concat_op.getValues()); + + IntegerAttr axis_attr; + { + auto tmpAttr = tfl_concat_op.getAxisAttr(); + if (!tmpAttr) { + tmpAttr = rewriter.getI32IntegerAttr(0); + } + axis_attr = tmpAttr; + } + int32_t axis = axis_attr.getInt(); + + std::optional result = + convertConcatV2Op(rewriter, op, result_type, values, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); +} + +LogicalResult ConvertTFLReshapeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_reshape_op = cast(op); + + Value shape = tfl_reshape_op.getShape(); + ShapedType shape_type = dyn_cast(shape.getType()); + ShapedType output_type = dyn_cast(tfl_reshape_op.getType()); + + int64_t rank = ShapedType::kDynamic; + if (output_type.hasRank()) rank = output_type.getRank(); + + // Check the inferred rank from the shape tensor matches the output. + if (shape_type.hasRank() && !shape_type.isDynamicDim(0)) { + int64_t dim = shape_type.getDimSize(0); + if (rank != ShapedType::kDynamic && rank != dim) { + return rewriter.notifyMatchFailure(op, + "static dim mismatch on tfl.reshape"); + } + rank = dim; + } + + if (rank == ShapedType::kDynamic) { + return rewriter.notifyMatchFailure(op, "unknown rank for output shape"); + } + + // Extract the dynamically shaped values for each dimension. + SmallVector shape_vals; + shape_vals.reserve(rank); + auto shape_ty = dyn_cast(shape.getType()); + for (int i = 0; i < rank; i++) { + auto e_ty = shape_ty.getElementType(); + Value dim = rewriter.createOrFold( + op->getLoc(), RankedTensorType::get({1}, e_ty), shape, + getTosaConstShape(rewriter, op->getLoc(), {i}), + getTosaConstShape(rewriter, op->getLoc(), {1})); + + auto shape_value = getTosaConstShape(rewriter, op->getLoc(), {}); + dim = rewriter.createOrFold( + op->getLoc(), RankedTensorType::get({}, e_ty), dim, shape_value); + shape_vals.push_back(dim); + } + + // Build the reshape operation with dynamic shapes. + auto reshape = + buildReshapeWithDynamicDims(rewriter, op, tfl_reshape_op.getInput(), + tfl_reshape_op.getType(), shape_vals); + + if (!reshape.has_value()) return failure(); + + rewriter.replaceOp(op, {reshape.value()}); + return success(); +} + +LogicalResult ConvertTFLRankOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_rank_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_rank_op.getInput().getType()); + if (!input_type) return failure(); + + int32_t rank = input_type.getRank(); + + RankedTensorType rank_type = + RankedTensorType::get({1}, rewriter.getIntegerType(32)); + auto rank_attr = DenseI32ArrayAttr::get(rewriter.getContext(), {rank}); + auto rank_const = CreateOpAndInfer( + rewriter, op->getLoc(), rank_type, mlir::cast(rank_attr)); + + rewriter.replaceOp(op, {rank_const.getResult()}); + + return success(); +} + +LogicalResult ConvertTFLShapeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_shape_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_shape_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + RankedTensorType input_type = + dyn_cast(tfl_shape_op.getInput().getType()); + if (!input_type || !input_type.hasStaticShape()) + return rewriter.notifyMatchFailure(op, "input shape not static"); + + auto input_shape = input_type.getShape(); + + SmallVector shape_arr; + for (int i = 0; i < input_shape.size(); i++) { + shape_arr.emplace_back(input_shape[i]); + } + + RankedTensorType shape_type = RankedTensorType::get( + {static_cast(shape_arr.size())}, rewriter.getIntegerType(32)); + auto shape_attr = + DenseI32ArrayAttr::get(rewriter.getContext(), llvm::ArrayRef(shape_arr)); + auto shape_const = CreateOpAndInfer( + rewriter, op->getLoc(), shape_type, mlir::cast(shape_attr)); + + rewriter.replaceOp(op, {shape_const.getResult()}); + + return success(); +} + +LogicalResult ConvertTFLExpandDimsOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_expanddims_op = cast(op); + + std::optional result = convertExpandDimsOp( + rewriter, op, tfl_expanddims_op.getResult(), tfl_expanddims_op.getInput(), + tfl_expanddims_op.getDim()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSqueezeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_squeeze_op = cast(op); + + // Copy squeeze_dims into int32_t array + auto squeeze_dims_attr = tfl_squeeze_op.getSqueezeDimsAttr(); + SmallVector squeeze_dims; + for (auto& squeeze_dim : squeeze_dims_attr) { + squeeze_dims.emplace_back(dyn_cast(squeeze_dim).getInt()); + } + + std::optional result = + convertSqueezeOp(rewriter, op, tfl_squeeze_op.getResult(), + tfl_squeeze_op.getInput(), squeeze_dims); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLFillOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_fill_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_fill_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + ElementsAttr dims_elems; + if (!matchPattern(tfl_fill_op.getDims(), m_Constant(&dims_elems))) + return failure(); + SmallVector dims_vals; + uint32_t total_size = 1; + for (int i = 0; i < dims_elems.getNumElements(); i++) { + dims_vals.push_back(dims_elems.getValues()[i].getSExtValue()); + total_size *= dims_vals[i]; + } + + ElementsAttr value_elem; + if (!matchPattern(tfl_fill_op.getInput(), m_Constant(&value_elem))) + return failure(); + + RankedTensorType fill_type = + RankedTensorType::get(ArrayRef(dims_vals), + value_elem.getShapedType().getElementType()); + DenseArrayAttr fill_attr; + + // Convert to a compatible zero type. + if (mlir::isa(value_elem.getShapedType().getElementType())) { + SmallVector fill_arr( + total_size, value_elem.getValues()[0].convertToFloat()); + fill_attr = + DenseF32ArrayAttr::get(rewriter.getContext(), llvm::ArrayRef(fill_arr)); + } else { + SmallVector fill_arr( + total_size, value_elem.getValues()[0].getLimitedValue()); + fill_attr = + DenseI32ArrayAttr::get(rewriter.getContext(), llvm::ArrayRef(fill_arr)); + } + auto fill_const_op = CreateOpAndInfer( + rewriter, op->getLoc(), fill_type, mlir::cast(fill_attr)); + rewriter.replaceOp(op, {fill_const_op.getResult()}); + + return success(); +} + +LogicalResult ConvertTFLReduceAllOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_all_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_all_op.getResult().getType()); + + if (!output_type) + return rewriter.notifyMatchFailure(op, "output not a ranked tensor"); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_all_op.getReductionIndices(), m_Constant(&axes_elems))) + return rewriter.notifyMatchFailure(op, "fail to get reduction indices"); + + std::optional result = convertReduceAllOp( + rewriter, op, output_type, tfl_all_op.getInput(), axes_elems, tfl_all_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLReduceAnyOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_any_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_any_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_any_op.getReductionIndices(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceAnyOp( + rewriter, op, output_type, tfl_any_op.getInput(), axes_elems, tfl_any_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLReduceMaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_max_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_max_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_max_op.getAxes(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceMaxOp( + rewriter, op, output_type, tfl_max_op.getInput(), axes_elems, tfl_max_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLReduceMinOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_min_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_min_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_min_op.getAxes(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceMinOp( + rewriter, op, output_type, tfl_min_op.getInput(), axes_elems, tfl_min_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLReduceProdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_prod_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_prod_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_prod_op.getAxes(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceProdOp( + rewriter, op, output_type, tfl_prod_op.getInput(), axes_elems, tfl_prod_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLMeanOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_mean_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_mean_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_mean_op.getAxis(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceMeanOp( + rewriter, op, output_type, tfl_mean_op.getInput(), axes_elems, tfl_mean_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSumOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_sum_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_sum_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr axes_elems; + if (!matchPattern(tfl_sum_op.getAxes(), m_Constant(&axes_elems))) + return failure(); + + std::optional result = convertReduceSumOp( + rewriter, op, output_type, tfl_sum_op.getInput(), axes_elems, tfl_sum_op.getKeepDims()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLEluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_elu_op = cast(op); + + std::optional result = + convertEluOp(rewriter, op, tfl_elu_op.getResult(), tfl_elu_op.getX()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSoftmaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_softmax_op = cast(op); + + std::optional result = convertSoftmaxOp( + rewriter, op, tfl_softmax_op.getResult(), tfl_softmax_op.getInput(), + tfl_softmax_op.getBetaAttr().getValueAsDouble()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLRsqrtOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_rsqrt_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_rsqrt_op.getResult().getType()); + RankedTensorType input_type = + dyn_cast(tfl_rsqrt_op.getX().getType()); + + mlir::quant::UniformQuantizedType input_qtype = + mlir::dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType output_qtype = + mlir::dyn_cast_or_null( + output_type.getElementType()); + + // Quantization case + if (input_qtype && output_qtype) { + // 16-bit is pending review for TFL + // https://github.com/tensorflow/tensorflow/pull/58406 + if (input_qtype.getStorageTypeIntegralWidth() != 8) { + return rewriter.notifyMatchFailure(op, + "input qtype storage width is not 8"); + } + + // Implement with 8-bit table lookup. + Value table_const = getTosaConstRsqrt8bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint()); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_rsqrt_op.getX(), table_const); + return success(); + } + + CreateReplaceOpAndInfer(rewriter, op, tfl_rsqrt_op.getType(), + tfl_rsqrt_op.getX()); + + return success(); +} + +LogicalResult ConvertTFLSqrtOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_rsqrt_op = cast(op); + auto rsqrt = CreateOpAndInfer( + rewriter, op->getLoc(), tfl_rsqrt_op.getType(), tfl_rsqrt_op.getX()); + + CreateReplaceOpAndInfer(rewriter, op, rsqrt.getType(), + rsqrt); + + return success(); +} + +LogicalResult ConvertTFLL2NormalizationOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_l2norm_op = cast(op); + auto input = tfl_l2norm_op.getInput(); + auto input_ty = mlir::cast(input.getType()); + auto loc = op->getLoc(); + + if (!input_ty.hasRank()) return failure(); + + auto rank = input_ty.getRank(); + + if (input_ty.getElementType().isF32()) { + auto result_ty = UnrankedTensorType::get(input_ty.getElementType()); + auto mul = CreateMulOpAndInfer(rewriter, op, result_ty, input, input); + auto sum = CreateOpAndInfer( + rewriter, loc, result_ty, mul, + rewriter.getI32IntegerAttr(input_ty.getRank() - 1)); + + SmallVector min(1, sqrt(std::numeric_limits::min())); + Value min_val = getTosaConstTensorSingleF32( + rewriter, op, sqrt(std::numeric_limits::min()), rank); + auto max = CreateOpAndInfer(rewriter, loc, result_ty, sum, + min_val); + auto rsqrt = CreateOpAndInfer(rewriter, loc, result_ty, max) + .getResult(); + Value result = + CreateMulOpAndInfer(rewriter, op, result_ty, rsqrt, input).getResult(); + + auto fused_activation_fn = tfl_l2norm_op.getFusedActivationFunctionAttr(); + + if (fused_activation_fn) { + std::optional fused_activation_val = + convertFusedActivation(rewriter, op, result, fused_activation_fn); + if (!fused_activation_val) return failure(); + result = fused_activation_val.value(); + } + + rewriter.replaceOp(op, result); + return success(); + } + + return failure(); +} + +LogicalResult ConvertTFLLogSoftmaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_logsoftmax_op = cast(op); + + std::optional result = + convertLogSoftmaxOp(rewriter, op, tfl_logsoftmax_op.getResult(), + tfl_logsoftmax_op.getInput()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSliceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_slice_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_slice_op.getResult().getType()); + // Not a shaped tensor output + if (!output_type) return failure(); + + ElementsAttr begin_elems, size_elems; + + SmallVector begin_vals, size_vals; + + if (!matchPattern(tfl_slice_op.getBegin(), m_Constant(&begin_elems)) || + !matchPattern(tfl_slice_op.getSize(), m_Constant(&size_elems))) { + return failure(); + } + + auto input = tfl_slice_op.getInput(); + RankedTensorType input_type = cast(input.getType()); + ArrayRef shape = input_type.getShape(); + size_t rank = shape.size(); + assert(begin_elems.getNumElements() == rank); + assert(size_elems.getNumElements() == rank); + + const int64_t to_end = -1; + for (int i = 0; i < rank; i++) { + int64_t begin = begin_elems.getValues()[i].getSExtValue(); + int64_t size = size_elems.getValues()[i].getSExtValue(); + size = (size == to_end) ? shape[i] - begin : size; + begin_vals.push_back(begin); + size_vals.push_back(size); + } + + CreateReplaceOpAndInfer( + rewriter, op, output_type, input, + getTosaConstShape(rewriter, op->getLoc(), begin_vals), + getTosaConstShape(rewriter, op->getLoc(), size_vals)); + + return success(); +} + +LogicalResult ConvertTFLTileOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_tile_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_tile_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + ElementsAttr multiples_elems; + if (!matchPattern(tfl_tile_op.getMultiples(), m_Constant(&multiples_elems))) + return failure(); + SmallVector multiples_vals; + for (int i = 0; i < multiples_elems.getNumElements(); i++) + multiples_vals.push_back( + multiples_elems.getValues()[i].getSExtValue()); + + auto multiples = getTosaConstShape(rewriter, op->getLoc(), multiples_vals); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_tile_op.getInput(), multiples); + + return success(); +} + +LogicalResult ConvertTFLTransposeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_transpose_op = cast(op); + + // Get the constant values for perm input + ElementsAttr permsAttrElems; + if (!matchPattern(tfl_transpose_op.getPerm(), m_Constant(&permsAttrElems))) { + return rewriter.notifyMatchFailure(op, "perm value is not constant"); + } + + SmallVector perms; + for (auto v : permsAttrElems.getValues()) { + perms.push_back(v.getSExtValue()); + } + + Type output_type = tfl_transpose_op.getResult().getType(); + CreateReplaceOpAndInfer( + rewriter, op, output_type, tfl_transpose_op.getInput(), + rewriter.getDenseI32ArrayAttr(perms)); + + return success(); +} + +LogicalResult ConvertTFLPackOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_pack_op = cast(op); + + SmallVector inputs(tfl_pack_op.getValues()); + assert(!inputs.empty()); + + IntegerAttr axis_attr; + { + auto tmpAttr = tfl_pack_op.getAxisAttr(); + if (!tmpAttr) tmpAttr = rewriter.getI32IntegerAttr(0); + axis_attr = tmpAttr; + } + int32_t axis_i32 = axis_attr.getInt(); + + std::optional result = + convertPackOp(rewriter, op, tfl_pack_op.getResult(), inputs, axis_i32); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLUnpackOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_unpack_op = cast(op); + + IntegerAttr axis_attr; + { + auto tmpAttr = tfl_unpack_op.getAxisAttr(); + if (!tmpAttr) tmpAttr = rewriter.getI32IntegerAttr(0); + axis_attr = tmpAttr; + } + int32_t axis_i32 = axis_attr.getInt(); + + std::optional> results = + convertUnpackOp(rewriter, op, tfl_unpack_op.getInput(), axis_i32); + + if (!results) return failure(); + + rewriter.replaceOp(op, results.value()); + + return success(); +} + +// Splits in num_split parts along split_dim +LogicalResult ConvertTFLSplitOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_split_op = cast(op); + + // Get the number of splits + int32_t num_split = -1; + auto numSplitAttr = tfl_split_op.getNumSplitsAttr(); + if (numSplitAttr) { + num_split = numSplitAttr.getInt(); + } else { + return failure(); + } + + // Get the axis + ElementsAttr axisAttrElems; + if (!matchPattern(tfl_split_op.getSplitDim(), m_Constant(&axisAttrElems))) { + return rewriter.notifyMatchFailure(op, "cannot read split_dim elems"); + } + + // The axis/split_dim parameter is stored as a 0D tensor instead of + // an integer attribute in TFLite MLIR. + int32_t axis = axisAttrElems.getValues()[0].getSExtValue(); + + std::optional> results = + convertSplitOp(rewriter, op, tfl_split_op.getResult(0), + tfl_split_op.getValue(), num_split, axis); + + if (!results) return failure(); + + rewriter.replaceOp(op, results.value()); + + return success(); +} + +// Splits in num_split parts along split_dim +LogicalResult ConvertTFLSplitVOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_splitv_op = cast(op); + + // Get the size_splits array + SmallVector size_split; + ElementsAttr size_split_elems; + if (!matchPattern(tfl_splitv_op.getSizeSplits(), + m_Constant(&size_split_elems))) { + return failure(); + } + + for (int i = 0; i < size_split_elems.getNumElements(); i++) { + size_split.push_back(size_split_elems.getValues()[i].getSExtValue()); + } + + // Get the axis + ElementsAttr axisAttrElems; + if (!matchPattern(tfl_splitv_op.getSplitDim(), m_Constant(&axisAttrElems))) { + return rewriter.notifyMatchFailure(op, "cannot read split_dim elems"); + } + + // The axis/split_dim parameter is stored as a 0D tensor instead of + // an integer attribute in TFLite MLIR. + int32_t axis = axisAttrElems.getValues()[0].getSExtValue(); + + std::optional> results = + convertSplitVOp(rewriter, op, tfl_splitv_op.getResult(0), + tfl_splitv_op.getValue(), size_split, axis); + + if (!results) return failure(); + + rewriter.replaceOp(op, results.value()); + + return success(); +} + +LogicalResult ConvertTFLPadOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_pad_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_pad_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + SmallVector padding_vals; + if (failed(getVectorFromValue64(tfl_pad_op.getPadding(), padding_vals))) { + return rewriter.notifyMatchFailure(op, "padding is not a constant value"); + } + Value padding = getTosaConstShape(rewriter, op->getLoc(), padding_vals); + + auto pad_op = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, tfl_pad_op.getInput(), padding); + + rewriter.replaceOp(op, {pad_op.getResult()}); + return success(); +} + +LogicalResult ConvertTFLMirrorPadOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_mirrorpad_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_mirrorpad_op.getResult().getType()); + if (!output_type) { + return rewriter.notifyMatchFailure(op, "output type isn't a ranked tensor"); + } + + TFTFLMirrorPaddingType mode; + switch (tfl_mirrorpad_op.getMode()) { + case mlir::TFL::MirrorPaddingType::REFLECT: + mode = TFTFLMirrorPaddingType::REFLECT; + break; + case mlir::TFL::MirrorPaddingType::SYMMETRIC: + mode = TFTFLMirrorPaddingType::SYMMETRIC; + break; + default: + return rewriter.notifyMatchFailure( + op, "mode isn't one of REFLECT or SYMMETRIC"); + } + + std::optional result = convertMirrorPadCommon( + rewriter, op, output_type, tfl_mirrorpad_op.getInput(), + tfl_mirrorpad_op.getPad(), mode); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLPadV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_pad_op = cast(op); + + Value input = tfl_pad_op.getInput(); + Value constant_value = tfl_pad_op.getConstantValues(); + + Value rank1_scalar_value = + reshapeScalarTo1D(rewriter, op->getLoc(), constant_value); + if (!rank1_scalar_value) { + return rewriter.notifyMatchFailure( + op, "cannot reshape constant_value input to rank 1"); + } + + SmallVector padding_vals; + if (failed(getVectorFromValue64(tfl_pad_op.getPadding(), padding_vals))) { + return rewriter.notifyMatchFailure(op, "padding is not a constant value"); + } + + Value padding = getTosaConstShape(rewriter, op->getLoc(), padding_vals); + + CreateReplaceOpAndInfer(rewriter, op, tfl_pad_op.getType(), + input, padding, rank1_scalar_value); + + return success(); +} + +LogicalResult ConvertTFLResizeBilinearOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_resize_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_resize_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + std::optional result = convertResizeOp( + rewriter, op, output_type, tfl_resize_op.getInput(), + tosa::ResizeMode::BILINEAR, + tfl_resize_op.getAlignCornersAttr().getValue(), + tfl_resize_op.getHalfPixelCentersAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLResizeNearestNeighborOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_resize_op = cast(op); + + RankedTensorType output_type = + dyn_cast(tfl_resize_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + std::optional result = + convertResizeOp(rewriter, op, output_type, tfl_resize_op.getInput(), + tosa::ResizeMode::NEAREST_NEIGHBOR, + tfl_resize_op.getAlignCornersAttr().getValue(), + tfl_resize_op.getHalfPixelCentersAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSelectOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_sel_op = cast(op); + + std::optional result = convertSelectOp( + rewriter, op, tfl_sel_op.getResult(), tfl_sel_op.getCondition(), + tfl_sel_op.getX(), tfl_sel_op.getY()); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSelectV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_sel_op = cast(op); + + std::optional result = convertSelectOp( + rewriter, op, tfl_sel_op.getResult(), tfl_sel_op.getCondition(), + tfl_sel_op.getX(), tfl_sel_op.getY()); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSpaceToBatchNdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_s2b_op = cast(op); + std::optional result = convertSpaceToBatchNDOp( + rewriter, op, tfl_s2b_op.getResult(), tfl_s2b_op.getInput(), + tfl_s2b_op.getBlockShape(), tfl_s2b_op.getPaddings()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLBatchToSpaceNdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_b2s_op = cast(op); + + std::optional result = convertBatchToSpaceNDOp( + rewriter, op, tfl_b2s_op.getResult(), tfl_b2s_op.getInput(), + tfl_b2s_op.getBlockShape(), tfl_b2s_op.getIndices()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSpaceToDepthOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_s2d_op = cast(op); + + auto block_size_attr = tfl_s2d_op.getBlockSizeAttr(); + std::optional result = convertSpaceToDepthOp( + rewriter, op, tfl_s2d_op.getResult(), tfl_s2d_op.getInput(), + block_size_attr, rewriter.getStringAttr("NHWC")); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLDepthToSpaceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_d2s_op = cast(op); + + auto block_size_attr = tfl_d2s_op.getBlockSizeAttr(); + std::optional result = convertDepthToSpaceOp( + rewriter, op, tfl_d2s_op.getResult(), tfl_d2s_op.getInput(), + block_size_attr, rewriter.getStringAttr("NHWC")); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLBucketizeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_bucketize_op = cast(op); + Location loc = op->getLoc(); + + Value input = tfl_bucketize_op.getInput(); + auto boundaries_attr = tfl_bucketize_op.getBoundaries(); + RankedTensorType input_type = dyn_cast(input.getType()); + if (!input_type) { + return rewriter.notifyMatchFailure(op, "input is not a ranked tensor"); + } + + // The lowering is done by broadcasting the input and boundaries together, and + // using GE comparison for each input against each boundary. Adding the + // results of the comparison for each input generates the bucket it belongs + // to, as the boundaries are sorted. + ShapedType output_type = + dyn_cast(tfl_bucketize_op.getResult().getType()); + + auto input_shape = input_type.getShape(); + + SmallVector boundaries; + for (auto& boundary : boundaries_attr) { + boundaries.emplace_back(dyn_cast(boundary).getValue()); + } + int64_t boundaries_size = boundaries.size(); + + // Add a dim at the end of input shape for broadcasting with the boundaries. + SmallVector broadcast_shape(input_shape.begin(), input_shape.end()); + broadcast_shape.push_back(boundaries_size); + SmallVector new_input_shape(input_shape.begin(), input_shape.end()); + new_input_shape.push_back(1); + + auto boundaries_type = + RankedTensorType::get({boundaries_size}, rewriter.getF32Type()); + + auto boundaries_op = CreateOpAndInfer( + rewriter, loc, boundaries_type, + DenseElementsAttr::get(boundaries_type, boundaries)); + + auto boundaries_input_type = + boundaries_type.clone(input_type.getElementType()); + Value boundaries_op_casted = CreateOpAndInfer( + rewriter, loc, boundaries_input_type, boundaries_op); + + auto new_input_shape_value = getTosaConstShape(rewriter, op->getLoc(), new_input_shape); + Value reshaped_input = CreateOpAndInfer( + rewriter, loc, input_type.clone(new_input_shape), input, + new_input_shape_value); + + auto ge = CreateOpAndInfer( + rewriter, loc, UnrankedTensorType::get(rewriter.getIntegerType(1)), + reshaped_input, boundaries_op_casted); + + auto casted = CreateOpAndInfer( + rewriter, loc, UnrankedTensorType::get(rewriter.getIntegerType(32)), ge); + + auto sum = CreateOpAndInfer( + rewriter, loc, output_type, casted, + rewriter.getI32IntegerAttr(input_type.getRank())); + + auto output_shape_value = + getTosaConstShape(rewriter, op->getLoc(), output_type.getShape()); + CreateReplaceOpAndInfer(rewriter, op, output_type, sum, + output_shape_value); + + return success(); +} + +LogicalResult ConvertTFLStridedSliceOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_ss_op = cast(op); + + std::optional result = convertStridedSliceOp( + rewriter, op, tfl_ss_op.getResult(), tfl_ss_op.getInput(), + tfl_ss_op.getBegin(), tfl_ss_op.getEnd(), tfl_ss_op.getStrides(), + tfl_ss_op.getBeginMaskAttr().getInt(), + tfl_ss_op.getEndMaskAttr().getInt(), + tfl_ss_op.getEllipsisMaskAttr().getInt(), + tfl_ss_op.getNewAxisMaskAttr().getInt(), + tfl_ss_op.getShrinkAxisMaskAttr().getInt()); + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLZerosLikeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_zeroslike_op = cast(op); + + std::optional result = convertZerosLikeOp( + rewriter, op, tfl_zeroslike_op.getResult(), tfl_zeroslike_op.getInput()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLHardSwishOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_hardswish_op = cast(op); + RankedTensorType output_type = + dyn_cast(tfl_hardswish_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + RankedTensorType input_type = + dyn_cast(tfl_hardswish_op.getInput().getType()); + // Not a ranked tensor output + if (!input_type) return failure(); + + // TFL hardswish: f(x) -> (x * relu6(x+3))/6 + + if (mlir::isa(input_type.getElementType()) && + mlir::isa(output_type.getElementType())) { + // Should match TFLite reference numerical behavior + mlir::quant::UniformQuantizedType input_qtype = + mlir::dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType output_qtype = + mlir::dyn_cast_or_null( + output_type.getElementType()); + + if (input_qtype.getStorageTypeIntegralWidth() == 8) { + // Implement with 8-bit table lookup. + Value table_const = getTosaConstHardSwish8bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint()); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tfl_hardswish_op.getInput(), table_const); + } + + } else { + // op1 = constop(3) + // op2 = add(x, op1) + // op3 = clamp(op2, 0, 6) + // op4 = mul(x, op3) + // op5 = reciprocal(6) + // op6 = mul (op4, op5) + + auto rank = input_type.getRank(); + + Value op1_value = getTosaConstTensorSingleF32(rewriter, op, 3.0, rank); + + auto op2_add_x_op1 = + CreateOpAndInfer(rewriter, op->getLoc(), output_type, + tfl_hardswish_op.getInput(), op1_value); + + auto op3_relu_op2_6 = CreateOpAndInfer( + rewriter, op->getLoc(), output_type, op2_add_x_op1.getResult(), + /* min_val = */ rewriter.getF32FloatAttr(0.0f), + /* max_val = */ rewriter.getF32FloatAttr(6.0f)); + + auto op4_mul_x_op3 = CreateMulOpAndInfer(rewriter, op, output_type, + tfl_hardswish_op.getInput(), + op3_relu_op2_6.getResult()); + + auto const_6 = getTosaConstTensorSingleF32(rewriter, op, 6.0, rank); + auto op5_reciprocal_6 = CreateOpAndInfer( + rewriter, op->getLoc(), const_6.getType(), const_6); + + auto op6_mul_op4_op5 = CreateMulOpAndInfer(rewriter, op, output_type, + op4_mul_x_op3.getResult(), + op5_reciprocal_6.getResult()); + + rewriter.replaceOp(op, {op6_mul_op4_op5.getResult()}); + } + + return success(); +} + +LogicalResult ConvertTFLSinOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_sin_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_sin_op.getResult().getType()); + + if (!output_type) + return rewriter.notifyMatchFailure(op, "output_type required"); + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_sin_op.getX()); + + return success(); +} + +LogicalResult ConvertTFLCosOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_cos_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_cos_op.getResult().getType()); + if (!output_type) + return rewriter.notifyMatchFailure(op, "output_type required"); + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_cos_op.getX()); + + return success(); +} + +LogicalResult ConvertTFLAtan2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_atan2_op = cast(op); + Location loc = op->getLoc(); + Value input_y = tfl_atan2_op.getY(); + Value input_x = tfl_atan2_op.getX(); + + auto input_y_ty = dyn_cast(input_y.getType()); + auto input_x_ty = dyn_cast(input_x.getType()); + auto output_ty = dyn_cast(tfl_atan2_op.getResult().getType()); + + if (!input_y_ty || !input_x_ty || !output_ty) { + return rewriter.notifyMatchFailure(op, "ranked inputs/output required"); + } + + if (!input_y_ty.getElementType().isF32()) { + return rewriter.notifyMatchFailure(op, "input must be fp32"); + } + + // To perform an atan2 operation we make use of an atan lookup table, + // then determine the correct quadrant for each output. To restrict the + // input domain of the lookup table from [-inf, inf] to [0, 1], we make + // use of two identities and undo the transformation later on: + // + // acrtan(z) = π/2 - arctan(1/z) (0) + // + // and + // + // arctan(-z) = -arctan(z) (1) + + auto rank = input_x_ty.getRank(); + Value pi = getTosaConstTensorSingleF32(rewriter, op, M_PI, rank); + Value pi_2 = getTosaConstTensorSingleF32(rewriter, op, M_PI_2, rank); + Value zero = getTosaConstTensorSingleF32(rewriter, op, 0.0, rank); + Value one = getTosaConstTensorSingleF32(rewriter, op, 1.0, rank); + Value two = getTosaConstTensorSingleF32(rewriter, op, 2.0, rank); + + // 1. Restrict the input to the atan lookup from [-inf, inf] to [0, 1]. + // By utilizing (0) and (1) we compute: min(|x|, |y|) / max(|x|, |y|). + auto abs_y = + CreateOpAndInfer(rewriter, loc, input_y_ty, input_y); + auto abs_x = + CreateOpAndInfer(rewriter, loc, input_y_ty, input_x); + auto min_xy = CreateOpAndInfer(rewriter, loc, input_y_ty, + abs_y, abs_x); + auto max_xy = CreateOpAndInfer(rewriter, loc, input_y_ty, + abs_y, abs_x); + auto recip = + CreateOpAndInfer(rewriter, loc, input_y_ty, max_xy); + auto atan_input = + CreateMulOpAndInfer(rewriter, op, input_y_ty, recip, min_xy); + + // 2. Scale and translate the normalized domain to the table domain. This + // includes a translating and scaling to [-int16_max, int16_max] and casting + // to an i16 as it is the highest precision the table operation supports. + auto fp_scalar_ty = RankedTensorType::get({}, rewriter.getF32Type()); + auto scale_up = + CreateMulOpAndInfer(rewriter, op, input_y_ty, atan_input, two); + Value translate = + CreateOpAndInfer(rewriter, loc, input_y_ty, scale_up, one); + Value int_limit = rewriter.create( + loc, fp_scalar_ty, + DenseElementsAttr::get( + fp_scalar_ty, + {static_cast(std::numeric_limits::max())})); + auto int_scaled = + CreateMulOpAndInfer(rewriter, op, input_y_ty, translate, int_limit); + + auto int16_ty = input_y_ty.clone(rewriter.getIntegerType(16)); + auto casted = + CreateOpAndInfer(rewriter, loc, int16_ty, int_scaled); + + // 3. Compute a lookup table using the domain of [0, 1] for atan. + // Note: the implementation of std::atan2 may be different on + // different machines, so may result in varying numerical results. + auto atan_func = [](double x) -> double { return std::atan(x); }; + Value table_const = getTosaConst16bitTable( + rewriter, op, 1.0 / 65535.0, -32768, 2.0 / 65535.0, 0, atan_func); + auto table_result = CreateOpAndInfer( + rewriter, loc, output_ty.clone(rewriter.getIntegerType(32)), casted, + table_const); + + // 4. The range of table is a 23-bit two's complement value. Normalize the + // range by casting to an fp32 and dividing by 2^22. + auto table_result_fp = + CreateOpAndInfer(rewriter, loc, output_ty, table_result); + auto output_scale = rewriter.create( + loc, fp_scalar_ty, + DenseElementsAttr::get( + fp_scalar_ty, + {static_cast(1.0 / static_cast(1 << 22))})); + auto table_output = CreateMulOpAndInfer(rewriter, op, output_ty, + table_result_fp, output_scale); + + auto bool_ty = output_ty.clone(rewriter.getIntegerType(1)); + + // 5. If (0) was applied to the atan input, apply π/2 - table_output. + auto sub_pi_2 = CreateOpAndInfer(rewriter, loc, output_ty, pi_2, + table_output); + auto condition = + CreateOpAndInfer(rewriter, loc, bool_ty, abs_y, abs_x); + auto transform_output = CreateOpAndInfer( + rewriter, loc, output_ty, condition, sub_pi_2, table_output); + + // 6. Determine the correct atan2 quadrant. + // If x < 0, apply π - transform_output. + auto sub_pi = CreateOpAndInfer(rewriter, loc, output_ty, pi, + transform_output); + auto cond_1 = + CreateOpAndInfer(rewriter, loc, bool_ty, zero, input_x); + auto quadrant_select = CreateOpAndInfer( + rewriter, loc, output_ty, cond_1, sub_pi, transform_output); + + // 7. If (1) was applied to the atan input, negate output. + auto neg_r = CreateOpAndInfer(rewriter, loc, output_ty, + quadrant_select); + auto cond_2 = + CreateOpAndInfer(rewriter, loc, bool_ty, zero, input_y); + CreateReplaceOpAndInfer(rewriter, op, output_ty, cond_2, + neg_r, quadrant_select); + + return success(); +} + +LogicalResult ConvertTFLLogisticOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_logistic_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_logistic_op.getResult().getType()); + RankedTensorType input_type = + dyn_cast(tfl_logistic_op.getX().getType()); + if (!input_type || !output_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + if (input_is_qtype) { + ShapedType int32_type = output_type.clone(rewriter.getIntegerType(32)); + mlir::quant::UniformQuantizedType input_qtype = + mlir::dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType output_qtype = + mlir::dyn_cast_or_null( + output_type.getElementType()); + + auto sigmoid_func = [](double x) -> double { + return 1.0 / (1.0 + std::exp(-x)); + }; + + if (input_qtype.getStorageTypeIntegralWidth() == 8) { + Value table_const = getTosaConst8bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint(), sigmoid_func); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tfl_logistic_op.getX(), table_const); + } else { // int16 + if (input_qtype.getZeroPoint() != 0 || output_qtype.getZeroPoint() != 0) { + return rewriter.notifyMatchFailure( + op, "input/output zeropoint should be 0 in 16-bit mode"); + } + + Value table_const = + getTosaConst16bitTable(rewriter, op, input_qtype.getScale(), + 0, 2.0 / 65535.0, 0, sigmoid_func); + + auto op1_table_in = + CreateOpAndInfer(rewriter, op->getLoc(), int32_type, + tfl_logistic_op.getX(), table_const); + + Value op2_rescale_op1 = + buildRescale(rewriter, op, output_type, op1_table_in.getResult(), + 1.0 / 128.0, 0, 0, tosa::RoundingMode::SINGLE_ROUND, true); + + rewriter.replaceOp(op, {op2_rescale_op1}); + } + } else { + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_logistic_op.getX()); + } + + return success(); +} + +LogicalResult ConvertTFLTanhOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_tanh_op = cast(op); + ShapedType output_type = + dyn_cast(tfl_tanh_op.getResult().getType()); + RankedTensorType input_type = + dyn_cast(tfl_tanh_op.getInput().getType()); + if (!input_type || !output_type) return failure(); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + if (input_is_qtype) { + ShapedType int32_type = output_type.clone(rewriter.getIntegerType(32)); + mlir::quant::UniformQuantizedType input_qtype = + mlir::dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType output_qtype = + mlir::dyn_cast_or_null( + output_type.getElementType()); + + auto tanh_func = [](double x) -> double { + x = std::exp(-2.0 * x); + return (1.0 - x) / (1.0 + x); + }; + + if (input_qtype.getStorageTypeIntegralWidth() == 8) { + Value table_const = getTosaConst8bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint(), tanh_func); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, tfl_tanh_op.getInput(), table_const); + } else { // int16 + if (input_qtype.getZeroPoint() != 0 || output_qtype.getZeroPoint() != 0) { + return rewriter.notifyMatchFailure( + op, "input/output zeropoint should be 0 in 16-bit mode"); + } + + Value table_const = getTosaConst16bitTable( + rewriter, op, input_qtype.getScale(), 0, 2.0 / 65535.0, 0, tanh_func); + + auto op1_table_in = + CreateOpAndInfer(rewriter, op->getLoc(), int32_type, + tfl_tanh_op.getInput(), table_const); + + Value op2_rescale_op1 = + buildRescale(rewriter, op, output_type, op1_table_in.getResult(), + 1.0 / 128.0, 0, 0, tosa::RoundingMode::SINGLE_ROUND, true); + + rewriter.replaceOp(op, {op2_rescale_op1}); + } + + } else { + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_tanh_op.getInput()); + } + + return success(); +} + +static LogicalResult LegalizeFloatingPointPrelu(Operation* op, + PatternRewriter& rewriter, + Value input, Value alpha, + ShapedType output_type) { + Value mul = CreateMulOpAndInfer(rewriter, op, output_type, input, alpha); + auto rank = mlir::cast(mul.getType()).getRank(); + Value const_zero = getTosaConstTensorSingleF32(rewriter, op, 0.0, rank); + auto ge = CreateOpAndInfer( + rewriter, op->getLoc(), output_type.clone(rewriter.getIntegerType(1)), + input, const_zero); + + CreateReplaceOpAndInfer(rewriter, op, output_type, ge, input, + mul); + + return success(); +} + +static LogicalResult LegalizeQuantizedPrelu(Operation* op, + PatternRewriter& rewriter, + Value input, double alpha_scale, + ShapedType output_type) { + auto tfl_prelu_op = dyn_cast(op); + + if (tfl_prelu_op == nullptr) + return rewriter.notifyMatchFailure(op, "op is not PReLU"); + + ShapedType rescale_type = output_type.clone(rewriter.getI32Type()); + ShapedType input_type = dyn_cast(input.getType()); + + UniformQuantizedType input_qtype = + dyn_cast(input_type.getElementType()); + UniformQuantizedType output_qtype = + dyn_cast(output_type.getElementType()); + + if (!input_qtype || !output_qtype) + return rewriter.notifyMatchFailure( + op, "input or output is not an uniform quantized type"); + + double scale_alpha = + input_qtype.getScale() * alpha_scale / output_qtype.getScale(); + + double scale_identity = input_qtype.getScale() / output_qtype.getScale(); + + // Implement PReLU as: + // rescaled_in = rescale(in) + // rescaled_alpha = rescale(alpha) + // rescaled_identity_in = rescale(in, scale_identity) + // slope_in = mul(rescaled_in, rescaled_alpha) + // rescaled_slope_in = rescale(slope_in, scale_alpha) + // cond_result = greater_equal(rescaled_in, 0) + // output = select(cond_result, rescaled_identity_in, rescaled_slope_in) + + Value op_rescale_in = removeZeroPointAndCastToInt32( + rewriter, op, input, input_qtype.getZeroPoint()); + auto rank = rescale_type.getRank(); + Value const_zero = getTosaConstTensorSingleI32(rewriter, op, 0, rank); + Value op_ge = CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type.clone(rewriter.getI1Type()), + op_rescale_in, const_zero); + + // Initalize the negative values to the slope of leaky ReLU. + Value op_rescale_slope_in = buildRescale( + rewriter, op, output_type, input, scale_alpha, input_qtype.getZeroPoint(), + output_qtype.getZeroPoint(), tosa::RoundingMode::DOUBLE_ROUND, true); + + // Perform an element-wise multiplication on rescaled alpha and input for + // PReLU. + Value alpha = tfl_prelu_op.getAlpha(); + ShapedType alpha_type = mlir::cast(alpha.getType()); + UniformQuantizedType alpha_qtype = + mlir::cast(alpha_type.getElementType()); + + Value op_rescale_alpha = removeZeroPointAndCastToInt32( + rewriter, op, alpha, alpha_qtype.getZeroPoint()); + + Value op_mul = CreateMulOpAndInfer(rewriter, op, rescale_type, op_rescale_in, + op_rescale_alpha); + + op_rescale_slope_in = + buildRescale(rewriter, op, output_type, op_mul, scale_alpha, + /* input_zp = */ 0, output_qtype.getZeroPoint(), tosa::RoundingMode::DOUBLE_ROUND, true); + + Value op_rescale_identity_in = buildRescale( + rewriter, op, output_type, input, scale_identity, + input_qtype.getZeroPoint(), output_qtype.getZeroPoint(), tosa::RoundingMode::DOUBLE_ROUND, true); + + CreateReplaceOpAndInfer(rewriter, op, output_type, op_ge, + op_rescale_identity_in, + op_rescale_slope_in); + + return success(); +} + +LogicalResult ConvertTFLPReluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_prelu_op = cast(op); + + ShapedType input_type = + dyn_cast(tfl_prelu_op.getInput().getType()); + ShapedType output_type = + dyn_cast(tfl_prelu_op.getResult().getType()); + ShapedType alpha_type = + dyn_cast(tfl_prelu_op.getAlpha().getType()); + + if (!input_type || !output_type || !alpha_type) + return rewriter.notifyMatchFailure( + op, "input, output, or alpha is not a ShapedType"); + + if (auto alpha_qtype = + dyn_cast(alpha_type.getElementType())) { + return LegalizeQuantizedPrelu(op, rewriter, tfl_prelu_op.getInput(), + alpha_qtype.getScale(), output_type); + } + + return LegalizeFloatingPointPrelu(op, rewriter, tfl_prelu_op.getInput(), + tfl_prelu_op.getAlpha(), output_type); +} + +static LogicalResult LegalizeQuantizedLeakyRelu(Operation* op, + PatternRewriter& rewriter, + Value input, double alpha, + ShapedType output_type) { + ShapedType input_type = mlir::cast(input.getType()); + ShapedType rescale_type = input_type.clone(rewriter.getI32Type()); + + UniformQuantizedType input_qtype = + cast(input_type.getElementType()); + + UniformQuantizedType output_qtype = + cast(output_type.getElementType()); + + double scale_alpha = input_qtype.getScale() * alpha / output_qtype.getScale(); + + double scale_identity = input_qtype.getScale() / output_qtype.getScale(); + + // Implement leaky ReLU as: + // op_rescale_identity_in = rescale(in, scale_identity) to Int32 + // op_rescale_alpha_in = rescale(in, scale_alpha) to Int32 + // + // alpha <= 1: result_int32 = max(op_rescale_identity_in, + // op_rescale_alpha_in) + // alpha >= 1: result_int32 = min(op_rescale_identity_in, + // op_rescale_alpha_in) + // + // output = rescaleFromInt32(result_int32) to output_type + + Value op_rescale_alpha_in = + buildRescale(rewriter, op, rescale_type, input, scale_alpha, + input_qtype.getZeroPoint(), 0, tosa::RoundingMode::DOUBLE_ROUND, true); + + Value op_rescale_identity_in = + buildRescale(rewriter, op, rescale_type, input, scale_identity, + input_qtype.getZeroPoint(), 0, tosa::RoundingMode::DOUBLE_ROUND, true); + + Value result_int32; + if (alpha <= 1.0) { + auto max_op = CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type, op_rescale_identity_in, + op_rescale_alpha_in); + result_int32 = max_op.getResult(); + } else { + auto min_op = CreateOpAndInfer( + rewriter, op->getLoc(), rescale_type, op_rescale_identity_in, + op_rescale_alpha_in); + result_int32 = min_op.getResult(); + } + + Value output = buildRescaleFromInt32(rewriter, op, output_type, result_int32, + 1.0, output_qtype.getZeroPoint()); + + rewriter.replaceOp(op, {output}); + + return success(); +} + +static LogicalResult LegalizeFloatingPointLeakyRelu(Operation* op, + PatternRewriter& rewriter, + Value input, double alpha, + ShapedType output_type) { + auto rank = mlir::cast(input.getType()).getRank(); + Value const_alpha = getTosaConstTensorSingleF32(rewriter, op, alpha, rank); + auto mul = CreateMulOpAndInfer(rewriter, op, output_type, input, const_alpha); + if (alpha <= 1.0) { + // leaky_relu( input ) = max(input*alpha, input) + CreateReplaceOpAndInfer(rewriter, op, output_type, mul, + input); + } else { + // leaky_relu( input ) = min(input*alpha, input) + CreateReplaceOpAndInfer(rewriter, op, output_type, mul, + input); + } + return success(); +} + +LogicalResult ConvertTFLLeakyReluOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_leakyrelu_op = cast(op); + RankedTensorType input_type = + dyn_cast(tfl_leakyrelu_op.getInput().getType()); + + ShapedType output_type = + dyn_cast(tfl_leakyrelu_op.getResult().getType()); + + if (!input_type || !output_type) + return rewriter.notifyMatchFailure(op, + "input or output is not a ShapedType"); + + bool input_is_qtype = + mlir::isa(input_type.getElementType()); + bool output_is_qtype = mlir::isa( + output_type.getElementType()); + + if (input_is_qtype != output_is_qtype) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or " + "all floating-point"); + } + + // Implement LeakyRelu as element-wise: + // out = x > 0 ? x : alpha * x + // + // alpha <= 1: leaky_relu( x ) = max(x*alpha, x) + // alpha >= 1: leaky_relu( x ) = min(x*alpha, x) + + FloatAttr tmpAttr = tfl_leakyrelu_op.getAlphaAttr(); + // There is disagreement between the MLIR .td defaults and TF + // documentation on 0.2 vs 0.3, but 0.2 will be used here. + double alpha = 0.2; + + if (tmpAttr) { + alpha = tmpAttr.getValueAsDouble(); + } + + Value input = tfl_leakyrelu_op.getInput(); + + if (output_is_qtype) { + return LegalizeQuantizedLeakyRelu(op, rewriter, input, alpha, output_type); + } + return LegalizeFloatingPointLeakyRelu(op, rewriter, input, alpha, + output_type); +} + +LogicalResult ConvertTFLNegOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_neg_op = cast(op); + ShapedType output_type = + dyn_cast(tfl_neg_op.getResult().getType()); + if (!output_type) return failure(); + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_neg_op.getX()); + + return success(); +} + +LogicalResult ConvertTFLYieldOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + rewriter.replaceOpWithNewOp(op, op->getResultTypes(), + op->getOperands()); + + return success(); +} + +LogicalResult ConvertTFLCustomOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_custom_op = cast(op); + rewriter.replaceOpWithNewOp( + op, op->getResultTypes(), tfl_custom_op.getCustomCode(), + rewriter.getStringAttr("TFL"), + mlir::cast(tfl_custom_op.getCustomOption()) + .getValue() + .str(), + op->getOperands()); + + return success(); +} + +LogicalResult ConvertTFLReverseV2Op::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_reverse_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_reverse_op.getInput().getType()); + if (!input_type) { + return rewriter.notifyMatchFailure(op, "input_type is unranked"); + } + + ElementsAttr axis_elems; + if (!matchPattern(tfl_reverse_op.getAxis(), m_Constant(&axis_elems))) { + return rewriter.notifyMatchFailure(op, "axis values not constant"); + } + + auto input_rank = input_type.getShape().size(); + llvm::SmallVector axis_vals; + for (auto axis : axis_elems.getValues()) { + int64_t axis_val = axis.getSExtValue(); + if (axis_val < 0) axis_val += input_rank; + if (axis_val < 0 || axis_val >= input_rank) { + return rewriter.notifyMatchFailure( + op, "axis values not within range of input shape"); + } + axis_vals.push_back(axis_val); + } + + Value val = tfl_reverse_op.getInput(); + if (axis_elems.getNumElements() == 0) { + auto identity_op = CreateOpAndInfer( + rewriter, op->getLoc(), input_type, val); + val = identity_op.getResult(); + } else { + for (auto axis_val : axis_vals) { + auto axis_attr = rewriter.getI32IntegerAttr(axis_val); + auto reverse_op = CreateOpAndInfer( + rewriter, op->getLoc(), input_type, val, axis_attr); + + val = reverse_op.getResult(); + } + } + + rewriter.replaceOp(op, {val}); + + return success(); +} + +LogicalResult ConvertTFLQuantizeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_quantize_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_quantize_op.getInput().getType()); + ShapedType output_type = + dyn_cast(tfl_quantize_op.getResult().getType()); + if (!input_type || !output_type) return failure(); + + ShapedType qtype = + dyn_cast(tfl_quantize_op.getResult().getType()); + if (!qtype) return failure(); + + UniformQuantizedType element_type = + dyn_cast(qtype.getElementType()); + if (!element_type) return failure(); + + UniformQuantizedType input_element_type = + dyn_cast(input_type.getElementType()); + + // If input is already a quantized type, this is basically a RESCALE (or + // tensorflow::ops::Requantize) + if (input_element_type) { + double rescale_scale = + input_element_type.getScale() / element_type.getScale(); + Value rescale_op = + buildRescale(rewriter, op, output_type, tfl_quantize_op.getInput(), + rescale_scale, input_element_type.getZeroPoint(), + element_type.getZeroPoint(), tosa::RoundingMode::DOUBLE_ROUND, true); + + rewriter.replaceOp(op, {rescale_op}); + return success(); + } else { + double scale = 1 / element_type.getScale(); + int64_t zp = element_type.getZeroPoint(); + int64_t num_bits = element_type.getStorageTypeIntegralWidth(); + zp = element_type.isSigned() ? zp : zp - (1 << (num_bits - 1)); + + std::optional result = convertQuantizeOp( + rewriter, op, output_type, tfl_quantize_op.getInput(), scale, zp); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); + } +} + +LogicalResult ConvertTFLDequantizeOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_dequantize_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_dequantize_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + RankedTensorType qtype = + dyn_cast(tfl_dequantize_op.getInput().getType()); + if (!qtype) return failure(); + + Type element_type = qtype.getElementType(); + if (mlir::isa(element_type)) { + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_dequantize_op.getInput()); + return success(); + } + + if (auto eq_ty = dyn_cast(element_type)) { + double scale = eq_ty.getScale(); + int64_t zp = eq_ty.getZeroPoint(); + int64_t num_bits = eq_ty.getStorageTypeIntegralWidth(); + zp = eq_ty.isSigned() ? zp : zp - (1 << (num_bits - 1)); + + std::optional result = convertDequantizeOp( + rewriter, op, output_type, tfl_dequantize_op.getInput(), scale, zp, 0); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); + } + + if (quant::UniformQuantizedPerAxisType eq_ty = + dyn_cast(element_type)) { + SmallVector zps; + for (auto zp : eq_ty.getZeroPoints()) { + int64_t num_bits = eq_ty.getStorageTypeIntegralWidth(); + zps.push_back(eq_ty.isSigned() ? zp : zp - (1 << (num_bits - 1))); + } + + SmallVector scales; + for (auto scale : eq_ty.getScales()) { + scales.push_back(scale); + } + + std::optional result = convertDequantizeOp( + rewriter, op, output_type, tfl_dequantize_op.getInput(), scales, zps, + eq_ty.getQuantizedDimension()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + return success(); + } + + return failure(); +} + +LogicalResult ConvertTFLConstOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_const_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_const_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr elements = tfl_const_op.getValue(); + Type element_type = elements.getShapedType().getElementType(); + if (mlir::isa(output_type.getElementType())) { + output_type = RankedTensorType::get(output_type.getShape(), element_type); + } + + // If the output shape is unranked we can extract the result shape from the + // attribute shape. This occurs as some TFLite folders create constants with + // unranked shapes. + if (!output_type.hasRank()) { + output_type = + mlir::cast(elements.getType()).clone(element_type); + } + + rewriter.replaceOpWithNewOp(op, output_type, elements); + + return success(); +} + +LogicalResult ConvertTFLQConstOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_qconst_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_qconst_op.getResult().getType()); + if (!output_type) return failure(); + + ElementsAttr elements = tfl_qconst_op.getValue(); + + // If the output shape is unranked we can extract the result shape from the + // attribute shape. This occurs as some TFLite folders create constants with + // unranked shapes. + if (!output_type.hasRank()) { + output_type = mlir::cast(elements.getType()) + .clone(output_type.getElementType()); + } + + rewriter.replaceOpWithNewOp(op, output_type, elements); + + return success(); +} + +LogicalResult ConvertConstantOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_const_op = cast(op); + + ShapedType output_type = + dyn_cast(tfl_const_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + ElementsAttr attr = dyn_cast(tfl_const_op.getValueAttr()); + + auto e_type = output_type.getElementType(); + + if (!output_type.hasRank()) { + if (auto attr_type = dyn_cast(attr.getType())) { + output_type = attr_type.clone(e_type); + } + } + + output_type = output_type.clone(e_type); + rewriter.replaceOpWithNewOp(op, output_type, attr); + + return success(); +} + +LogicalResult ConvertTFLGatherOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_gather_op = cast(op); + + int32_t axis = tfl_gather_op.getAxisAttr().getInt(); + int32_t batch_dims = 0; + if (auto batch_attr = tfl_gather_op.getBatchDimsAttr()) { + batch_dims = static_cast(batch_attr.getInt()); + } + + std::optional result = + convertGatherOp(rewriter, op, tfl_gather_op.getParams(), + tfl_gather_op.getIndices(), batch_dims, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLGatherNdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_gathernd_op = cast(op); + + std::optional result = convertGatherNdOp( + rewriter, op, tfl_gathernd_op.getResult(), tfl_gathernd_op.getParams(), + tfl_gathernd_op.getIndices()); + + if (!result) return failure(); + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLScatterNdOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_scatternd_op = cast(op); + + const std::optional result = convertScatterNdOp( + rewriter, op, tfl_scatternd_op.getResult(), tfl_scatternd_op.getIndices(), + tfl_scatternd_op.getUpdates(), tfl_scatternd_op.getShape()); + + if (!result) { + return failure(); + } + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLSparseToDenseOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_sparse_to_dense_op = cast(op); + auto indices = tfl_sparse_to_dense_op.getSparseIndices(); + auto values = tfl_sparse_to_dense_op.getSparseValues(); + auto default_value = tfl_sparse_to_dense_op.getDefaultValue(); + auto indices_ty = mlir::cast(indices.getType()); + auto indices_ety = indices_ty.getElementType(); + auto values_ty = mlir::cast(values.getType()); + auto result_ty = + mlir::cast(tfl_sparse_to_dense_op.getResult().getType()); + auto result_ety = result_ty.getElementType(); + auto loc = op->getLoc(); + + if (!result_ty.hasStaticShape()) return failure(); + auto result_rank = result_ty.getRank(); + + // We want to generate the default tensor we need to scatter. Note that the + // result_ty needs to be a statically shaped tensor. + ElementsAttr default_value_attr; + if (!matchPattern(default_value, m_Constant(&default_value_attr))) + return failure(); + + if (!default_value_attr.isSplat()) return failure(); + + ShapedType scatter_ty = + RankedTensorType::get({1, result_ty.getNumElements(), 1}, result_ety); + + Value default_const = rewriter.create( + loc, scatter_ty, + DenseElementsAttr::get(scatter_ty, + default_value_attr.getSplatValue().sext( + result_ety.getIntOrFloatBitWidth()))); + + // We need to determine what the index multiplier does + llvm::SmallVector multiply_constant_ints; + multiply_constant_ints.resize(result_rank, 1); + for (int i = result_rank - 1; i > 0; i--) { + multiply_constant_ints[i - 1] = + result_ty.getDimSize(i) * multiply_constant_ints[i]; + } + + indices_ety = rewriter.getI32Type(); + indices_ty = RankedTensorType::get(indices_ty.getShape(), indices_ety); + indices = CreateOpAndInfer(rewriter, loc, indices_ty, indices); + + auto multiply_constant_type = + RankedTensorType::get({result_rank}, indices_ety); + auto multiply_constant_attr = DenseElementsAttr::get( + multiply_constant_type, llvm::ArrayRef(multiply_constant_ints)); + Value multiply_constant = CreateOpAndInfer( + rewriter, loc, multiply_constant_type, multiply_constant_attr); + + Value multiply_op = + CreateMulOpAndInfer(rewriter, op, indices_ty, indices, multiply_constant); + + Value reduce_op = CreateOpAndInfer( + rewriter, loc, UnrankedTensorType::get(indices_ety), multiply_op, + rewriter.getI32IntegerAttr(1)); + + auto shape_value = getTosaConstShape( + rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF({1, values_ty.getDimSize(0), 1})); + auto values_reshape_op = CreateOpAndInfer( + rewriter, loc, UnrankedTensorType::get(result_ety), values, shape_value); + + shape_value = getTosaConstShape( + rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF({1, indices_ty.getDimSize(0)})); + auto index_reshape_op = CreateOpAndInfer( + rewriter, loc, UnrankedTensorType::get(indices_ety), reduce_op, + shape_value); + + auto scatter = CreateOpAndInfer( + rewriter, loc, UnrankedTensorType::get(result_ety), default_const, + index_reshape_op, values_reshape_op); + + auto result_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(result_ty.getShape())); + CreateReplaceOpAndInfer(rewriter, op, result_ty, scatter, + result_shape_value); + + return success(); +} + +LogicalResult ConvertTFLOneHotOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_one_hot_op = cast(op); + + ElementsAttr depth_elems; + if (!matchPattern(tfl_one_hot_op.getDepth(), m_Constant(&depth_elems))) + return failure(); + int32_t depth = depth_elems.getValues()[0].getSExtValue(); + + IntegerAttr axisAttr = tfl_one_hot_op.getAxisAttr(); + int32_t axis = axisAttr.getInt(); + + std::optional result = convertOneHotOp( + rewriter, op, tfl_one_hot_op.getResult(), tfl_one_hot_op.getIndices(), + tfl_one_hot_op.getOnValue(), tfl_one_hot_op.getOffValue(), depth, axis); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLArgMaxOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto arg_max_op = cast(op); + + ElementsAttr dim_elems; + if (!matchPattern(arg_max_op.getDim(), m_Constant(&dim_elems))) + return failure(); + + int32_t dim = dim_elems.getValues()[0].getSExtValue(); + + if (dim < 0) { + auto input_type = cast(arg_max_op.getInput().getType()); + dim += input_type.getRank(); + } + + const auto propagate_nan_attr = tosa::NanPropagationModeAttr::get( + rewriter.getContext(), tosa::NanPropagationMode::PROPAGATE); + CreateReplaceOpAndInfer( + rewriter, op, arg_max_op.getType(), arg_max_op.getInput(), + rewriter.getI32IntegerAttr(dim), propagate_nan_attr); + + return success(); +} + +LogicalResult ConvertTFLArgMinOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto arg_min_op = cast(op); + auto loc = arg_min_op.getLoc(); + Value input = arg_min_op.getInput(); + auto input_ty = mlir::cast(input.getType()); + Type input_ety = input_ty.getElementType(); + bool input_type_casted = false; + + if (auto quantized_ty = dyn_cast(input_ety)) { + input_ety = + rewriter.getIntegerType(quantized_ty.getStorageTypeIntegralWidth()); + if (quantized_ty.getZeroPoint() != 0) { + // cast to input_ety type to get rid of zero point + // so that sub operands are both of type input_ety + input = CreateOpAndInfer(rewriter, loc, + input_ty.clone(input_ety), input); + input_type_casted = true; + } + } + + if (!input_ety.isIntOrFloat()) + return rewriter.notifyMatchFailure(op, "unsupported element type"); + + ElementsAttr dim_elems; + if (!matchPattern(arg_min_op.getDim(), m_Constant(&dim_elems))) + return rewriter.notifyMatchFailure(op, "Non-constant dim"); + + // When negative dim is measured from the back of the array. + int32_t dim = dim_elems.getValues()[0].getSExtValue(); + if (dim < 0) dim += input_ty.getRank(); + + if (mlir::isa(input_ety)) { + input = CreateOpAndInfer(rewriter, loc, input_ty, input); + } else if (mlir::isa(input_ety)) { + std::vector shape(input_ty.getRank(), 1); + auto reverse_ty = RankedTensorType::get(shape, input_ety); + Value reverse_val = rewriter.create( + loc, reverse_ty, + DenseElementsAttr::get(reverse_ty, + rewriter.getIntegerAttr(input_ety, -1))); + input = CreateOpAndInfer( + rewriter, loc, input_ty.clone(input_ety), reverse_val, input); + } + + // if output type has zero point, the input has been type cast to integer + // so need to rescale ArgMax output to original output zero point + int output_zp = 0; + Type output_ty = arg_min_op.getType(); + Type output_ety = mlir::cast(output_ty).getElementType(); + if (auto output_quantized_ty = dyn_cast(output_ety)) { + output_zp = output_quantized_ty.getZeroPoint(); + if (output_zp != 0) { + // need to rescale arg_max output to output zero point + output_ty = mlir::cast(output_ty).clone(input_ety); + } + } + + // double check input/output type cast consistency + assert(input_type_casted == (output_zp != 0)); + + const auto propagate_nan_attr = tosa::NanPropagationModeAttr::get( + rewriter.getContext(), tosa::NanPropagationMode::PROPAGATE); + Value result = CreateOpAndInfer( + rewriter, loc, output_ty, input, rewriter.getI32IntegerAttr(dim), + propagate_nan_attr); + + if (output_zp != 0) { + // rescale result to output_zp + result = buildRescale(rewriter, op, arg_min_op.getType(), result, + /* sclae = */ 1.0, + /* input_zp = */ 0, + /* output_zp = */ output_zp, tosa::RoundingMode::SINGLE_ROUND, true); + } + + rewriter.replaceOp(op, {result}); + + return success(); +} + +LogicalResult ConvertTFLFakeQuantOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto fakequant_op = cast(op); + + ShapedType output_type = + dyn_cast(fakequant_op.getResult().getType()); + // Not a ranked tensor output + if (!output_type) return failure(); + + std::optional result = + convertFakeQuantOp(rewriter, op, output_type, fakequant_op.getInput(), + fakequant_op.getMinAttr().getValueAsDouble(), + fakequant_op.getMaxAttr().getValueAsDouble(), + fakequant_op.getNumBitsAttr().getInt(), + fakequant_op.getNarrowRangeAttr().getValue()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +// Clone block, convert yield from TFL to TOSA +static void inlineWhileCase(Region& srcRegion, Region& dstRegion, + PatternRewriter& rewriter) { + rewriter.cloneRegionBefore(srcRegion, &dstRegion.back()); + rewriter.eraseBlock(&dstRegion.back()); + + Block* headBlock = &dstRegion.front(); + + auto yield = cast(headBlock->getTerminator()); + rewriter.setInsertionPoint(yield); + rewriter.create(yield.getLoc(), yield.getOperands()); + rewriter.eraseOp(yield); +} + +LogicalResult ConvertTFLWhileOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_while_op = cast(op); + + auto while_op = rewriter.create( + op->getLoc(), op->getResultTypes(), op->getOperands()); + + rewriter.createBlock(&while_op.getCondGraph()); + rewriter.createBlock(&while_op.getBodyGraph()); + + inlineWhileCase(tfl_while_op.getCond(), while_op.getCondGraph(), rewriter); + inlineWhileCase(tfl_while_op.getBody(), while_op.getBodyGraph(), rewriter); + + rewriter.replaceOp(tfl_while_op, while_op.getResults()); + + return success(); +} + +LogicalResult ConvertTFLRealOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_real_op = cast(op); + Value input = tfl_real_op.getInput(); + + auto input_ty = dyn_cast(input.getType()); + auto output_ty = dyn_cast(tfl_real_op.getResult().getType()); + + if (!input_ty || !output_ty) { + return rewriter.notifyMatchFailure(op, "ranked input/output required"); + } + + Type input_ety = input_ty.getElementType(); + + // For non-complex inputs, return the original tensor. + if (!mlir::isa(input_ety)) { + CreateReplaceOpAndInfer(rewriter, op, input_ty, input); + return success(); + } + + if (!mlir::cast(input_ety).getElementType().isF32()) { + return rewriter.notifyMatchFailure( + op, "complex input must be of type complex64"); + } + + // Complex64 inputs of shape [x, ..., y] are lowered to TOSA + // as a tensor of datatype float32 and shape [x, ..., y, 2]. + // This is because TOSA does not have support for complex + // types. An unrealized conversion is inserted to handle + // this discrepancy. + llvm::SmallVector cast_size = to_vector(input_ty.getShape()); + cast_size.push_back(2); + auto casted_ty = RankedTensorType::get(cast_size, rewriter.getF32Type()); + Value casted = rewriter + .create(op->getLoc(), + casted_ty, input) + .getResult(0); + + // Slice the input to get the "real" values. + const int64_t rank = input_ty.getRank(); + llvm::SmallVector start(rank + 1, 0); + llvm::SmallVector size = to_vector(input_ty.getShape()); + size.push_back(1); + auto slice_ty = RankedTensorType::get(size, rewriter.getF32Type()); + auto slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), slice_ty, casted, + getTosaConstShape(rewriter, op->getLoc(), start), + getTosaConstShape(rewriter, op->getLoc(), size)); + auto output_shape_value = + getTosaConstShape(rewriter, op->getLoc(), output_ty.getShape()); + CreateReplaceOpAndInfer(rewriter, op, output_ty, slice_op, + output_shape_value); + + return success(); +} + +LogicalResult ConvertTFLImagOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_imag_op = cast(op); + Value input = tfl_imag_op.getInput(); + + auto input_ty = dyn_cast(input.getType()); + auto output_ty = dyn_cast(tfl_imag_op.getResult().getType()); + + if (!input_ty || !output_ty) { + return rewriter.notifyMatchFailure(op, "ranked input/output required"); + } + + Type input_ety = input_ty.getElementType(); + + // For non-complex inputs return all zero's. + if (!mlir::isa(input_ety)) { + CreateReplaceOpAndInfer( + rewriter, op, input_ty, DenseElementsAttr::get(input_ty, {0.0f})); + return success(); + } + + if (!mlir::cast(input_ety).getElementType().isF32()) { + return rewriter.notifyMatchFailure( + op, "complex input must be of type complex64"); + } + + // Complex64 inputs of shape [x, ..., y] are lowered to TOSA + // as a tensor of datatype float32 and shape [x, ..., y, 2]. + // This is because TOSA does not have support for complex + // types. An unrealized conversion is inserted to handle + // this discrepancy. + llvm::SmallVector cast_size = to_vector(input_ty.getShape()); + cast_size.push_back(2); + auto casted_ty = RankedTensorType::get(cast_size, rewriter.getF32Type()); + Value casted = rewriter + .create(op->getLoc(), + casted_ty, input) + .getResult(0); + + // Slice the input to the "imag" values. + llvm::SmallVector start(input_ty.getRank(), 0); + start.push_back(1); + llvm::SmallVector size = to_vector(input_ty.getShape()); + size.push_back(1); + + auto slice_ty = RankedTensorType::get(size, rewriter.getF32Type()); + auto slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), slice_ty, casted, + getTosaConstShape(rewriter, op->getLoc(), start), + getTosaConstShape(rewriter, op->getLoc(), size)); + auto output_shape_value = + getTosaConstShape(rewriter, op->getLoc(), output_ty.getShape()); + CreateReplaceOpAndInfer(rewriter, op, output_ty, slice_op, + output_shape_value); + + return success(); +} + +LogicalResult ConvertTFLRFFT2dOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto rfft2d_op = cast(op); + auto loc = op->getLoc(); + Value input = rfft2d_op.getInput(); + + auto input_type = dyn_cast(input.getType()); + auto output_type = dyn_cast(rfft2d_op.getResult().getType()); + + if (!input_type || !output_type) { + return rewriter.notifyMatchFailure(op, "ranked input/output required"); + } + + if (!input_type.getElementType().isF32()) { + return rewriter.notifyMatchFailure(op, "input type must be fp32"); + } + + Value fft_length_value = rfft2d_op.getFftLength(); + llvm::SmallVector fft_length; + if (failed(getVectorFromValue32(fft_length_value, fft_length))) { + return rewriter.notifyMatchFailure(op, "fft_length is not a constant"); + } + + auto fp32_ty = UnrankedTensorType::get(rewriter.getF32Type()); + + // Padding is automatically inserted during the lowering when + // fft_length > input shape. However, to take care of the + // case fft_length < input shape we need to crop the input. + const int64_t rank = input_type.getRank(); + auto input_shape = input_type.getShape(); + if (fft_length[0] < input_shape[rank - 2] || + fft_length[1] < input_shape[rank - 1]) { + llvm::SmallVector slice_begin(rank, 0); + llvm::SmallVector slice_size; + for (auto dim : input_type.getShape().drop_back(2)) { + slice_size.push_back(dim); + } + slice_size.push_back(fft_length[0]); + slice_size.push_back(fft_length[1]); + input = CreateOpAndInfer( + rewriter, loc, fp32_ty, input, + getTosaConstShape(rewriter, op->getLoc(), slice_begin), + getTosaConstShape(rewriter, op->getLoc(), slice_size)); + } + + auto rfft2d = + CreateOpAndInfer(rewriter, loc, fp32_ty, fp32_ty, input); + + auto output_shape = output_type.getShape(); + llvm::SmallVector new_shape{output_shape}; + new_shape.push_back(1); + auto new_shape_value = getTosaConstShape(rewriter, op->getLoc(), new_shape); + auto reshape_1 = CreateOpAndInfer( + rewriter, loc, fp32_ty, rfft2d.getResult(0), new_shape_value); + auto reshape_2 = CreateOpAndInfer( + rewriter, loc, fp32_ty, rfft2d.getResult(1), new_shape_value); + + llvm::SmallVector values = {reshape_1, reshape_2}; + auto concat = CreateOpAndInfer(rewriter, loc, fp32_ty, values, + rewriter.getI32IntegerAttr(3)); + + CreateReplaceOpAndInfer( + rewriter, op, output_type, concat.getResult()); + + return success(); +} + +LogicalResult ConvertTFLLogicalAndOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFLLogicalOrOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFLBitwiseXorOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFLPowOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + return ConvertBinaryOp(op, rewriter); +} + +LogicalResult ConvertTFLBroadcastToOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_broadcast_to_op = cast(op); + + std::optional result = + convertBroadcastToOp(rewriter, op, tfl_broadcast_to_op.getInput(), + tfl_broadcast_to_op.getShape()); + + if (!result) return failure(); + + rewriter.replaceOp(op, {result.value()}); + + return success(); +} + +LogicalResult ConvertTFLExpOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_exp_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_exp_op.getX().getType()); + RankedTensorType output_type = + dyn_cast(tfl_exp_op.getResult().getType()); + + if (!input_type || !output_type) { + return rewriter.notifyMatchFailure( + op, "input/output are not all a ranked tensor"); + } + + mlir::quant::UniformQuantizedType input_qtype = + dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType output_qtype = + dyn_cast_or_null( + output_type.getElementType()); + + if ((input_qtype == nullptr) != (output_qtype == nullptr)) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + // Quantization case + if (input_qtype && output_qtype) { + auto exp_func = [](float x) -> float { return std::exp(x); }; + + Value table_const; + if (input_qtype.getStorageTypeIntegralWidth() == 8) { + table_const = getTosaConst8bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint(), exp_func); + } else if (input_qtype.getStorageTypeIntegralWidth() == 16) { + table_const = getTosaConst16bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint(), exp_func); + } else { + return rewriter.notifyMatchFailure( + op, "only quantized int8 and int16 are supported"); + } + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_exp_op.getX(), table_const); + return success(); + } + + CreateReplaceOpAndInfer(rewriter, op, tfl_exp_op.getType(), + tfl_exp_op.getX()); + + return success(); +} + +LogicalResult ConvertTFLLogOp::matchAndRewrite( + Operation* op, PatternRewriter& rewriter) const { + auto tfl_log_op = cast(op); + + RankedTensorType input_type = + dyn_cast(tfl_log_op.getX().getType()); + RankedTensorType output_type = + dyn_cast(tfl_log_op.getResult().getType()); + + if (!input_type || !output_type) { + return rewriter.notifyMatchFailure( + op, "input/output are not all a ranked tensor"); + } + + mlir::quant::UniformQuantizedType input_qtype = + dyn_cast_or_null( + input_type.getElementType()); + mlir::quant::UniformQuantizedType output_qtype = + dyn_cast_or_null( + output_type.getElementType()); + + if ((input_qtype == nullptr) != (output_qtype == nullptr)) { + return rewriter.notifyMatchFailure( + op, + "input/output tensor should be all quantized or all floating-point"); + } + + // Quantization case + if (input_qtype && output_qtype) { + const float output_min = + ((input_qtype.getStorageTypeIntegralWidth() == 8 ? -128 : -32768) - + output_qtype.getZeroPoint()) * + static_cast(output_qtype.getScale()); + + auto log_func = [&](float x) -> float { + if (x <= 0.0f) { + return output_min; + } + return std::log(x); + }; + + Value table_const; + if (input_qtype.getStorageTypeIntegralWidth() == 8) { + table_const = getTosaConst8bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint(), log_func); + } else if (input_qtype.getStorageTypeIntegralWidth() == 16) { + table_const = getTosaConst16bitTable( + rewriter, op, input_qtype.getScale(), input_qtype.getZeroPoint(), + output_qtype.getScale(), output_qtype.getZeroPoint(), log_func); + } else { + return rewriter.notifyMatchFailure( + op, "only quantized int8 and int16 are supported"); + } + + CreateReplaceOpAndInfer(rewriter, op, output_type, + tfl_log_op.getX(), table_const); + return success(); + } + + CreateReplaceOpAndInfer(rewriter, op, tfl_log_op.getType(), + tfl_log_op.getX()); + + return success(); +} + +LogicalResult LegalizeTFL::initialize(MLIRContext* context) { + RewritePatternSet patterns(context); + mlir::tosa::populateLegalizeTFLPatterns(context, patterns); + frozen_patterns_ = FrozenRewritePatternSet( + std::move(patterns), this->disabled_patterns_, this->enabled_patterns_); + return success(); +} + +void LegalizeTFL::runOnOperation() { + if (ApplyPatternsWithShapeResolution(getOperation(), this->frozen_patterns_) + .failed()) { + signalPassFailure(); + } +} + +} // namespace + +void populateLegalizeTFLPatterns(MLIRContext* ctx, + RewritePatternSet& patterns) { +#define DEF_PATTERN_INSERT(PAT) \ + patterns.addWithLabel({#PAT}, ctx); + + DEF_PATTERN_INSERT(TFLAbs); + DEF_PATTERN_INSERT(TFLCeil); + DEF_PATTERN_INSERT(TFLFloor); + DEF_PATTERN_INSERT(TFLExp); + DEF_PATTERN_INSERT(TFLLog); + DEF_PATTERN_INSERT(TFLRsqrt); + DEF_PATTERN_INSERT(TFLLogicalNot); + DEF_PATTERN_INSERT(TFLCast); + + DEF_PATTERN_INSERT(QuantStat); + + DEF_PATTERN_INSERT(TFLLogicalAnd); + DEF_PATTERN_INSERT(TFLLogicalOr); + DEF_PATTERN_INSERT(TFLBitwiseXor); + DEF_PATTERN_INSERT(TFLPow); + + DEF_PATTERN_INSERT(TFLGelu); + DEF_PATTERN_INSERT(TFLRelu); + DEF_PATTERN_INSERT(TFLRelu1); + DEF_PATTERN_INSERT(TFLRelu0To1); + DEF_PATTERN_INSERT(TFLRelu6); + DEF_PATTERN_INSERT(TFLEqual); + DEF_PATTERN_INSERT(TFLNotEqual); + DEF_PATTERN_INSERT(TFLGreater); + DEF_PATTERN_INSERT(TFLGreaterEqual); + DEF_PATTERN_INSERT(TFLAdd); + DEF_PATTERN_INSERT(TFLSub); + DEF_PATTERN_INSERT(TFLMul); + DEF_PATTERN_INSERT(TFLSquare); + DEF_PATTERN_INSERT(TFLSquaredDifference); + DEF_PATTERN_INSERT(TFLSign); + DEF_PATTERN_INSERT(TFLRound); + DEF_PATTERN_INSERT(TFLDiv); + DEF_PATTERN_INSERT(TFLMaximum); + DEF_PATTERN_INSERT(TFLMinimum); + DEF_PATTERN_INSERT(TFLFloorMod); + DEF_PATTERN_INSERT(TFLFloorDiv); + DEF_PATTERN_INSERT(TFLAddN); + DEF_PATTERN_INSERT(TFLAveragePool2D); + DEF_PATTERN_INSERT(TFLMaxPool2D); + DEF_PATTERN_INSERT(TFLConcatenation); + DEF_PATTERN_INSERT(TFLReshape); + DEF_PATTERN_INSERT(TFLRank); + DEF_PATTERN_INSERT(TFLShape); + DEF_PATTERN_INSERT(TFLExpandDims); + DEF_PATTERN_INSERT(TFLSqueeze); + DEF_PATTERN_INSERT(TFLFill); + DEF_PATTERN_INSERT(TFLElu); + DEF_PATTERN_INSERT(TFLSoftmax); + DEF_PATTERN_INSERT(TFLLogSoftmax); + DEF_PATTERN_INSERT(TFLSqrt); + DEF_PATTERN_INSERT(TFLL2Normalization); + DEF_PATTERN_INSERT(TFLReduceAll); + DEF_PATTERN_INSERT(TFLReduceAny); + DEF_PATTERN_INSERT(TFLReduceMax); + DEF_PATTERN_INSERT(TFLReduceMin); + DEF_PATTERN_INSERT(TFLMean); + DEF_PATTERN_INSERT(TFLReduceProd); + DEF_PATTERN_INSERT(TFLSum); + DEF_PATTERN_INSERT(TFLConv2D); + DEF_PATTERN_INSERT(TFLConv3D); + DEF_PATTERN_INSERT(TFLTransposeConv); + DEF_PATTERN_INSERT(TFLDepthwiseConv2D); + DEF_PATTERN_INSERT(TFLFullyConnected); + DEF_PATTERN_INSERT(TFLBatchMatMul); + DEF_PATTERN_INSERT(TFLSplit); + DEF_PATTERN_INSERT(TFLSplitV); + DEF_PATTERN_INSERT(TFLPack); + DEF_PATTERN_INSERT(TFLUnpack); + DEF_PATTERN_INSERT(TFLTranspose); + DEF_PATTERN_INSERT(TFLTile); + DEF_PATTERN_INSERT(TFLSlice); + DEF_PATTERN_INSERT(TFLStridedSlice); + DEF_PATTERN_INSERT(TFLHardSwish); + DEF_PATTERN_INSERT(TFLZerosLike); + DEF_PATTERN_INSERT(TFLLess); + DEF_PATTERN_INSERT(TFLLessEqual); + DEF_PATTERN_INSERT(TFLPad); + DEF_PATTERN_INSERT(TFLMirrorPad); + DEF_PATTERN_INSERT(TFLPadV2); + DEF_PATTERN_INSERT(TFLResizeBilinear); + DEF_PATTERN_INSERT(TFLResizeNearestNeighbor); + DEF_PATTERN_INSERT(TFLSelect); + DEF_PATTERN_INSERT(TFLSelectV2); + DEF_PATTERN_INSERT(TFLSpaceToBatchNd); + DEF_PATTERN_INSERT(TFLBatchToSpaceNd); + DEF_PATTERN_INSERT(TFLSpaceToDepth); + DEF_PATTERN_INSERT(TFLDepthToSpace); + DEF_PATTERN_INSERT(TFLBucketize); + DEF_PATTERN_INSERT(TFLSin); + DEF_PATTERN_INSERT(TFLCos); + DEF_PATTERN_INSERT(TFLAtan2); + DEF_PATTERN_INSERT(TFLLogistic); + DEF_PATTERN_INSERT(TFLTanh); + DEF_PATTERN_INSERT(TFLPRelu); + DEF_PATTERN_INSERT(TFLLeakyRelu); + DEF_PATTERN_INSERT(TFLNeg); + DEF_PATTERN_INSERT(TFLYield); + DEF_PATTERN_INSERT(TFLCustom); + DEF_PATTERN_INSERT(TFLReverseV2); + DEF_PATTERN_INSERT(TFLQuantize); + DEF_PATTERN_INSERT(TFLDequantize); + DEF_PATTERN_INSERT(TFLConst); + DEF_PATTERN_INSERT(TFLQConst); + DEF_PATTERN_INSERT(TFLGatherNd); + DEF_PATTERN_INSERT(TFLScatterNd); + DEF_PATTERN_INSERT(TFLSparseToDense); + DEF_PATTERN_INSERT(Constant); + DEF_PATTERN_INSERT(TFLOneHot); + DEF_PATTERN_INSERT(TFLArgMax); + DEF_PATTERN_INSERT(TFLArgMin); + DEF_PATTERN_INSERT(TFLFakeQuant); + DEF_PATTERN_INSERT(TFLWhile); + DEF_PATTERN_INSERT(TFLReal); + DEF_PATTERN_INSERT(TFLImag); + DEF_PATTERN_INSERT(TFLRFFT2d); + DEF_PATTERN_INSERT(TFLBroadcastTo); +#undef DEF_PATTERN_INSERT + + // Patterns which may optionally generate non-TOSA dialects +#define DEF_PATTERN_INSERT(PAT) \ + patterns.addWithLabel({#PAT "ToTensor"}, ctx); + + DEF_PATTERN_INSERT(TFLGather); + +#undef DEF_PATTERN_INSERT +} + +// Creates an instance of the TensorFlow Lite dialect LegalizeTFL pass. +std::unique_ptr> createLegalizeTFLPass( + ArrayRef disabled_patterns, + ArrayRef enabled_patterns) { + return std::make_unique(disabled_patterns, enabled_patterns); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tfl_stateful.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tfl_stateful.cc new file mode 100644 index 0000000000000000000000000000000000000000..08dc839e294aac2f08d742247520828c6b16413b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_tfl_stateful.cc @@ -0,0 +1,189 @@ +/* Copyright 2023 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. +==============================================================================*/ + +// Legalize TensorFlow Lite StatefulOps to TOSA + +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/Matchers.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-legalize-tfl-stateful" + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSALEGALIZETFLSTATEFULPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +// Performs lowering tfl stateful operators to TOSA +class TosaLegalizeTFLStateful + : public impl::TosaLegalizeTFLStatefulPassBase { + public: + explicit TosaLegalizeTFLStateful() = default; + void runOnOperation() override; +}; + +void TosaLegalizeTFLStateful::runOnOperation() { + auto moduleOp = getOperation(); + mlir::OpBuilder builder(moduleOp.getBodyRegion()); + + DenseMap symNameToFunction; + for (auto func : moduleOp.getOps()) { + symNameToFunction[func.getSymName()] = func; + } + + llvm::SmallVector handleOps; + llvm::SmallVector assignOps; + llvm::SmallVector readOps; + SmallVector callOnceOps; + DenseMap symbolRefMap; + + for (auto it : symNameToFunction) { + auto func = std::get<1>(it); + // We also want to grab the list of operations to replace. + for (auto& op : func.getOps()) { + if (auto handle = dyn_cast(op)) + handleOps.push_back(handle); + if (auto assign = dyn_cast(op)) + assignOps.push_back(assign); + if (auto read = dyn_cast(op)) + readOps.push_back(read); + } + } + + for (auto func : moduleOp.getOps()) { + for (auto init : func.getOps()) { + callOnceOps.push_back(init); + } + } + + // Look through the initialization functions and find the assigned values + // for each handle, save out the constant value. + for (auto init : callOnceOps) { + auto findInitFunc = + symNameToFunction.find(init.getSessionInitFunctionAttr()); + if (findInitFunc == symNameToFunction.end()) { + init.emitError("unable to find initialization function: "); + continue; + } + func::FuncOp initFunc = std::get<1>(*findInitFunc); + for (auto assign : initFunc.getOps()) { + // 1. var_handle part + auto handle = dyn_cast( + assign.getResourceId().getDefiningOp()); + if (!handle) continue; + + // 2. pseudo_const part + DenseElementsAttr constant; + if (!matchPattern(assign.getValue(), m_Constant(&constant))) { + // Quantized types we can not use the m_Constant matcher. + if (auto constOp = dyn_cast( + assign.getValue().getDefiningOp())) { + constant = cast(constOp.getValue()); + } + } + if (!constant) continue; + + // Create TOSA VariableOps + auto name = handle.getSharedName(); + auto global = builder.create( + handle.getLoc(), name, constant.getType(), constant); + symbolRefMap[name] = global; + } + } + // TF::CallOnceOps are no longer needed as we have already extracted their + // state. + for (auto op : callOnceOps) op.erase(); + + // Replace the assign ops with a tosa store operation. + for (auto assign : assignOps) { + auto handle = dyn_cast( + assign.getResourceId().getDefiningOp()); + if (!handle) continue; + + Value value = assign.getValue(); + auto globalOpIt = symbolRefMap.find(handle.getSharedName()); + if (globalOpIt == symbolRefMap.end()) { + assign->emitError( + "unable to find corresponding TosaOp for op's VarHandle"); + continue; + } + auto globalOp = std::get<1>(*globalOpIt); + + builder.setInsertionPoint(assign); + auto variableType = mlir::tosa::getVariableType(globalOp); + if (variableType != value.getType()) { + value = builder + .create(assign.getLoc(), + variableType, value) + .getResult(0); + } + + builder.create( + assign.getLoc(), llvm::StringRef(globalOp.getName()), value); + assign.erase(); + } + + for (auto read : readOps) { + auto handle = + dyn_cast(read.getResourceId().getDefiningOp()); + if (!handle) continue; + + auto globalOpIt = symbolRefMap.find(handle.getSharedName()); + if (globalOpIt == symbolRefMap.end()) continue; + auto globalOp = std::get<1>(*globalOpIt); + + builder.setInsertionPoint(read); + + Value load = builder.create( + read.getLoc(), mlir::tosa::getVariableType(globalOp), + llvm::StringRef(globalOp.getName())); + + if (read.getType() != load.getType()) { + load = builder + .create(read.getLoc(), + read.getType(), load) + .getResult(0); + } + read.getResult().replaceAllUsesWith(load); + read.erase(); + } + + for (auto handle : handleOps) { + if (handle.getResult().use_empty()) { + handle.erase(); + } + } +} + +} // namespace + +// Creates an instance of the TensorFlow Lite dialect LegalizeTFLStateful pass. +std::unique_ptr> createLegalizeTFLStatefulPass() { + return std::make_unique(); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..815e6f34ecfabe47368ddbeb3359dc8e44cc08ee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_utils.cc @@ -0,0 +1,1548 @@ +/* Copyright 2020 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/mlir/tosa/transforms/legalize_utils.h" + +#include +#include +#include +#include +#include + +#include "llvm/ADT/SmallVector.h" +#include "mlir/Dialect/Arith/IR/Arith.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Tensor/IR/Tensor.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/QuantUtils.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypeInterfaces.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/lite/kernels/internal/common.h" +#include "tensorflow/compiler/mlir/lite/kernels/internal/quantization_util.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/dynamic_shape_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/lite/kernels/internal/common.h" +#include "tensorflow/lite/kernels/internal/quantization_util.h" +#include "tensorflow/lite/kernels/internal/reference/hard_swish.h" +#include "xla/tsl/framework/fixedpoint/FixedPoint.h" + +// Implements legalization and post-legalization optimization helper functions + +namespace mlir { +namespace tosa { + +mlir::TypeAttr getConvAccTypeAttr(PatternRewriter& rewriter, + mlir::Type input_etype, + mlir::Type output_etype) { + // in case of quantized types: get base element types + if (auto qtype = + llvm::dyn_cast(input_etype)) + input_etype = tosa::getStorageElementTypeFromQuantized(qtype); + + if (auto qtype = + llvm::dyn_cast(output_etype)) + output_etype = tosa::getStorageElementTypeFromQuantized(qtype); + + // special cases: input_etype and output_etype are both f16 or bf16: use + // acc_type=f32 + if ((input_etype.isF16() && output_etype.isF16()) || + (input_etype.isBF16() && output_etype.isBF16())) { + return mlir::TypeAttr::get(rewriter.getF32Type()); + } + + // otherwise, use output_etype as acc_type + return mlir::TypeAttr::get(output_etype); +} + +std::optional convertTFConv2DCommon( + PatternRewriter& rewriter, Operation* op, RankedTensorType output_type, + Value input, Value filter, Value bias, ArrayAttr strides_attr, + ArrayAttr dilations_attr, ArrayAttr explicit_padding_attr, + StringRef padding_ref, StringRef data_format_ref) { + RankedTensorType input_type = dyn_cast(input.getType()); + RankedTensorType filter_type = dyn_cast(filter.getType()); + // Not a ranked tensor output + if (!input_type) return std::nullopt; + if (!filter_type) return std::nullopt; + + // Transpose [H, W, I, O] to [O, H, W, I] + auto filter_shape = filter_type.getShape(); + SmallVector a1_transpose_dims; + a1_transpose_dims.push_back(filter_shape[3]); + a1_transpose_dims.push_back(filter_shape[0]); + a1_transpose_dims.push_back(filter_shape[1]); + a1_transpose_dims.push_back(filter_shape[2]); + + auto a1_filter_transpose_perm_attr = + rewriter.getDenseI32ArrayAttr({3, 0, 1, 2}); + + auto a1_filter_transpose_op = CreateOpAndInfer( + rewriter, op->getLoc(), + tensorflow::GetTypeFromTFTensorShape(a1_transpose_dims, + filter_type.getElementType()), + filter, a1_filter_transpose_perm_attr); + + // Only support NHWC now. + if (data_format_ref.str() != "NHWC") { + op->emitWarning("convertTDConv2DCommon only supports NHWC!"); + return std::nullopt; + } + + DenseI64ArrayAttr stride; + DenseI64ArrayAttr dilation; + DenseI64ArrayAttr pad; + { + if (!strides_attr) { + stride = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t stride_h = mlir::cast(strides_attr[1]).getInt(); + int64_t stride_w = mlir::cast(strides_attr[2]).getInt(); + stride = rewriter.getDenseI64ArrayAttr({stride_h, stride_w}); + } + } + { + if (!dilations_attr) { + dilation = rewriter.getDenseI64ArrayAttr({1, 1}); + } else { + // Note: hardcoded to NHWC for now + int64_t dilation_h = mlir::cast(dilations_attr[1]).getInt(); + int64_t dilation_w = mlir::cast(dilations_attr[2]).getInt(); + dilation = rewriter.getDenseI64ArrayAttr({dilation_h, dilation_w}); + } + } + { + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(padding_ref.str(), &tf_pad).ok()) { + op->emitWarning("Could not get padding data from padding string term!"); + return std::nullopt; + } + + tensorflow::TensorFormat data_format_tf; + if (!FormatFromString(data_format_ref.str(), &data_format_tf)) + return std::nullopt; + + if (tf_pad == tensorflow::Padding::EXPLICIT) { + pad = getPaddingValuesFromExplicitPadAttr(explicit_padding_attr, + data_format_tf, rewriter); + } else { + if (!getPaddingValuesFromPadType(tf_pad, data_format_tf, + 0, // tensorflow::FORMAT_HWIO + input_type, filter_type, stride, + dilation, rewriter, pad)) + return std::nullopt; + } + } + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ output_type.getElementType()); + return CreateOpAndInfer(rewriter, op->getLoc(), output_type, + input, + a1_filter_transpose_op.getResult(), + bias, pad, stride, dilation, acc_type) + .getResult(); +} + +std::optional convertTFConv3DCommon( + PatternRewriter& rewriter, Operation* op, ShapedType output_type, + Value input, Value filter, Value bias, ArrayAttr strides_attr, + ArrayAttr dilations_attr, StringRef padding_ref, + StringRef data_format_ref) { + DenseI64ArrayAttr strides; + if (!strides_attr) { + // Defaults to [1, 1, 1]. + strides = rewriter.getDenseI64ArrayAttr({1, 1, 1}); + } else { + int64_t stride_d = mlir::cast(strides_attr[1]).getInt(); + int64_t stride_h = mlir::cast(strides_attr[2]).getInt(); + int64_t stride_w = mlir::cast(strides_attr[3]).getInt(); + strides = rewriter.getDenseI64ArrayAttr({stride_d, stride_h, stride_w}); + } + + DenseI64ArrayAttr dilations; + if (!dilations_attr) { + // Defaults to [1, 1, 1]. + dilations = rewriter.getDenseI64ArrayAttr({1, 1, 1}); + } else { + int64_t dilation_d = mlir::cast(dilations_attr[1]).getInt(); + int64_t dilation_h = mlir::cast(dilations_attr[2]).getInt(); + int64_t dilation_w = mlir::cast(dilations_attr[3]).getInt(); + dilations = + rewriter.getDenseI64ArrayAttr({dilation_d, dilation_h, dilation_w}); + } + + RankedTensorType input_type = mlir::cast(input.getType()); + DenseI64ArrayAttr pads; + { + RankedTensorType filter_type = + mlir::cast(filter.getType()); + + tensorflow::TensorFormat data_format_tf; + if (!FormatFromString(data_format_ref, &data_format_tf)) { + return std::nullopt; + } + + tensorflow::Padding tf_pad; + if (!GetPaddingFromString(padding_ref.str(), &tf_pad).ok()) { + (void)rewriter.notifyMatchFailure( + op, "could not get padding data from padding string term"); + return std::nullopt; + } + + if (tf_pad == tensorflow::Padding::EXPLICIT) { + (void)rewriter.notifyMatchFailure(op, "don't have explicit padding"); + return std::nullopt; + } + + if (!getPaddingValuesFromPadType(tf_pad, data_format_tf, 0, input_type, + filter_type, strides, dilations, rewriter, + pads)) { + return std::nullopt; + } + } + + auto acc_type = + getConvAccTypeAttr(rewriter, + /* input_etype = */ input_type.getElementType(), + /* output_etype = */ output_type.getElementType()); + + return convertConv3DCommon(rewriter, op, output_type, input, filter, bias, + pads, strides, dilations, acc_type, + data_format_ref); +} + +LogicalResult getDynamicDims(PatternRewriter& rewriter, Operation* op, + Value value, llvm::SmallVector& dims) { + auto value_ty = dyn_cast(value.getType()); + if (!value_ty || !value_ty.hasRank()) return failure(); + + dims.resize(value_ty.getRank()); + RankedTensorType dim_ty = + tensorflow::GetTypeFromTFTensorShape({}, rewriter.getI32Type()); + + for (int i = 0, s = value_ty.getRank(); i < s; ++i) { + if (!value_ty.isDynamicDim(i)) { + dims[i] = rewriter.create( + op->getLoc(), dim_ty, + SplatElementsAttr::get(dim_ty, value_ty.getDimSize(i))); + continue; + } + + // TODO(suderman): This should be changed to TOSA operations when TOSA has + // a TOSA dimension op. + Value dim = rewriter.create(op->getLoc(), value, i); + dim = rewriter.create(op->getLoc(), + rewriter.getI32Type(), dim); + dim = rewriter.create(op->getLoc(), dim_ty, + ValueRange{dim}); + dims[i] = dim; + } + + return success(); +} + +std::optional buildReshapeWithDynamicDims(PatternRewriter& rewriter, + Operation* op, + Value input_value, + ShapedType output_type, + llvm::ArrayRef dims) { + const ShapedType input_ty = dyn_cast(input_value.getType()); + if (!input_ty) { + (void)rewriter.notifyMatchFailure(op, "input is not a shaped type"); + return std::nullopt; + } + + const auto e_ty = input_ty.getElementType(); + llvm::SmallVector static_dims; + + if (output_type.hasRank()) { + static_dims = tensorflow::ConvertMlirShapeToTF(output_type.getShape()); + } else { + static_dims.resize(dims.size(), tensorflow::kTFDynamicSize); + } + + int64_t dyn_count = 0; + for (int i = 0, s = dims.size(); i < s; ++i) { + auto dim = dims[i]; + SplatElementsAttr dim_attr; + if (matchPattern(dim, m_Constant(&dim_attr))) { + if (mlir::cast(dim_attr.getType()).getRank() != 0) { + (void)rewriter.notifyMatchFailure( + op, "dim for building tosa::ReshapeOp should be rank-0"); + return std::nullopt; + } + int64_t size = dim_attr.getSplatValue().getSExtValue(); + + // Check that static shapes agree. + if (size != tensorflow::kTFDynamicSize && + static_dims[i] != tensorflow::kTFDynamicSize && + size != static_dims[i]) { + (void)rewriter.notifyMatchFailure( + op, "mismatch reshape static dim when creating tosa::ReshapeOp"); + return std::nullopt; + } + + static_dims[i] = + size == tensorflow::kTFDynamicSize ? static_dims[i] : size; + } + + if (static_dims[i] == tensorflow::kTFDynamicSize) dyn_count++; + } + + if (dyn_count > 1) { + (void)rewriter.notifyMatchFailure( + op, "multiple dynamic shapes when creating tosa::ReshapeOp"); + return std::nullopt; + } + + // If the input shape is static and only one dynamic dim is detected, we + // can easily resolve the dim to be static + if (input_ty.hasStaticShape() && dyn_count == 1) { + const int64_t total_elements = input_ty.getNumElements(); + const int64_t shape_elements = std::accumulate( + static_dims.begin(), static_dims.end(), 1, [](int64_t a, int64_t b) { + return b == tensorflow::kTFDynamicSize ? a : a * b; + }); + const int64_t dynamic_dim_value = total_elements / shape_elements; + std::replace(static_dims.begin(), static_dims.end(), + tensorflow::kTFDynamicSize, dynamic_dim_value); + } + + DenseI64ArrayAttr shape_attr = rewriter.getDenseI64ArrayAttr(static_dims); + auto output_ty = tensorflow::GetTypeFromTFTensorShape(static_dims, e_ty); + + auto shape_value = getTosaConstShape(rewriter, op->getLoc(), static_dims); + + return rewriter + .create(op->getLoc(), output_ty, input_value, + shape_value) + .getResult(); +} + +Value buildRescaleMultiplier(bool scale32, OpBuilder& builder, Location loc, + ArrayRef multipliers) { + if (scale32) { + return tosa::getConstTensorInt(builder, loc, multipliers); + } else { + SmallVector vec(multipliers.begin(), multipliers.end()); + return tosa::getConstTensorInt(builder, loc, vec); + } +} + +// Create a TOSA rescale op from TFLite scaling multiplier, scaling shift, zero +// points and rounding mode +Value buildRescale(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value input_val, + int32_t scale_multiplier, int32_t scale_shift, + int64_t input_zp, int64_t output_zp, tosa::RoundingMode rounding_mode, + bool scale32) { + bool input_unsigned, output_unsigned; + if (auto qtype = dyn_cast( + cast(input_val.getType()).getElementType())) { + input_unsigned = !qtype.isSigned(); + } else { + input_unsigned = input_val.getType().isUnsignedInteger(); + } + if (auto qtype = + dyn_cast(output_type.getElementType())) { + output_unsigned = !qtype.isSigned(); + } else { + output_unsigned = output_type.isUnsignedInteger(); + } + auto loc = op->getLoc(); + Value multiplier_val = + buildRescaleMultiplier(scale32, rewriter, loc, {scale_multiplier}); + auto shift_val = tosa::getConstTensorInt(rewriter, loc, + {static_cast(scale_shift)}); + + // Create input_zp matches the input type and output_zp matches the output + // type of RescaleOp + const Value empty_output_val = rewriter.create( + loc, output_type.getShape(), output_type.getElementType()); + const auto input_zp_val = + tosa::createZeroPointTensor(rewriter, loc, input_val.getType(), input_zp); + if (!input_zp_val.has_value()) + op->emitError("Failed to create input zero-point tensor for RescaleOp."); + + const auto output_zp_val = + tosa::createZeroPointTensor(rewriter, loc, empty_output_val.getType(), output_zp); + if (!output_zp_val.has_value()) + op->emitError("Failed to create output zero-point tensor for RescaleOp."); + + const auto rounding_mode_attr = tosa::RoundingModeAttr::get( + rewriter.getContext(), rounding_mode); + auto rescale_op = CreateOpAndInfer( + rewriter, loc, output_type, input_val, multiplier_val, shift_val, + input_zp_val.value(), output_zp_val.value(), + rewriter.getBoolAttr(scale32), rounding_mode_attr, + rewriter.getBoolAttr(false), rewriter.getBoolAttr(input_unsigned), + rewriter.getBoolAttr(output_unsigned)); + + return rescale_op.getResult(); +} + +// Create a TOSA rescale op from TFLite scaling, zero points and rounding mode +Value buildRescale(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value input_val, double scale, + int64_t input_zp, int64_t output_zp, tosa::RoundingMode rounding_mode, + bool scale32) { + int32_t multiplier; + int32_t shift; + + int32_t scale_width = scale32 ? 32 : 16; + + if (!computeMultiplierAndShift(scale, multiplier, shift, scale_width)) { + op->emitError("buildRescale: shift must be in the range 2 <= shift <= 62"); + } + + return buildRescale(rewriter, op, output_type, input_val, multiplier, shift, + input_zp, output_zp, rounding_mode, scale32); +} + +// Removes the zero point and cast to int32, no need to handle roundings modes +Value removeZeroPointAndCastToInt32(PatternRewriter& rewriter, Operation* op, + Value input_val, int64_t input_zp) { + return buildRescaleToInt32(rewriter, op, input_val, 1.0f, input_zp); +} + +// Creates TOSA rescale op with int32 output +Value buildRescaleToInt32(PatternRewriter& rewriter, Operation* op, + Value input_val, int32_t input_scale_multiplier, + int32_t input_scale_shift, int64_t input_zp) { + // Output is always int32 type + auto input_type = dyn_cast(input_val.getType()); + assert(input_type); + auto output_type = input_type.clone(rewriter.getI32Type()); + + const tosa::RoundingMode rounding_mode = + IsTFLDoubleRoundingMode() ? tosa::RoundingMode::DOUBLE_ROUND : tosa::RoundingMode::SINGLE_ROUND; + + return buildRescale(rewriter, op, output_type, input_val, + input_scale_multiplier, input_scale_shift, input_zp, + /*output_zp=*/0, rounding_mode, + /*scale32=*/true); +} + +// Creates TOSA rescale op with int32 output +Value buildRescaleToInt32(PatternRewriter& rewriter, Operation* op, + Value input_val, double input_scale, + int64_t input_zp) { + int32_t multiplier; + int32_t shift; + + const int32_t scale_width = 32; + computeMultiplierAndShift(input_scale, multiplier, shift, scale_width); + + return buildRescaleToInt32(rewriter, op, input_val, multiplier, shift, + input_zp); +} + +// Creates TOSA rescale op with int32 input +Value buildRescaleFromInt32(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value input_val, + double output_scale, int64_t output_zp) { + // Input should be int32 type + auto input_type = dyn_cast(input_val.getType()); + (void)input_type; + assert(input_type && input_type.getElementType().isInteger(32) && + "expected rescale input element type to be i32"); + + const tosa::RoundingMode rounding_mode = + IsTFLDoubleRoundingMode() ? tosa::RoundingMode::DOUBLE_ROUND : tosa::RoundingMode::SINGLE_ROUND; + + // Potentially check input_shape == output_shape here + return buildRescale(rewriter, op, output_type, input_val, output_scale, + /*input_zp=*/0, output_zp, rounding_mode, + /*scale32=*/true); +} + +// Creates a TOSA rescale op based on conv2d parameters. +Value buildRescaleOpConvOutput(PatternRewriter& rewriter, Operation* op, + Value conv_val, ShapedType input_type, + ShapedType weight_type, ShapedType output_type) { + auto input_qtype = + dyn_cast(input_type.getElementType()); + auto output_qtype = + dyn_cast(output_type.getElementType()); + + double input_scale = input_qtype.getScale(); + + int64_t output_zp = output_qtype.getZeroPoint(); + double output_scale = output_qtype.getScale(); + + bool scale32 = isScale32(output_qtype); + int32_t scale_width = scale32 ? 32 : 16; + // Only use double round if we are doing 32 bit scaling + const tosa::RoundingMode rounding_mode = scale32 ? tosa::RoundingMode::DOUBLE_ROUND + : tosa::RoundingMode::SINGLE_ROUND; + const auto rounding_mode_attr = tosa::RoundingModeAttr::get( + rewriter.getContext(), rounding_mode); + + bool input_unsigned = !input_qtype.isSigned(); + bool output_unsigned = !output_qtype.isSigned(); + + auto loc = op->getLoc(); + const Value empty_output_val = rewriter.create( + loc, output_type.getShape(), output_type.getElementType()); + + const auto input_zp_val = tosa::createZeroPointTensor( + rewriter, loc, conv_val.getType(), static_cast(0)); + if (!input_zp_val.has_value()) + op->emitError("Failed to create input zero-point tensor for RescaleOp."); + + const auto output_zp_val = + tosa::createZeroPointTensor(rewriter, loc, empty_output_val.getType(), output_zp); + if (!output_zp_val.has_value()) + op->emitError("Failed to create output zero-point tensor for RescaleOp."); + + if (auto weight_per_tensor_qtype = + dyn_cast( + weight_type.getElementType())) { + // Per-tensor quantization + double weight_scale = weight_per_tensor_qtype.getScale(); + + int32_t multiplier; + int32_t shift; + + double op_tensor_scale = (input_scale * weight_scale) / output_scale; + + computeMultiplierAndShift(op_tensor_scale, multiplier, shift, scale_width); + + Value multiplier_val = + buildRescaleMultiplier(scale32, rewriter, loc, {multiplier}); + auto shift_val = + tosa::getConstTensorInt(rewriter, loc, {static_cast(shift)}); + + auto rescale_op = CreateOpAndInfer( + rewriter, loc, output_type, conv_val, multiplier_val, shift_val, + input_zp_val.value(), output_zp_val.value(), + rewriter.getBoolAttr(scale32), rounding_mode_attr, + rewriter.getBoolAttr(false), rewriter.getBoolAttr(input_unsigned), + rewriter.getBoolAttr(output_unsigned)); + + return rescale_op.getResult(); + + } else if (auto weight_per_channel_qtype = + dyn_cast( + weight_type.getElementType())) { + // Per-channel quantization + SmallVector multiplier_arr; + SmallVector shift_arr; + + SmallVector weight_scale_arr( + weight_per_channel_qtype.getScales().begin(), + weight_per_channel_qtype.getScales().end()); + + int64_t output_zp = output_qtype.getZeroPoint(); + double output_scale = output_qtype.getScale(); + + for (double weight_scale : weight_scale_arr) { + int32_t multiplier; + int32_t shift; + + double op_channel_scale = (input_scale * weight_scale) / output_scale; + + if (!computeMultiplierAndShift(op_channel_scale, multiplier, shift, 32)) { + op->emitError( + "buildRescaleOpConvOutput: shift must be in the range 2 <= shift " + "<= 62"); + } + // We are matching the tflite behaviour here by scaling by 32-bit + // then down-scaling to 16-bit for int16x8 + // Reference: tensorflow/lite/kernels/internal/common.cc + if (!scale32) { + multiplier = (multiplier < 0x7FFF0000) + ? ((multiplier + (1 << 15)) >> 16) + : 0x7FFF; + shift = shift - 16; + } + + multiplier_arr.push_back(multiplier); + shift_arr.push_back(static_cast(shift)); + } + + Value multiplier_val = + buildRescaleMultiplier(scale32, rewriter, loc, multiplier_arr); + auto shift_val = tosa::getConstTensorInt(rewriter, loc, shift_arr); + + auto rescale_op = CreateOpAndInfer( + rewriter, loc, output_type, conv_val, multiplier_val, shift_val, + input_zp_val.value(), output_zp_val.value(), + rewriter.getBoolAttr(scale32), rounding_mode_attr, + rewriter.getBoolAttr(true), rewriter.getBoolAttr(input_unsigned), + rewriter.getBoolAttr(output_unsigned)); + + return rescale_op.getResult(); + + } else { + op->emitOpError("buildConvRescaleOp: unknown weight quantized type"); + return nullptr; + } +} + +Value getTosaConstHardSwish8bitTable(PatternRewriter& rewriter, Operation* op, + float input_scale, int32_t input_zp, + float output_scale, int32_t output_zp) { + // Define tflite params: + // See: HardSwishPrepare / HardSwishParams + const float hires_input_scale = (1.0f / 128.0f) * input_scale; + const float reluish_scale = 3.0f / 32768.0f; + const float output_multiplier = hires_input_scale / output_scale; + + int16_t output_multiplier_fixedpoint_int16; + int output_multiplier_exponent; + + int16_t reluish_multiplier_fixedpoint_int16; + int reluish_multiplier_exponent; + + int32_t output_multiplier_fixedpoint_int32; + tflite::QuantizeMultiplier(output_multiplier, + &output_multiplier_fixedpoint_int32, + &output_multiplier_exponent); + tflite::DownScaleInt32ToInt16Multiplier(output_multiplier_fixedpoint_int32, + &output_multiplier_fixedpoint_int16); + assert(output_multiplier_exponent <= 0); + + const float reluish_multiplier = hires_input_scale / reluish_scale; + int32_t reluish_multiplier_fixedpoint_int32; + + tflite::QuantizeMultiplier(reluish_multiplier, + &reluish_multiplier_fixedpoint_int32, + &reluish_multiplier_exponent); + tflite::DownScaleInt32ToInt16Multiplier(reluish_multiplier_fixedpoint_int32, + &reluish_multiplier_fixedpoint_int16); + + // See HardSwish function in + // tensorflow/lite/kernels/internal/reference/hardswish.h + SmallVector table; + for (int32_t i = -128; i < 128; i++) { + const int16_t input_value = i - input_zp; + const int16_t input_value_on_hires_input_scale = input_value * (1 << 7); + const int16_t input_value_on_preshift_output_scale = + gemmlowp::SaturatingRoundingDoublingHighMul( + input_value_on_hires_input_scale, + output_multiplier_fixedpoint_int16); + int16_t reluish_value = input_value_on_hires_input_scale; + if (reluish_multiplier_exponent > 0) { + reluish_value = tflite::reference_ops::SaturatingLeftShift( + reluish_value, reluish_multiplier_exponent - 1); + } + reluish_value = gemmlowp::SaturatingRoundingDoublingHighMul( + reluish_value, reluish_multiplier_fixedpoint_int16); + if (reluish_multiplier_exponent > 0) { + reluish_value = + tflite::reference_ops::SaturatingLeftShift(reluish_value, 1); + } + if (reluish_multiplier_exponent < 0) { + reluish_value = gemmlowp::RoundingDivideByPOT( + reluish_value, -reluish_multiplier_exponent); + } + reluish_value = (reluish_value + (1 << 15)) >> 1; + const int16_t preshift_output_value = + tflite::reference_ops::SaturatingDoublingHighMul( + reluish_value, input_value_on_preshift_output_scale); + int16_t output_value = gemmlowp::RoundingDivideByPOT( + preshift_output_value, -output_multiplier_exponent); + output_value += output_zp; + output_value = + std::min(output_value, std::numeric_limits::max()); + output_value = + std::max(output_value, std::numeric_limits::min()); + table.push_back(output_value); + } + + auto element_qtype = + UniformQuantizedType::get(true, rewriter.getIntegerType(8), + rewriter.getF32Type(), 1.0f, 0, -128, 127); + auto const_type = tensorflow::GetTypeFromTFTensorShape({256}, element_qtype); + auto storage_type = tensorflow::GetTypeFromTFTensorShape( + {256}, getStorageElementTypeFromQuantized(element_qtype)); + auto const_attr = DenseElementsAttr::get(storage_type, llvm::ArrayRef(table)); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +Value getTosaConstRsqrt8bitTable(PatternRewriter& rewriter, Operation* op, + float input_scale, int32_t input_zp, + float output_scale, int32_t output_zp) { + // See RsqrtEvalQuantized (elementwise.cc) + const int kMin = std::numeric_limits::min(); + const int kMax = std::numeric_limits::max(); + SmallVector table; + + int32_t output_scale_multiplier; + int32_t output_scale_shift; + + const double scale = 1. / (std::sqrt(input_scale) * output_scale); + tflite_migration::QuantizeMultiplier(scale, &output_scale_multiplier, + &output_scale_shift); + + std::function quantRsqrtFunc = [&](int8_t i) { + const int32_t value = (i - input_zp); + const int32_t kShift = 20; // Shift to keep value integer. + if (value <= 0) { + // Assume that any value close to 0 (or negative values) represents the max + // output value. + return static_cast(kMax); + } + int32_t inv_sqrt_multiplier; + int inv_sqrt_shift; + tflite_migration::GetInvSqrtQuantizedMultiplierExp( + value, tflite_migration::kReverseShift, &inv_sqrt_multiplier, + &inv_sqrt_shift); + const int32_t data = tflite_migration::MultiplyByQuantizedMultiplier( + 1, inv_sqrt_multiplier, inv_sqrt_shift + kShift); + const int32_t output = + tflite_migration::MultiplyByQuantizedMultiplier( + data, output_scale_multiplier, output_scale_shift - kShift) + + output_zp; + return static_cast(std::min(std::max(output, kMin), kMax)); + }; + + for (int32_t i = -128; i < 128; i++) { + table.push_back(quantRsqrtFunc(i)); + } + + auto element_qtype = + UniformQuantizedType::get(true, rewriter.getIntegerType(8), + rewriter.getF32Type(), 1.0f, 0, -128, 127); + auto const_type = tensorflow::GetTypeFromTFTensorShape({256}, element_qtype); + auto storage_type = tensorflow::GetTypeFromTFTensorShape( + {256}, + tosa::getStorageElementTypeFromQuantized(element_qtype)); + auto const_attr = DenseElementsAttr::get(storage_type, llvm::ArrayRef(table)); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Create a 8-bit TOSA TABLE constant tensor with int8[256] array. +// Follow LUTPopulateInt8() tensorflow/lite/kernels/internal/common.h +Value getTosaConst8bitTable(PatternRewriter& rewriter, Operation* op, + float input_scale, int32_t input_zp, + float output_scale, int32_t output_zp, + std::function func) { + SmallVector table; + + float inverse_scale = 1.0f / output_scale; + for (int32_t i = -128; i < 128; i++) { + float dequantized = input_scale * (i - input_zp); + float transformed = func(dequantized); + + float max = (output_scale > 1.0) ? FLT_MAX : (FLT_MAX * output_scale); + if (transformed >= max) { + table.push_back(INT8_MAX); + continue; + } + + int32_t rescaled = std::round(transformed * inverse_scale); + int32_t quantized = static_cast(rescaled + output_zp); + table.push_back( + static_cast(std::min(std::max(quantized, -128), 127))); + } + + auto element_qtype = + UniformQuantizedType::get(true, rewriter.getIntegerType(8), + rewriter.getF32Type(), 1.0f, 0, -128, 127); + auto const_type = tensorflow::GetTypeFromTFTensorShape({256}, element_qtype); + auto storage_type = tensorflow::GetTypeFromTFTensorShape( + {256}, tosa::getStorageElementTypeFromQuantized(element_qtype)); + auto const_attr = DenseElementsAttr::get(storage_type, llvm::ArrayRef(table)); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Create a 16-bit TOSA TABLE constant tensor. +// A float should be used by default for FloatT except if a double is required +// for backward compatibility. +// Follow LUTPopulateInt16() tensorflow/lite/kernels/internal/common.h +template +Value getTosaConst16bitTable(PatternRewriter& rewriter, Operation* op, + FloatT input_scale, int32_t input_zp, + FloatT output_scale, int32_t output_zp, + std::function func) { + static_assert(std::is_floating_point::value, + "FloatT must be a floating-point type."); + + SmallVector table; + + FloatT input_min = + input_scale * (std::numeric_limits::min() - input_zp); + FloatT input_max = + input_scale * (std::numeric_limits::max() - input_zp); + FloatT output_min = + output_scale * (std::numeric_limits::min() - output_zp); + FloatT output_max = + output_scale * (std::numeric_limits::max() - output_zp); + + FloatT step = (input_max - input_min) / 512; + FloatT half_step = step / 2; + FloatT output_scaling_inv = 65536 / (output_max - output_min); + + for (int32_t i = 0; i < 512; i++) { + FloatT sample_val = + std::round(func(input_min + (i * step)) * output_scaling_inv); + FloatT midpoint_interp_val = std::round( + ((func(input_min + (i + 1) * step) * output_scaling_inv) + + std::round(func(input_min + (i * step)) * output_scaling_inv)) / + 2); + FloatT midpoint_val = std::round(func(input_min + (i * step) + half_step) * + output_scaling_inv); + FloatT midpoint_err = midpoint_interp_val - midpoint_val; + FloatT bias = std::round(midpoint_err / 2); + + table.push_back(static_cast( + std::min(std::max(sample_val - bias, -32768), 32767))); + } + + FloatT max_val = std::round(func(input_max) * output_scaling_inv); + table.push_back(static_cast( + std::min(std::max(max_val, -32768), 32767))); + + auto const_type = + tensorflow::GetTypeFromTFTensorShape({513}, rewriter.getIntegerType(16)); + auto const_attr = DenseElementsAttr::get(const_type, llvm::ArrayRef(table)); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +template Value getTosaConst16bitTable(PatternRewriter& rewriter, + Operation* op, float input_scale, + int32_t input_zp, + float output_scale, + int32_t output_zp, + std::function func); + +template Value getTosaConst16bitTable( + PatternRewriter& rewriter, Operation* op, double input_scale, + int32_t input_zp, double output_scale, int32_t output_zp, + std::function func); + +// Create a 32-bit TOSA TABLE for Softmax Exp +void getTosaConst32bitSoftmaxExpTable(PatternRewriter& rewriter, Operation* op, + double beta, double input_scale, + Value& first_const, Value& second_const, + Value& third_const, Value& fourth_const) { + const int kScaledDiffIntegerBits = 5; + using FixedPointScaledDiff = + gemmlowp::FixedPoint; + + int32_t input_beta_multiplier; + int input_beta_left_shift; + tflite_migration::PreprocessSoftmaxScaling( + beta, input_scale, kScaledDiffIntegerBits, &input_beta_multiplier, + &input_beta_left_shift); + + int diff_min = -tflite_migration::CalculateInputRadius(kScaledDiffIntegerBits, + input_beta_left_shift); + + SmallVector first_table, second_table, third_table, + fourth_table; + for (int32_t input_diff = -256; input_diff <= 256; input_diff++) { + int32_t output = 0; + if (input_diff >= diff_min) { + const int32_t input_diff_rescaled = + tflite_migration::MultiplyByQuantizedMultiplierGreaterThanOne( + input_diff, input_beta_multiplier, input_beta_left_shift); + const FixedPointScaledDiff input_diff_fixed_point = + FixedPointScaledDiff::FromRaw(input_diff_rescaled); + output = gemmlowp::exp_on_negative_values(input_diff_fixed_point).raw(); + } + + // Only copy the 8-bit groups + int32_t first = (output >> 24) & 0xFF; + int32_t second = (output >> 16) & 0xFF; + int32_t third = (output >> 8) & 0xFF; + int32_t fourth = (output) & 0xFF; + + first_table.push_back(first); + second_table.push_back(second); + third_table.push_back(third); + fourth_table.push_back(fourth); + } + + auto element_qtype = + UniformQuantizedType::get(true, rewriter.getIntegerType(16), + rewriter.getF32Type(), 1.0f, 0, -32768, 32767); + auto const_type = tensorflow::GetTypeFromTFTensorShape({513}, element_qtype); + auto storage_type = tensorflow::GetTypeFromTFTensorShape( + {513}, tosa::getStorageElementTypeFromQuantized(element_qtype)); + + auto first_const_attr = + DenseElementsAttr::get(storage_type, llvm::ArrayRef(first_table)); + auto second_const_attr = + DenseElementsAttr::get(storage_type, llvm::ArrayRef(second_table)); + auto third_const_attr = + DenseElementsAttr::get(storage_type, llvm::ArrayRef(third_table)); + auto fourth_const_attr = + DenseElementsAttr::get(storage_type, llvm::ArrayRef(fourth_table)); + + first_const = + rewriter.create(op->getLoc(), const_type, first_const_attr) + .getResult(); + second_const = + rewriter + .create(op->getLoc(), const_type, second_const_attr) + .getResult(); + third_const = + rewriter.create(op->getLoc(), const_type, third_const_attr) + .getResult(); + fourth_const = + rewriter + .create(op->getLoc(), const_type, fourth_const_attr) + .getResult(); +} + +// Create a 32-bit float constant operator from a float +Value getTosaConstTensorSingleF32(PatternRewriter& rewriter, Operation* op, + float val, int rank) { + assert(rank >= 0); + mlir::RankedTensorType const_type; + mlir::DenseElementsAttr const_attr; + auto element_type = rewriter.getF32Type(); + if (rank == 0) { + const_type = tensorflow::GetTypeFromTFTensorShape({}, element_type); + const_attr = DenseElementsAttr::get(const_type, val); + } else { + std::vector shape(rank, 1); + const_type = tensorflow::GetTypeFromTFTensorShape(llvm::ArrayRef(shape), + element_type); + std::vector values(1, val); + const_attr = DenseElementsAttr::get(const_type, llvm::ArrayRef(values)); + } + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Create a 32-bit integer constant operator from an int +Value getTosaConstTensorSingleI32(PatternRewriter& rewriter, Operation* op, + int32_t val, int rank) { + assert(rank >= 0); + mlir::RankedTensorType const_type; + mlir::DenseElementsAttr const_attr; + auto element_type = rewriter.getIntegerType(32); + if (rank == 0) { + const_type = tensorflow::GetTypeFromTFTensorShape({}, element_type); + const_attr = DenseElementsAttr::get(const_type, val); + } else { + std::vector shape(rank, 1); + const_type = tensorflow::GetTypeFromTFTensorShape(llvm::ArrayRef(shape), + element_type); + std::vector values(1, val); + const_attr = DenseElementsAttr::get(const_type, llvm::ArrayRef(values)); + } + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Create an expected bitwidth integer constant operator based on the type +// parameter. +Value getTosaConstTensorScalarInt(ImplicitLocOpBuilder& builder, Type type, + int64_t val, int rank) { + assert(rank >= 0); + assert(mlir::isa(type)); + mlir::RankedTensorType const_type; + mlir::DenseElementsAttr const_attr; + auto bit_width = type.getIntOrFloatBitWidth(); + auto element_type = builder.getIntegerType(bit_width); + if (rank == 0) { + const_type = tensorflow::GetTypeFromTFTensorShape({}, element_type); + const_attr = DenseElementsAttr::get(const_type, val); + } else { + std::vector shape(rank, 1); + const_type = tensorflow::GetTypeFromTFTensorShape(llvm::ArrayRef(shape), + element_type); + std::vector values(1, val); + const_attr = DenseElementsAttr::get(const_type, llvm::ArrayRef(values)); + } + + auto const_op = + builder.create(builder.getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Create a vector from a 32-bit value tensor. Returns the size of +// the new vector or -1 on error. +// Populate a int32_t vector from a val tensor +// return failure if val is not a constant value +// return success otherwise +LogicalResult getVectorFromValue32(Value val, SmallVectorImpl& vec) { + int i = 0; + + ElementsAttr elems; + + vec.clear(); + + if (!matchPattern(val, m_Constant(&elems))) return failure(); + + for (auto idx : elems.getValues()) { + vec.push_back(idx.getInt()); + i++; + } + + return success(); +} + +// Populate a int64_t vector from a val tensor +// return failure if val is not a constant value +// return success otherwise +LogicalResult getVectorFromValue64(Value val, SmallVectorImpl& vec) { + int i = 0; + + ElementsAttr elems; + + vec.clear(); + + if (!matchPattern(val, m_Constant(&elems))) return failure(); + + for (auto idx : elems.getValues()) { + vec.push_back(static_cast(idx.getInt())); + i++; + } + + return success(); +} + +// Calculates the TOSA padding values based on TF operators padded with +// SAME/VALID. +// +// This could pass tensorflow::FilterTensorFormat and do +// GetFilterTensorSpatialDimIndex but the current TF core libs do not support +// FORMAT_OHWI parsing by that function in core/util/tensor_format.h +bool getPaddingValuesFromPadType(tensorflow::Padding tf_pad, + tensorflow::TensorFormat data_format_tf, + uint32_t first_filter_spatial_dim, + ShapedType input_type, ShapedType filter_type, + DenseI64ArrayAttr strides, + DenseI64ArrayAttr dilations, + PatternRewriter& rewriter, + DenseI64ArrayAttr& explicit_padding) { + assert(tf_pad != tensorflow::Padding::EXPLICIT); + if (!input_type.hasRank() || !filter_type.getRank()) return false; + // Only support NHWC for now. + if (data_format_tf != tensorflow::FORMAT_NHWC) return false; + + // Storing the numeric padding values is useful for TOSA codegen, as opposed + // to holding the padding regime mnemonic, i.e. SAME, VALID, FULL, ... + SmallVector computed_paddings; + + int64_t dim_index_shift, dim_count; + if (input_type.getRank() == 4) { + // 4D tensor, NHWC/NCHW format. + dim_index_shift = GetTensorSpatialDimIndex(4, data_format_tf, 0); + dim_count = 2; + } else { + if (input_type.getRank() != 5) return false; + // 5D tensor, NDHWC/NCDHW format. + dim_index_shift = 1; + dim_count = 3; + } + + int64_t pad_before, pad_after; + // Iterating the given spatial dimensions. + for (int i = 0; i < dim_count; i++) { + int64_t ifm_dim = i + dim_index_shift; + int64_t filter_dim = first_filter_spatial_dim + i; + + int64_t dim_dilation = dilations[i]; + int64_t dim_stride = strides[i]; + + // if input size is dynamic then we cannot compute static pad shapes for + // "SAME" padding for stride != 1 + if (tf_pad == tensorflow::Padding::SAME && dim_stride != 1 && + input_type.isDynamicDim(ifm_dim)) { + return false; + } + + int64_t ip_size = input_type.getDimSize(ifm_dim); + int64_t f_size = filter_type.getDimSize(filter_dim); + // If we have a dynamic shape we should assume it is wide enough. + ip_size = ip_size < 0 ? f_size * dim_dilation : ip_size; + int64_t op_size, pad_before_tf, + pad_after_tf; // Complains if using int64_T + absl::Status status = tensorflow::GetWindowedOutputSizeVerbose( + ip_size, f_size, dim_dilation, dim_stride, tf_pad, &op_size, + &pad_before_tf, &pad_after_tf); + if (!status.ok()) return false; + + pad_before = pad_before_tf; + pad_after = pad_after_tf; + computed_paddings.push_back(pad_before); + computed_paddings.push_back(pad_after); + } + + explicit_padding = rewriter.getDenseI64ArrayAttr(computed_paddings); + return true; +} + +// Calculates the TOSA padding values for explicit-padded TF operators. +// +// This function only handles the TF padding array explicit_padding, which is +// only present in certain TF ops. All others encode padding using the string +// SAME/VALID, which is interpreted using the getPaddingValuesFromPadString +// function below. + +// The explicit padding array in TF holds 2 pad values for every +// dimension, even those that are not the 2 spatial ones. Just extract the +// 2x pad values for the XY dims. +DenseI64ArrayAttr getPaddingValuesFromExplicitPadAttr( + ArrayAttr explicit_pad, tensorflow::TensorFormat data_format_tf, + PatternRewriter& rewriter) { + SmallVector computed_paddings; + + int64_t pad_before, pad_after; + for (int i = 0; i < 2; i++) { // Two spatial dimensions X&Y + int64_t dim = GetTensorSpatialDimIndex(4, data_format_tf, + i); // 4D tensor, NHWC/NCHW format + pad_before = mlir::cast(explicit_pad[dim * 2]).getInt(); + pad_after = mlir::cast(explicit_pad[dim * 2 + 1]).getInt(); + computed_paddings.push_back(pad_before); + computed_paddings.push_back(pad_after); + } + + return rewriter.getDenseI64ArrayAttr(computed_paddings); +} + +// Calculates the TOSA padding values for transposeConv2d +bool getTransposeConv2dPaddingValues( + tensorflow::Padding tf_pad, tensorflow::TensorFormat data_format_tf, + uint32_t first_filter_spatial_dim, ShapedType input_type, + ShapedType filter_type, ShapedType output_type, DenseI64ArrayAttr strides, + PatternRewriter& rewriter, DenseI64ArrayAttr& explicit_padding) { + assert(tf_pad != tensorflow::Padding::EXPLICIT); + if (!input_type.hasRank() || !filter_type.hasRank() || !output_type.hasRank()) + return false; + + // Storing the numeric padding values is useful for TOSA codegen, as opposed + // to holding the padding regime mnemonic, i.e. SAME, VALID, FULL, ... + + SmallVector computed_paddings; + + int64_t pad_before, pad_after; + for (int i = 0; i < 2; i++) { // Two spatial dimensions X&Y + int64_t ifm_dim = GetTensorSpatialDimIndex( + 4, data_format_tf, i); // 4D tensor, NHWC/NCHW format + int64_t ofm_dim = GetTensorSpatialDimIndex( + 4, data_format_tf, i); // 4D tensor, NHWC/NCHW format + int64_t filter_dim = first_filter_spatial_dim + i; + + int64_t ifm_size = input_type.getDimSize(ifm_dim); + int64_t filter_size = filter_type.getDimSize(filter_dim); + int64_t ofm_size = output_type.getDimSize(ofm_dim); + int64_t dim_stride = strides[i]; + + // These dimensions need to be static to legalize. + if (ShapedType::isDynamic(filter_size) || ShapedType::isDynamic(ifm_size) || + ShapedType::isDynamic(ofm_size)) { + return false; + } + + int total_padding = + ((ifm_size - 1) * dim_stride + filter_size - ofm_size); + + pad_before = total_padding / 2; + pad_after = total_padding - pad_before; + + computed_paddings.push_back(-pad_before); + computed_paddings.push_back(-pad_after); + } + + explicit_padding = rewriter.getDenseI64ArrayAttr(computed_paddings); + return true; +} + +// Templated function to create a constant op for given type and shape. +// T: storage C type. +// Default template creates a constant tensor in T. +template +std::optional getConstTensor(PatternRewriter& rewriter, Operation* op, + ArrayRef vec, ArrayRef shape) { + int64_t num_total_elements = 1; + for (int64_t a : shape) { + num_total_elements *= a; + } + + if (vec.size() != num_total_elements) { + op->emitOpError("getConstTensor(): number of elements mismatch."); + return std::nullopt; + } + + auto const_type = tensorflow::GetTypeFromTFTensorShape( + shape, rewriter.getIntegerType(sizeof(T) * 8)); + auto const_attr = DenseElementsAttr::get(const_type, vec); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Template specialization for APInt +template <> +std::optional getConstTensor(PatternRewriter& rewriter, + Operation* op, ArrayRef vec, + ArrayRef shape) { + int64_t num_total_elements = 1; + for (int64_t a : shape) { + num_total_elements *= a; + } + + if (vec.size() != num_total_elements) { + op->emitOpError("getConstTensor(): number of elements mismatch."); + return std::nullopt; + } + + auto const_type = tensorflow::GetTypeFromTFTensorShape( + shape, rewriter.getIntegerType(vec[0].getBitWidth())); + auto const_attr = DenseElementsAttr::get(const_type, vec); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Template specialization for float +template <> +std::optional getConstTensor(PatternRewriter& rewriter, + Operation* op, ArrayRef vec, + ArrayRef shape) { + int64_t num_total_elements = 1; + for (int64_t a : shape) { + num_total_elements *= a; + } + + if (vec.size() != num_total_elements) { + op->emitOpError("getConstTensor(): number of elements mismatch."); + return std::nullopt; + } + + auto const_type = + tensorflow::GetTypeFromTFTensorShape(shape, rewriter.getF32Type()); + auto const_attr = DenseElementsAttr::get(const_type, vec); + + auto const_op = + rewriter.create(op->getLoc(), const_type, const_attr); + return const_op.getResult(); +} + +// Template instantiation +template std::optional getConstTensor(PatternRewriter&, + Operation*, + ArrayRef vec, + ArrayRef shape); + +llvm::SmallVector getOutputSpatialSizeRemainder( + tensorflow::TensorFormat data_format_tf, ShapedType input_type, + DenseI64ArrayAttr kernel_size, DenseI64ArrayAttr pads, + DenseI64ArrayAttr strides, DenseI64ArrayAttr dilations) { + llvm::SmallVector output_size_remainder; + + const int nb_spatial_dims = + GetTensorSpatialDims(input_type.getRank(), data_format_tf); + for (int spatial_dim = 0; spatial_dim < nb_spatial_dims; spatial_dim++) { + const int64_t in_size = input_type.getDimSize(GetTensorSpatialDimIndex( + input_type.getRank(), data_format_tf, spatial_dim)); + const int64_t full_pad = + pads[2 * spatial_dim + 0] + pads[2 * spatial_dim + 1]; + + const int64_t full_size = + in_size - 1 + full_pad - + (kernel_size[spatial_dim] - 1) * dilations[spatial_dim]; + output_size_remainder.push_back(full_size % strides[spatial_dim]); + } + + return output_size_remainder; +} + +Value getInputSlicedToItsUsedSize(PatternRewriter& rewriter, Operation* op, + tensorflow::TensorFormat data_format_tf, + ShapedType input_type, Value input_val, + DenseI64ArrayAttr kernel_size, + DenseI64ArrayAttr pads, + DenseI64ArrayAttr strides, + DenseI64ArrayAttr dilations) { + const int nb_spatial_dims = + GetTensorSpatialDims(input_type.getRank(), data_format_tf); + // Don't slice the input if any spatial dimension is dynamic + for (int spatial_dim = 0; spatial_dim < nb_spatial_dims; spatial_dim++) { + if (input_type.isDynamicDim(GetTensorSpatialDimIndex( + input_type.getRank(), data_format_tf, spatial_dim))) { + return input_val; + } + } + + const llvm::SmallVector output_size_remainder = + getOutputSpatialSizeRemainder(data_format_tf, input_type, kernel_size, + pads, strides, dilations); + + const bool need_slicing = + llvm::any_of(output_size_remainder, [](int64_t v) { return v > 0; }); + const bool zero_pads = + llvm::all_of(pads.asArrayRef(), [](int64_t v) { return v == 0; }); + if (need_slicing && zero_pads) { + llvm::SmallVector start(input_type.getRank(), 0); + llvm::SmallVector size = + tensorflow::ConvertMlirShapeToTF(input_type.getShape()); + for (int spatial_dim = 0; spatial_dim < nb_spatial_dims; spatial_dim++) { + const int index = GetTensorSpatialDimIndex(input_type.getRank(), + data_format_tf, spatial_dim); + size[index] -= output_size_remainder[spatial_dim]; + } + + auto slice_op = CreateOpAndInfer( + rewriter, op->getLoc(), + UnrankedTensorType::get(input_type.getElementType()), input_val, + getTosaConstShape(rewriter, op->getLoc(), start), + getTosaConstShape(rewriter, op->getLoc(), size)); + return slice_op.getResult(); + } + + return input_val; +} + +// Check if scale32 mode is used for given output_element_type +bool isScale32(mlir::quant::UniformQuantizedType output_element_type) { + return (output_element_type.getStorageTypeIntegralWidth() == 8); +} + +LogicalResult ApplyPatternsWithShapeResolution( + func::FuncOp func, const FrozenRewritePatternSet& patterns) { + // We use top-down traversal so that shape inference can fully infer types + // during pattern rewrite. + GreedyRewriteConfig config; + config.setUseTopDownTraversal(true); + if (failed(applyPatternsGreedily(func, patterns, config))) { + return failure(); + } + + // Check that constant attributes types and op types match up. If the lowering + // needs to change a type (e.g. fp16 -> fp32) its possible the return type + // could be incorrect. + // + // This should be investigate for whether it is still necessary due to quant + // type stripping changing. + func.walk([&](tosa::ConstOp op) { + if (mlir::isa(op.getType().getElementType())) { + return; + } + auto ety = op.getValues().getShapedType().getElementType(); + auto new_ty = mlir::cast(op.getType()).clone(ety); + op.getResult().setType(new_ty); + }); + + auto returnOp = cast(func.getBody().front().getTerminator()); + llvm::SmallVector result_tys(returnOp.getOperandTypes()); + + func.setType(FunctionType::get( + func.getContext(), func.getFunctionType().getInputs(), result_tys)); + + return success(); +} + +void TrimQuantizedIntegerRangeMin(UniformQuantizedType dtype, + int64_t& val_min) { + val_min = + val_min < dtype.getStorageTypeMin() ? dtype.getStorageTypeMin() : val_min; +} + +void TrimQuantizedIntegerRangeMax(UniformQuantizedType dtype, + int64_t& val_max) { + val_max = + val_max > dtype.getStorageTypeMax() ? dtype.getStorageTypeMax() : val_max; +} + +void TrimQuantizedIntegerRange(UniformQuantizedType dtype, int64_t& val_min, + int64_t& val_max) { + TrimQuantizedIntegerRangeMin(dtype, val_min); + TrimQuantizedIntegerRangeMax(dtype, val_max); +} + +tosa::MulOp CreateMulOpAndInfer(PatternRewriter& rewriter, Operation* op, + Type result_ty, Value input1, Value input2, + int8_t shift) { + if (EqualizeRanks(rewriter, op->getLoc(), input1, input2).failed()) { + // uncompatible broadcast shapes, no reshape is inserted + // ResultsBroadcastableShape verify will handle this + } + return CreateOpAndInfer(rewriter, op->getLoc(), result_ty, input1, + input2, getConstTensor(rewriter, op, shift, {1}).value()); +} + +Value reshapeScalarTo1D(PatternRewriter& rewriter, Location loc, Value value) { + ShapedType type = dyn_cast(value.getType()); + if (!type || !type.hasRank()) { + return nullptr; + } + if (type.getRank() == 1) { + return value; + } + if (type.getRank() != 0) { + return nullptr; + } + + auto element_type = type.getElementType(); + auto output_type = tensorflow::GetTypeFromTFTensorShape({1}, element_type); + + // for rank-0 constant value, return a rank-1 constant value + mlir::DenseElementsAttr attr; + if (matchPattern(value, m_Constant(&attr))) { + auto storage_type = tensorflow::GetTypeFromTFTensorShape({1}, element_type); + auto element_qtype = dyn_cast(element_type); + if (element_qtype) { + storage_type = tensorflow::GetTypeFromTFTensorShape( + {1}, tosa::getStorageElementTypeFromQuantized(element_qtype)); + } + + DenseElementsAttr const_attr; + if (mlir::isa(attr.getElementType())) { + const_attr = DenseElementsAttr::get(storage_type, + {attr.getValues()[0]}); + } else if (mlir::isa(attr.getElementType())) { + const_attr = DenseElementsAttr::get(storage_type, + {attr.getValues()[0]}); + } else { + // unexpected attribute element type + return nullptr; + } + + auto const_op = + rewriter.create(loc, output_type, const_attr); + return const_op.getResult(); + } + + // reshape rank0 value to rank1 + auto rank1_scalar_shape = getTosaConstShape(rewriter, loc, {1}); + Value rank1_value = CreateOpAndInfer( + rewriter, loc, output_type, value, rank1_scalar_shape); + return rank1_value; +} + +LogicalResult broadcastLowRankTensor(PatternRewriter& rewriter, Operation* op, + Value& input1, Value& input2) { + auto input1_ty = llvm::dyn_cast(input1.getType()); + auto input2_ty = llvm::dyn_cast(input2.getType()); + + if (!input1_ty || !input2_ty) { + return rewriter.notifyMatchFailure(op, + "input tensors should be all ranked"); + } + + int64_t input1_rank = input1_ty.getRank(); + int64_t input2_rank = input2_ty.getRank(); + + if (input1_rank == input2_rank) return success(); + + Value high_rank_tensor, low_rank_tensor; + int64_t high_rank, low_rank; + if (input1_rank > input2_rank) { + high_rank_tensor = input1; + low_rank_tensor = input2; + high_rank = input1_rank; + low_rank = input2_rank; + } else { + high_rank_tensor = input2; + low_rank_tensor = input1; + high_rank = input2_rank; + low_rank = input1_rank; + } + + ArrayRef high_rank_shape = + llvm::cast(high_rank_tensor.getType()).getShape(); + ArrayRef low_rank_shape = + llvm::cast(low_rank_tensor.getType()).getShape(); + + // broadcasting if the first dimension of the low-rank tensor is '1' + // example hight_rank: [1,a,b,c]; low_rank: [1,d,e]; low_rank should broadcast + // to [1, a, d, e] + if (low_rank_shape[0] == 1) { + low_rank -= 1; + } + int64_t broadcast_rank = high_rank - low_rank; + SmallVector broadcast_shape(high_rank, 1); + + for (int i = 0; i < broadcast_rank; i++) { + broadcast_shape[i] = high_rank_shape[i]; + } + + auto broadcast_shape_value = + getTosaConstShape(rewriter, op->getLoc(), + tensorflow::ConvertMlirShapeToTF(broadcast_shape)); + + std::optional result = convertBroadcastToOp( + rewriter, op, low_rank_tensor, broadcast_shape_value); + if (!result) return failure(); + + low_rank_tensor = result.value(); + + if (input1_rank < input2_rank) { + input1 = low_rank_tensor; + input2 = high_rank_tensor; + } else { + input1 = high_rank_tensor; + input2 = low_rank_tensor; + } + return success(); +} + +bool checkUniqueConstantScatterIndices(ShapedType indices_type, + ShapedType result_type, + ElementsAttr const_data) { + llvm::ArrayRef const indices_shape = indices_type.getShape(); + const unsigned int indices_rank = indices_shape.size(); + const unsigned int result_rank = result_type.getRank(); + const unsigned int last_dim_size = indices_shape[indices_rank - 1]; + + // Reconstruct each index from the unshaped constant data array and + // calculate the corresponding flattened index + auto const const_data_range = const_data.getValues(); + assert((const_data_range.size() % last_dim_size == 0) && + "Constant data length should be a multiple of indices_shape[-1]"); + + std::vector flattened_indices; + flattened_indices.reserve(const_data_range.size() / last_dim_size); + for (auto beg = const_data_range.begin(); beg < const_data_range.end(); + beg += last_dim_size) { + std::vector current_single_index(result_rank); + std::copy(beg, beg + last_dim_size, current_single_index.begin()); + const uint64_t f_index{ + ElementsAttr::getFlattenedIndex(result_type, current_single_index)}; + flattened_indices.push_back(f_index); + } + + // If adjacent flattened values are found, there are non-unique indices + std::sort(flattened_indices.begin(), flattened_indices.end()); + return std::adjacent_find(flattened_indices.begin(), + flattened_indices.end()) == flattened_indices.end(); +} + +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..be6860750718ede8a6d04335e50f70ca349c7519 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h @@ -0,0 +1,308 @@ +/* Copyright 2020 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_MLIR_TOSA_TRANSFORMS_LEGALIZE_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_UTILS_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Dialect/Quant/IR/QuantTypes.h" // from @llvm-project +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ConversionUtils.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/ShapeUtils.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/ImplicitLocOpBuilder.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Interfaces/InferTypeOpInterface.h" // from @llvm-project +#include "mlir/Rewrite/FrozenRewritePatternSet.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/dynamic_shape_utils.h" +#include "tensorflow/core/framework/kernel_shape_util.h" +#include "tensorflow/core/kernels/conv_grad_shape_utils.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace mlir { +namespace tosa { + +// returns acc_type attribute for Conv ops with specified input/output element +// types +mlir::TypeAttr getConvAccTypeAttr(PatternRewriter& rewriter, + mlir::Type input_etype, + mlir::Type output_etype); + +LogicalResult getDynamicDims(PatternRewriter& rewriter, Value value, + llvm::SmallVector& dims); + +std::optional buildReshapeWithDynamicDims(PatternRewriter& rewriter, + Operation* op, + Value input_value, + ShapedType output_type, + llvm::ArrayRef dims); + +// Create a TOSA rescale op from TFLite scaling multiplier, scaling shift, zero +// points and rounding mode +Value buildRescale(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value input_val, + int32_t scale_multiplier, int32_t scale_shit, + int64_t input_zp, int64_t output_zp, tosa::RoundingMode rounding_mode, + bool scale32); + +// Create a TOSA rescale op from TFLite scaling, zero points and rounding mode +Value buildRescale(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value input_val, double scale, + int64_t input_zp, int64_t output_zp, tosa::RoundingMode rounding_mode, + bool scale32); + +// Removes the zero point and cast to int32, no need to handle roundings modes +Value removeZeroPointAndCastToInt32(PatternRewriter& rewriter, Operation* op, + Value input_val, int64_t input_zp); + +// Creates TOSA rescale op with int32 output +Value buildRescaleToInt32(PatternRewriter& rewriter, Operation* op, + Value input_val, int32_t input_scale_multiplier, + int32_t input_scale_shift, int64_t input_zp); + +// Creates TOSA rescale op with int32 output +Value buildRescaleToInt32(PatternRewriter& rewriter, Operation* op, + Value input_val, double input_scale, + int64_t input_zp); + +// Creates TOSA rescale op with int32 input +Value buildRescaleFromInt32(PatternRewriter& rewriter, Operation* op, + ShapedType output_type, Value input_val, + double output_scale, int64_t output_zp); + +// Creates a TOSA rescale op based on conv2d parameters. +Value buildRescaleOpConvOutput(PatternRewriter& rewriter, Operation* op, + Value conv_val, ShapedType input_type, + ShapedType weight_type, ShapedType output_type); + +// Create a 8-bit TOSA TABLE constant tensor +Value getTosaConst8bitTable(PatternRewriter& rewriter, Operation* op, + float input_scale, int32_t input_zp, + float output_scale, int32_t output_zp, + std::function func); + +// Create a 16-bit TOSA TABLE constant tensor +// A float should be used by default for FloatT except if a double is required +// for backward compatibility +template +Value getTosaConst16bitTable(PatternRewriter& rewriter, Operation* op, + FloatT input_scale, int32_t input_zp, + FloatT output_scale, int32_t output_zp, + std::function func); + +// Create a 32-bit TOSA TABLE for Softmax Exp +void getTosaConst32bitSoftmaxExpTable(PatternRewriter& rewriter, Operation* op, + double beta, double input_scale, + Value& first_const, Value& second_const, + Value& third_const, Value& fourth_const); + +// Create 8 bit TOSA TABLE constant tensor for the RSqrt operator +Value getTosaConstRsqrt8bitTable(PatternRewriter& rewriter, Operation* op, + float input_scale, int32_t input_zp, + float output_scale, int32_t output_zp); + +// Create an 8-bit TOSA Table constant tensor for the HardSwish operator +Value getTosaConstHardSwish8bitTable(PatternRewriter& rewriter, Operation* op, + float input_scale, int32_t input_zp, + float output_scale, int32_t output_zp); + +// Create a 32-bit float constant operator from a float +Value getTosaConstTensorSingleF32(PatternRewriter& rewriter, Operation* op, + float val, int rank); + +// Create a 32-bit integer constant operator from an int of specified rank +Value getTosaConstTensorSingleI32(PatternRewriter& rewriter, Operation* op, + int32_t val, int rank); + +// Create an expected bitwidth integer constant operator based on the type +// parameter, of specified rank +Value getTosaConstTensorScalarInt(ImplicitLocOpBuilder& builder, Type type, + int64_t val, int rank); + +// Populate a int32_t vector from a val tensor +// return failure if val is not a constant value +// return success otherwise +LogicalResult getVectorFromValue32(Value val, SmallVectorImpl& vec); + +// Populate a int64_t vector from a val tensor +// return failure if val is not a constant value +// return success otherwise +LogicalResult getVectorFromValue64(Value val, SmallVectorImpl& vec); + +// Calculates the TOSA padding values based on TF operators padded with +// SAME/VALID. +bool getPaddingValuesFromPadType(tensorflow::Padding tf_pad, + tensorflow::TensorFormat data_format_tf, + uint32_t first_filter_spatial_dim, + ShapedType input_type, ShapedType filter_type, + DenseI64ArrayAttr strides, + DenseI64ArrayAttr dilations, + PatternRewriter& rewriter, + DenseI64ArrayAttr& explicit_pad); + +// Calculates the TOSA padding values for explicit-padded TF operators. +DenseI64ArrayAttr getPaddingValuesFromExplicitPadAttr( + ArrayAttr explicit_pad, tensorflow::TensorFormat data_format_tf, + PatternRewriter& rewriter); + +// Calculates the TOSA padding values for transposeConv2d +bool getTransposeConv2dPaddingValues( + tensorflow::Padding tf_pad, tensorflow::TensorFormat data_format_tf, + uint32_t first_filter_spatial_dim, ShapedType input_type, + ShapedType filter_type, ShapedType output_type, DenseI64ArrayAttr strides, + PatternRewriter& rewriter, DenseI64ArrayAttr& explicit_pad); + +// Templated function to create a constant op for given type and shape. +// T: storage C type. +// Default template creates a constant tensor in T. +// To create INT48 TOSA constant, need to pass in llvm::APInt instead. +template +std::optional getConstTensor(PatternRewriter& rewriter, Operation* op, + ArrayRef vec, ArrayRef shape); + +// For each spatial dimension, return the remainder of the output size +// calculation: (I - 1 + pad - (K - 1) * dilation) % stride. +llvm::SmallVector getOutputSpatialSizeRemainder( + tensorflow::TensorFormat data_format_tf, ShapedType input_type, + DenseI64ArrayAttr kernel_size, DenseI64ArrayAttr pads, + DenseI64ArrayAttr strides, DenseI64ArrayAttr dilations); + +// The TOSA specification requires the full size of the input to be used during +// the convolution (the output size remainder calculation must be 0). If input +// slicing is necessary to satisfy the condition, return a tosa::SliceOp, +// otherwise return input_val. +Value getInputSlicedToItsUsedSize(PatternRewriter& rewriter, Operation* op, + tensorflow::TensorFormat data_format_tf, + ShapedType input_type, Value input_val, + DenseI64ArrayAttr kernel_size, + DenseI64ArrayAttr pads, + DenseI64ArrayAttr strides, + DenseI64ArrayAttr dilations); + +// Check if scale32 mode is used for given output_element_type +bool isScale32(mlir::quant::UniformQuantizedType output_element_type); + +// Checks if the multi-dimensional indices supplied by a constant tensor +// are unique. This is a useful check for legalizations to tosa.scatter +// which requires indices are unique, while in TF/TFLite they may be +// non-unique. +bool checkUniqueConstantScatterIndices(ShapedType indices_type, + ShapedType result_type, + ElementsAttr const_data); + +// Applies a set of patterns greedily to the specified function, then applies +// a cleanup to guarantee the function contract and constants are valid. This +// means patterns can performed shape inference while not altering immutable +// types. +LogicalResult ApplyPatternsWithShapeResolution( + func::FuncOp func, const FrozenRewritePatternSet& patterns); + +// Creates a TOSA operation and performs shape inference on the individual +// op. This allows shape inference during the TFLite to TOSA lowering. +template +TosaOp CreateOpAndInfer(ImplicitLocOpBuilder& builder, Type result_ty, + Args&&... args) { + return CreateOpAndInferShape(builder, result_ty, args...); +} + +template +TosaOp CreateOpAndInfer(PatternRewriter& rewriter, Location loc, Type result_ty, + Args&&... args) { + ImplicitLocOpBuilder builder(loc, rewriter); + return CreateOpAndInfer(builder, result_ty, args...); +} + +template +void CreateReplaceOpAndInfer(PatternRewriter& rewriter, Operation* op, + Type result_ty, Args&&... args) { + auto result = + CreateOpAndInfer(rewriter, op->getLoc(), result_ty, args...); + rewriter.replaceOp(op, result->getResults()); +} + +// Nan propagation mode is only applied to maximum and mininum. +template +LogicalResult ConvertBinaryOp(Operation* op, PatternRewriter& rewriter, + std::optional nan_mode = std::nullopt) { + TensorType output_type = dyn_cast(op->getResults()[0].getType()); + if (!output_type) return failure(); + + Value x = op->getOperands()[0]; + Value y = op->getOperands()[1]; + + RankedTensorType x_type = dyn_cast(x.getType()); + RankedTensorType y_type = dyn_cast(y.getType()); + if (!x_type || !y_type) return failure(); + + if constexpr (std::is_same_v || + std::is_same_v) { + if (!nan_mode) { + (void)rewriter.notifyMatchFailure(op, "invalid NaN mode: must be either 'PROPAGATE' or 'IGNORE'"); + return failure(); + } + const auto nan_mode_attr = tosa::NanPropagationModeAttr::get( + rewriter.getContext(), *nan_mode); + CreateReplaceOpAndInfer(rewriter, op, output_type, x, y, nan_mode); + } else + CreateReplaceOpAndInfer(rewriter, op, output_type, x, y); + + return success(); +} + +// Create TOSA mul ops and infer the shape of the operation. During the +// creation, fill in the shift value if applied. +tosa::MulOp CreateMulOpAndInfer(PatternRewriter& rewriter, Operation* op, + Type result_ty, Value input1, Value input2, + int8_t shift = 0); + +void TrimQuantizedIntegerRangeMin(mlir::quant::UniformQuantizedType dtype, + int64_t& val_min); + +void TrimQuantizedIntegerRangeMax(mlir::quant::UniformQuantizedType dtype, + int64_t& val_max); + +void TrimQuantizedIntegerRange(mlir::quant::UniformQuantizedType dtype, + int64_t& val_min, int64_t& val_max); + +inline bool IsTFLDoubleRoundingMode() { +#if TFLITE_SINGLE_ROUNDING + return false; +#else + return true; +#endif // TFLITE_SINGLE_ROUNDING +} + +Value reshapeScalarTo1D(PatternRewriter& rewriter, Location loc, Value value); + +LogicalResult broadcastLowRankTensor(PatternRewriter &rewriter, Operation* op, + Value &input1, Value &input2); + +} // namespace tosa +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_LEGALIZE_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/lower_complex_types.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/lower_complex_types.cc new file mode 100644 index 0000000000000000000000000000000000000000..0c192741b040b1b5f94a9911d7d49dd134cc97cc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/lower_complex_types.cc @@ -0,0 +1,171 @@ +/* Copyright 2023 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. +==============================================================================*/ + +// TOSA has no notion of complex datatypes, it represents a single complex +// input tensor using two floating point input tensors corresponding to the +// "real" and "imag" parts of the complex input. +// +// To maintain the correct mapping of these tensors during the legalization +// from TFL to TOSA, a complex tensor of shape [x, ..., y] is converted to +// a single floating point tensor of shape [x, ..., y, 2] where each resulting +// pair of values can be used to represent a complex value, which ensures a +// 1:1 mapping between TFL and TOSA input/output tensors. In legalization, +// "unrealized_conversion_cast" operations are inserted to express this +// conversion. +// +// This pass removes complex tensors from the graph by rewriting them using +// the above [x, ..., y, 2] floating point format. Consequently, it removes +// any remaining "unrealized_conversion_cast" operations and ensures the +// resulting graph is free of illegal complex tensors. + +#include +#include +#include + +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/IR/TypeUtilities.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "mlir/Transforms/GreedyPatternRewriteDriver.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-lower-complex-types" +#define DEBUG_TYPE PASS_NAME + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSALOWERCOMPLEXTYPESPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +class LowerComplexTypes + : public impl::TosaLowerComplexTypesPassBase { + public: + explicit LowerComplexTypes() = default; + void runOnOperation() override; +}; + +class ComplexTypeConverter : public TypeConverter { + public: + static Type convertTensor(RankedTensorType type) { + if (auto elementType = dyn_cast(type.getElementType())) { + llvm::SmallVector newShape; + for (auto dim : type.getShape()) { + newShape.push_back(dim); + } + newShape.push_back(2); + return RankedTensorType::get(newShape, elementType.getElementType()); + } + return type; + } + + explicit ComplexTypeConverter() { addConversion(convertTensor); } +}; + +// Handles the type conversion component of the TypeConversion. This updates +// conversion patterns that used the original complex tensor types to be +// updated to the non-complex variants. +class GenericTypeConvert : public ConversionPattern { + public: + GenericTypeConvert(MLIRContext* context, TypeConverter& converter) + : ConversionPattern(converter, MatchAnyOpTypeTag(), 0, context) {} + LogicalResult matchAndRewrite( + Operation* op, ArrayRef operands, + ConversionPatternRewriter& rewriter) const override { + if (isa(op)) { + return failure(); + } + + llvm::SmallVector newResults; + (void)getTypeConverter()->convertTypes(op->getResultTypes(), newResults); + OperationState state(op->getLoc(), op->getName().getStringRef(), operands, + newResults, op->getAttrs(), op->getSuccessors()); + for (Region& r : op->getRegions()) { + Region* newRegion = state.addRegion(); + rewriter.inlineRegionBefore(r, *newRegion, newRegion->begin()); + TypeConverter::SignatureConversion result(newRegion->getNumArguments()); + (void)getTypeConverter()->convertSignatureArgs( + newRegion->getArgumentTypes(), result); + rewriter.applySignatureConversion(&newRegion->front(), result); + } + Operation* newOp = rewriter.create(state); + rewriter.replaceOp(op, newOp->getResults()); + return success(); + } +}; + +static bool isIllegalType(Type type) { + if (auto shapedType = dyn_cast(type)) { + return mlir::isa(shapedType.getElementType()); + } + return false; +} + +void LowerComplexTypes::runOnOperation() { + ComplexTypeConverter converter; + ConversionTarget target(getContext()); + + // Operations are legal if they don't contain any illegal type. + target.markUnknownOpDynamicallyLegal([](Operation* op) { + if (auto funcOp = dyn_cast(op)) { + for (Type type : funcOp.getFunctionType().getInputs()) { + if (isIllegalType(type)) return false; + } + for (Type type : funcOp.getFunctionType().getResults()) { + if (isIllegalType(type)) return false; + } + } + for (Type type : op->getResultTypes()) { + if (type && isIllegalType(type)) return false; + } + for (Type type : op->getOperandTypes()) { + if (type && isIllegalType(type)) return false; + } + return true; + }); + + auto func = getOperation(); + auto* ctx = &getContext(); + + RewritePatternSet patterns(ctx); + patterns.add(ctx, converter); + populateFunctionOpInterfaceTypeConversionPattern(patterns, + converter); + if (failed(applyFullConversion(func, target, std::move(patterns)))) { + signalPassFailure(); + } + + // We need to run folders post rewrite to cleanup conversion casts. + RewritePatternSet emptyRewriters(ctx); + if (failed(applyPatternsGreedily(func, std::move(emptyRewriters)))) { + signalPassFailure(); + } +} + +} // anonymous namespace + +std::unique_ptr> createLowerComplexTypesPass() { + return std::make_unique(); +} +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/passes.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/passes.h new file mode 100644 index 0000000000000000000000000000000000000000..a2ca988628c29242282f07c8ba7b03ac3a1756d7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/passes.h @@ -0,0 +1,94 @@ +/* Copyright 2020 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_MLIR_TOSA_TRANSFORMS_PASSES_H_ +#define TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_PASSES_H_ + +#include +#include +#include +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project + +namespace mlir { + +namespace quant { +class QuantDialect; +} + +namespace quantfork { +class QuantizationForkDialect; +} + +namespace TFL { +class TFLDialect; +} + +namespace tosa { +class TosaDialect; + +void populateLegalizeTFPatterns(MLIRContext* ctx, RewritePatternSet& patterns); +void populateLegalizeTFLPatterns(MLIRContext* ctx, RewritePatternSet& patterns); + +std::unique_ptr> createLegalizeTFPass(); +std::unique_ptr> createFuseBiasTFPass(); + +// `disabledPatterns` is a set of labels used to filter out input patterns with +// a debug label or debug name in this set. +// `enabledPatterns` is a set of labels used to filter out input patterns that +// do not have one of the labels in this set. +std::unique_ptr> createLegalizeTFLPass( + ArrayRef disabled_patterns = {}, + ArrayRef enabled_patterns = {}); + +std::unique_ptr> createRetainCallOnceFuncsPass(); +std::unique_ptr> createStripModuleMetadataPass(); +std::unique_ptr> +createConvertTFLUnsignedIntToSignedPass(); +std::unique_ptr> +createConvertFunctionMetadataPass(); +std::unique_ptr> createDequantizeTFLSoftmaxPass(); +std::unique_ptr> createLegalizeTFTFLPass(); +std::unique_ptr> createLowerComplexTypesPass(); +std::unique_ptr> createStripFunctionMetadataPass(); +std::unique_ptr> createStripQuantTypesPass(); +std::unique_ptr> createVerifyFullyConvertedPass(); +std::unique_ptr> createLegalizeTFLStatefulPass(); + +#define GEN_PASS_REGISTRATION +#define GEN_PASS_DECL_TOSALEGALIZETFPASS +#define GEN_PASS_DECL_TOSALEGALIZETFLPASS +#define GEN_PASS_DECL_TOSALEGALIZETFTFLPASS +#define GEN_PASS_DECL_TOSAFUSEBIASTFPASS +#define GEN_PASS_DECL_TOSACONVERTTFLUNSIGNEDINTTOSIGNEDPASS +#define GEN_PASS_DECL_TOSASTRIPQUANTTYPESPASS +#define GEN_PASS_DECL_TOSALOWERCOMPLEXTYPESPASS +#define GEN_PASS_DECL_TOSADEQUANTIZETFLSOFTMAXPASS +#define GEN_PASS_DECL_RETAINCALLONCEFUNCS +#define GEN_PASS_DECL_STRIPFUNCTIONMETADATA +#define GEN_PASS_DECL_STRIPMODULEMETADATA +#define GEN_PASS_DECL_VERIFYFULLYCONVERTED +#define GEN_PASS_DECL_CONVERTFUNCTIONMETADATA +#define GEN_PASS_DECL_TOSALEGALIZESTATEFULPASS + +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +} // namespace tosa +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_TOSA_TRANSFORMS_PASSES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/passes.td b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/passes.td new file mode 100644 index 0000000000000000000000000000000000000000..43a0bbb4cd01c3da958db0723d1b6e9803ddf8fc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/passes.td @@ -0,0 +1,129 @@ +/* Copyright 2020 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 "mlir/Pass/PassBase.td" + +def TosaLegalizeTFPass : Pass<"tosa-legalize-tf", "mlir::func::FuncOp"> { + let summary = "Legalize from TensorFlow to TOSA"; + let constructor = "createLegalizeTFPass()"; + let dependentDialects = ["TosaDialect", + "quant::QuantDialect","quantfork::QuantizationForkDialect" + ]; +} + +def TosaLegalizeTFLPass : Pass<"tosa-legalize-tfl", "mlir::func::FuncOp"> { + let summary = "Legalize from TensorFlow Lite to TOSA. Options allow selective disabling/enabling of rewrites"; + let constructor = "createLegalizeTFLPass()"; + + let dependentDialects = ["TosaDialect"]; + let options = [ + ListOption<"disabled_patterns_", "disable-patterns", "std::string", + "Labels of patterns that should be filtered out during application">, + ListOption<"enabled_patterns_", "enable-patterns", "std::string", + "Labels of patterns that should be used during application, all other patterns are filtered out">, + ]; +} + +def TosaLegalizeTFTFLPass : Pass<"tosa-legalize-tf-tfl", "mlir::func::FuncOp"> { + let summary = "Legalize from TensorFlow / TensorFlow Lite to TOSA"; + let constructor = "createLegalizeTFTFLPass()"; + let dependentDialects = ["TosaDialect"]; +} + +def TosaFusebiasTFPass : Pass<"tosa-fuse-bias-tf", "mlir::func::FuncOp"> { + let summary = "Fuse tf.Op + tf.BiasAdd and legalized to TOSA"; + let constructor = "createFuseBiasTFPass()"; + let dependentDialects = ["TosaDialect"]; +} + +def TosaConvertTFLUnsignedIntToSignedPass : Pass<"tosa-convert-tfl-uint-to-int", "mlir::func::FuncOp"> { + let summary = "Convert unsigned integer graph to integer graph"; + let constructor = "createConvertTFLUnsignedIntToSignedPass()"; + let dependentDialects = ["TosaDialect"]; +} + +def TosaStripQuantTypesPass : Pass<"tosa-strip-quant-types", "mlir::func::FuncOp"> { + let summary = "Convert all quant types to their storage type."; + let constructor = "createStripQuantTypesPass()"; + let dependentDialects = ["TosaDialect"]; +} + +def TosaLowerComplexTypesPass : Pass<"tosa-lower-complex-types", "mlir::func::FuncOp"> { + let summary = "Convert all complex types to their storage type."; + let description = [{ + Complex tensors are not supported in TOSA and are instead represented by two floating + point tensors corresponding to the "real" and "imag" parts of the complex tensor. This + pass replaces all complex tensors of shape [x, ..., y] with floating point tensors of + shape [x, ..., y, 2] where each inner pair of values represents a complex value. In + doing so, a 1:1 mapping between TFL and TOSA input/output tensors is maintained. The + pass will fail if not all complex tensors are converted. + }]; + let constructor = "createLowerComplexTypesPass()"; + let dependentDialects = ["TosaDialect"]; +} + +def TosaDequantizeTFLSoftmaxPass : Pass<"tosa-dequantize-tfl-softmax", "mlir::func::FuncOp"> { + let summary = "Dequantize TFLite Softmax ops."; + let description = [{ + This pass rewrites quantized TFLite Softmax ops as: Dequantize, (float) Softmax, Quantize. + It is a work around for current performance issues with quantized Softmax codegen. + For instance it is a 20% end-to-end speedup on certain Softmax-heavy BERTs. + The compromise here is that this breaks bit-for-bit agreement with the quantized + Softmax lowering. But as Softmax isn't currently a TOSA op, this isn't a TOSA + spec violation - just breaking an invariant in the TFL-to-TOSA import pipeline. + See https://github.com/google/iree/issues/8974. + }]; + let constructor = "createDequantizeTFLSoftmaxPass()"; + let dependentDialects = ["mlir::TFL::TFLDialect", "quantfork::QuantizationForkDialect"]; +} + +def RetainCallOnceFuncs : + Pass<"tflite-retain-call-once-funcs", "mlir::ModuleOp"> { + let summary = "Guarantees that functions used by tfl.call_once are retained."; + let constructor = "createRetainCallOnceFuncsPass()"; +} + +def StripFunctionMetadata : + Pass<"tosa-tflite-strip-function-metadata", "mlir::func::FuncOp"> { + let summary = "Strip all unneeded TF/TFLite specific metadata."; + let constructor = "createStripFunctionMetadataPass()"; +} + +def StripModuleMetadata : + Pass<"tosa-tflite-strip-module-metadata", "mlir::ModuleOp"> { + let summary = "Strip all unneeded TF/TFLite specific metadata."; + let constructor = "createStripModuleMetadataPass()"; +} + +def VerifyFullyConverted : + Pass<"tosa-tflite-verify-fully-converted", "mlir::func::FuncOp"> { + let summary = "Verifies that all TFLite frontend ops were converted and none remain."; + let constructor = "createVerifyFullyConvertedPass()"; +} + +def ConvertFunctionMetadata : + Pass<"tosa-tflite-convert-function-metadata", "mlir::func::FuncOp"> { + let summary = "Converts TFLite input attributes to MLProgram arg attributes on functions."; + let constructor = "createConvertFunctionMetadataPass()"; +} + +def TosaLegalizeTFLStatefulPass : Pass<"tosa-legalize-tfl-stateful-tensors", "mlir::ModuleOp"> { + let summary = "Legalize tfl stateful operators to tosa stateful operators"; + let description = [{ + This pass is legalizing the tfl.call_once op to tosa stateful operators + }]; + let constructor = "createLegalizeTFLStatefulPass()"; + let dependentDialects = ["mlir::TFL::TFLDialect"]; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/retain_call_once_funcs.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/retain_call_once_funcs.cc new file mode 100644 index 0000000000000000000000000000000000000000..4ee02bf3ae563abc55888983e2f3354b98261cb2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/retain_call_once_funcs.cc @@ -0,0 +1,68 @@ +/* Copyright 2023 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 + +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/FormatVariadic.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "retain-call-once-funcs" +#define DEBUG_TYPE PASS_NAME + +namespace mlir::tosa { + +#define GEN_PASS_DEF_RETAINCALLONCEFUNCS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +namespace { + +class RetainCallOnceFuncsPass + : public impl::RetainCallOnceFuncsBase { + public: + void getDependentDialects(DialectRegistry& registry) const override { + registry.insert(); + } + + void runOnOperation() override { + auto moduleOp = getOperation(); + + llvm::DenseMap funcMap; + for (auto func : moduleOp.getOps()) { + funcMap[func.getSymName()] = func; + } + + for (auto func : moduleOp.getOps()) { + for (auto callOnce : func.getOps()) { + auto callFunc = funcMap[callOnce.getSessionInitFunction()]; + callOnce->setAttr("session_init_function_symbol", + SymbolRefAttr::get(callFunc)); + } + } + } +}; + +} // anonymous namespace + +std::unique_ptr> createRetainCallOnceFuncsPass() { + return std::make_unique(); +} + +} // namespace mlir::tosa diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/strip_metadata.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/strip_metadata.cc new file mode 100644 index 0000000000000000000000000000000000000000..e83f616086734c0088d7423fafdcbc27cd808f5b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/strip_metadata.cc @@ -0,0 +1,104 @@ +/* Copyright 2023 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 + +#include "mlir/Interfaces/FunctionInterfaces.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-strip-metadata" +#define DEBUG_TYPE PASS_NAME + +namespace mlir::tosa { + +#define GEN_PASS_DEF_STRIPFUNCTIONMETADATA +#define GEN_PASS_DEF_STRIPMODULEMETADATA +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +namespace { + +static bool isTFLAttr(NamedAttribute &namedAttr) { + // TFLite uses both tf and tfl in attribute annotations. + auto name = namedAttr.getName().strref(); + // Don't trim attributes from tf_saved_model---they carry ABI information. + if (name.starts_with("tf_saved_model.")) return false; + + if (name.starts_with("tf.") || name.starts_with("tf_") || + name.starts_with("tfl.") || name.starts_with("tfl_")) { + return true; + } + StringRef attrNamespace = namedAttr.getValue().getDialect().getNamespace(); + return attrNamespace == "tf" || attrNamespace == "tfl"; +} + +class StripModuleMetadataPass + : public impl::StripModuleMetadataBase { + public: + void runOnOperation() override { + auto moduleOp = getOperation(); + auto stripAttrs = llvm::to_vector<4>(llvm::make_filter_range( + moduleOp->getAttrs(), + [](NamedAttribute namedAttr) { return isTFLAttr(namedAttr); })); + for (auto namedAttr : stripAttrs) { + moduleOp->removeAttr(namedAttr.getName()); + } + } +}; + +class StripFunctionMetadataPass + : public impl::StripFunctionMetadataBase { + public: + void runOnOperation() override { + auto funcOp = getOperation(); + auto stripAttrs = llvm::to_vector<4>(llvm::make_filter_range( + funcOp->getAttrs(), + [](NamedAttribute namedAttr) { return isTFLAttr(namedAttr); })); + for (auto namedAttr : stripAttrs) { + funcOp->removeAttr(namedAttr.getName()); + } + + for (int i = 0, e = funcOp.getNumArguments(); i < e; ++i) { + auto stripAttrs = llvm::to_vector<4>(llvm::make_filter_range( + mlir::function_interface_impl::getArgAttrs(funcOp, i), + [](NamedAttribute namedAttr) { return isTFLAttr(namedAttr); })); + for (auto namedAttr : stripAttrs) { + funcOp.removeArgAttr(i, namedAttr.getName()); + } + } + + for (int i = 0, e = funcOp.getNumResults(); i < e; ++i) { + auto stripAttrs = llvm::to_vector<4>(llvm::make_filter_range( + mlir::function_interface_impl::getResultAttrs(funcOp, i), + [](NamedAttribute namedAttr) { return isTFLAttr(namedAttr); })); + for (auto namedAttr : stripAttrs) { + funcOp.removeResultAttr(i, namedAttr.getName()); + } + } + } +}; + +} // anonymous namespace + +std::unique_ptr> createStripModuleMetadataPass() { + return std::make_unique(); +} + +std::unique_ptr> createStripFunctionMetadataPass() { + return std::make_unique(); +} + +} // namespace mlir::tosa diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/strip_quant_types.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/strip_quant_types.cc new file mode 100644 index 0000000000000000000000000000000000000000..d0ae96d0fbff1a25d224f39c849ef03520aef9da --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/strip_quant_types.cc @@ -0,0 +1,170 @@ +/* Copyright 2021 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. +==============================================================================*/ + +// This pass converts a TFLite uint8 graph to the int8 domain, with adaptors at +// input and output tensors. This is needed because TOSA precision is +// implemented in the int8 domain. This pass does: +// 1. match TFL::QConst with uint8, generate TFL::QConst with int8 with value +// remapped. +// 2. insert tosa.RESCALE uint8 -> int8 if block argument (placeholder of graph) +// is uint8 typed. +// 3. insert tosa.RESCALE int8 -> uint8 if original returned tensor is uint8 +// typed. + +#include +#include + +#include "mlir/Dialect/Tosa/IR/TosaOps.h" // from @llvm-project +#include "mlir/Dialect/Tosa/Utils/QuantUtils.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/PatternMatch.h" // from @llvm-project +#include "mlir/Pass/PassRegistry.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_common.h" +#include "tensorflow/compiler/mlir/tosa/transforms/legalize_utils.h" +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h" + +#define PASS_NAME "tosa-convert-tfl-uint8" +#define DEBUG_TYPE PASS_NAME + +namespace mlir { +namespace tosa { +namespace { + +#define GEN_PASS_DEF_TOSASTRIPQUANTTYPESPASS +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +class StripQuantTypes + : public impl::TosaStripQuantTypesPassBase { + public: + explicit StripQuantTypes() = default; + void runOnOperation() override; +}; + +class QuantTypeConverter : public TypeConverter { + public: + static Type convertType(Type type) { + if (auto qType = dyn_cast(type)) { + if (qType.isSigned() || qType.getStorageTypeIntegralWidth() != 8) { + return IntegerType::get(type.getContext(), + qType.getStorageTypeIntegralWidth()); + } + + return IntegerType::get(type.getContext(), + qType.getStorageTypeIntegralWidth(), + IntegerType::SignednessSemantics::Unsigned); + } + return type; + } + static Type convertTensor(RankedTensorType type) { + auto newType = RankedTensorType::get(type.getShape(), + convertType(type.getElementType())); + return newType; + } + explicit QuantTypeConverter() { + addConversion([](Type type) { return convertType(type); }); + addConversion(convertTensor); + } +}; + +// Handles the type conversion component of the TypeConversion. This updates +// conversion patterns that used the original Quant types to be updated to +// the non-quant variants. +class GenericTypeConvert : public ConversionPattern { + public: + GenericTypeConvert(MLIRContext* context, TypeConverter& converter) + : ConversionPattern(converter, MatchAnyOpTypeTag(), 0, context) {} + LogicalResult matchAndRewrite( + Operation* op, ArrayRef operands, + ConversionPatternRewriter& rewriter) const override { + llvm::SmallVector newResults; + if (isa(op)) { + return failure(); + } + + (void)getTypeConverter()->convertTypes(op->getResultTypes(), newResults); + OperationState state(op->getLoc(), op->getName().getStringRef(), operands, + newResults, op->getAttrs(), op->getSuccessors()); + for (Region& r : op->getRegions()) { + Region* newRegion = state.addRegion(); + rewriter.inlineRegionBefore(r, *newRegion, newRegion->begin()); + TypeConverter::SignatureConversion result(newRegion->getNumArguments()); + (void)getTypeConverter()->convertSignatureArgs( + newRegion->getArgumentTypes(), result); + rewriter.applySignatureConversion(&newRegion->front(), result); + } + Operation* newOp = rewriter.create(state); + rewriter.replaceOp(op, newOp->getResults()); + return success(); + } +}; + +static bool isIllegalType(Type type) { + if (mlir::isa(type)) return true; + if (auto shapedType = dyn_cast(type)) { + return isIllegalType(shapedType.getElementType()); + } + return false; +} + +void StripQuantTypes::runOnOperation() { + QuantTypeConverter converter; + ConversionTarget target(getContext()); + + target.addIllegalDialect(); + // Operations are legal if they don't contain any illegal type. + target.markUnknownOpDynamicallyLegal([](Operation* op) { + if (auto funcOp = dyn_cast(op)) { + for (Type type : funcOp.getFunctionType().getInputs()) { + if (isIllegalType(type)) return false; + } + for (Type type : funcOp.getFunctionType().getResults()) { + if (isIllegalType(type)) return false; + } + } + for (Type type : op->getResultTypes()) { + if (type && isIllegalType(type)) return false; + } + for (Type type : op->getOperandTypes()) { + if (type && isIllegalType(type)) return false; + } + return true; + }); + + auto* ctx = &getContext(); + auto func = getOperation(); + + RewritePatternSet patterns(&getContext()); + patterns.add(ctx, converter); + populateFunctionOpInterfaceTypeConversionPattern(patterns, + converter); + + if (failed(applyFullConversion(func, target, std::move(patterns)))) { + signalPassFailure(); + } +} + +} // anonymous namespace + +std::unique_ptr> createStripQuantTypesPass() { + return std::make_unique(); +} +} // namespace tosa +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/tf_legalize_patterns.td b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/tf_legalize_patterns.td new file mode 100644 index 0000000000000000000000000000000000000000..19d66f663c81e24ccd4ae4e7e7ed312e9c525d3d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/tf_legalize_patterns.td @@ -0,0 +1,43 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// TensorFlow legalization patterns + +include "mlir/IR/OpBase.td" +include "mlir/IR/PatternBase.td" +include "mlir/Dialect/Func/IR/FuncOps.td" +include "mlir/Dialect/Tosa/IR/TosaOps.td" +include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.td" + +// Nullary ops patterns. + +def : Pat<(TF_ConstOp ElementsAttr : $value), (Tosa_ConstOp $value)>; + +// Unary ops patterns. + +def : Pat<(TF_IdentityOp $value), (replaceWithValue $value)>; +def : Pat<(TF_AbsOp $arg), (Tosa_AbsOp $arg)>; +def : Pat<(TF_CeilOp $arg), (Tosa_CeilOp $arg)>; +def : Pat<(TF_FloorOp $arg), (Tosa_FloorOp $arg)>; +def : Pat<(TF_ExpOp $arg), (Tosa_ExpOp $arg)>; +def : Pat<(TF_ErfOp $arg), (Tosa_ErfOp $arg)>; +def : Pat<(TF_LogOp $arg), (Tosa_LogOp $arg)>; +def : Pat<(TF_ReciprocalOp $arg), (Tosa_ReciprocalOp $arg)>; +def : Pat<(TF_RsqrtOp $arg), (Tosa_RsqrtOp $arg)>; +def : Pat<(TF_LogicalNotOp $arg), (Tosa_LogicalNotOp $arg)>; +def : Pat<(TF_InvertOp $arg1), (Tosa_BitwiseNotOp $arg1)>; +def : Pat<(TF_CastOp $in, BoolAttr : $truncate), (Tosa_CastOp $in)>; + +// Binary ops patterns. diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/tfl_legalize_patterns.td b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/tfl_legalize_patterns.td new file mode 100644 index 0000000000000000000000000000000000000000..fce804cc96564bb5a054d90cf859e781f44c7a65 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/tfl_legalize_patterns.td @@ -0,0 +1,44 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// TFLite legalization patterns + +include "mlir/IR/OpBase.td" +include "mlir/IR/PatternBase.td" +include "mlir/Dialect/Func/IR/FuncOps.td" +include "tensorflow/compiler/mlir/lite/ir/tfl_ops.td" +include "tensorflow/compiler/mlir/lite/quantization/ir/QuantOps.td" +include "mlir/Dialect/Tosa/IR/TosaOps.td" + +//===----------------------------------------------------------------------===// +// Unary ops patterns. +//===----------------------------------------------------------------------===// + +def ConvertTFLAbsOp : Pat<(TFL_AbsOp $arg), (Tosa_AbsOp $arg)>; +def ConvertTFLCeilOp : Pat<(TFL_CeilOp $arg), (Tosa_CeilOp $arg)>; +def ConvertTFLFloorOp : Pat<(TFL_FloorOp $arg), (Tosa_FloorOp $arg)>; +def ConvertTFLLogicalNotOp : Pat<(TFL_LogicalNotOp $arg), (Tosa_LogicalNotOp $arg)>; + +// Removing the quant.stats op for unquantized models. +def ConvertQuantStatOp : Pat<(quantfork_StatisticsOp $value, $layer_stats, $axis_stats, $axis), + (replaceWithValue $value)>; + +//===----------------------------------------------------------------------===// +// Binary ops patterns. +//===----------------------------------------------------------------------===// + +//===----------------------------------------------------------------------===// +// Ternary ops patterns. +//===----------------------------------------------------------------------===// diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/verify_fully_converted.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/verify_fully_converted.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b84242338165cef0cbd4f9a9484a9856d9faae0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/tosa/transforms/verify_fully_converted.cc @@ -0,0 +1,90 @@ +/* Copyright 2023 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 +#include +#include + +#include "llvm/ADT/StringExtras.h" +#include "llvm/Support/FormatVariadic.h" +#include "mlir/Pass/Pass.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Transforms/DialectConversion.h" // from @llvm-project +#include "tensorflow/compiler/mlir/lite/ir/tfl_ops.h" + +namespace mlir::tosa { + +#define GEN_PASS_DEF_VERIFYFULLYCONVERTED +#include "tensorflow/compiler/mlir/tosa/transforms/passes.h.inc" + +namespace { + +static void emitLegalizationErrors(Location loc, + const DenseSet &illegalOps) { + // Print op errors for each of the illegal ops that still remain. + llvm::MapVector opNameCounts; + for (Operation *illegalOp : illegalOps) { + StringRef opName = illegalOp->getName().getStringRef(); + opNameCounts[opName]++; + illegalOp->emitOpError() << ": illegal op still exists"; + } + + std::vector errorMessages; + errorMessages.reserve(opNameCounts.size()); + for (const auto &opInfo : opNameCounts) { + errorMessages.push_back( + llvm::formatv("\t{0} (count: {1})", opInfo.first, opInfo.second)); + } + emitError(loc) << "The following illegal operations still remain: \n" + << llvm::join(errorMessages, "\n") << "\n"; +} + +LogicalResult verifyAllOperationsAreLegal(Operation *op, + const ConversionTarget &target) { + DenseSet illegalOps; + op->walk([&](Operation *op) { + if (!target.isLegal(op)) { + illegalOps.insert(op); + } + }); + if (illegalOps.empty()) return success(); + emitLegalizationErrors(op->getLoc(), illegalOps); + return failure(); +} + +class VerifyFullyConvertedPass + : public impl::VerifyFullyConvertedBase { + public: + // Validates that no TFLite frontends ops are in the function. + void runOnOperation() override { + // We don't just use applyPartialConversion with no patterns because this + // pass shouldn't alter the IR at all (including via folding or + // canonicalizations that dialect conversion does automatically). + ConversionTarget target(getContext()); + target.markUnknownOpDynamicallyLegal([](Operation *) { return true; }); + target.addIllegalDialect(); + target.addIllegalOp(); + if (failed(verifyAllOperationsAreLegal(getOperation(), target))) + return signalPassFailure(); + } +}; + +} // anonymous namespace + +std::unique_ptr> createVerifyFullyConvertedPass() { + return std::make_unique(); +} + +} // namespace mlir::tosa diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..4a623dafdec517c11c7af1c37a9e6ac4af452724 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/BUILD @@ -0,0 +1,76 @@ +# Description: +# Tensorflow / MLIR utils. + +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//visibility:public"], + licenses = ["notice"], +) + +cc_library( + name = "name_utils", + srcs = ["name_utils.cc"], + hdrs = ["name_utils.h"], + deps = [ + "@llvm-project//llvm:Support", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Support", + ], +) + +cc_library( + name = "string_container_utils", + hdrs = ["string_container_utils.h"], + deps = [ + "@com_google_absl//absl/strings", + "@llvm-project//llvm:Support", + ], +) + +cc_library( + name = "array_container_utils", + hdrs = ["array_container_utils.h"], + deps = [ + "@com_google_absl//absl/types:span", + "@llvm-project//llvm:Support", + ], +) + +cc_library( + name = "saved_model_converter_utils", + srcs = ["saved_model_converter_utils.cc"], + hdrs = ["saved_model_converter_utils.h"], + visibility = [ + "//tensorflow/cc/experimental/tfa:__subpackages__", + ], + deps = [ + "//tensorflow/cc/saved_model:loader", + "//tensorflow/compiler/mlir/tensorflow:mlir_import_options", + "//tensorflow/compiler/mlir/tensorflow:translate_lib", + "//tensorflow/compiler/mlir/tf2xla/api/v2:mlir_roundtrip_flags", + "//tensorflow/core/framework:op", + "//tensorflow/core/framework:op_def_builder", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:span", + "@llvm-project//mlir:IR", + ], +) + +cc_library( + name = "validators", + srcs = [ + "validators.cc", + ], + hdrs = [ + "validators.h", + ], + deps = [ + "@llvm-project//mlir:Dialect", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Support", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/array_container_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/array_container_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..dd2fbb22a6ad34f1362ea280103c41bfb8b69c75 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/array_container_utils.h @@ -0,0 +1,46 @@ +/* Copyright 2020 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_MLIR_UTILS_ARRAY_CONTAINER_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_UTILS_ARRAY_CONTAINER_UTILS_H_ + +#include "absl/types/span.h" +#include "llvm/ADT/ArrayRef.h" + +namespace mlir { + +template +inline llvm::ArrayRef SpanToArrayRef(absl::Span span) { + return llvm::ArrayRef(span.data(), span.size()); +} + +template +inline llvm::ArrayRef SpanToArrayRef(absl::Span span) { + return llvm::ArrayRef(span.data(), span.size()); +} + +template +inline llvm::MutableArrayRef SpanToMutableArrayRef(absl::Span span) { + return llvm::MutableArrayRef(span.data(), span.size()); +} + +template +inline absl::Span ArrayRefToSpan(llvm::ArrayRef ref) { + return absl::Span(ref.data(), ref.size()); +} + +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_UTILS_ARRAY_CONTAINER_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/name_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/name_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..12d50e97496de5780533d53988940debbc43a63a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/name_utils.cc @@ -0,0 +1,100 @@ +/* Copyright 2020 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/mlir/utils/name_utils.h" + +#include +#include + +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/ADT/StringExtras.h" +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/Location.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project + +namespace mlir { + +namespace { +// Checks if a character is legal for a TensorFlow node name, with special +// handling if a character is at the beginning. +bool IsLegalChar(char c, bool first_char) { + if (llvm::isAlpha(c)) return true; + if (llvm::isDigit(c)) return true; + if (c == '.') return true; + if (c == '_') return true; + + // First character of a node name can only be a letter, digit, dot or + // underscore. + if (first_char) return false; + + if (c == '/') return true; + if (c == '-') return true; + + return false; +} +} // anonymous namespace + +void LegalizeNodeName(std::string& name) { + if (name.empty()) return; + + if (!IsLegalChar(name[0], /*first_char=*/true)) name[0] = '.'; + + for (char& c : llvm::drop_begin(name, 1)) + if (!IsLegalChar(c, /*first_char=*/false)) c = '.'; +} + +std::string GetNameFromLoc(Location loc) { + llvm::SmallVector loc_names; + llvm::SmallVector locs; + locs.push_back(loc); + bool names_is_nonempty = false; + + while (!locs.empty()) { + Location curr_loc = locs.pop_back_val(); + + if (auto name_loc = mlir::dyn_cast(curr_loc)) { + // Add name in NameLoc. For NameLoc we also account for names due to ops + // in functions where the op's name is first. + auto name = name_loc.getName().strref().split('@').first; + // Skip if the name is for op type. + if (!name.ends_with(":")) { + loc_names.push_back(name); + if (!name.empty()) names_is_nonempty = true; + } + continue; + } else if (auto call_loc = mlir::dyn_cast(curr_loc)) { + // Use location of the Callee to generate the name. + locs.push_back(call_loc.getCallee()); + continue; + } else if (auto fused_loc = mlir::dyn_cast(curr_loc)) { + // Push all locations in FusedLoc in reverse order, so locations are + // visited based on order in FusedLoc. + auto reversed_fused_locs = llvm::reverse(fused_loc.getLocations()); + locs.append(reversed_fused_locs.begin(), reversed_fused_locs.end()); + continue; + } + + // Location is not a supported, so an empty StringRef is added. + loc_names.push_back(llvm::StringRef()); + } + + if (names_is_nonempty) + return llvm::join(loc_names.begin(), loc_names.end(), ";"); + + return ""; +} + +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/name_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/name_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..bdfbe47c827c5a4bab99b128d5f7f2fa0e9a1eb5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/name_utils.h @@ -0,0 +1,34 @@ +/* Copyright 2020 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_MLIR_UTILS_NAME_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_UTILS_NAME_UTILS_H_ + +#include + +#include "mlir/IR/Location.h" // from @llvm-project + +namespace mlir { + +// Converts characters in name that are considered illegal in TensorFlow Node +// name to '.'. +void LegalizeNodeName(std::string& name); + +// Returns the TensorFlow node name associated with a location. +std::string GetNameFromLoc(Location loc); + +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_UTILS_NAME_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/saved_model_converter_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/saved_model_converter_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..d4340e801930025fe82fc924d9c9fd9d63ef3b91 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/saved_model_converter_utils.cc @@ -0,0 +1,94 @@ +/* Copyright 2019 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/mlir/utils/saved_model_converter_utils.h" + +#include +#include +#include +#include +#include + +#include "absl/log/log.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_import_options.h" +#include "tensorflow/compiler/mlir/tensorflow/translate/tf_mlir_translate.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_def_builder.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v2/mlir_roundtrip_flags.h" + + +namespace tensorflow { +namespace utils { + +// Util that registers 'extra_tf_opdefs' to the TF global registry. +// Return OK on success, failure if registering failed. +absl::Status RegisterExtraTfOpDefs( + absl::Span extra_tf_opdefs) { + for (const auto& tf_opdefs_string : extra_tf_opdefs) { + OpDef opdef; + // NOLINTNEXTLINE: Use tsl::protobuf to be compatible with OSS. + if (!tsl::protobuf::TextFormat::ParseFromString(tf_opdefs_string, &opdef)) { + LOG(ERROR) << "OpDef parsing failed for: " << tf_opdefs_string; + return absl::InvalidArgumentError("fail to parse extra OpDef"); + } + // Register extra opdefs. + // TODO: b/133770952 - Support shape functions. + OpRegistry::Global()->Register( + [opdef](OpRegistrationData* op_reg_data) -> absl::Status { + *op_reg_data = OpRegistrationData(opdef); + return absl::OkStatus(); + }); + } + return absl::OkStatus(); +} + +absl::StatusOr> ImportSavedModel( + const std::string& input_filename, const int saved_model_version, + const std::unordered_set& tags, + absl::Span extra_tf_opdefs, + absl::Span exported_names, const GraphImportConfig& specs, + bool enable_variable_lifting, mlir::MLIRContext* context, + std::unique_ptr* saved_model_bundle) { + // Register extra TF ops passed as OpDef. + auto extra_opdefs_status = RegisterExtraTfOpDefs(extra_tf_opdefs); + if (!extra_opdefs_status.ok()) return extra_opdefs_status; + + if (saved_model_version == 2) { + auto module_or = SavedModelObjectGraphToMlirImport( + input_filename, tags, exported_names, context, + /*unconditionally_use_set_output_shapes=*/true); + if (!module_or.status().ok()) return module_or.status(); + return std::move(module_or).value(); + } else if (saved_model_version == 1) { + MLIRImportOptions options; + options.upgrade_legacy = specs.upgrade_legacy; + options.unconditionally_use_set_output_shapes = true; + options.lift_variables = enable_variable_lifting; + auto module_or = SavedModelSignatureDefsToMlirImport( + input_filename, tags, exported_names, context, options, + saved_model_bundle); + + if (!module_or.status().ok()) return module_or.status(); + return std::move(module_or).value(); + } else { + return absl::InvalidArgumentError("Should be either saved model v1 or v2."); + } +} + +} // namespace utils +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/saved_model_converter_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/saved_model_converter_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..26ed46741f9e8ecd3357877ed41f4bb0ea248b5e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/saved_model_converter_utils.h @@ -0,0 +1,46 @@ +/* Copyright 2019 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_MLIR_UTILS_SAVED_MODEL_CONVERTER_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_UTILS_SAVED_MODEL_CONVERTER_UTILS_H_ + +#include +#include +#include + +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "tensorflow/cc/saved_model/loader.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v2/mlir_roundtrip_flags.h" + +namespace tensorflow { +namespace utils { + +// 'saved_model_bundle' will be initialized if V1 model was loaded. +absl::StatusOr> ImportSavedModel( + const std::string& input_filename, int saved_model_version, + const std::unordered_set& tags, + absl::Span extra_tf_opdefs, + absl::Span exported_names, const GraphImportConfig& specs, + bool enable_variable_lifting, mlir::MLIRContext* context, + std::unique_ptr* saved_model_bundle); + +} // namespace utils +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_MLIR_UTILS_SAVED_MODEL_CONVERTER_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/string_container_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/string_container_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..ebcd732fe1441a02ed5cafe81b12111468228779 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/string_container_utils.h @@ -0,0 +1,34 @@ +/* Copyright 2020 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_MLIR_UTILS_STRING_CONTAINER_UTILS_H_ +#define TENSORFLOW_COMPILER_MLIR_UTILS_STRING_CONTAINER_UTILS_H_ + +#include "absl/strings/string_view.h" +#include "llvm/ADT/StringRef.h" + +namespace mlir { + +inline absl::string_view StringRefToView(llvm::StringRef ref) { + return absl::string_view(ref.data(), ref.size()); +} + +inline llvm::StringRef StringViewToRef(absl::string_view view) { + return llvm::StringRef(view.data(), view.size()); +} + +} // namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_UTILS_STRING_CONTAINER_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/validators.cc b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/validators.cc new file mode 100644 index 0000000000000000000000000000000000000000..9be53d705e2fdbbf26a3b862a328f0e687ce7ed1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/validators.cc @@ -0,0 +1,147 @@ +/* Copyright 2019 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/mlir/utils/validators.h" + +#include +#include + +#include "mlir/Dialect/Traits.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributeInterfaces.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project + +namespace mlir { +namespace TF { + +// Returns true if the given `op` +// * has an attribute with the given `name`, +// * and the attribute is an integer list of the form [1, X, Y, 1], +// and writes X, Y as 32-bit integer attribute to `x`, `y`. +bool TFIntListIs1XY1(Operation *op, StringRef name, IntegerAttr *x, + IntegerAttr *y) { + auto attr = op->getAttrOfType(name); + if (!attr) return false; + + auto elements = attr.getValue(); + if (elements.size() != 4 || + std::any_of(elements.begin(), elements.end(), + [](Attribute e) { return !mlir::isa(e); })) + return false; + + if (mlir::cast(elements.front()).getInt() != 1 || + mlir::cast(elements.back()).getInt() != 1) + return false; + + Builder b(op->getContext()); + *x = b.getI32IntegerAttr(mlir::cast(elements[1]).getInt()); + *y = b.getI32IntegerAttr(mlir::cast(elements[2]).getInt()); + + return true; +} + +// Returns true if the attribute is an integer list of the form [1, X, Y, 1]. +bool TFIntListIs1XY1(const Attribute attr) { + const auto &elements = mlir::cast(attr).getValue(); + if (elements.size() != 4 || + std::any_of(elements.begin(), elements.end(), + [](Attribute e) { return !mlir::isa(e); })) + return false; + + if (mlir::cast(elements.front()).getValue() != 1 || + mlir::cast(elements.back()).getValue() != 1) + return false; + return true; +} + +// Returns true if the attribute is an integer list of the form [1, 1, X, Y]. +bool TFIntListIs11XY(const Attribute attr) { + const auto &elements = mlir::cast(attr).getValue(); + if (elements.size() != 4 || + std::any_of(elements.begin(), elements.end(), + [](Attribute e) { return !mlir::isa(e); })) + return false; + + const Attribute *data = elements.data(); + if (mlir::cast(data[0]).getValue() != 1 || + mlir::cast(data[1]).getValue() != 1) + return false; + return true; +} + +// Returns true if the given `op` +// * has an attribute with the given `name`, +// * and the attribute is an integer list of the form [1, X, Y, Z, 1], +// and writes X, Y as 32-bit integer attribute to `x`, `y`, z. +bool TFIntListIs1XYZ1(Operation *op, StringRef name, IntegerAttr *x, + IntegerAttr *y, IntegerAttr *z) { + auto attr = op->getAttrOfType(name); + if (!attr) return false; + + auto elements = attr.getValue(); + if (elements.size() != 5 || + std::any_of(elements.begin(), elements.end(), + [](Attribute e) { return !mlir::isa(e); })) + return false; + + if (mlir::cast(elements.front()).getInt() != 1 || + mlir::cast(elements.back()).getInt() != 1) + return false; + + Builder b(op->getContext()); + *x = b.getI32IntegerAttr(mlir::cast(elements[1]).getInt()); + *y = b.getI32IntegerAttr(mlir::cast(elements[2]).getInt()); + *z = b.getI32IntegerAttr(mlir::cast(elements[3]).getInt()); + + return true; +} + +// Returns true if every element of the attribute is 1. All elements of `attr` +// must be `IntegerAttr`. +bool TFIntListIsAllOnes(const Attribute attr) { + const auto &elements = mlir::cast(attr).getValue(); + + return !std::any_of(elements.begin(), elements.end(), [](Attribute e) { + return mlir::cast(e).getValue() != 1; + }); +} + +bool IsBroadcastableElementsAttrs(mlir::TypedAttr a, mlir::TypedAttr b) { + // This would return false if we had unranked tensors (where they should + // probably be considered as broadcastable), but given we are working with + // attributes here that shouldn't be an issue, + return OpTrait::util::getBroadcastedType(a.getType(), b.getType()) != Type(); +} + +bool IsDimensionsDegenerateExceptLastOne(ArrayRef elements_shape) { + if (elements_shape.empty()) return true; + + for (auto dim : elements_shape.drop_back(1)) { + if (dim != 1) return false; + } + return true; +} + +bool IsDimensionsDegenerateExceptLastOne(TypedAttr val) { + if (auto ranked_type = mlir::dyn_cast(val.getType())) { + return IsDimensionsDegenerateExceptLastOne(ranked_type.getShape()); + } + return false; +} + +} // namespace TF +} // namespace mlir diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/validators.h b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/validators.h new file mode 100644 index 0000000000000000000000000000000000000000..1f68d25e2dd7249ffc8f81b9f1fb40b7830037f4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/mlir/utils/validators.h @@ -0,0 +1,126 @@ +/* Copyright 2019 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. +==============================================================================*/ + +// This header file defines common validators used by TFLite transformation +// passes to validate op attributes or values. + +#ifndef TENSORFLOW_COMPILER_MLIR_UTILS_VALIDATORS_H_ +#define TENSORFLOW_COMPILER_MLIR_UTILS_VALIDATORS_H_ + +#include + +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributeInterfaces.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/Operation.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project + +namespace mlir { +namespace TF { + +// TODO(jpienaar): Change these to being one of these variants and/or generate +// these predicates. + +// Returns true if the given TensorFlow op does not have a `data_format` +// attribute (then default to "NHWC"), or its `data_format` attribute is "NHWC". +inline bool TFDataFormatIsNHWC(Operation *op) { + auto attr = op->getAttrOfType("data_format"); + return !attr || attr.getValue() == "NHWC"; +} + +// Returns true if the given TensorFlow op does not have a `data_format` +// attribute (then default to "NDHWC"), or its `data_format` attribute is +// "NDHWC". +inline bool TFDataFormatIsNDHWC(Operation *op) { + auto attr = op->getAttrOfType("data_format"); + return !attr || attr.getValue() == "NDHWC"; +} + +// Returns true if the given `op` +// * has an attribute with the given `name`, +// * and the attribute is an integer list of the form [1, X, Y, 1], +// and writes X, Y as 32-bit integer attribute to `x`, `y`. +bool TFIntListIs1XY1(Operation *op, StringRef name, IntegerAttr *x, + IntegerAttr *y); + +// Returns true if the attribute is an integer list of the form [1, X, Y, 1]. +bool TFIntListIs1XY1(Attribute attr); + +// Returns true if the attribute is an integer list of the form [1, 1, X, Y]. +bool TFIntListIs11XY(Attribute attr); + +// Returns true if the given `op` +// * has an attribute with the given `name`, +// * and the attribute is an integer list of the form [1, X, Y, Z, 1], +// and writes X, Y as 32-bit integer attribute to `x`, `y`, z. +bool TFIntListIs1XYZ1(Operation *op, StringRef name, IntegerAttr *x, + IntegerAttr *y, IntegerAttr *z); + +// Returns true if every element of the attribute is 1. All elements of `attr` +// must be `IntegerAttr`. +bool TFIntListIsAllOnes(Attribute attr); + +// Returns true iff the given value is a float32 tensor. +// is "DT_FLOAT". +inline bool TFTypeIsFloat32Tensor(Value value) { + auto tensorType = mlir::dyn_cast(value.getType()); + if (!tensorType) return false; + return tensorType.getElementType().isF32(); +} + +// Returns true iff the given value is a bf16 tensor. +inline bool TFTypeIsBFloat16Tensor(Value value) { + auto tensorType = mlir::dyn_cast(value.getType()); + if (!tensorType) return false; + return tensorType.getElementType().isBF16(); +} + +// Returns true iff the given value is a f16 tensor. +inline bool TFTypeIsHalfTensor(Value value) { + auto tensorType = mlir::dyn_cast(value.getType()); + if (!tensorType) return false; + return tensorType.getElementType().isF16(); +} + +// Returns true iff the given value is a f16 or bf16 tensor. +inline bool TFTypeIsBFloat16OrHalfTensor(Value value) { + return TFTypeIsBFloat16Tensor(value) || TFTypeIsHalfTensor(value); +} + +// Returns true iff the given TensorFlow op has a `padding` attribute whose +// value is "SAME" or "VALID", and writes the attribute to `padding`. +inline bool TFPaddingIsSameOrValid(Operation *op, StringAttr *padding) { + auto padding_attr = op->getAttrOfType("padding"); + if (padding_attr.getValue() != "SAME" && padding_attr.getValue() != "VALID") + return false; + *padding = padding_attr; + return true; +} + +/// Returns whether the given `a` and `b` have broadcast-compatible +/// types. +bool IsBroadcastableElementsAttrs(mlir::TypedAttr a, mlir::TypedAttr b); +// Returns true if every dimension of the attribute is 1 except the last one. +bool IsDimensionsDegenerateExceptLastOne(mlir::TypedAttr val); +// Returns true if every element is 1 except the last one. +bool IsDimensionsDegenerateExceptLastOne(ArrayRef elements_shape); + +} // end namespace TF +} // end namespace mlir + +#endif // TENSORFLOW_COMPILER_MLIR_UTILS_VALIDATORS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/plugin/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/plugin/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..c94925f8c0277ac2c7d6e7f3adc22a74d1fa803b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/plugin/BUILD @@ -0,0 +1,53 @@ +# 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. +# ============================================================================== + +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +"""Configuration file for an XLA plugin. + + please don't check in changes to this file. to prevent changes appearing + in git status, use: + + git update-index --assume-unchanged tensorflow/compiler/plugin/BUILD + + To add additional devices to the XLA subsystem, add targets to the + dependency list in the 'plugin' target. For instance: + + deps = ["//tensorflow/compiler/plugin/example:plugin_lib"], + + ** Please don't remove this file - it is supporting some 3rd party plugins ** +""" + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//visibility:public"], + licenses = ["notice"], +) + +cc_library( + name = "plugin", + deps = [ + #"//tensorflow/compiler/plugin/example:example_lib", + ], +) + +# This target is added purely for the purpose of ensuring that `:xla_device` is +# always publicly visible to external XLA backend/plugin developers. +cc_library( + name = "plugin_device", + deps = [ + "//tensorflow/compiler/jit:xla_device", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/plugin/README.md b/western_ai/usa/tensorflow/tensorflow/compiler/plugin/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b1aad8194a5157db43a877e918397130b94cb5c0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/plugin/README.md @@ -0,0 +1,12 @@ +## 3rd party XLA devices + +This directory is intended as a place for 3rd party XLA devices which are _not_ +integrated into the public repository. + +By adding entries to the BUILD target in this directory, a third party device +can be included as a dependency of the JIT subsystem. + +For integration into the unit test system, see the files: + +- tensorflow/compiler/tests/plugin.bzl +- tensorflow/compiler/xla/tests/plugin.bzl diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tests/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..54efbf42d19f93726e43b25a533b102c7f9af663 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/BUILD @@ -0,0 +1,3020 @@ +load("@xla//third_party/rules_python/python:py_library.bzl", "py_library") +load("//tensorflow:tensorflow.bzl", "py_test") +load("//tensorflow:tensorflow.default.bzl", "cuda_py_strict_test", "tf_cuda_cc_test") +load("//tensorflow/compiler/aot:tfcompile.bzl", "tf_library") +load("//tensorflow/compiler/tests:build_combined_defs.bzl", "tf_xla_combined_py_test") +load( + "//tensorflow/compiler/tests:build_defs.bzl", + "generate_backend_suites", + "tf_xla_py_strict_test", + # copybara:uncomment_begin(google-only) + # "tpu_backends", + # copybara:uncomment_end +) +load( + "//tensorflow/core/platform:build_config_root.bzl", + "tf_cuda_tests_tags", +) +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") +load("//tensorflow/python/tpu:tpu.bzl", "tpu_py_strict_test") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [":internal"], + licenses = ["notice"], +) + +package_group( + name = "internal", + includes = [ + "//tensorflow/compiler/tf2xla:internal", + ], +) + +package_group( + name = "friends", + includes = [ + "//tensorflow/compiler/tf2xla:friends", + ], + packages = [ + # To pass open source testing in the pip Kokoros. + "//platforms/xla/tests/neural_nets", + ], +) + +generate_backend_suites() + +py_library( + name = "xla_test", + testonly = 1, + srcs = ["xla_test.py"], + visibility = [":friends"], + deps = [ + "//tensorflow/core:protos_all_py", + "//tensorflow/python/client:session", + "//tensorflow/python/compiler/xla:compiler_py", + "//tensorflow/python/eager:context", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:random_seed", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:flags", + "//tensorflow/python/platform:tf_logging", + "//tensorflow/python/tpu:tpu_py", + "//third_party/py/numpy", + ], +) + +py_library( + name = "test_utils", + testonly = 1, + srcs = [ + "__init__.py", + "test_utils.py", + ], + strict_deps = True, + deps = [ + "//third_party/py/numpy", + "@six_archive//:six", + ], +) + +py_test( + name = "xla_test_test", + size = "small", + srcs = ["xla_test_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/platform:client_testlib", + ], +) + +#LINT.IfChange(combined_tests) +# If you add a new tf_xla_py_strict_test please either add the test file to one of the combined test +# targets that matches in all tags and other settings or add a new combined test target. + +tf_xla_combined_py_test( + name = "combined_ops_test_a", + size = "medium", + timeout = "long", + package = "tensorflow.compiler.tests", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + tests = [ + # go/keep-sorted start + ":adadelta_test_lib", + ":adagrad_test_lib", + ":bincount_op_test_lib", + ":bucketize_op_test_lib", + ":clustering_test_lib", + ":const_arg_test_lib", + ":conv2d_test_lib", + ":conv3d_test_lib", + ":data_format_ops_test_lib", + ":dynamic_slice_ops_test_lib", + ":dynamic_stitch_test_lib", + # go/keep-sorted end + ], +) + +tf_xla_combined_py_test( + name = "combined_ops_test_b", + size = "medium", + timeout = "long", + package = "tensorflow.compiler.tests", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + tests = [ + # go/keep-sorted start + ":extract_image_patches_op_test_lib", + ":fake_quant_ops_test_lib", + ":fifo_queue_test_lib", + ":ftrl_test_lib", + ":function_test_lib", + ":fused_batchnorm_test_lib", + ":gather_nd_op_test_lib", + ":lrn_ops_test_lib", + ":manip_ops_test_lib", + # go/keep-sorted end + ], +) + +tf_xla_combined_py_test( + name = "combined_ops_test_c", + size = "medium", + timeout = "long", + package = "tensorflow.compiler.tests", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + tests = [ + # go/keep-sorted start + ":matrix_inverse_op_test_lib", + ":matrix_solve_op_test_lib", + ":momentum_test_lib", + ":nary_ops_test_lib", + ":nullary_ops_test_lib", + ":placeholder_test_lib", + ":pooling_ops_3d_test_lib", + ":pooling_ops_test_lib", + ":proximal_adagrad_test_lib", + ":proximal_gradient_descent_test_lib", + # go/keep-sorted end + ], +) + +tf_xla_combined_py_test( + name = "combined_ops_test_d", + size = "medium", + timeout = "long", + package = "tensorflow.compiler.tests", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + tests = [ + # go/keep-sorted start + ":quantized_ops_test_lib", + ":random_ops_test_lib", + ":reduce_ops_test_lib", + ":reduce_window_test_lib", + ":reverse_ops_test_lib", + ":rmsprop_test_lib", + ":searchsorted_op_test_lib", + ":spacetobatch_op_test_lib", + ":sparse_to_dense_op_test_lib", + # go/keep-sorted end + ], +) + +tf_xla_combined_py_test( + name = "combined_ops_test_e", + size = "medium", + timeout = "long", + exec_properties = { + "cpp_link.mem": "16g", + }, + package = "tensorflow.compiler.tests", + tags = [ + "no_cuda_asan", # times out in individual tests + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "noasan", # times out consistently from 2023-08-24 + ], + tests = [ + # go/keep-sorted start + ":adagrad_da_test_lib", + ":adam_test_lib", + ":argminmax_test_lib", + ":listdiff_op_test_lib", + ":slice_ops_test_lib", + ":unary_ops_test_lib", + # go/keep-sorted end + ], +) + +tf_xla_combined_py_test( + name = "combined_ops_test_f", + size = "medium", + timeout = "long", + # copybara:uncomment_begin(google-only) + # disabled_backends = tpu_backends(), + # copybara:uncomment_end + exec_properties = { + "cpp_link.mem": "16g", + }, + package = "tensorflow.compiler.tests", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + tests = [ + # go/keep-sorted start + ":add_n_test_lib", + ":cond_test_lib", + ":float_ops_test_lib", + ":while_test_lib", + # go/keep-sorted end + ], +) + +tf_xla_combined_py_test( + name = "combined_ops_test_g", + size = "medium", + timeout = "long", + exec_properties = { + "cpp_link.mem": "16g", + }, + package = "tensorflow.compiler.tests", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + tests = [ + # go/keep-sorted start + ":cast_test_lib", + # go/keep-sorted end + ], +) +#LINT.ThenChange(:individual_tests) + +#LINT.IfChange(individual_tests) +tf_xla_py_strict_test( + name = "adadelta_test", + size = "medium", + srcs = ["adadelta_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:adadelta", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "adagrad_test", + size = "small", + srcs = ["adagrad_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:adagrad", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "adagrad_da_test", + size = "small", + srcs = ["adagrad_da_test.py"], + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:adagrad_da", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "adam_test", + size = "small", + srcs = ["adam_test.py"], + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variable_scope", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:adam", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "add_n_test", + size = "small", + srcs = ["add_n_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:list_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "argminmax_test", + size = "small", + srcs = ["argminmax_test.py"], + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "noasan", # times out consistently from 2023-08-24 + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "binary_ops_test", + size = "medium", + srcs = ["binary_ops_test.py"], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", # Times out frequently in fastbuild mode. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_gen", + "//tensorflow/python/ops:bitwise_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:math_ops_gen", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "complex_div_test", + size = "medium", + srcs = ["complex_div_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", # Times out frequently in fastbuild mode. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "bucketize_op_test", + size = "small", + srcs = ["bucketize_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "categorical_op_test", + size = "small", + srcs = ["categorical_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:random_seed", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/ops:stateless_random_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "cholesky_op_test", + size = "medium", + srcs = ["cholesky_op_test.py"], + disabled_backends = ["gpu_h100"], # TODO: b/362907482 - Re-enable after fixing. + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "no_rocm", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "cond_test", + size = "small", + srcs = ["cond_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/client:session", + "//tensorflow/python/compiler/xla", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:cond", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/ops:control_flow_switch_case", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/ops:tensor_array_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "self_adjoint_eig_op_test", + size = "medium", + srcs = ["self_adjoint_eig_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "searchsorted_op_test", + size = "small", + timeout = "moderate", + srcs = ["searchsorted_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "svd_op_test", + size = "medium", + srcs = ["svd_op_test.py"], + disabled_backends = [ + # TODO(b/129396575): Fails on CPU. + "cpu", + "cpu_ondemand", + ], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "no_rocm", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:tensor_shape", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/ops:linalg_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "matrix_inverse_op_test", + size = "small", + timeout = "moderate", + srcs = ["matrix_inverse_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "matrix_solve_op_test", + size = "small", + timeout = "moderate", + srcs = ["matrix_solve_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/platform:sysconfig", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "matrix_triangular_solve_op_test", + size = "small", + timeout = "moderate", + srcs = ["matrix_triangular_solve_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "clustering_test", + size = "small", + srcs = ["clustering_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "concat_ops_test", + size = "medium", + srcs = ["concat_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "noasan", # Timed out on 2023-07-12 + ], + deps = [ + ":xla_test", + "//tensorflow/python:pywrap_sanitizers", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_gen", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/ops:gradients_impl", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "conv2d_test", + size = "medium", + srcs = ["conv2d_test.py"], + shard_count = 10, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":test_utils", + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "tensor_float_32_test", + size = "medium", + srcs = ["tensor_float_32_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/platform:sysconfig", + "//tensorflow/python/platform:test", + ], +) + +tf_xla_py_strict_test( + name = "conv3d_test", + size = "medium", + srcs = ["conv3d_test.py"], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":test_utils", + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:gradient_checker", + "//tensorflow/python/ops:nn_grad", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "depthwise_conv_op_test", + size = "medium", + srcs = ["depthwise_conv_op_test.py"], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "no_rocm", + "optonly", # Times out frequently in fastbuild mode. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn_grad", + "//tensorflow/python/ops:nn_impl", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "dynamic_slice_ops_test", + size = "small", + srcs = ["dynamic_slice_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "einsum_op_test", + size = "medium", + srcs = ["einsum_op_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:special_math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "reshape_op_test", + size = "small", + srcs = ["reshape_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:test", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "dynamic_stitch_test", + size = "small", + srcs = ["dynamic_stitch_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:data_flow_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "extract_image_patches_op_test", + size = "small", + srcs = ["extract_image_patches_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "eager_test", + size = "medium", + srcs = ["eager_test.py"], + tags = [ + "multi_and_single_gpu", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/core:protos_all_py", + "//tensorflow/python/eager:backprop", + "//tensorflow/python/eager:context", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:indexed_slices", + "//tensorflow/python/framework:ops", + "//tensorflow/python/layers", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/ops:cond", + "//tensorflow/python/ops:embedding_ops", + "//tensorflow/python/ops:functional_ops", + "//tensorflow/python/ops:init_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:random_ops_gen", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:while_loop", + "//tensorflow/python/platform:test", + "//tensorflow/python/training:adam", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "fifo_queue_test", + size = "medium", + srcs = ["fifo_queue_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python:extra_py_tests_deps", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:data_flow_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "fft_test", + size = "medium", + srcs = ["fft_test.py"], + shard_count = 12, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "no_rocm", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python:extra_py_tests_deps", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:gradients_impl", + "//tensorflow/python/ops/signal", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "slice_ops_test", + size = "medium", + srcs = ["slice_ops_test.py"], + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:tensor_shape", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + ], +) + +tf_xla_py_strict_test( + name = "ftrl_test", + size = "medium", + srcs = ["ftrl_test.py"], + shard_count = 8, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:adagrad", + "//tensorflow/python/training:ftrl", + "//tensorflow/python/training:gradient_descent", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "ftrl_ops_test", + size = "medium", + srcs = ["ftrl_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:training_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "function_test", + size = "small", + srcs = ["function_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:function", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "image_ops_test", + size = "small", + timeout = "long", + srcs = ["image_ops_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + shard_count = 10, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", # Times out frequently in fastbuild mode. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/ops:image_ops", + "//tensorflow/python/ops:image_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "listdiff_op_test", + size = "small", + srcs = ["listdiff_op_test.py"], + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:for_generated_wrappers", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "lrn_ops_test", + size = "medium", + srcs = ["lrn_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "manip_ops_test", + size = "small", + srcs = ["manip_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:manip_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "matrix_band_part_test", + size = "medium", + timeout = "long", + srcs = ["matrix_band_part_test.py"], + tags = [ + "no_aarch64", # TODO(b/315533266) + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "matrix_diag_ops_test", + size = "medium", + timeout = "long", + srcs = ["matrix_diag_ops_test.py"], + shard_count = 4, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "momentum_test", + size = "small", + srcs = ["momentum_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:momentum", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "nary_ops_test", + size = "small", + srcs = ["nary_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "nullary_ops_test", + size = "small", + srcs = ["nullary_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "pooling_ops_test", + size = "medium", + srcs = ["pooling_ops_test.py"], + shard_count = 20, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:tensor", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "pooling_ops_3d_test", + size = "medium", + srcs = ["pooling_ops_3d_test.py"], + shard_count = 20, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "proximal_adagrad_test", + size = "medium", + srcs = ["proximal_adagrad_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:adagrad", + "//tensorflow/python/training:proximal_adagrad", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "proximal_gradient_descent_test", + size = "medium", + srcs = ["proximal_gradient_descent_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:gradient_descent", + "//tensorflow/python/training:proximal_gradient_descent", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "qr_op_test", + size = "medium", + srcs = ["qr_op_test.py"], + disabled_backends = [ + # Test is very slow on CPU. + "cpu", + "cpu_ondemand", + ], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "nozapfhahn", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:linalg_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "unstack_test", + size = "medium", + srcs = ["unstack_test.py"], + disabled_backends = [ + # TODO(b/149750262): timeout on CPU. + "cpu", + "cpu_ondemand", + ], + shard_count = 1, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "random_ops_test", + size = "medium", + srcs = ["random_ops_test.py"], + shard_count = 10, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/ops/distributions:special_math", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "reduce_ops_test", + size = "medium", + srcs = ["reduce_ops_test.py"], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "reduce_window_test", + size = "small", + srcs = ["reduce_window_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:function", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "reverse_ops_test", + size = "medium", + srcs = ["reverse_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "reverse_sequence_op_test", + size = "medium", + srcs = ["reverse_sequence_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +# copybara:uncomment_begin(google-only) +# tf_xla_py_strict_test( +# name = "reverse_sequence_op_args_test", +# size = "medium", +# srcs = ["reverse_sequence_op_args_test.py"], +# main = "reverse_sequence_op_args_test.py", +# tags = [ +# "no_pip", +# "optonly", +# ], +# deps = [ +# ":xla_test", +# "//tensorflow/compiler/jit:xla_cpu_jit", # DisableOnExport +# "//tensorflow/python/compat:v2_compat", +# "//tensorflow/python/eager:def_function", +# "//tensorflow/python/framework:errors", +# "//tensorflow/python/ops:array_ops", +# "//tensorflow/python/platform:client_testlib", +# ], +# ) +# copybara:uncomment_end + +tf_xla_py_strict_test( + name = "rmsprop_test", + size = "small", + srcs = ["rmsprop_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/training:rmsprop", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "scan_ops_test", + size = "medium", + timeout = "long", + srcs = ["scan_ops_test.py"], + shard_count = 6, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "nozapfhahn", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "segment_reduction_ops_test", + size = "medium", + srcs = ["segment_reduction_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/client:device_lib", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "spacetobatch_op_test", + size = "medium", + srcs = ["spacetobatch_op_test.py"], + shard_count = 3, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "sparse_to_dense_op_test", + size = "medium", + srcs = ["sparse_to_dense_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:sparse_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "stack_ops_test", + size = "small", + srcs = ["stack_ops_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "config-cuda-only", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, + deps = [ + ":xla_test", + "//tensorflow/python/compiler/xla", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:data_flow_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "stateful_random_ops_test", + size = "medium", + srcs = ["stateful_random_ops_test.py"], + disabled_backends = [ + "gpu", + "gpu_a100", + "gpu_h100", + ], + shard_count = 10, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/client", + "//tensorflow/python/client:device_lib", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/kernel_tests/random:util", + "//tensorflow/python/ops:random_ops_util", + "//tensorflow/python/ops:stateful_random_ops", + "//tensorflow/python/ops:stateful_random_ops_gen", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:flags", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "stateless_random_ops_test", + size = "medium", + srcs = ["stateless_random_ops_test.py"], + disabled_backends = [ + "gpu", + "gpu_a100", + "gpu_h100", + ], + shard_count = 10, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "nozapfhahn", # Times out under coverage + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/client:device_lib", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/kernel_tests/random:util", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:random_ops_util", + "//tensorflow/python/ops:stateless_random_ops", + "//tensorflow/python/ops:stateless_random_ops_v2_gen", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "stochastic_cast_op_test", + size = "medium", + srcs = ["stochastic_cast_op_test.py"], + # TODO(b/232442915): Enable GPUs. + disabled_backends = [ + "gpu", + "gpu_a100", + "gpu_h100", + ], + shard_count = 20, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/kernel_tests/random:util", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:standard_ops", + "//tensorflow/python/ops:stateless_random_ops", + "//tensorflow/python/ops:stochastic_cast_op", + "//tensorflow/python/ops:tensor_array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "tensor_array_ops_test", + size = "medium", + srcs = ["tensor_array_ops_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "config-cuda-only", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "v1only", + ], + use_xla_device = False, + deps = [ + ":xla_test", + "//tensorflow/python/compiler/xla", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_util", + "//tensorflow/python/ops:data_flow_ops_gen", + "//tensorflow/python/ops:gradients_impl", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:tensor_array_grad", + "//tensorflow/python/ops:tensor_array_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "tensor_list_ops_test", + size = "small", + srcs = ["tensor_list_ops_test.py"], + # TensorList ops are only implemented on CPU. + enabled_backends = ["cpu"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:list_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "ternary_ops_test", + size = "medium", + srcs = ["ternary_ops_test.py"], + shard_count = 4, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python:extra_py_tests_deps", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:math_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "unary_ops_test", + size = "medium", + srcs = ["unary_ops_test.py"], + shard_count = 20, + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "noasan", #times out + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/ops:bitwise_ops", + "//tensorflow/python/ops:functional_ops_gen", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@six_archive//:six", + ], +) + +tf_xla_py_strict_test( + name = "float_ops_test", + size = "medium", + srcs = ["float_ops_test.py"], + tags = [ + "no_cuda_asan", # times out + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "noasan", #times out + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "cast_test", + size = "medium", + srcs = ["cast_test.py"], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "fused_batchnorm_test", + size = "medium", + srcs = ["fused_batchnorm_test.py"], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":test_utils", + ":xla_test", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:gradient_checker", + "//tensorflow/python/ops:nn", + "//tensorflow/python/ops:nn_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "variable_ops_test", + size = "small", + timeout = "moderate", + srcs = ["variable_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:init_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:state_ops", + "//tensorflow/python/ops:state_ops_gen", + "//tensorflow/python/ops:variable_scope", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:test", + "//tensorflow/python/training:gradient_descent", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "while_test", + size = "small", + srcs = ["while_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/ops:gradients_impl", + "//tensorflow/python/ops:map_fn", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:while_loop", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "case_test", + size = "small", + srcs = ["case_test.py"], + disabled_backends = ["cpu_ondemand"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_switch_case", + "//tensorflow/python/ops:image_ops", + "//tensorflow/python/ops:io_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "cast_ops_test", + size = "small", + srcs = ["cast_ops_test.py"], + disabled_backends = ["cpu_ondemand"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/ops:image_ops", + "//tensorflow/python/ops:io_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "gather_test", + size = "medium", + srcs = ["gather_test.py"], + tags = [ + "no_pip", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:flags", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "gather_nd_op_test", + size = "medium", + srcs = ["gather_nd_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "scatter_nd_op_test", + size = "medium", + srcs = ["scatter_nd_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "sort_ops_test", + size = "medium", + srcs = ["sort_ops_test.py"], + shard_count = 50, + # Times out in fastbuild mode. + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "nozapfhahn", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:tensor", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:sort_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "data_format_ops_test", + size = "small", + srcs = ["data_format_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "xla_device_test", + size = "medium", + srcs = ["xla_device_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "fake_quant_ops_test", + size = "medium", + srcs = ["fake_quant_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "placeholder_test", + size = "small", + srcs = ["placeholder_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:test", + ], +) + +tf_xla_py_strict_test( + name = "quantized_ops_test", + size = "medium", + srcs = ["quantized_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:bitwise_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "xla_ops_test", + size = "medium", + srcs = ["xla_ops_test.py"], + disabled_backends = [ + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/ops:gen_xla_ops", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:tensor_shape", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/ops:random_ops_util", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + "@xla//xla:xla_data_proto_py", + ], +) + +tf_xla_py_strict_test( + name = "xla_custom_call_ops_test", + size = "small", + srcs = ["xla_custom_call_ops_test.py"], + disabled_backends = [ + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:tensor_spec", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "runtime_shape_check_test", + size = "small", + srcs = ["runtime_shape_check_test.py"], + disabled_backends = [ + "cpu", + "cpu_ondemand", + ], + tags = [ + "no_pip", + "notap", + ], + use_xla_device = False, + deps = [ + ":xla_test", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "conv_node_name_test", + size = "medium", + srcs = ["conv_node_name_test.py"], + tags = [ + "no_oss", # TODO(b/148108508): Re-enable this test in OSS. + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:ops", + "//tensorflow/python/layers", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "tridiagonal_solve_ops_test", + size = "medium", + srcs = ["tridiagonal_solve_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:gradients", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops/linalg:linalg_impl", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "tridiagonal_matmul_ops_test", + size = "medium", + srcs = ["tridiagonal_matmul_ops_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_stack", + "//tensorflow/python/ops:gradient_checker_v2", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:stateless_random_ops", + "//tensorflow/python/ops/linalg:linalg_impl", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tf_xla_py_strict_test( + name = "special_math_test", + size = "medium", + srcs = ["special_math_test.py"], + shard_count = 5, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python:extra_py_tests_deps", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/ops:gradient_checker_v2", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:math_ops_gen", + "//tensorflow/python/ops:random_ops_gen", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/flags", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "repeat_op_test", + size = "medium", + srcs = ["repeat_op_test.py"], + shard_count = 1, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python:extra_py_tests_deps", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "image_ops_jit_compile_test", + size = "medium", + srcs = ["image_ops_jit_compile_test.py"], + disabled_backends = [ + "cpu_ondemand", + ], + shard_count = 1, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + use_xla_device = False, + deps = [ + ":xla_test", + "//tensorflow/python:extra_py_tests_deps", + "//tensorflow/python/eager:backprop", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:image_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "ensure_shape_op_test", + size = "medium", + srcs = ["ensure_shape_op_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:check_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "where_op_test", + size = "small", + srcs = ["where_op_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "no_pip", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/tpu:tpu_py", + ], +) + +tf_xla_py_strict_test( + name = "where_op_tpu_test", + size = "small", + srcs = ["where_op_test.py"], + disabled_backends = [ + "cpu", + "cpu_ondemand", + "gpu", + "gpu_a100", + "gpu_h100", + ], + main = "where_op_test.py", + tags = [ + "no_pip", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/tpu:tpu_py", + ], +) + +tf_xla_py_strict_test( + name = "const_arg_test", + size = "small", + srcs = ["const_arg_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:test", + ], +) + +tf_xla_py_strict_test( + name = "sharding_util_ops_test", + srcs = ["sharding_util_ops_test.py"], + disabled_backends = [ + "cpu", + "cpu_ondemand", + "gpu", + "gpu_a100", + "gpu_h100", + ], + shard_count = 10, + tags = [ + "notap", + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/client:session", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:tensor", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:resource_variable_ops", + "//tensorflow/python/ops:tpu_ops_gen", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tpu_py_strict_test( + name = "approx_topk_test", + srcs = ["approx_topk_test.py"], + disable_experimental = False, + deps = [ + "//tensorflow/python/eager:backprop", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/eager:test", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:variables", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "xla_call_module_test", + size = "small", + srcs = ["xla_call_module_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/compiler/mlir/stablehlo", + "//tensorflow/compiler/tf2xla/ops:gen_xla_ops", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/core:protos_all_py", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "xla_call_module_no_platform_check_test", + size = "small", + srcs = ["xla_call_module_test.py"], + # cpu_ondemand overrides the TF_XLA_FLAGS + disabled_backends = ["cpu_ondemand"], + env = {"TF_XLA_FLAGS": "--tf_xla_call_module_disabled_checks=platform"}, + main = "xla_call_module_test.py", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/compiler/mlir/stablehlo", + "//tensorflow/compiler/tf2xla/ops:gen_xla_ops", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/core:protos_all_py", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "xla_call_module_no_shape_assertions_check_test", + size = "small", + srcs = ["xla_call_module_test.py"], + disabled_backends = ["cpu_ondemand"], # cpu_ondemand overrides the TF_XLA_FLAGS + env = {"TF_XLA_FLAGS": "--tf_xla_call_module_disabled_checks=shape_assertions"}, + main = "xla_call_module_test.py", + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + use_xla_device = False, # Uses tf.function(jit_compile=True) + deps = [ + ":xla_test", + "//tensorflow/compiler/mlir/stablehlo", + "//tensorflow/compiler/tf2xla/ops:gen_xla_ops", + "//tensorflow/compiler/tf2xla/python:xla", + "//tensorflow/core:protos_all_py", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + "@absl_py//absl/testing:parameterized", + ], +) + +tf_xla_py_strict_test( + name = "bincount_op_test", + size = "small", + srcs = ["bincount_op_test.py"], + shard_count = 1, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", # Handled in the combined test above. + ], + deps = [ + ":xla_test", + "//tensorflow/python/compat:v2_compat", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:errors", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops_gen", + "//tensorflow/python/platform:test", + ], +) + +tf_xla_py_strict_test( + name = "unique_ops_test", + size = "small", + srcs = ["unique_ops_test.py"], + enabled_backends = [ + "cpu", + "gpu", + "gpu_a100", + "gpu_h100", + ], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + deps = [ + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:array_ops_gen", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +tpu_py_strict_test( + name = "mean_op_test", + size = "small", + srcs = ["mean_op_test.py"], + disable_experimental = False, + tags = [ + "notsan", # timesout + ], + deps = [ + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +tf_xla_py_strict_test( + name = "xla_dump_to_test", + size = "medium", + srcs = ["xla_dump_to_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "optonly", + ], + deps = [ + ":xla_test", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:test", + "//third_party/py/numpy", + ], +) + +# copybara:uncomment_begin(google-only) +# tf_xla_py_strict_test( +# name = "xla_dump_to_sponge_test", +# size = "medium", +# srcs = ["xla_dump_to_sponge_test.py"], +# tags = [ +# "optonly", +# ], +# deps = [ +# ":xla_test", +# "//third_party/py/numpy", +# "//tensorflow/python/ops:array_ops", +# "//tensorflow/python/ops:math_ops", +# "//tensorflow/python/platform:test", +# ], +# ) +# copybara:uncomment_end +#LINT.ThenChange(:combined_tests) + +cuda_py_strict_test( + name = "xla_device_gpu_test", + size = "small", + srcs = ["xla_device_gpu_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + xla_enable_strict_auto_jit = False, + xla_enabled = True, + deps = [ + "//tensorflow/python/client:session", + "//tensorflow/python/eager:context", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +cuda_py_strict_test( + name = "jit_test", + size = "medium", + srcs = ["jit_test.py"], + #shard_count = 5, + tags = [ + "no_cuda_asan", # Times out. + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + xla_enable_strict_auto_jit = False, + xla_enabled = True, + deps = [ + ":test_utils", + "//tensorflow/core:protos_all_py", + "//tensorflow/python/client:session", + "//tensorflow/python/compiler/xla:compiler_py", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:cond", + "//tensorflow/python/ops:control_flow_ops", + "//tensorflow/python/ops:gradients_impl", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:while_loop", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +cuda_py_strict_test( + name = "async_comp_test", + size = "medium", + srcs = ["async_comp_test.py"], + shard_count = 1, + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + xla_enable_strict_auto_jit = False, + xla_enabled = True, + deps = [ + "//tensorflow/core:protos_all_py", + "//tensorflow/python/client:session", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/platform:client_testlib", + ], +) + +cuda_py_strict_test( + name = "dense_layer_test", + size = "medium", + srcs = ["dense_layer_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + xla_enable_strict_auto_jit = False, + xla_enabled = True, + deps = [ + ":test_utils", + "//tensorflow/core:protos_all_py", + "//tensorflow/python/compiler/xla:compiler_py", + "//tensorflow/python/framework:ops", + "//tensorflow/python/layers", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +cc_library( + name = "randomized_tests_library", + testonly = 1, + srcs = ["randomized_tests.cc"], + deps = [ + "//tensorflow/compiler/jit", + "//tensorflow/compiler/jit:common", + "//tensorflow/compiler/jit:flags_headers", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:tensorflow_opensource", + "//tensorflow/core:test", + "//tensorflow/core:testlib", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/container:fixed_array", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/tsl/platform:status", + ], +) + +tf_cuda_cc_test( + name = "randomized_tests", + size = "medium", + args = ["--tf_xla_test_use_mlir=false"], + shard_count = 20, + # This test is randomized, so only run it if explicitly requested. + tags = [ + "manual", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ] + tf_cuda_tests_tags(), + deps = [":randomized_tests_library"], +) + +tf_cuda_cc_test( + name = "randomized_tests_mlir", + size = "medium", + args = ["--tf_xla_test_use_mlir=true"], + shard_count = 20, + # This test is randomized, so only run it if explicitly requested. + tags = [ + "manual", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "notap", + ] + tf_cuda_tests_tags(), + deps = [":randomized_tests_library"], +) + +# Create a deterministic version of randomized_tests_mlir with fixed seed. +# This can be used in presubmit checks as it is no longer randomized. +tf_cuda_cc_test( + name = "randomized_tests_mlir_seeded", + size = "medium", + args = [ + "--tf_xla_random_seed=200839030", + "--tf_xla_test_use_mlir=true", + "--tf_xla_test_device=GPU:0", + ], + shard_count = 20, + tags = [ + "config-cuda-only", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "no_rocm", # ROCmSoftwarePlatform #958 + "noasan", # TODO(b/201651800) + "requires-gpu-nvidia", + ] + tf_cuda_tests_tags(), + deps = [":randomized_tests_library"], +) + +# Create a deterministic version of randomized_tests with fixed seed. +# This can be used in presubmit checks as it is no longer randomized. +tf_cuda_cc_test( + name = "randomized_tests_seeded", + size = "medium", + args = [ + "--tf_xla_random_seed=200839030", + "--tf_xla_test_use_mlir=false", + "--tf_xla_test_device=GPU:0", + ], + shard_count = 20, + tags = [ + "config-cuda-only", + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + "no_rocm", # ROCmSoftwarePlatform #958 + "noasan", # TODO(b/201651800) + "requires-gpu-nvidia", + ] + tf_cuda_tests_tags(), + deps = [":randomized_tests_library"], +) + +tf_cuda_cc_test( + name = "unary_ops_composition_test", + srcs = ["unary_ops_composition_test.cc"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ] + tf_cuda_tests_tags(), + deps = [ + "//tensorflow/cc:cc_ops", + "//tensorflow/compiler/jit", + "//tensorflow/compiler/jit:flags", + "//tensorflow/compiler/jit:xla_kernel_creator", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "//tensorflow/core/kernels:ops_testutil", + "@com_google_absl//absl/log:check", + ], +) + +py_library( + name = "lstm", + testonly = 1, + srcs = ["lstm.py"], + strict_deps = True, + deps = [ + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/ops:variable_v1", + "@six_archive//:six", + ], +) + +cuda_py_strict_test( + name = "lstm_test", + srcs = ["lstm_test.py"], + tags = [ + "no_pip", # TODO(b/149738646): fix pip install so these tests run on kokoro pip + ], + xla_enable_strict_auto_jit = False, + xla_enabled = True, + deps = [ + ":lstm", + ":xla_test", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:gradients_impl", + "//tensorflow/python/ops:init_ops", + "//tensorflow/python/ops:math_ops", + "//tensorflow/python/ops:variables", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +# An example of ahead-of-time compilation using tfcompile. The +# lstm_layer_inference.pbtxt file was generated by running lstm_test +# --dump_graph_dir, and the config file was written by hand. +# +# Run the following to build a minimal benchmark of the computation on Android: +# $ bazel build -c opt --cxxopt='-std=c++11' --linkopt='-lm' \ +# --cpu=armeabi-v7a \ +# --host_crosstool_top=@bazel_tools//tools/cpp:toolchain \ +# --crosstool_top=//external:android/crosstool \ +# //tensorflow/compiler/tests:lstm_layer_inference_benchmark + +# +# Currently the resulting binary size is ~190KB +tf_library( + name = "lstm_layer_inference", + testonly = 1, + config = "lstm_layer_inference.config.pbtxt", + cpp_class = "LSTMLayerInference", + graph = "lstm_layer_inference.pbtxt", + tags = ["manual"], + tfcompile_flags = ["--xla_cpu_multi_thread_eigen=false"], +) + +cuda_py_strict_test( + name = "const_test", + size = "small", + srcs = ["const_test.py"], + xla_enable_strict_auto_jit = False, + xla_enabled = True, + deps = [ + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/platform:client_testlib", + "//third_party/py/numpy", + ], +) + +tpu_py_strict_test( + name = "giant_const_op_test", + srcs = [ + "giant_const_op_test.py", + ], + disable_experimental = True, + # TODO(b/188995810): Add an optimization in MLIR importer to not + # materialize giant splat constants. + deps = [ + "//tensorflow/python/distribute:tpu_strategy", + "//tensorflow/python/distribute/cluster_resolver:tpu_cluster_resolver_py", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/eager:remote", + "//tensorflow/python/eager:test", + "//tensorflow/python/framework:config", + "//tensorflow/python/framework:constant_op", + "//tensorflow/python/framework:dtypes", + "//tensorflow/python/platform:flags", + "//third_party/py/numpy", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/__init__.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/adadelta_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adadelta_test.py new file mode 100644 index 0000000000000000000000000000000000000000..f1a495ba427bb3daaee0261c0bcbc92f8c6a216d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adadelta_test.py @@ -0,0 +1,138 @@ +# 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 Adadelta Optimizer.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import adadelta + + +class AdadeltaOptimizerTest(xla_test.XLATestCase): + + def testBasic(self): + num_updates = 4 # number of ADADELTA steps to perform + if "CPU" in self.device: + # To avoid timeout on CPU. + all_grad = [0.2, 0.01] + all_lr = [1.0, 0.1] + else: + all_grad = [0.2, 0.1, 0.01] + all_lr = [1.0, 0.5, 0.1] + + for dtype in self.float_types | self.complex_types: + with self.session(), self.test_scope(): + for grad in all_grad: + for lr in all_lr: + var0_init = [1.0, 2.0] + var1_init = [3.0, 4.0] + var0 = resource_variable_ops.ResourceVariable( + var0_init, dtype=dtype) + var1 = resource_variable_ops.ResourceVariable( + var1_init, dtype=dtype) + + grads = constant_op.constant([grad, grad], dtype=dtype) + + accum = 0.0 + accum_update = 0.0 + + # ADADELTA gradient optimizer + rho = 0.95 + epsilon = 1e-8 + adadelta_opt = adadelta.AdadeltaOptimizer( + learning_rate=lr, rho=rho, epsilon=epsilon) + adadelta_update = adadelta_opt.apply_gradients( + zip([grads, grads], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + opt_vars = adadelta_opt.variables() + self.assertStartsWith(opt_vars[0].name, var0._shared_name) + self.assertStartsWith(opt_vars[1].name, var0._shared_name) + self.assertStartsWith(opt_vars[2].name, var1._shared_name) + self.assertStartsWith(opt_vars[3].name, var1._shared_name) + self.assertEqual(4, len(opt_vars)) + # Assign slots + slot = [None] * 2 + slot_update = [None] * 2 + self.assertEqual(["accum", "accum_update"], + adadelta_opt.get_slot_names()) + slot[0] = adadelta_opt.get_slot(var0, "accum") + self.assertEqual(slot[0].get_shape(), var0.get_shape()) + self.assertNotIn(slot[0], variables.trainable_variables()) + + slot_update[0] = adadelta_opt.get_slot(var0, "accum_update") + self.assertEqual(slot_update[0].get_shape(), var0.get_shape()) + self.assertNotIn(slot_update[0], variables.trainable_variables()) + + slot[1] = adadelta_opt.get_slot(var1, "accum") + self.assertEqual(slot[1].get_shape(), var1.get_shape()) + self.assertNotIn(slot[1], variables.trainable_variables()) + + slot_update[1] = adadelta_opt.get_slot(var1, "accum_update") + self.assertEqual(slot_update[1].get_shape(), var1.get_shape()) + self.assertNotIn(slot_update[1], variables.trainable_variables()) + + # Fetch params to validate initial values + self.assertAllClose(var0_init, self.evaluate(var0)) + self.assertAllClose(var1_init, self.evaluate(var1)) + + update = [None] * num_updates + tot_update = 0 + for step in range(num_updates): + # Run adadelta update for comparison + self.evaluate(adadelta_update) + + # Perform initial update without previous accum values + accum = accum * rho + (grad**2) * (1 - rho) + update[step] = ( + np.sqrt(accum_update + epsilon) * + (1. / np.sqrt(accum + epsilon)) * grad) + accum_update = ( + accum_update * rho + (update[step]**2) * (1.0 - rho)) + tot_update += update[step] * lr + + # Check that the accumulators have been updated + for slot_idx in range(2): + self.assertAllCloseAccordingToType( + np.array([accum, accum], dtype=dtype), + self.evaluate(slot[slot_idx]), + rtol=1e-5) + + self.assertAllCloseAccordingToType( + np.array([accum_update, accum_update], dtype=dtype), + self.evaluate(slot_update[slot_idx]), + rtol=1e-5) + + # Check that the parameters have been updated + self.assertAllCloseAccordingToType( + np.array( + [var0_init[0] - tot_update, var0_init[1] - tot_update], + dtype=dtype), + self.evaluate(var0), + rtol=1e-5) + + self.assertAllCloseAccordingToType( + np.array( + [var1_init[0] - tot_update, var1_init[1] - tot_update], + dtype=dtype), + self.evaluate(var1), + rtol=1e-5) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/adagrad_da_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adagrad_da_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a9000a30d4e731ffad8300b6e5edff88048bf84b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adagrad_da_test.py @@ -0,0 +1,161 @@ +# 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 AdagradDA optimizer.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import adagrad_da + + +class AdagradDAOptimizerTest(xla_test.XLATestCase): + + def testAdagradDAWithoutRegularizationBasic1(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + global_step = resource_variable_ops.ResourceVariable( + 0, dtype=dtypes.int64) + var0 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + opt = adagrad_da.AdagradDAOptimizer( + 3.0, + global_step, + initial_gradient_squared_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + update = opt.apply_gradients( + zip([grads0, grads1], [var0, var1]), global_step=global_step) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run a step of AdagradDA + update.run() + + # Let g be the gradient accumulator, gg be the gradient squared + # accumulator, T be the global step, lr be the learning rate, + # and k the initial gradient squared accumulator value. + # w = \dfrac{sign(-g)*lr*|g - l1*T|_{+}}{l2*T*lr + \sqrt{k+gg})} + # For -0.1*3.0*(0.1 - 0)/(0 + sqrt(0.1 + 0.1*0.1)) = -0.904534 + # similarly for others. + self.assertAllCloseAccordingToType( + np.array([-0.904534, -1.603567]), self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([-0.094821, -0.189358]), self.evaluate(var1)) + + def testAdagradDAwithoutRegularizationBasic2(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + global_step = resource_variable_ops.ResourceVariable( + 0, dtype=dtypes.int64) + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + + opt = adagrad_da.AdagradDAOptimizer( + 3.0, + global_step, + initial_gradient_squared_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + update = opt.apply_gradients( + zip([grads0, grads1], [var0, var1]), global_step=global_step) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) + self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) + + # Run a step of AdagradDA + update.run() + + self.assertAllCloseAccordingToType( + np.array([-0.904534, -1.603567]), self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([-0.094821, -0.189358]), self.evaluate(var1)) + + def testAdagradDAWithL1(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + global_step = resource_variable_ops.ResourceVariable( + 0, dtype=dtypes.int64) + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + + opt = adagrad_da.AdagradDAOptimizer( + 3.0, + global_step, + initial_gradient_squared_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=0.0) + update = opt.apply_gradients( + zip([grads0, grads1], [var0, var1]), global_step=global_step) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) + self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) + + # Run a step of AdagradDA + update.run() + + self.assertAllCloseAccordingToType( + np.array([-0.895489, -1.59555]), self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([-0.085339, -0.17989]), self.evaluate(var1)) + + def testAdagradDAWithL1_L2(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + global_step = resource_variable_ops.ResourceVariable( + 0, dtype=dtypes.int64) + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + + opt = adagrad_da.AdagradDAOptimizer( + 3.0, + global_step, + initial_gradient_squared_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=2.0) + update = opt.apply_gradients( + zip([grads0, grads1], [var0, var1]), global_step=global_step) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) + self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) + + # Run a step of AdagradDA + update.run() + + self.assertAllCloseAccordingToType( + np.array([-0.046907, -0.093659]), self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([-0.004275, -0.009023]), self.evaluate(var1)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/adagrad_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adagrad_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e664b3bb1e9e5e18cf9de8a24ccb4760ea26645c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adagrad_test.py @@ -0,0 +1,124 @@ +# 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 Adagrad.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import adagrad + + +class AdagradOptimizerTest(xla_test.XLATestCase): + + def testBasic(self): + for dtype in self.float_types | self.complex_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) + ada_opt = adagrad.AdagradOptimizer(3.0, initial_accumulator_value=0.1) + ada_update = ada_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + # Run 3 steps of adagrad + for _ in range(3): + ada_update.run() + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-1.6026098728179932, -0.6026098728179932]), + self.evaluate(var0), + float_rtol=1e-5) + self.assertAllCloseAccordingToType( + np.array([2.715679168701172, 3.715679168701172]), + self.evaluate(var1), + float_rtol=1e-5) + + def testTensorLearningRate(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) + ada_opt = adagrad.AdagradOptimizer( + constant_op.constant(3.0), initial_accumulator_value=0.1) + ada_update = ada_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + # Run 3 steps of adagrad + for _ in range(3): + ada_update.run() + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-1.6026098728179932, -0.6026098728179932]), + self.evaluate(var0), + float_rtol=1e-5) + self.assertAllCloseAccordingToType( + np.array([2.715679168701172, 3.715679168701172]), + self.evaluate(var1), + float_rtol=1e-5) + + def testSharing(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) + ada_opt = adagrad.AdagradOptimizer(3.0) + # Apply the optimizer twice. Both applications will use + # the same accums. + ada_update1 = ada_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + ada_update2 = ada_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + self.assertEqual(["accumulator"], ada_opt.get_slot_names()) + slot0 = ada_opt.get_slot(var0, "accumulator") + self.assertEqual(slot0.get_shape(), var0.get_shape()) + slot1 = ada_opt.get_slot(var1, "accumulator") + self.assertEqual(slot1.get_shape(), var1.get_shape()) + self.evaluate(variables.global_variables_initializer()) + + # Fetch params to validate initial values. + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + # Mix the first and the second adagrad for 3 steps. + ada_update1.run() + ada_update2.run() + ada_update1.run() + # Validate updated params (the same as with only 1 Adagrad). + self.assertAllCloseAccordingToType( + np.array([-1.6026098728179932, -0.6026098728179932]), + self.evaluate(var0), + float_rtol=1e-5) + self.assertAllCloseAccordingToType( + np.array([2.715679168701172, 3.715679168701172]), + self.evaluate(var1), + float_rtol=1e-5) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/adam_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adam_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1330b9247f77f0d00478e01c871ed6094df75a7a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/adam_test.py @@ -0,0 +1,185 @@ +# 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 Adam.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +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.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import adam + + +def adam_update_numpy(param, + g_t, + t, + m, + v, + alpha=0.001, + beta1=0.9, + beta2=0.999, + epsilon=1e-8): + alpha_t = alpha * np.sqrt(1 - beta2**t) / (1 - beta1**t) + + m_t = beta1 * m + (1 - beta1) * g_t + v_t = beta2 * v + (1 - beta2) * g_t * g_t + + param_t = param - alpha_t * m_t / (np.sqrt(v_t) + epsilon) + return param_t, m_t, v_t + + +class AdamOptimizerTest(xla_test.XLATestCase): + + def testBasic(self): + for dtype in self.float_types | self.complex_types: + # TODO: test fails for float16 due to excessive precision requirements. + if dtype in [np.float16, dtypes.bfloat16.as_numpy_dtype]: + continue + with self.session(), self.test_scope(): + variable_scope.get_variable_scope().set_use_resource(True) + + # Initialize variables for numpy implementation. + m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 + var0_np = np.array([1.0, 2.0], dtype=dtype) + grads0_np = np.array([0.1, 0.1], dtype=dtype) + var1_np = np.array([3.0, 4.0], dtype=dtype) + grads1_np = np.array([0.01, 0.01], dtype=dtype) + + var0 = resource_variable_ops.ResourceVariable(var0_np) + var1 = resource_variable_ops.ResourceVariable(var1_np) + grads0 = array_ops.placeholder(dtype) + grads1 = array_ops.placeholder(dtype) + opt = adam.AdamOptimizer() + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + + beta1_power, beta2_power = opt._get_beta_accumulators() + + # Run 3 steps of Adam + for t in range(1, 4): + self.assertAllCloseAccordingToType(0.9**t, self.evaluate(beta1_power)) + self.assertAllCloseAccordingToType(0.999**t, + self.evaluate(beta2_power)) + update.run(feed_dict={grads0: grads0_np, grads1: grads1_np}) + + var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) + var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) + + # Validate updated params + self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) + self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) + + def testTensorLearningRate(self): + for dtype in self.float_types | self.complex_types: + # TODO: test fails for float16 due to excessive precision requirements. + if dtype in [np.float16, dtypes.bfloat16.as_numpy_dtype]: + continue + with self.session(), self.test_scope(): + variable_scope.get_variable_scope().set_use_resource(True) + + # Initialize variables for numpy implementation. + m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 + var0_np = np.array([1.0, 2.0], dtype=dtype) + grads0_np = np.array([0.1, 0.1], dtype=dtype) + var1_np = np.array([3.0, 4.0], dtype=dtype) + grads1_np = np.array([0.01, 0.01], dtype=dtype) + + var0 = resource_variable_ops.ResourceVariable(var0_np) + var1 = resource_variable_ops.ResourceVariable(var1_np) + grads0 = array_ops.placeholder(dtype) + grads1 = array_ops.placeholder(dtype) + opt = adam.AdamOptimizer(constant_op.constant(0.001)) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + + beta1_power, beta2_power = opt._get_beta_accumulators() + + # Run 3 steps of Adam + for t in range(1, 4): + self.assertAllCloseAccordingToType(0.9**t, self.evaluate(beta1_power)) + self.assertAllCloseAccordingToType(0.999**t, + self.evaluate(beta2_power)) + update.run(feed_dict={grads0: grads0_np, grads1: grads1_np}) + + var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) + var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) + + # Validate updated params + self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) + self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) + + def testSharing(self): + for dtype in self.float_types | self.complex_types: + # TODO: test fails for float16 due to excessive precision requirements. + if dtype in [np.float16, dtypes.bfloat16.as_numpy_dtype]: + continue + with self.session(), self.test_scope(): + variable_scope.get_variable_scope().set_use_resource(True) + + # Initialize variables for numpy implementation. + m0, v0, m1, v1 = 0.0, 0.0, 0.0, 0.0 + var0_np = np.array([1.0, 2.0], dtype=dtype) + grads0_np = np.array([0.1, 0.1], dtype=dtype) + var1_np = np.array([3.0, 4.0], dtype=dtype) + grads1_np = np.array([0.01, 0.01], dtype=dtype) + + var0 = resource_variable_ops.ResourceVariable(var0_np) + var1 = resource_variable_ops.ResourceVariable(var1_np) + grads0 = array_ops.placeholder(dtype) + grads1 = array_ops.placeholder(dtype) + opt = adam.AdamOptimizer() + update1 = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + update2 = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + beta1_power, beta2_power = opt._get_beta_accumulators() + + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + + # Run 3 steps of intertwined Adam1 and Adam2. + for t in range(1, 4): + self.assertAllCloseAccordingToType(0.9**t, self.evaluate(beta1_power)) + self.assertAllCloseAccordingToType(0.999**t, + self.evaluate(beta2_power)) + if t % 2 == 0: + update1.run(feed_dict={grads0: grads0_np, grads1: grads1_np}) + else: + update2.run(feed_dict={grads0: grads0_np, grads1: grads1_np}) + + var0_np, m0, v0 = adam_update_numpy(var0_np, grads0_np, t, m0, v0) + var1_np, m1, v1 = adam_update_numpy(var1_np, grads1_np, t, m1, v1) + + # Validate updated params + self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) + self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/add_n_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/add_n_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ba3bb4ba1975c309f0ab3b852916dd8a090ed95f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/add_n_test.py @@ -0,0 +1,80 @@ +# Copyright 2019 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 AddN.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import list_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +class XlaAddNTest(xla_test.XLATestCase): + + def testAddTensorLists(self): + with self.session(), self.test_scope(): + l1 = list_ops.tensor_list_reserve( + element_shape=[], element_dtype=dtypes.float32, num_elements=3) + l2 = list_ops.tensor_list_reserve( + element_shape=[], element_dtype=dtypes.float32, num_elements=3) + l1 = list_ops.tensor_list_set_item(l1, 0, 5.) + l2 = list_ops.tensor_list_set_item(l2, 2, 10.) + + l = math_ops.add_n([l1, l2]) + self.assertAllEqual( + list_ops.tensor_list_stack(l, element_dtype=dtypes.float32), + [5.0, 0.0, 10.0]) + + def testAddTensorListsFailsIfLeadingDimsMismatch(self): + with self.session(), self.test_scope(): + l1 = list_ops.tensor_list_reserve( + element_shape=[], element_dtype=dtypes.float32, num_elements=2) + l2 = list_ops.tensor_list_reserve( + element_shape=[], element_dtype=dtypes.float32, num_elements=3) + l = math_ops.add_n([l1, l2]) + with self.assertRaisesRegex( + errors.InvalidArgumentError, + "TensorList arguments to AddN must all have the same shape"): + list_ops.tensor_list_stack(l, element_dtype=dtypes.float32).eval() + + def testAddTensorListsFailsIfElementShapesMismatch(self): + with self.session() as session, self.test_scope(): + # Use placeholders instead of constant values for shapes to prevent TF's + # shape inference from catching this early. + l1_element_shape = array_ops.placeholder(dtype=dtypes.int32) + l2_element_shape = array_ops.placeholder(dtype=dtypes.int32) + l1 = list_ops.tensor_list_reserve( + element_shape=l1_element_shape, + element_dtype=dtypes.float32, + num_elements=3) + l2 = list_ops.tensor_list_reserve( + element_shape=l2_element_shape, + element_dtype=dtypes.float32, + num_elements=3) + l = math_ops.add_n([l1, l2]) + with self.assertRaisesRegex( + errors.InvalidArgumentError, + "TensorList arguments to AddN must all have the same shape"): + session.run( + list_ops.tensor_list_stack(l, element_dtype=dtypes.float32), { + l1_element_shape: [], + l2_element_shape: [2] + }) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/approx_topk_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/approx_topk_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a3049caae1117657c1ed30075b2e3435c880e088 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/approx_topk_test.py @@ -0,0 +1,254 @@ +# Copyright 2022 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 approx_max_k and approx_min_k.""" + +import itertools +from absl.testing import parameterized + +import numpy as np + +from tensorflow.python.eager import backprop +from tensorflow.python.eager import test +from tensorflow.python.eager.def_function import function +from tensorflow.python.framework import dtypes +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 nn_ops +from tensorflow.python.ops import variables + + +class ApproxTopkTest(test.TestCase, parameterized.TestCase): + + def setUp(self): + test.TestCase.setUp(self) + self._rng = np.random.default_rng(42) + + def compute_recall(self, result_neighbors, ground_truth_neighbors): + """Computes the recall of an approximate nearest neighbor search. + + Args: + result_neighbors: int32 numpy array of the shape [num_queries, + neighbors_per_query] where the values are the indices of the dataset. + ground_truth_neighbors: int32 numpy array of with shape [num_queries, + ground_truth_neighbors_per_query] where the values are the indices of + the dataset. + + Returns: + The recall. + """ + self.assertLen(result_neighbors.shape, 2) + self.assertLen(ground_truth_neighbors.shape, 2) + self.assertEqual(result_neighbors.shape[0], ground_truth_neighbors.shape[0]) + gt_sets = [set(np.asarray(x)) for x in ground_truth_neighbors] + + def hits_per_q(q, nn_per_q): + return len(list(x for x in nn_per_q if x.item() in gt_sets[q])) + + hits = sum( + hits_per_q(q, nn_per_q) for q, nn_per_q in enumerate(result_neighbors)) + return hits / ground_truth_neighbors.size + + @parameterized.parameters( + itertools.product( + [1, 10], # k + [100, 500], # row_size + [1, 10, 128], # num_rows + [True, False], # aggregate_to_topk + )) + def test_non_fused_max_k(self, k, row_size, num_rows, aggregate_to_topk): + row = np.arange(row_size, dtype=np.float32) + db = np.stack(list(self._rng.permutation(row) for _ in range(num_rows))) + + @function(jit_compile=True) + def ann(db, k): + return nn_ops.approx_max_k(db, k, aggregate_to_topk=aggregate_to_topk) + + with ops.device('/device:TPU:0'): + db_op = variables.Variable(db) + result = ann(db_op, k)[1] + + gt = np.argsort(-db)[:, :k] + ann_recall = self.compute_recall(result.numpy(), gt) + self.assertGreaterEqual(ann_recall, 0.95) + + @parameterized.parameters( + itertools.product( + [1, 10], # k + [100, 500], # row_size + [1, 10, 128], # num_rows + [True, False], # aggregate_to_topk + )) + def test_non_fused_min_k(self, k, row_size, num_rows, aggregate_to_topk): + # Use the new rng api + row = np.arange(row_size, dtype=np.float32) + db = np.stack(list(self._rng.permutation(row) for _ in range(num_rows))) + + @function(jit_compile=True) + def ann(db, k=10): + return nn_ops.approx_min_k(db, k, aggregate_to_topk=aggregate_to_topk) + + with ops.device('/device:TPU:0'): + db_op = variables.Variable(db) + result = ann(db_op, k)[1] + + gt = np.argsort(db)[:, :k] + ann_recall = self.compute_recall(result.numpy(), gt) + self.assertGreaterEqual(ann_recall, 0.95) + + @parameterized.parameters( + itertools.product( + [1, 10], # k + [100, 500], # db_size + [1, 10, 128], # qy_size + [2, 32], # feature dim + )) + # MIPS = Maximal Inner Product Search + def test_mips(self, k, db_size, qy_size, feature_dim): + qy = self._rng.random([qy_size, feature_dim], dtype=np.float32) + db = self._rng.random([db_size, feature_dim], dtype=np.float32) + + @function(jit_compile=True) + def ann(qy, db, k): + scores = math_ops.matmul(qy, db, transpose_b=True) + return nn_ops.approx_max_k(scores, k) + + with ops.device('/device:TPU:0'): + qy_op = variables.Variable(qy) + db_op = variables.Variable(db) + result = ann(qy_op, db_op, k)[1] + scores = -math_ops.matmul(qy_op, db_op, transpose_b=True) + + gt = np.argsort(scores.numpy())[:, :k] + ann_recall = self.compute_recall(result.numpy(), gt) + self.assertGreaterEqual(ann_recall, 0.95) + + @parameterized.parameters( + itertools.product( + [1, 10], # k + [100, 500], # db_size + [10, 128], # qy_size + [2, 8], # feature dim + )) + # L2ANN = Approximate Nearest Neighbor search in the L2 metric space + def test_l2ann(self, k, db_size, qy_size, feature_dim): + qy = self._rng.random([qy_size, feature_dim], dtype=np.float32) + db = self._rng.random([db_size, feature_dim], dtype=np.float32) + db_half_norm_sq = np.linalg.norm(db, axis=1)**2 / 2 + + @function(jit_compile=True) + def ann(qy, db, db_half_norm_sq, k): + scores = db_half_norm_sq - math_ops.matmul(qy, db, transpose_b=True) + return nn_ops.approx_min_k(scores, k) + + with ops.device('/device:TPU:0'): + qy_op = variables.Variable(qy) + db_op = variables.Variable(db) + db_half_norm_sq_op = variables.Variable(db_half_norm_sq) + result = ann(qy_op, db_op, db_half_norm_sq_op, k)[1] + scores = db_half_norm_sq_op - math_ops.matmul( + qy_op, db_op, transpose_b=True) + + gt = np.argsort(scores.numpy())[:, :k] + ann_recall = self.compute_recall(result.numpy(), gt) + self.assertGreaterEqual(ann_recall, 0.95) + + def test_highdim(self): + db = self._rng.random([2, 10, 200, 3], dtype=np.float32) + k = 5 + + @function(jit_compile=True) + def ann(db, k): + return nn_ops.approx_min_k(db, k=k, reduction_dimension=2) + + with ops.device('/device:TPU:0'): + db_op = variables.Variable(db) + result = ann(db_op, k)[1] + + gt = np.argsort(db, axis=2)[:, :, :k, :] + flat_idx = np.reshape( + np.transpose(result.numpy(), [0, 1, 3, 2]), [2 * 10 * 3, k]) + flat_gt = np.reshape(np.transpose(gt, [0, 1, 3, 2]), [2 * 10 * 3, k]) + ann_recall = self.compute_recall(flat_idx, flat_gt) + self.assertGreaterEqual(ann_recall, 0.95) + + @parameterized.parameters( + itertools.product( + [dtypes.bfloat16, dtypes.float16, dtypes.float32], + [1, 10], # k + [100, 500], # row_size + [1, 10, 128], # num_rows + )) + def test_gradients(self, dtype, k, row_size, num_rows): + row = np.arange(row_size, dtype=np.float32) + db = np.stack(list(self._rng.permutation(row) for _ in range(num_rows))) + out_grads = self._rng.random([num_rows, k]) + + @function(jit_compile=True) + def ann_with_grads(db, out_grads): + with backprop.GradientTape() as tape: + val, idx = nn_ops.approx_max_k(db, k) + result_in_grads = tape.gradient(val, db, out_grads) + lifted_k_idx = array_ops.reshape(idx, [num_rows, k, 1]) + iota_idx = array_ops.broadcast_to( + array_ops.reshape(math_ops.range(num_rows), [num_rows, 1, 1]), + [num_rows, k, 1]) + lifted_idx = array_ops.concat([iota_idx, lifted_k_idx], axis=2) + k_idx_s = array_ops.reshape(lifted_idx, [num_rows * k, 2]) + k_gra_s = array_ops.reshape(out_grads, [num_rows * k]) + expected_in_grads = array_ops.scatter_nd(k_idx_s, k_gra_s, + [num_rows, row_size]) + return [expected_in_grads, result_in_grads] + + with ops.device('/device:TPU:0'): + db_op = variables.Variable(db, dtype=dtype) + out_grads_op = variables.Variable(out_grads, dtype=dtype) + expected_in_grads, result_in_grads = ann_with_grads(db_op, out_grads_op) + + self.assertAllClose(expected_in_grads, result_in_grads) + + # Tests that multiple ops are supported and the comparison functions are + # renamed properly to avoid conflict while using the MLIR bridge. + def test_multiple_ops(self): + k = 1 + + row_size = 100 + num_rows = 10 + + row = np.arange(row_size, dtype=np.float32) + db1 = np.stack(list(self._rng.permutation(row) for _ in range(num_rows))) + db2 = np.stack(list(self._rng.permutation(row) for _ in range(num_rows))) + + @function(jit_compile=True) + def ann(db1, db2): + result1 = nn_ops.approx_max_k(db1, k, aggregate_to_topk=True) + result2 = nn_ops.approx_max_k(db2, k, aggregate_to_topk=True) + return (result1, result2) + + with ops.device('/device:TPU:0'): + db1_op = variables.Variable(db1) + db2_op = variables.Variable(db2) + result1, result2 = ann(db1_op, db2_op) + + gt = np.argsort(-db1)[:, :k] + ann_recall = self.compute_recall(result1[1].numpy(), gt) + self.assertGreaterEqual(ann_recall, 0.95) + + gt = np.argsort(-db2)[:, :k] + ann_recall = self.compute_recall(result2[1].numpy(), gt) + self.assertGreaterEqual(ann_recall, 0.95) + +if __name__ == '__main__': + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/argminmax_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/argminmax_test.py new file mode 100644 index 0000000000000000000000000000000000000000..05d626d84f2c08f1f7287f1f3366e69fb5aa6ef3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/argminmax_test.py @@ -0,0 +1,95 @@ +# 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. +# ============================================================================== +"""Functional tests for ArgMin and ArgMax Ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +class ArgMinMaxTest(xla_test.XLATestCase): + + def _assertOpOutputMatchesExpected(self, op, axis, output_type, op_input, + expected): + """Verifies that 'op' produces 'expected' when fed input 'op_input' . + + Args: + op: argmin or argmax operator to test. + axis: integer axis to reduce across. + output_type: numpy datatype of the output to produce. + op_input: numpy input array to use as input to 'op'. + expected: numpy array representing the expected output of 'op'. + """ + with self.session() as session: + with self.test_scope(): + pinp = array_ops.placeholder( + dtypes.as_dtype(op_input.dtype), op_input.shape, name="a") + output = op(pinp, axis=axis, output_type=output_type) + result = session.run(output, {pinp: op_input}) + self.assertAllEqual(result, expected) + + def testArgMinMax(self): + # Complex numbers do not support argmin/argmax. + minmax_types = self.all_types & {np.int32, np.int64} + for dtype in self.int_types | self.float_types: + # output_type is a numpy data type that is used to specify the desired + # output type of the op as well as to convert the Python number to the + # array scalar of the type. + for output_type in minmax_types: + self._assertOpOutputMatchesExpected( + math_ops.argmax, + axis=0, + output_type=output_type, + op_input=np.array([1, 10, 27, 3, 3, 4], dtype=dtype), + expected=output_type(2)) + self._assertOpOutputMatchesExpected( + math_ops.argmax, + axis=0, + output_type=output_type, + op_input=np.array([[4, 1, 7], [3, 2, 4]], dtype=dtype), + expected=np.array([0, 1, 0], dtype=output_type)) + self._assertOpOutputMatchesExpected( + math_ops.argmax, + axis=1, + output_type=output_type, + op_input=np.array([[4, 1], [3, 2]], dtype=dtype), + expected=np.array([0, 0], dtype=output_type)) + + self._assertOpOutputMatchesExpected( + math_ops.argmin, + axis=0, + output_type=output_type, + op_input=np.array([3, 10, 27, 3, 2, 4], dtype=dtype), + expected=output_type(4)) + self._assertOpOutputMatchesExpected( + math_ops.argmin, + axis=0, + output_type=output_type, + op_input=np.array([[4, 1, 7], [3, 2, 4]], dtype=dtype), + expected=np.array([1, 0, 1], dtype=output_type)) + self._assertOpOutputMatchesExpected( + math_ops.argmin, + axis=1, + output_type=output_type, + op_input=np.array([[4, 1], [3, 2]], dtype=dtype), + expected=np.array([1, 1], dtype=output_type)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/async_comp_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/async_comp_test.py new file mode 100644 index 0000000000000000000000000000000000000000..567d8f1d2ea639b09fb1a8a1a7218ccb66296d68 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/async_comp_test.py @@ -0,0 +1,95 @@ +# 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 asynchronous compilation on the CPU and GPU devices.""" + +import os + +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.framework import dtypes +from tensorflow.python.framework 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.platform import test + + +def RunMetadataLabels(run_metadata): + """Returns all labels in run_metadata.""" + labels = [] + for dev_stats in run_metadata.step_stats.dev_stats: + for node_stats in dev_stats.node_stats: + labels.append(node_stats.timeline_label) + return labels + + +def InLabels(labels, substr): + """Returns true iff one of the labels contains substr.""" + return any(substr in x for x in labels) + + +def MetadataHasXlaRunOp(run_metadata): + """Returns true if there are XlaRun kernels in run_metadata's timeline.""" + + # TODO(phawkins): find a less hacky way to test whether a kernel ran. + return InLabels(RunMetadataLabels(run_metadata), "_XlaRun") + + +class AsyncCompilationTest(test.TestCase): + + # Asynchrobnous compilation uses the existing fallback path and existing + # compiler. This test only tests that asynchronous compilation is performed. + def testAsyncCompilationJit(self): + + @function.Defun(compiled=True) + def CompiledFunction(x): + return math_ops.log(x) + + with session_lib.Session() as sess: + x = array_ops.placeholder(dtypes.float32) + y = CompiledFunction(x) + + run_metadata = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [0.] * 60}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + # For The first iteration, the fall back path is chosen. + hasXlaRunOp = MetadataHasXlaRunOp(run_metadata) + self.assertFalse(hasXlaRunOp) + + # Execute the session until after asynchronous compilation is finished + # and the compiled cluster has been executed once. + while (not hasXlaRunOp): + run_metadata = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [0.] * 60}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + hasXlaRunOp = MetadataHasXlaRunOp(run_metadata) + + +if __name__ == "__main__": + os.environ["TF_XLA_FLAGS"] = ("--tf_xla_async_compilation=true " + + "--tf_xla_enable_lazy_compilation=true " + + os.environ.get("TF_XLA_FLAGS", "")) + # This test is using Tensorflow sessions which are not compatible with eager + # mode. + ops.disable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/binary_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/binary_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..cd4f8492734f564368670e687a4e6d64dc5b8d24 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/binary_ops_test.py @@ -0,0 +1,1673 @@ +# 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. +# ============================================================================== +"""Test cases for binary operators.""" + +import itertools + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import bitwise_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import googletest +from tensorflow.python.platform import test as test_lib + + +class BinaryOpsTest(xla_test.XLATestCase): + """Test cases for binary operators.""" + + def _testBinary(self, + op, + a, + b, + expected, + equality_test=None, + rtol=None, + atol=None): + with self.session() as session: + with self.test_scope(): + pa = array_ops.placeholder(dtypes.as_dtype(a.dtype), a.shape, name="a") + pb = array_ops.placeholder(dtypes.as_dtype(b.dtype), b.shape, name="b") + output = op(pa, pb) + result = session.run(output, {pa: a, pb: b}) + if equality_test is None: + equality_test = self.assertAllCloseAccordingToType + if rtol is None: + rtol = 1e-15 if a.dtype == np.float64 else 1e-3 + if atol is None: + atol = 1e-15 if a.dtype == np.float64 else 1e-6 + equality_test(result, expected, rtol=rtol, atol=atol) + + def _testSymmetricBinary(self, op, a, b, expected, equality_test=None): + self._testBinary(op, a, b, expected, equality_test) + self._testBinary(op, b, a, expected, equality_test) + + def ListsAreClose(self, result, expected, rtol, atol): + """Tests closeness of two lists of floats.""" + self.assertEqual(len(result), len(expected)) + for i in range(len(result)): + self.assertAllCloseAccordingToType( + result[i], expected[i], rtol=rtol, atol=atol) + + def testFloatOps(self): + for dtype in self.float_types: + if dtype == dtypes.bfloat16.as_numpy_dtype: + a = -1.01 + b = 4.1 + else: + a = -1.001 + b = 4.01 + + self._testBinary( + lambda x, y: math_ops.approximate_equal(x, y, tolerance=0.0001), + np.array([[[[-1, 2.00009999], [-3, b]]]], dtype=dtype), + np.array([[[[a, 2], [-3.00009, 4]]]], dtype=dtype), + expected=np.array([[[[False, True], [True, False]]]], dtype=dtype)) + + self._testBinary( + gen_math_ops.real_div, + np.array([3, 3, -1.5, -8, 44], dtype=dtype), + np.array([2, -2, 7, -4, 0], dtype=dtype), + expected=np.array( + [1.5, -1.5, -0.2142857, 2, float("inf")], dtype=dtype), + rtol=1e-6, + atol=1e-8) + + self._testBinary( + math_ops.atan2, + np.array([0, np.sqrt(2), 1, np.sqrt(2), 0], dtype), + np.array([1, np.sqrt(2), 0, -np.sqrt(2), -1], dtype), + expected=np.array([0, np.pi / 4, np.pi / 2, np.pi * 3 / 4, np.pi], + dtype=dtype)) + + self._testBinary( + gen_math_ops.reciprocal_grad, + np.array([4, -3, -2, 1], dtype=dtype), + np.array([5, -6, 7, -8], dtype=dtype), + expected=np.array([-80, 54, -28, 8], dtype=dtype)) + + self._testBinary( + gen_math_ops.sigmoid_grad, + np.array([4, 3, 2, 1], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([-60, -36, -14, 0], dtype=dtype)) + + self._testBinary( + gen_math_ops.rsqrt_grad, + np.array([4, 3, 2, 1], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([-160, -81, -28, -4], dtype=dtype)) + + self._testBinary( + gen_math_ops.sqrt_grad, + np.array([4, 3, 2, 1], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([0.625, 1, 1.75, 4], dtype=dtype)) + + self._testBinary( + gen_nn_ops.softplus_grad, + np.array([4, 3, 2, 1], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([3.97322869, 2.99258232, 1.99817801, 0.99966466], + dtype=dtype), + rtol=1e-4, + atol=1e-8) + + self._testBinary( + gen_nn_ops.softsign_grad, + np.array([4, 3, 2, 1], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([0.11111111, 0.06122449, 0.03125, 0.01234568], + dtype=dtype), + rtol=1e-6, + atol=1e-8) + + self._testBinary( + gen_math_ops.tanh_grad, + np.array([4, 3, 2, 1], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([-75, -48, -21, 0], dtype=dtype)) + + self._testBinary( + gen_nn_ops.elu_grad, + np.array([1, 2, 3, 4, 5, 6], dtype=dtype), + np.array([-.6, -.4, -.2, 0, .2, .4], dtype=dtype), + expected=np.array([0.4, 1.2, 2.4, 4, 5, 6], dtype=dtype)) + + self._testBinary( + gen_nn_ops.selu_grad, + np.array([1, 2, 3, 4, 5, 6], dtype=dtype), + np.array([-.6, -.4, -.2, .2, .4, .6], dtype=dtype), + expected=np.array([ + 1.158099340847, 2.7161986816948, 4.67429802254, 4.202803949422, + 5.2535049367774, 6.30420592413 + ], + dtype=dtype), + rtol=1e-10, + atol=1e-10) + + self._testBinary( + gen_nn_ops.relu_grad, + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dtype), + np.array([0, 0, 0, 0, 0, 0.1, 0.3, 0.5, 0.7, 0.9], dtype=dtype), + expected=np.array([0, 0, 0, 0, 0, 6, 7, 8, 9, 10], dtype=dtype)) + + self._testBinary( + gen_nn_ops.relu6_grad, + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], dtype=dtype), + np.array([0, 0, 0, 0, 0, 0.1, 0.3, 0.5, 0.7, 0.9, 6.1, 10.0], + dtype=dtype), + expected=np.array([0, 0, 0, 0, 0, 6, 7, 8, 9, 10, 0, 0], dtype=dtype)) + + self._testBinary( + gen_nn_ops.leaky_relu_grad, + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dtype), + np.array([0, 0, 0, 0, 0, 0.1, 0.3, 0.5, 0.7, 0.9], dtype=dtype), + expected=np.array([0.2, 0.4, 0.6, 0.8, 1, 6, 7, 8, 9, 10], + dtype=dtype), + rtol=1e-8, + atol=1e-8) + + self._testBinary( + gen_nn_ops.softmax_cross_entropy_with_logits, + np.array([[1, 2, 3, 4], [5, 6, 7, 8]], dtype=dtype), + np.array([[0.1, 0.2, 0.3, 0.4], [0.4, 0.3, 0.2, 0.1]], dtype=dtype), + expected=[ + np.array([1.44019, 2.44019], dtype=dtype), + np.array([[-0.067941, -0.112856, -0.063117, 0.243914], + [-0.367941, -0.212856, 0.036883, 0.543914]], + dtype=dtype), + ], + equality_test=self.ListsAreClose, + rtol=1e-4, + atol=1e-8) + + # Check -inf logits doesn't create NaNs. + self._testBinary( + gen_nn_ops.sparse_softmax_cross_entropy_with_logits, + np.array([[-np.inf, 0.]], dtype=dtype), + np.array([1], dtype=np.int32), + expected=[ + np.array([0.], dtype=dtype), + np.array([[0., 0.]], dtype=dtype) + ], + equality_test=self.ListsAreClose, + rtol=1e-4, + atol=1e-8) + + # TODO(b/68813416): Fails with bfloat16. + if dtype != dtypes.bfloat16.as_numpy_dtype: + self._testBinary( + gen_nn_ops.sparse_softmax_cross_entropy_with_logits, + np.array([[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8], + [0.9, 1.0, 1.1, 1.2]], + dtype=dtype), + np.array([2, 1, 7], dtype=np.int32), + expected=[ + np.array([1.342536, 1.442536, np.nan], dtype=dtype), + np.array([[0.213838, 0.236328, -0.738817, 0.288651], + [0.213838, -0.763672, 0.261183, 0.288651], + [np.nan, np.nan, np.nan, np.nan]], + dtype=dtype), + ], + equality_test=self.ListsAreClose, + rtol=1e-5, + atol=1e-8) + + # TF doesn't define these for bf16. + if dtype != dtypes.bfloat16.as_numpy_dtype: + self._testBinary( + gen_math_ops.xdivy, + np.array([0, 4, 3, 2, 1, 0], dtype=dtype), + np.array([[0, 5, 6, 7, 8, float("NaN")]], dtype=dtype), + expected=np.array([[0, 0.8, 0.5, 0.285714, 0.125, 0]], dtype=dtype), + rtol=1e-6, + atol=1e-6) + + self._testBinary( + gen_math_ops.xlogy, + np.array([0, 4, 3, 2, 1, 0], dtype=dtype), + np.array([[0, 5, 6, 7, 8, float("NaN")]], dtype=dtype), + expected=np.array([[0, 6.437752, 5.375278, 3.89182, 2.079442, 0]], + dtype=dtype), + rtol=1e-4, + atol=1e-6) + + self._testBinary( + gen_math_ops.xlog1py, + np.array([0, 4, 3, 2, 1, 0], dtype=dtype), + np.array([[-1, 5, 6, 7, 8, float("NaN")]], dtype=dtype), + expected=np.array([[0, 7.167038, 5.837730, 4.158883, 2.197225, 0]], + dtype=dtype), + rtol=1e-4, + atol=1e-6) + + def testIntOps(self): + for dtype in self.signed_int_types: + self._testBinary( + gen_math_ops.truncate_div, + np.array([3, 3, -1, -9, -8], dtype=dtype), + np.array([2, -2, 7, 2, -4], dtype=dtype), + expected=np.array([1, -1, 0, -4, 2], dtype=dtype)) + self._testSymmetricBinary( + bitwise_ops.bitwise_and, + np.array([0b1, 0b101, 0b1000], dtype=dtype), + np.array([0b0, 0b101, 0b1001], dtype=dtype), + expected=np.array([0b0, 0b101, 0b1000], dtype=dtype)) + self._testSymmetricBinary( + bitwise_ops.bitwise_or, + np.array([0b1, 0b101, 0b1000], dtype=dtype), + np.array([0b0, 0b101, 0b1001], dtype=dtype), + expected=np.array([0b1, 0b101, 0b1001], dtype=dtype)) + self._testSymmetricBinary( + bitwise_ops.bitwise_xor, + np.array([0b1, 0b111, 0b1100], dtype=dtype), + np.array([0b0, 0b101, 0b1001], dtype=dtype), + expected=np.array([0b1, 0b010, 0b0101], dtype=dtype)) + + lhs = np.array([0, 5, 3, 14], dtype=dtype) + rhs = np.array([5, 0, 7, 11], dtype=dtype) + self._testBinary( + bitwise_ops.left_shift, lhs, rhs, expected=np.left_shift(lhs, rhs)) + self._testBinary( + bitwise_ops.right_shift, lhs, rhs, expected=np.right_shift(lhs, rhs)) + + if dtype in [np.int8, np.int16, np.int32, np.int64]: + lhs = np.array([-1, -5, -3, -14, -2], dtype=dtype) + rhs = np.array([5, 0, 1, 11, 36], dtype=dtype) + # HLO has saturating shift behavior. + bits = np.ceil( + np.log(np.iinfo(dtype).max - np.iinfo(dtype).min) / np.log(2)) + expected = [ + np.right_shift(l, r) if r < bits else np.sign(l) + for l, r in zip(lhs, rhs) + ] + self._testBinary(bitwise_ops.right_shift, lhs, rhs, expected=expected) + + def testAdd(self): + for dtype in self.numeric_types: + self._testBinary( + math_ops.add, + np.array([1, 2, 0], dtype=dtype), + np.array([10, 20, 0], dtype=dtype), + expected=np.array([11, 22, 0], dtype=dtype)) + self._testBinary( + math_ops.add, + dtype(5), + np.array([1, 2], dtype=dtype), + expected=np.array([6, 7], dtype=dtype)) + self._testBinary( + math_ops.add, + np.array([[1], [2]], dtype=dtype), + dtype(7), + expected=np.array([[8], [9]], dtype=dtype)) + + if dtype not in self.int_types: + self._testBinary( + math_ops.add, + np.array([1.9131952969218875, 1.596299504298079], dtype=dtype), + np.array([1.1137667913355869, 1.7186636469261405], dtype=dtype), + expected=np.array([3.0269620882574744, 3.3149631512242195], + dtype=dtype)) + + def testMultiply(self): + for dtype in self.numeric_types: + self._testBinary( + math_ops.multiply, + np.array([1, 20], dtype=dtype), + np.array([10, 2], dtype=dtype), + expected=np.array([10, 40], dtype=dtype)) + self._testBinary( + math_ops.multiply, + dtype(5), + np.array([1, 20], dtype=dtype), + expected=np.array([5, 100], dtype=dtype)) + self._testBinary( + math_ops.multiply, + np.array([[10], [2]], dtype=dtype), + dtype(7), + expected=np.array([[70], [14]], dtype=dtype)) + + if dtype not in self.int_types: + self._testBinary( + math_ops.multiply, + np.array([1.9131952969218875, 1.596299504298079], dtype=dtype), + np.array([1.1137667913355869, 1.7186636469261405], dtype=dtype), + expected=np.array([2.130853387051026, 2.743501927643327], + dtype=dtype), + rtol=1e-14) + + def testPow(self): + for dtype in self.float_types: + rtol = 1e-14 if dtype == np.float64 else None + + self._testBinary( + math_ops.pow, dtype(3), dtype(4), expected=dtype(81), rtol=rtol) + + self._testBinary( + math_ops.pow, + np.array([1, 2], dtype=dtype), + np.zeros(shape=[0, 2], dtype=dtype), + expected=np.zeros(shape=[0, 2], dtype=dtype), + rtol=rtol) + self._testBinary( + math_ops.pow, + np.array([10, 4], dtype=dtype), + np.array([2, 3], dtype=dtype), + expected=np.array([100, 64], dtype=dtype), + rtol=rtol) + self._testBinary( + math_ops.pow, + dtype(2), + np.array([3, 4], dtype=dtype), + expected=np.array([8, 16], dtype=dtype), + rtol=rtol) + self._testBinary( + math_ops.pow, + np.array([[2], [3]], dtype=dtype), + dtype(4), + expected=np.array([[16], [81]], dtype=dtype), + rtol=rtol) + + def testNumericOps(self): + for dtype in self.numeric_types: + self._testBinary( + math_ops.subtract, + np.array([1, 20, 100], dtype=dtype), + np.array([1, 2, 1], dtype=dtype), + expected=np.array([0, 18, 99], dtype=dtype)) + self._testBinary( + math_ops.subtract, + dtype(5), + np.array([1, 2], dtype=dtype), + expected=np.array([4, 3], dtype=dtype)) + self._testBinary( + math_ops.subtract, + np.array([[7], [10]], dtype=dtype), + dtype(7), + expected=np.array([[0], [3]], dtype=dtype)) + + # min/max not supported for complex + if dtype not in self.complex_types | {np.uint8, np.int8}: + self._testBinary( + math_ops.maximum, + np.array([1, 2], dtype=dtype), + np.array([10, 20], dtype=dtype), + expected=np.array([10, 20], dtype=dtype)) + self._testBinary( + math_ops.maximum, + dtype(5), + np.array([1, 20], dtype=dtype), + expected=np.array([5, 20], dtype=dtype)) + self._testBinary( + math_ops.maximum, + np.array([[10], [2]], dtype=dtype), + dtype(7), + expected=np.array([[10], [7]], dtype=dtype)) + + self._testBinary( + math_ops.minimum, + np.array([1, 20], dtype=dtype), + np.array([10, 2], dtype=dtype), + expected=np.array([1, 2], dtype=dtype)) + self._testBinary( + math_ops.minimum, + dtype(5), + np.array([1, 20], dtype=dtype), + expected=np.array([1, 5], dtype=dtype)) + self._testBinary( + math_ops.minimum, + np.array([[10], [2]], dtype=dtype), + dtype(7), + expected=np.array([[7], [2]], dtype=dtype)) + + # Complex support for squared_difference is incidental, see b/68205550 + if dtype not in self.complex_types | {np.uint8, np.int8}: + self._testBinary( + math_ops.squared_difference, + np.array([1, 2], dtype=dtype), + np.array([10, 20], dtype=dtype), + expected=np.array([81, 324], dtype=dtype)) + self._testBinary( + math_ops.squared_difference, + dtype(5), + np.array([1, 2], dtype=dtype), + expected=np.array([16, 9], dtype=dtype)) + self._testBinary( + math_ops.squared_difference, + np.array([[1], [2]], dtype=dtype), + dtype(7), + expected=np.array([[36], [25]], dtype=dtype)) + + self._testBinary( + nn_ops.bias_add, + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([2, 0], dtype=dtype), + expected=np.array([[3, 2], [5, 4]], dtype=dtype)) + self._testBinary( + nn_ops.bias_add, + np.array([[[[1, 2], [3, 4]]]], dtype=dtype), + np.array([2, 0], dtype=dtype), + expected=np.array([[[[3, 2], [5, 4]]]], dtype=dtype)) + + if np.int64 in self.numeric_types: + self._testBinary( + math_ops.add, + np.array([0xffffffff, 0xfffffffff, 1, 1], dtype=np.int64), + np.array([1, 1, 0xffffffff, 0xfffffffff], dtype=np.int64), + expected=np.array([1 << 32, 1 << 36, 1 << 32, 1 << 36], + dtype=np.int64)) + + def testNextAfter(self): + for dtype in self.numeric_types: + if dtype in [np.float32, np.float64]: + x = np.array([ + -0.0, 0.0, -0.0, +0.0, np.inf, np.inf, -np.inf, -np.inf, 2.0, 2.0, + 1.0 + ], + dtype=dtype) + y = np.array( + [-0.0, 0.0, +0.0, -0.0, 1.0, -1.0, 1.0, -1.0, 2.0, 1.0, 2.0], + dtype=dtype) + expected = np.nextafter(x, y) + + # We use assertAllEqual to expose any bugs hidden by relative or + # absolute error tolerances. + def NextAfterEqualityTest(result, expected, rtol, atol): + del rtol + del atol + return self.assertAllEqual(result, expected) + + self._testBinary( + math_ops.nextafter, + x, + y, + expected=expected, + equality_test=NextAfterEqualityTest) + + def testComplexOps(self): + for dtype in self.complex_types: + ctypes = {np.complex64: np.float32, np.complex128: np.float64} + self._testBinary( + math_ops.complex, + np.array([[[[-1, 2], [2, 0]]]], dtype=ctypes[dtype]), + np.array([[[[2, -3], [0, 4]]]], dtype=ctypes[dtype]), + expected=np.array([[[[-1 + 2j, 2 - 3j], [2, 4j]]]], dtype=dtype)) + + self._testBinary( + lambda x, y: math_ops.approximate_equal(x, y, tolerance=0.0001), + np.array([[[[-1 + 2j, 2.00009999 - 3j], [2 - 3j, 3 + 4.01j]]]], + dtype=dtype), + np.array([[[[-1.001 + 2j, 2 - 3j], [2 - 3.00009j, 3 + 4j]]]], + dtype=dtype), + expected=np.array([[[[False, True], [True, False]]]], dtype=dtype)) + + self._testBinary( + gen_math_ops.real_div, + np.array( + [3, 3j, -1.5j, -8, 2 + 3j, 2 + 4j, 9.663546088957395e-28 + 0j], + dtype=dtype), + np.array([ + 2, -2, 7j, -4j, 4 - 6j, 1 + 2j, + 9.39511792677288e-16 - 1.529841108938729e-23j + ], + dtype=dtype), + expected=np.array([ + 1.5, -1.5j, -0.2142857, -2j, + (2 + 3j) / (4 - 6j), 2, 1.028571e-12 + 1.674859e-20j + ], + dtype=dtype)) + + self._testBinary( + math_ops.pow, + dtype(3 + 2j), + dtype(4 - 5j), + expected=np.power(dtype(3 + 2j), dtype(4 - 5j))) + self._testBinary( # empty rhs + math_ops.pow, + np.array([1 + 2j, 2 - 3j], dtype=dtype), + np.zeros(shape=[0, 2], dtype=dtype), + expected=np.zeros(shape=[0, 2], dtype=dtype)) + self._testBinary( # to zero power + math_ops.pow, + np.array([1 + 2j, 2 - 3j], dtype=dtype), + np.zeros(shape=[1, 2], dtype=dtype), + expected=np.ones(shape=[1, 2], dtype=dtype)) + lhs = np.array([1 - 2j, 4 + 3j, 2 - 3j, 3, 2j, 1, 4], dtype=dtype) + rhs = np.array([2, 3j, 3 + 4j, 2 + 3j, 3 - 2j, 2, 3 + 3j], dtype=dtype) + scalar = dtype(2 + 2j) + self._testBinary(math_ops.pow, lhs, rhs, expected=np.power(lhs, rhs)) + self._testBinary( + math_ops.pow, scalar, rhs, expected=np.power(scalar, rhs)) + self._testBinary(math_ops.pow, lhs, scalar, np.power(lhs, scalar)) + + lhs = np.array([4 + 2j, -3 - 1j, 2j, 1], dtype=dtype) + rhs = np.array([5, -6j, 7 - 3j, -8j], dtype=dtype) + self._testBinary( + gen_math_ops.reciprocal_grad, lhs, rhs, expected=-rhs * lhs * lhs) + + self._testBinary( + gen_math_ops.sigmoid_grad, lhs, rhs, expected=rhs * lhs * (1 - lhs)) + + self._testBinary( + gen_math_ops.rsqrt_grad, lhs, rhs, expected=lhs**3 * rhs / -2) + + self._testBinary( + gen_math_ops.sqrt_grad, lhs, rhs, expected=rhs / (2 * lhs)) + + self._testBinary( + gen_math_ops.tanh_grad, lhs, rhs, expected=rhs * (1 - lhs * lhs)) + + def testComplexMath(self): + for dtype in self.complex_types: + self._testBinary( + math_ops.add, + np.array([1 + 3j, 2 + 7j], dtype=dtype), + np.array([10 - 4j, 20 + 17j], dtype=dtype), + expected=np.array([11 - 1j, 22 + 24j], dtype=dtype)) + self._testBinary( + math_ops.add, + dtype(5 - 7j), + np.array([1 + 2j, 2 + 4j], dtype=dtype), + expected=np.array([6 - 5j, 7 - 3j], dtype=dtype)) + self._testBinary( + math_ops.add, + np.array([[1 - 2j], [2 + 1j]], dtype=dtype), + dtype(7 + 5j), + expected=np.array([[8 + 3j], [9 + 6j]], dtype=dtype)) + + self._testBinary( + math_ops.subtract, + np.array([1 + 3j, 2 + 7j], dtype=dtype), + np.array([10 - 4j, 20 + 17j], dtype=dtype), + expected=np.array([-9 + 7j, -18 - 10j], dtype=dtype)) + self._testBinary( + math_ops.subtract, + dtype(5 - 7j), + np.array([1 + 2j, 2 + 4j], dtype=dtype), + expected=np.array([4 - 9j, 3 - 11j], dtype=dtype)) + self._testBinary( + math_ops.subtract, + np.array([[1 - 2j], [2 + 1j]], dtype=dtype), + dtype(7 + 5j), + expected=np.array([[-6 - 7j], [-5 - 4j]], dtype=dtype)) + + self._testBinary( + math_ops.multiply, + np.array([1 + 3j, 2 + 7j], dtype=dtype), + np.array([10 - 4j, 20 + 17j], dtype=dtype), + expected=np.array([(1 + 3j) * (10 - 4j), (2 + 7j) * (20 + 17j)], + dtype=dtype)) + self._testBinary( + math_ops.multiply, + dtype(5 - 7j), + np.array([1 + 2j, 2 + 4j], dtype=dtype), + expected=np.array([(5 - 7j) * (1 + 2j), (5 - 7j) * (2 + 4j)], + dtype=dtype)) + self._testBinary( + math_ops.multiply, + np.array([[1 - 2j], [2 + 1j]], dtype=dtype), + dtype(7 + 5j), + expected=np.array([[(7 + 5j) * (1 - 2j)], [(7 + 5j) * (2 + 1j)]], + dtype=dtype)) + + self._testBinary( + math_ops.div, + np.array([8 - 1j, 2 + 16j], dtype=dtype), + np.array([2 + 4j, 4 - 8j], dtype=dtype), + expected=np.array([(8 - 1j) / (2 + 4j), (2 + 16j) / (4 - 8j)], + dtype=dtype)) + self._testBinary( + math_ops.div, + dtype(1 + 2j), + np.array([2 + 4j, 4 - 8j], dtype=dtype), + expected=np.array([(1 + 2j) / (2 + 4j), (1 + 2j) / (4 - 8j)], + dtype=dtype)) + self._testBinary( + math_ops.div, + np.array([2 + 4j, 4 - 8j], dtype=dtype), + dtype(1 + 2j), + expected=np.array([(2 + 4j) / (1 + 2j), (4 - 8j) / (1 + 2j)], + dtype=dtype)) + + # TODO(b/68205550): math_ops.squared_difference shouldn't be supported. + + self._testBinary( + nn_ops.bias_add, + np.array([[1 + 2j, 2 + 7j], [3 - 5j, 4 + 2j]], dtype=dtype), + np.array([2 + 6j, -1 - 3j], dtype=dtype), + expected=np.array([[3 + 8j, 1 + 4j], [5 + 1j, 3 - 1j]], dtype=dtype)) + self._testBinary( + nn_ops.bias_add, + np.array([[[[1 + 4j, 2 - 1j], [3 + 7j, 4]]]], dtype=dtype), + np.array([2 + 1j, -1 + 2j], dtype=dtype), + expected=np.array([[[[3 + 5j, 1 + 1j], [5 + 8j, 3 + 2j]]]], + dtype=dtype)) + + def _testDivision(self, dtype): + """Test cases for division operators.""" + self._testBinary( + math_ops.div, + np.array([10, 20], dtype=dtype), + np.array([10, 2], dtype=dtype), + expected=np.array([1, 10], dtype=dtype)) + self._testBinary( + math_ops.div, + dtype(40), + np.array([2, 20], dtype=dtype), + expected=np.array([20, 2], dtype=dtype)) + self._testBinary( + math_ops.div, + np.array([[10], [4]], dtype=dtype), + dtype(2), + expected=np.array([[5], [2]], dtype=dtype)) + + if 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 + self._testBinary( + gen_math_ops.div_no_nan, + nums, + divs, + expected=np_result, + rtol=7e-15 if dtype == np.float64 else None, + atol=3.9e-15 if dtype == np.float64 else None) + + # floordiv/truncatediv unsupported for complex. + if dtype not in self.complex_types: + self._testBinary( + gen_math_ops.floor_div, + np.array([3, 3, -1, -9, -8], dtype=dtype), + np.array([2, -2, 7, 2, -4], dtype=dtype), + expected=np.array([1, -2, -1, -5, 2], dtype=dtype)) + + self._testBinary( + gen_math_ops.truncate_div, + np.array([3, 3, -1, -9, -8.1], dtype=dtype), + np.array([2, -2, 7, 2, -4], dtype=dtype), + expected=np.array([1, -1, 0, -4, 2], dtype=dtype)) + + if dtype in self.signed_int_types: + # Overflow cases. + int_min = np.iinfo(dtype).min + int_max = np.iinfo(dtype).max + self._testBinary( + gen_math_ops.floor_div, + np.array([int_min, -1, 1, int_max], dtype=dtype).reshape([1, 4]), + np.array([int_min, -1, 1, int_max], dtype=dtype).reshape([4, 1]), + expected=np.array([[1, 0, -1, -1], [int_min, 1, -1, -1 * int_max], + [int_min, -1, 1, int_max], [-2, -1, 0, 1]], + dtype=dtype)) + + def testIntDivision(self): + for dtype in self.signed_int_types: + self._testDivision(dtype) + + def testFloatDivision(self): + for dtype in self.float_types | self.complex_types: + self._testDivision(dtype) + + def _testRemainder(self, dtype): + """Test cases for remainder operators.""" + self._testBinary( + gen_math_ops.floor_mod, + np.array([3, 3, -1, -8], dtype=dtype), + np.array([2, -2, 7, -4], dtype=dtype), + expected=np.array([1, -1, 6, 0], dtype=dtype)) + self._testBinary( + gen_math_ops.truncate_mod, + np.array([3, 3, -1, -8], dtype=dtype), + np.array([2, -2, 7, -4], dtype=dtype), + expected=np.array([1, 1, -1, 0], dtype=dtype)) + if dtype in self.signed_int_types: + # Overflow cases. + int_min = np.iinfo(dtype).min + int_max = np.iinfo(dtype).max + self._testBinary( + gen_math_ops.floor_mod, + np.array([int_min, -1, 1, int_max], dtype=dtype).reshape([1, 4]), + np.array([int_min, -1, 1, int_max], dtype=dtype).reshape([4, 1]), + expected=np.array([[0, -1, -1 * int_max, -1], [0, 0, 0, 0], + [0, 0, 0, 0], [int_max - 1, int_max - 1, 1, 0]], + dtype=dtype)) + self._testBinary( + gen_math_ops.truncate_mod, + np.array([int_min, -1, 1, int_max], dtype=dtype).reshape([1, 4]), + np.array([int_min, -1, 1, int_max], dtype=dtype).reshape([4, 1]), + expected=np.array( + [[0, -1, 1, int_max], [0, 0, 0, 0], [0, 0, 0, 0], [-1, -1, 1, 0]], + dtype=dtype)) + + def testIntRemainder(self): + for dtype in self.signed_int_types - {np.int8}: + self._testRemainder(dtype) + + def testFloatRemainder(self): + for dtype in self.float_types: + self._testRemainder(dtype) + + def testLogicalOps(self): + self._testBinary( + math_ops.logical_and, + np.array([[True, False], [False, True]], dtype=np.bool_), + np.array([[False, True], [False, True]], dtype=np.bool_), + expected=np.array([[False, False], [False, True]], dtype=np.bool_)) + + self._testBinary( + math_ops.logical_or, + np.array([[True, False], [False, True]], dtype=np.bool_), + np.array([[False, True], [False, True]], dtype=np.bool_), + expected=np.array([[True, True], [False, True]], dtype=np.bool_)) + + def testComparisons(self): + self._testBinary( + math_ops.equal, + np.array([1, 5, 20], dtype=np.float32), + np.array([10, 5, 2], dtype=np.float32), + expected=np.array([False, True, False], dtype=np.bool_)) + self._testBinary( + math_ops.equal, + np.float32(5), + np.array([1, 5, 20], dtype=np.float32), + expected=np.array([False, True, False], dtype=np.bool_)) + self._testBinary( + math_ops.equal, + np.array([[10], [7], [2]], dtype=np.float32), + np.float32(7), + expected=np.array([[False], [True], [False]], dtype=np.bool_)) + + self._testBinary( + math_ops.not_equal, + np.array([1, 5, 20], dtype=np.float32), + np.array([10, 5, 2], dtype=np.float32), + expected=np.array([True, False, True], dtype=np.bool_)) + self._testBinary( + math_ops.not_equal, + np.float32(5), + np.array([1, 5, 20], dtype=np.float32), + expected=np.array([True, False, True], dtype=np.bool_)) + self._testBinary( + math_ops.not_equal, + np.array([[10], [7], [2]], dtype=np.float32), + np.float32(7), + expected=np.array([[True], [False], [True]], dtype=np.bool_)) + + for greater_op in [math_ops.greater, (lambda x, y: x > y)]: + self._testBinary( + greater_op, + np.array([1, 5, 20], dtype=np.float32), + np.array([10, 5, 2], dtype=np.float32), + expected=np.array([False, False, True], dtype=np.bool_)) + self._testBinary( + greater_op, + np.float32(5), + np.array([1, 5, 20], dtype=np.float32), + expected=np.array([True, False, False], dtype=np.bool_)) + self._testBinary( + greater_op, + np.array([[10], [7], [2]], dtype=np.float32), + np.float32(7), + expected=np.array([[True], [False], [False]], dtype=np.bool_)) + + for greater_equal_op in [math_ops.greater_equal, (lambda x, y: x >= y)]: + self._testBinary( + greater_equal_op, + np.array([1, 5, 20], dtype=np.float32), + np.array([10, 5, 2], dtype=np.float32), + expected=np.array([False, True, True], dtype=np.bool_)) + self._testBinary( + greater_equal_op, + np.float32(5), + np.array([1, 5, 20], dtype=np.float32), + expected=np.array([True, True, False], dtype=np.bool_)) + self._testBinary( + greater_equal_op, + np.array([[10], [7], [2]], dtype=np.float32), + np.float32(7), + expected=np.array([[True], [True], [False]], dtype=np.bool_)) + + for less_op in [math_ops.less, (lambda x, y: x < y)]: + self._testBinary( + less_op, + np.array([1, 5, 20], dtype=np.float32), + np.array([10, 5, 2], dtype=np.float32), + expected=np.array([True, False, False], dtype=np.bool_)) + self._testBinary( + less_op, + np.float32(5), + np.array([1, 5, 20], dtype=np.float32), + expected=np.array([False, False, True], dtype=np.bool_)) + self._testBinary( + less_op, + np.array([[10], [7], [2]], dtype=np.float32), + np.float32(7), + expected=np.array([[False], [False], [True]], dtype=np.bool_)) + if np.int64 in self.numeric_types: + self._testBinary( + less_op, + np.array([[10], [7], [2], [-1]], dtype=np.int64), + np.int64(7), + expected=np.array([[False], [False], [True], [True]], + dtype=np.bool_)) + + for less_equal_op in [math_ops.less_equal, (lambda x, y: x <= y)]: + self._testBinary( + less_equal_op, + np.array([1, 5, 20], dtype=np.float32), + np.array([10, 5, 2], dtype=np.float32), + expected=np.array([True, True, False], dtype=np.bool_)) + self._testBinary( + less_equal_op, + np.float32(5), + np.array([1, 5, 20], dtype=np.float32), + expected=np.array([False, True, True], dtype=np.bool_)) + self._testBinary( + less_equal_op, + np.array([[10], [7], [2]], dtype=np.float32), + np.float32(7), + expected=np.array([[False], [True], [True]], dtype=np.bool_)) + + def testS64Comparisons(self): + for op in [(lambda x, y: x < y), (lambda x, y: x <= y), + (lambda x, y: x >= y), (lambda x, y: x > y)]: + lhs = np.array([ + np.int64(0x000000007FFFFFFF), + np.int64(0x000000007FFFFFFF), + np.int64(0x0000000080000000), + np.int64(0x0000000080000000), + np.int64(0x0000000080000001), + np.int64(0x00000000FFFF0000), + np.int64(0x00000000FFFF0000), + np.int64(0x00000000FFFFFFFE), + np.int64(0x00000000FFFFFFFF), + np.int64(0x00000000FFFFFFFF), + np.int64(0x0000000100000000), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(0x0000000200000002), + np.int64(-0x7FFFFFFF00000002), + np.int64(-0x7FFFFFFF00000002), + np.int64(-0x7FFFFFFF00000001), + np.int64(-0x7FFFFFFF00000001), + np.int64(-0x7FFFFFFF00000001), + np.int64(-0x7FFFFFFF00000001), + np.int64(0x7ffffffefff00010), + np.int64(0x7ffffffefff00010), + np.int64(-1), + np.int64(-1) + ], + dtype=np.int64) + rhs = np.array([ + np.int64(0x000000007FFFFFFE), + np.int64(0x000000007FFFFFFF), + np.int64(0x000000007FFFFFFF), + np.int64(0x0000000080000000), + np.int64(0x0000000080000001), + np.int64(0x00000000FFFF0000), + np.int64(0x00000000FFFF0001), + np.int64(0x00000000FFFFFFFF), + np.int64(0x00000000FFFFFFFE), + np.int64(0x00000000FFFFFFFF), + np.int64(0x00000000FFFFFFFF), + np.int64(0x0000000100000001), + np.int64(0x0000000100000002), + np.int64(0x0000000100000003), + np.int64(0x0000000200000001), + np.int64(0x0000000200000002), + np.int64(0x0000000200000003), + np.int64(0x0000000300000001), + np.int64(0x0000000300000002), + np.int64(0x0000000300000003), + np.int64(0x00000000FFFFFFFF), + np.int64(-0x7FFFFFFF00000001), + np.int64(0x00000000FFFFFFFE), + np.int64(0x00000000FFFFFFFF), + np.int64(-0x7FFFFFFF00000002), + np.int64(-0x7FFFFFFF00000001), + np.int64(0x00000000FFFFFFFF), + np.int64(-0x7FFFFFFF00000001), + np.int64(-2), + np.int64(-1) + ], + dtype=np.int64) + expected = np.array([op(l, r) for l, r in zip(lhs, rhs)], dtype=np.bool_) + self._testBinary(op, lhs, rhs, expected=expected) + + def testBroadcasting(self): + """Tests broadcasting behavior of an operator.""" + + for dtype in self.numeric_types: + self._testBinary( + math_ops.add, + np.array(3, dtype=dtype), + np.array([10, 20], dtype=dtype), + expected=np.array([13, 23], dtype=dtype)) + self._testBinary( + math_ops.add, + np.array([10, 20], dtype=dtype), + np.array(4, dtype=dtype), + expected=np.array([14, 24], dtype=dtype)) + + # [1,3] x [4,1] => [4,3] + self._testBinary( + math_ops.add, + np.array([[10, 20, 30]], dtype=dtype), + np.array([[1], [2], [3], [4]], dtype=dtype), + expected=np.array( + [[11, 21, 31], [12, 22, 32], [13, 23, 33], [14, 24, 34]], + dtype=dtype)) + + # [3] * [4,1] => [4,3] + self._testBinary( + math_ops.add, + np.array([10, 20, 30], dtype=dtype), + np.array([[1], [2], [3], [4]], dtype=dtype), + expected=np.array( + [[11, 21, 31], [12, 22, 32], [13, 23, 33], [14, 24, 34]], + dtype=dtype)) + + def testFill(self): + for dtype in self.numeric_types: + self._testBinary( + array_ops.fill, + np.array([], dtype=np.int32), + dtype(42), + expected=dtype(42)) + self._testBinary( + array_ops.fill, + np.array([1, 2], dtype=np.int32), + dtype(7), + expected=np.array([[7, 7]], dtype=dtype)) + self._testBinary( + array_ops.fill, + np.array([3, 2], dtype=np.int32), + dtype(50), + expected=np.array([[50, 50], [50, 50], [50, 50]], dtype=dtype)) + + # Helper method used by testMatMul, testSparseMatMul below. + def _testMatMul(self, op, test_dtypes): + for dtype in test_dtypes: + self._testBinary( + op, + np.array([[-0.25]], dtype=dtype), + np.array([[8]], dtype=dtype), + expected=np.array([[-2]], dtype=dtype)) + self._testBinary( + op, + np.array([[100, 10, 0.5]], dtype=dtype), + np.array([[1, 3], [2, 5], [6, 8]], dtype=dtype), + expected=np.array([[123, 354]], dtype=dtype)) + self._testBinary( + op, + np.array([[1, 3], [2, 5], [6, 8]], dtype=dtype), + np.array([[100], [10]], dtype=dtype), + expected=np.array([[130], [250], [680]], dtype=dtype)) + self._testBinary( + op, + np.array([[1000, 100], [10, 1]], dtype=dtype), + np.array([[1, 2], [3, 4]], dtype=dtype), + expected=np.array([[1300, 2400], [13, 24]], dtype=dtype)) + + self._testBinary( + op, + np.array([], dtype=dtype).reshape((2, 0)), + np.array([], dtype=dtype).reshape((0, 3)), + expected=np.array([[0, 0, 0], [0, 0, 0]], dtype=dtype)) + + def testMatMul(self): + self._testMatMul(math_ops.matmul, self.float_types | {np.float64}) + + for dtype in self.float_types | {np.float64}: + self._testBinary( + math_ops.matmul, + np.array([[3.1415926535897932]], dtype=dtype), + np.array([[2.7182818284590452]], dtype=dtype), + expected=np.array([[8.5397342226735668]], dtype=dtype), + rtol=1e-14) + + # Edge case with a large range of exponent. Not supported by float16. + if dtype != np.float16: + self._testBinary( + math_ops.matmul, + np.array([[9.4039548065783000e-38]], dtype=dtype), + np.array([[4.5070591730234615e37]], dtype=dtype), + expected=np.array([[4.2384180773686798]], dtype=dtype), + rtol=1e-14) + + def testSparseMatMul(self): + # Binary wrappers for sparse_matmul with different hints + def SparseMatmulWrapperTF(a, b): + return math_ops.sparse_matmul(a, b, a_is_sparse=True) + + def SparseMatmulWrapperFT(a, b): + return math_ops.sparse_matmul(a, b, b_is_sparse=True) + + def SparseMatmulWrapperTT(a, b): + return math_ops.sparse_matmul(a, b, a_is_sparse=True, b_is_sparse=True) + + # TODO(b/314165739): SparseMatmul XlaBuilder lowering does not support + # float16 and float64. + float_types = self.float_types - {np.float16, np.float64} + self._testMatMul(math_ops.sparse_matmul, float_types) + self._testMatMul(SparseMatmulWrapperTF, float_types) + self._testMatMul(SparseMatmulWrapperFT, float_types) + self._testMatMul(SparseMatmulWrapperTT, float_types) + + def testBatchMatMul(self): + # Tests with batches of matrices. + for dtype in self.float_types | {np.float64}: + self._testBinary( + math_ops.matmul, + np.array([[[-0.25]]], dtype=dtype), + np.array([[[8]]], dtype=dtype), + expected=np.array([[[-2]]], dtype=dtype)) + self._testBinary( + math_ops.matmul, + np.array([[[-0.25]], [[4]]], dtype=dtype), + np.array([[[8]], [[2]]], dtype=dtype), + expected=np.array([[[-2]], [[8]]], dtype=dtype)) + self._testBinary( + math_ops.matmul, + np.array([[[[7, 13], [10, 1]], [[2, 0.25], [20, 2]]], + [[[3, 5], [30, 3]], [[0.75, 1], [40, 4]]]], + dtype=dtype), + np.array([[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], + [[[11, 22], [33, 44]], [[55, 66], [77, 88]]]], + dtype=dtype), + expected=np.array( + [[[[46, 66], [13, 24]], [[11.75, 14], [114, 136]]], + [[[198, 286], [429, 792]], [[118.25, 137.5], [2508, 2992]]]], + dtype=dtype)) + + self._testBinary( + math_ops.matmul, + np.array([], dtype=dtype).reshape((2, 2, 0)), + np.array([], dtype=dtype).reshape((2, 0, 3)), + expected=np.array([[[0, 0, 0], [0, 0, 0]], [[0, 0, 0], [0, 0, 0]]], + dtype=dtype)) + self._testBinary( + math_ops.matmul, + np.array([], dtype=dtype).reshape((0, 2, 4)), + np.array([], dtype=dtype).reshape((0, 4, 3)), + expected=np.array([], dtype=dtype).reshape(0, 2, 3)) # pylint: disable=too-many-function-args + + # Regression test for b/31472796. + if dtype != np.float16 and hasattr(np, "matmul"): + x = np.arange(0, 3 * 5 * 2 * 7, dtype=dtype).reshape((3, 5, 2, 7)) + self._testBinary( + lambda x, y: math_ops.matmul(x, y, adjoint_b=True), + x, + x, + expected=np.matmul(x, x.transpose([0, 1, 3, 2]))) + + def testBatchMatMulMixedPrecision(self): + # Verify that accumulation happens in the specified output type int32 by + # using a result (16 * 16 * 16) that doesn't fit in int8. + self._testBinary( + lambda x, y: math_ops.matmul(x, y, output_type=np.int32), + np.tile(np.array([[[16]]], dtype=np.int8), (1, 1, 16)), + np.tile(np.array([[[16]]], dtype=np.int8), (1, 16, 1)), + expected=np.array([[[16 * 16 * 16]]], dtype=np.int32)) + + def testExpandDims(self): + for dtype in self.numeric_types: + self._testBinary( + array_ops.expand_dims, + dtype(7), + np.int32(0), + expected=np.array([7], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([42], dtype=dtype), + np.array([0], dtype=np.int64), + expected=np.array([[42]], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([], dtype=dtype), + np.int32(0), + expected=np.array([[]], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([[[1, 2], [3, 4]]], dtype=dtype), + np.int32(0), + expected=np.array([[[[1, 2], [3, 4]]]], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([[[1, 2], [3, 4]]], dtype=dtype), + np.int32(1), + expected=np.array([[[[1, 2], [3, 4]]]], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([[[1, 2], [3, 4]]], dtype=dtype), + np.int32(2), + expected=np.array([[[[1, 2]], [[3, 4]]]], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([[[1, 2], [3, 4]]], dtype=dtype), + np.int32(3), + expected=np.array([[[[1], [2]], [[3], [4]]]], dtype=dtype)) + self._testBinary( + array_ops.expand_dims, + np.array([[[1, 2], [3, 4]]], dtype=dtype), + np.array([2], dtype=np.int64), + expected=np.array([[[[1, 2]], [[3, 4]]]], dtype=dtype)) + + def testBatchMatMulBroadcast(self): + """Tests broadcasting behavior of BatchMatMul.""" + # [2, 3] @ [1, 3, 4] -> [1, 2, 4] + self._testBinary( + math_ops.matmul, + np.array([[10, 20, 30], [11, 21, 31]], dtype=np.float32), + np.array([[[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]]], + dtype=np.float32), + expected=np.array([[[140, 280, 420, 560], [146, 292, 438, 584]]], + dtype=np.float32)) + # [1, 2, 3] @ [3, 4] -> [1, 2, 4] + self._testBinary( + math_ops.matmul, + np.array([[[10, 20, 30], [11, 21, 31]]], dtype=np.float32), + np.array([[1, 2, 3, 4], [2, 4, 6, 8], [3, 6, 9, 12]], dtype=np.float32), + expected=np.array([[[140, 280, 420, 560], [146, 292, 438, 584]]], + dtype=np.float32)) + # [2, 1, 3] @ [3, 1] -> [2, 1, 1] + self._testBinary( + math_ops.matmul, + np.array([[[10, 20, 30]], [[11, 21, 31]]], dtype=np.float32), + np.array([[1], [2], [3]], dtype=np.float32), + expected=np.array([[[140]], [[146]]], dtype=np.float32)) + # [2, 1, 3] @ [1, 3] -> [2, 1, 1] (adjoint_b) + self._testBinary( + lambda x, y: math_ops.matmul(x, y, adjoint_b=True), + np.array([[[10, 20, 30]], [[11, 21, 31]]], dtype=np.float32), + np.array([[1, 2, 3]], dtype=np.float32), + expected=np.array([[[140]], [[146]]], dtype=np.float32)) + # [2, 3, 1] @ [3, 1] -> [2, 1, 1] (adjoint_a) + self._testBinary( + lambda x, y: math_ops.matmul(x, y, adjoint_a=True), + np.array([[[10], [20], [30]], [[11], [21], [31]]], dtype=np.float32), + np.array([[1], [2], [3]], dtype=np.float32), + expected=np.array([[[140]], [[146]]], dtype=np.float32)) + # [2, 3, 1] @ [1, 3] -> [2, 1, 1] (adjoint_a and adjoint_b) + self._testBinary( + lambda x, y: math_ops.matmul(x, y, adjoint_a=True, adjoint_b=True), + np.array([[[10], [20], [30]], [[11], [21], [31]]], dtype=np.float32), + np.array([[1, 2, 3]], dtype=np.float32), + expected=np.array([[[140]], [[146]]], dtype=np.float32)) + # [5, 1, 2, 3] @ [1, 7, 3, 4] -> [5, 7, 2, 4] + self._testBinary( + math_ops.matmul, + np.ones([5, 1, 2, 3], dtype=np.float32), + np.ones([1, 7, 3, 4], dtype=np.float32), + expected=np.full([5, 7, 2, 4], 3, dtype=np.float32)) + # [4, 5, 1, 2, 3] @ [1, 1, 3, 5] -> [4, 5, 1, 2, 5] + self._testBinary( + math_ops.matmul, + np.full([4, 5, 1, 2, 3], 2., dtype=np.float32), + np.full([1, 1, 3, 5], 3., dtype=np.float32), + expected=np.full([4, 5, 1, 2, 5], 18., dtype=np.float32)) + + def testPad(self): + for dtype, pad_type in itertools.product(self.numeric_types, + [np.int32, np.int64]): + self._testBinary( + array_ops.pad, + np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype), + np.array([[1, 2], [2, 1]], dtype=pad_type), + expected=np.array( + [[0, 0, 0, 0, 0, 0], [0, 0, 1, 2, 3, 0], [0, 0, 4, 5, 6, 0], + [0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0]], + dtype=dtype)) + + self._testBinary( + lambda x, y: array_ops.pad(x, y, constant_values=7), + np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype), + np.array([[0, 3], [2, 1]], dtype=pad_type), + expected=np.array( + [[7, 7, 1, 2, 3, 7], [7, 7, 4, 5, 6, 7], [7, 7, 7, 7, 7, 7], + [7, 7, 7, 7, 7, 7], [7, 7, 7, 7, 7, 7]], + dtype=dtype)) + + def testSymmetricMirrorPad(self): + mirror_pad = lambda t, paddings: array_ops.pad(t, paddings, "SYMMETRIC") + for dtype in self.numeric_types: + self._testBinary( + mirror_pad, + np.array( + [ + [1, 2, 3], # + [4, 5, 6], # + ], + dtype=dtype), + np.array([[ + 2, + 2, + ], [3, 3]], dtype=np.int32), + expected=np.array( + [ + [6, 5, 4, 4, 5, 6, 6, 5, 4], # + [3, 2, 1, 1, 2, 3, 3, 2, 1], # + [3, 2, 1, 1, 2, 3, 3, 2, 1], # + [6, 5, 4, 4, 5, 6, 6, 5, 4], # + [6, 5, 4, 4, 5, 6, 6, 5, 4], # + [3, 2, 1, 1, 2, 3, 3, 2, 1], # + ], + dtype=dtype)) + self._testBinary( + mirror_pad, + np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype), + np.array([[0, 0], [0, 0]], dtype=np.int32), + expected=np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype)) + + def testReflectMirrorPad(self): + mirror_pad = lambda t, paddings: array_ops.pad(t, paddings, "REFLECT") + for dtype in self.numeric_types: + self._testBinary( + mirror_pad, + np.array( + [ + [1, 2, 3], # + [4, 5, 6], # + ], + dtype=dtype), + np.array([[ + 1, + 1, + ], [2, 2]], dtype=np.int32), + expected=np.array( + [ + [6, 5, 4, 5, 6, 5, 4], # + [3, 2, 1, 2, 3, 2, 1], # + [6, 5, 4, 5, 6, 5, 4], # + [3, 2, 1, 2, 3, 2, 1] + ], + dtype=dtype)) + self._testBinary( + mirror_pad, + np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype), + np.array([[0, 0], [0, 0]], dtype=np.int32), + expected=np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype)) + self._testBinary( + mirror_pad, + np.array( + [ + [1, 2, 3], # + [4, 5, 6], # + [7, 8, 9] + ], + dtype=dtype), + np.array([[2, 2], [0, 0]], dtype=np.int32), + expected=np.array( + [ + [7, 8, 9], # + [4, 5, 6], # + [1, 2, 3], # + [4, 5, 6], # + [7, 8, 9], # + [4, 5, 6], # + [1, 2, 3] + ], + dtype=dtype)) + self._testBinary( + mirror_pad, + np.array([ + [[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]], + ], + dtype=dtype), + np.array([[0, 0], [1, 1], [1, 1]], dtype=np.int32), + expected=np.array( + [ + [ + [5, 4, 5, 6, 5], # + [2, 1, 2, 3, 2], # + [5, 4, 5, 6, 5], # + [2, 1, 2, 3, 2], # + ], + [ + [11, 10, 11, 12, 11], # + [8, 7, 8, 9, 8], # + [11, 10, 11, 12, 11], # + [8, 7, 8, 9, 8], # + ] + ], + dtype=dtype)) + + def testSymmetricMirrorPadGrad(self): + mirror_pad_grad = lambda t, paddings: gen_array_ops.mirror_pad_grad( + t, paddings, "SYMMETRIC") + for dtype in self.numeric_types: + self._testBinary( + mirror_pad_grad, + np.broadcast_to(np.arange(0, 7, dtype=dtype), (3, 2, 1, 7)), + np.array([ + [1, 1], + [0, 0], + [0, 0], + [2, 2], + ], dtype=np.int32), + expected=np.broadcast_to( + np.array([9, 27, 27], dtype=dtype), (1, 2, 1, 3))) + + def testReflectMirrorPadGrad(self): + mirror_pad_grad = lambda t, paddings: gen_array_ops.mirror_pad_grad( + t, paddings, "REFLECT") + for dtype in self.numeric_types: + self._testBinary( + mirror_pad_grad, + np.broadcast_to( + np.reshape(np.arange(0, 7, dtype=dtype), (7, 1)), (1, 4, 7, 1)), + np.array([ + [0, 0], + [1, 1], + [2, 2], + [0, 0], + ], dtype=np.int32), + expected=np.broadcast_to( + np.reshape(np.array([16, 18, 8], dtype=dtype), (3, 1)), + (1, 2, 3, 1))) + + def testReshape(self): + for dtype in self.numeric_types: + self._testBinary( + array_ops.reshape, + np.array([], dtype=dtype), + np.array([0, 4], dtype=np.int32), + expected=np.zeros(shape=[0, 4], dtype=dtype)) + self._testBinary( + array_ops.reshape, + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([2, 3], dtype=np.int32), + expected=np.array([[0, 1, 2], [3, 4, 5]], dtype=dtype)) + self._testBinary( + array_ops.reshape, + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([3, 2], dtype=np.int32), + expected=np.array([[0, 1], [2, 3], [4, 5]], dtype=dtype)) + self._testBinary( + array_ops.reshape, + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([-1, 6], dtype=np.int32), + expected=np.array([[0, 1, 2, 3, 4, 5]], dtype=dtype)) + self._testBinary( + array_ops.reshape, + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([6, -1], dtype=np.int32), + expected=np.array([[0], [1], [2], [3], [4], [5]], dtype=dtype)) + self._testBinary( + array_ops.reshape, + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([2, -1], dtype=np.int32), + expected=np.array([[0, 1, 2], [3, 4, 5]], dtype=dtype)) + self._testBinary( + array_ops.reshape, + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([-1, 3], dtype=np.int32), + expected=np.array([[0, 1, 2], [3, 4, 5]], dtype=dtype)) + + def testSplit(self): + for dtype in self.numeric_types: + for axis in [0, -3]: + self._testBinary( + lambda x, y: array_ops.split(value=y, num_or_size_splits=3, axis=x), + np.int32(axis), + np.array([[[1], [2]], [[3], [4]], [[5], [6]]], dtype=dtype), + expected=[ + np.array([[[1], [2]]], dtype=dtype), + np.array([[[3], [4]]], dtype=dtype), + np.array([[[5], [6]]], dtype=dtype), + ], + equality_test=self.ListsAreClose) + + for axis in [1, -2]: + self._testBinary( + lambda x, y: array_ops.split(value=y, num_or_size_splits=2, axis=x), + np.int32(axis), + np.array([[[1], [2]], [[3], [4]], [[5], [6]]], dtype=dtype), + expected=[ + np.array([[[1]], [[3]], [[5]]], dtype=dtype), + np.array([[[2]], [[4]], [[6]]], dtype=dtype), + ], + equality_test=self.ListsAreClose) + + def splitvOp(x, y): # pylint: disable=invalid-name + return array_ops.split(value=y, num_or_size_splits=[2, 3], axis=x) + + for axis in [1, -1]: + self._testBinary( + splitvOp, + np.int32(axis), + np.array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]], dtype=dtype), + expected=[ + np.array([[0, 1], [5, 6]], dtype=dtype), + np.array([[2, 3, 4], [7, 8, 9]], dtype=dtype), + ], + equality_test=self.ListsAreClose) + + def testTile(self): + 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)) + self._testBinary( + array_ops.tile, + np.array([[1], [2]], dtype=dtype), + np.array([1, 2], dtype=np.int32), + expected=np.array([[1, 1], [2, 2]], dtype=dtype)) + self._testBinary( + array_ops.tile, + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([3, 2], dtype=np.int32), + expected=np.array([[1, 2, 1, 2], [3, 4, 3, 4], [1, 2, 1, 2], + [3, 4, 3, 4], [1, 2, 1, 2], [3, 4, 3, 4]], + dtype=dtype)) + self._testBinary( + array_ops.tile, + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([1, 1], dtype=np.int32), + expected=np.array([[1, 2], [3, 4]], dtype=dtype)) + self._testBinary( + array_ops.tile, + np.array([[1, 2]], dtype=dtype), + np.array([3, 1], dtype=np.int32), + expected=np.array([[1, 2], [1, 2], [1, 2]], dtype=dtype)) + + def testTranspose(self): + for dtype in self.numeric_types: + self._testBinary( + array_ops.transpose, + np.zeros(shape=[1, 0, 4], dtype=dtype), + np.array([1, 2, 0], dtype=np.int32), + expected=np.zeros(shape=[0, 4, 1], dtype=dtype)) + self._testBinary( + array_ops.transpose, + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([0, 1], dtype=np.int32), + expected=np.array([[1, 2], [3, 4]], dtype=dtype)) + self._testBinary( + array_ops.transpose, + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([1, 0], dtype=np.int32), + expected=np.array([[1, 3], [2, 4]], dtype=dtype)) + + def testConjugateTranspose(self): + for dtype in self.complex_types: + self._testBinary( + array_ops.conjugate_transpose, + np.zeros(shape=[1, 0, 4], dtype=dtype), + np.array([1, 2, 0], dtype=np.int32), + expected=np.zeros(shape=[0, 4, 1], dtype=dtype)) + self._testBinary( + array_ops.conjugate_transpose, + np.array([[1 - 1j, 2 + 2j], [3 - 3j, 4 + 4j]], dtype=dtype), + np.array([0, 1], dtype=np.int32), + expected=np.array([[1 + 1j, 2 - 2j], [3 + 3j, 4 - 4j]], dtype=dtype)) + self._testBinary( + array_ops.conjugate_transpose, + np.array([[1 - 1j, 2 + 2j], [3 - 3j, 4 + 4j]], dtype=dtype), + np.array([1, 0], dtype=np.int32), + expected=np.array([[1 + 1j, 3 + 3j], [2 - 2j, 4 - 4j]], dtype=dtype)) + + def testCross(self): + for dtype in self.float_types: + self._testBinary( + gen_math_ops.cross, + np.zeros((4, 3), dtype=dtype), + np.zeros((4, 3), dtype=dtype), + expected=np.zeros((4, 3), dtype=dtype)) + self._testBinary( + gen_math_ops.cross, + np.array([1, 2, 3], dtype=dtype), + np.array([4, 5, 6], dtype=dtype), + expected=np.array([-3, 6, -3], dtype=dtype)) + self._testBinary( + gen_math_ops.cross, + np.array([[1, 2, 3], [10, 11, 12]], dtype=dtype), + np.array([[4, 5, 6], [40, 50, 60]], dtype=dtype), + expected=np.array([[-3, 6, -3], [60, -120, 60]], dtype=dtype)) + + def testBroadcastArgs(self): + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([2, 3, 5], dtype=np.int32), + np.array([1], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([1], dtype=np.int32), + np.array([2, 3, 5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([2, 3, 5], dtype=np.int32), + np.array([5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([5], dtype=np.int32), + np.array([2, 3, 5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([2, 3, 5], dtype=np.int32), + np.array([3, 5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([3, 5], dtype=np.int32), + np.array([2, 3, 5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([2, 3, 5], dtype=np.int32), + np.array([3, 1], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([3, 1], dtype=np.int32), + np.array([2, 3, 5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([2, 1, 5], dtype=np.int32), + np.array([3, 1], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([3, 1], dtype=np.int32), + np.array([2, 1, 5], dtype=np.int32), + expected=np.array([2, 3, 5], dtype=np.int32)) + + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([2, 3, 5], dtype=np.int64), + np.array([1], dtype=np.int64), + expected=np.array([2, 3, 5], dtype=np.int64)) + + @test_util.disable_mlir_bridge("Error handling") + def testBroadcastArgsError(self): + with self.assertRaisesIncompatibleShapesError(): + self._testBinary( + array_ops.broadcast_dynamic_shape, + np.array([1, 2, 3], dtype=np.int32), + np.array([4, 5, 6], dtype=np.int32), + expected=None) + + def testBroadcastTo(self): + for dtype in self.all_types: + x = np.random.randint(0, high=100, size=[2, 3]) + self._testBinary( + array_ops.broadcast_to, + x, + np.array([2, 3], dtype=np.int32), + expected=x) + self._testBinary( + array_ops.broadcast_to, + np.zeros([2, 3], dtype=dtype), + np.array([2, 2, 3], dtype=np.int32), + expected=np.zeros([2, 2, 3], dtype=dtype)) + + x = np.arange(2).reshape((2, 1)).astype(dtype) + self._testBinary( + array_ops.broadcast_to, + x, + np.array([2, 2, 3], dtype=np.int32), + expected=np.tile(x, (2, 1, 3))) + + x = np.arange(3).reshape((3, 1, 1, 1)).astype(dtype) + self._testBinary( + array_ops.broadcast_to, + x, + np.array((3, 7, 8, 9), dtype=np.int32), + expected=np.tile(x, (1, 7, 8, 9))) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/bincount_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/bincount_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..433db4589c5ca6b8a1fac48b2257d107b9939cc5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/bincount_op_test.py @@ -0,0 +1,74 @@ +# Copyright 2023 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 bincount using the XLA JIT.""" +from tensorflow.compiler.tests import xla_test +from tensorflow.python.compat import v2_compat +from tensorflow.python.eager import def_function +from tensorflow.python.framework import errors +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.platform import googletest + + +class BincountTest(xla_test.XLATestCase): + + def testInputRank0(self): + with self.session(): + with self.test_scope(): + bincount = gen_math_ops.bincount(arr=6, size=804, weights=[52, 351]) + + with self.assertRaisesRegex( + errors.InvalidArgumentError, + ( + "`weights` must be the same shape as `arr` or a length-0" + " `Tensor`, in which case it acts as all weights equal to 1." + ), + ): + self.evaluate(bincount) + + def testNegativeInputConstant(self): + with self.session(): + with self.test_scope(): + + @def_function.function(jit_compile=True) + def f(): + return gen_math_ops.dense_bincount( + input=array_ops.constant([0, -1, 2]), size=3, weights=[] + ) + + with self.assertRaisesRegex( + errors.InvalidArgumentError, "Input arr must be non-negative!" + ): + self.evaluate(f()) + + def testNegativeInputConstantBincount(self): + with self.session(): + with self.test_scope(): + + @def_function.function(jit_compile=True) + def f(): + return gen_math_ops.bincount( + arr=array_ops.constant([0, -1, 2]), size=3, weights=[] + ) + + with self.assertRaisesRegex( + errors.InvalidArgumentError, "Input arr must be non-negative!" + ): + self.evaluate(f()) + + +if __name__ == "__main__": + v2_compat.enable_v2_behavior() + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/bucketize_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/bucketize_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..acb3c15cab333f6f777404337544a864bbdfe71d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/bucketize_op_test.py @@ -0,0 +1,76 @@ +# 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 bucketize_op.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +class BucketizationOpTest(xla_test.XLATestCase): + + def testInt(self): + with self.session() as sess: + p = array_ops.placeholder(dtypes.int32) + with self.test_scope(): + op = math_ops._bucketize(p, boundaries=[0, 3, 8, 11]) + expected_out = [0, 1, 1, 2, 2, 3, 3, 4, 4] + self.assertAllEqual(expected_out, + sess.run(op, {p: [-5, 0, 2, 3, 5, 8, 10, 11, 12]})) + + def testFloat(self): + with self.session() as sess: + p = array_ops.placeholder(dtypes.float32) + with self.test_scope(): + op = math_ops._bucketize(p, boundaries=[0., 3., 8., 11.]) + expected_out = [0, 1, 1, 2, 2, 3, 3, 4, 4] + self.assertAllEqual( + expected_out, + sess.run(op, {p: [-5., 0., 2., 3., 5., 8., 10., 11., 12.]})) + + def test2DInput(self): + with self.session() as sess: + p = array_ops.placeholder(dtypes.float32) + with self.test_scope(): + op = math_ops._bucketize(p, boundaries=[0, 3, 8, 11]) + expected_out = [[0, 1, 1, 2, 2], [3, 3, 4, 4, 1]] + self.assertAllEqual( + expected_out, sess.run(op, + {p: [[-5, 0, 2, 3, 5], [8, 10, 11, 12, 0]]})) + + @test_util.disable_mlir_bridge("Error handling") + def testInvalidBoundariesOrder(self): + with self.session() as sess: + p = array_ops.placeholder(dtypes.int32) + with self.test_scope(): + op = math_ops._bucketize(p, boundaries=[0, 8, 3, 11]) + with self.assertRaisesRegex(errors_impl.InvalidArgumentError, + "Expected sorted boundaries"): + sess.run(op, {p: [-5, 0]}) + + def testBoundariesNotList(self): + with self.session(): + with self.assertRaisesRegex(TypeError, "Expected list.*"): + p = array_ops.placeholder(dtypes.int32) + with self.test_scope(): + math_ops._bucketize(p, boundaries=0) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/build_combined_defs.bzl b/western_ai/usa/tensorflow/tensorflow/compiler/tests/build_combined_defs.bzl new file mode 100644 index 0000000000000000000000000000000000000000..4451009f9577f1b7858425476d9d331b5dd46ded --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/build_combined_defs.bzl @@ -0,0 +1,63 @@ +"""Build rule for combining Tensorflow/XLA tests.""" + +load("//tensorflow:tensorflow.bzl", "py_test") +load("//tensorflow/compiler/tests:build_defs.bzl", "tf_xla_py_test") + +def parse_label_name(label): + """Parse a label into just the name. + + Args: + label: string in relative or absolute form. + + Returns: + The name of the label. + """ + colon_split = label.split(":") + if len(colon_split) == 1: # no ":" in label + return label + return colon_split[-1] + +def tf_xla_combined_py_test(name = "", package = None, tests = [], **kwargs): + """Generates combined tf_xla_py_test targets, one per XLA backend. + + All srcs found in the list tests are combined into one new test which is then passed on to + tf_xla_py_test which creates a new target per XLA backend. + + Args: + name: Name of the target. + package: The package that all tests in tests belong to. + tests: The test targets to be combined and tested. Assumes all tests are in the same package. + **kwargs: keyword arguments passed onto the tf_xla_py_test rule. + """ + + test_file = name + ".py" + + # run the generator to create the combined test file containing all the tests in test_files + # redirecting the output of the generator to test_file. + native.genrule( + name = name + "_gen", + testonly = 1, + srcs = tests, + outs = [test_file], + cmd = """ +mkdir -p $(@D) && cat > $@ << EOF +from tensorflow.python.platform import test +%s + +if __name__ == "__main__": + test.main() +EOF + """ % "\n".join(["from %s.%s import *" % (package, parse_label_name(test)[:-4]) for test in tests]), + tools = [], + tags = ["generated_python_test=%s.%s" % (package, name)], + ) + + tf_xla_py_test( + name = name, + test_rule = py_test, + srcs = [test_file], + deps = [ + "//tensorflow/python/platform:client_testlib", + ] + tests, + **kwargs + ) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/build_defs.bzl b/western_ai/usa/tensorflow/tensorflow/compiler/tests/build_defs.bzl new file mode 100644 index 0000000000000000000000000000000000000000..354645770aae0c86e4ce4dd9724ebfb3715a4b0c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/build_defs.bzl @@ -0,0 +1,168 @@ +"""Build rules for Tensorflow/XLA testing.""" + +load("@xla//third_party/rules_python/python:defs.bzl", "py_library") +load("//tensorflow:tensorflow.bzl", "py_test") +load("//tensorflow/compiler/tests:plugin.bzl", "plugins") +load( + "//tensorflow/core/platform:build_config_root.bzl", + "tf_cuda_tests_tags", + "tf_exec_properties", +) + +all_backends = ["cpu", "gpu"] + plugins.keys() + +def tf_xla_py_test( + name, + srcs = [], + deps = [], + tags = [], + data = [], + main = None, + enabled_backends = None, + disabled_backends = None, + use_xla_device = True, + enable_mlir_bridge = True, + test_rule = py_test, + **kwargs): + """Generates py_test targets, one per XLA backend. + + This rule generates py_test() targets named name_backend, for each backend + in all_backends. The rule also generates a test suite with named `name` that + tests all backends for the test. + + For example, the following rule generates test cases foo_test_cpu, + foo_test_gpu, and a test suite name foo_test that tests both. + tf_xla_py_test( + name="foo_test", + srcs="foo_test.py", + deps=[...], + ) + + Args: + name: Name of the target. + srcs: Sources for the target. + deps: Dependencies of the target. + tags: Tags to apply to the generated targets. + data: Data dependencies of the target. + main: Same as py_test's main attribute. + enabled_backends: A list of backends that should be tested. Supported + values include "cpu" and "gpu". If not specified, defaults to None. + disabled_backends: A list of backends that should not be tested. Supported + values include "cpu" and "gpu". If not specified, defaults to None. + use_xla_device: If true then the --test_device argument is set to XLA_CPU + and XLA_GPU for the CPU and GPU tests. Otherwise it is set to CPU and + GPU. + enable_mlir_bridge: If true, then runs the test with and without mlir + bridge enabled. + **kwargs: keyword arguments passed onto the generated py_test() rules. + """ + if enabled_backends == None: + enabled_backends = all_backends + if disabled_backends == None: + disabled_backends = [] + if type(disabled_backends) != "list": + fail("disabled_backends must be a list of strings", "disabled_backends") + + backends = [b for b in enabled_backends if b not in disabled_backends] + test_names = [] + + if use_xla_device: + cpu_xla_device = "XLA_CPU" + gpu_xla_device = "XLA_GPU" + else: + cpu_xla_device = "CPU" + gpu_xla_device = "GPU" + + py_library( + name = name + "_lib", + srcs = srcs, + deps = deps, + testonly = 1, + ) + for backend in backends: + test_name = "{}_{}".format(name, backend) + backend_tags = ["tf_xla_{}".format(backend)] + backend_args = [] + backend_deps = [] + backend_data = [] + if backend == "cpu": + backend_args += [ + "--test_device=" + cpu_xla_device, + "--types=DT_HALF,DT_FLOAT,DT_DOUBLE,DT_UINT8,DT_QUINT8,DT_INT8,DT_QINT8,DT_INT32,DT_QINT32,DT_INT64,DT_BOOL,DT_COMPLEX64,DT_COMPLEX128", + ] + elif backend in ("gpu", "gpu_a100", "gpu_h100"): + backend_args += [ + "--test_device=" + gpu_xla_device, + "--types=DT_HALF,DT_FLOAT,DT_DOUBLE,DT_UINT8,DT_QUINT8,DT_INT8,DT_QINT8,DT_INT32,DT_QINT32,DT_INT64,DT_BOOL,DT_COMPLEX64,DT_COMPLEX128,DT_BFLOAT16", + ] + backend_tags += tf_cuda_tests_tags() + elif backend in plugins: + backend_args += [ + "--test_device=" + plugins[backend]["device"], + "--types=" + plugins[backend]["types"], + ] + backend_tags += plugins[backend]["tags"] + backend_args += plugins[backend]["args"] + backend_deps += plugins[backend]["deps"] + backend_data += plugins[backend]["data"] + else: + fail("Unknown backend {}".format(backend)) + + test_tags = tags + backend_tags + + enable_mlir_bridge_options = [False] + if enable_mlir_bridge: + enable_mlir_bridge_options.append(True) + + for mlir_option in enable_mlir_bridge_options: + extra_dep = [] + extra_tag = [] + updated_name = test_name + + mlir_bridge_dep = "//tensorflow/python/framework:is_mlir_bridge_test_true" + has_mlir_dep = (mlir_bridge_dep in deps) + if mlir_option: + if updated_name.endswith("_test"): + updated_name = updated_name[:-5] + updated_name += "_mlir_bridge_test" + extra_dep = [] if has_mlir_dep else [mlir_bridge_dep] + + # Mark gpu mlir_bridge tests as ondemand + # + # This is for testing book keeping because the bridge does not have any gpu specific + # logic at this time, so CPU testing is good enough and cheaper. + extra_tag = ["ondemand"] if backend in ("gpu", "gpu_a100", "gpu_h100") else [] + elif has_mlir_dep: + # Some tests run only with mlir_bridge by explicitly adding the MLIR + # bridge dep so if the dep is already present skip non MLIR + # version. + continue + + # Rules may set exec_properties, but Google has internal + # exec_properties values so they don't merge easily. Just strip them + # all for now. + kwargs.pop("exec_properties", {}) + test_rule( + name = updated_name, + srcs = srcs, + srcs_version = "PY3", + args = backend_args, + main = "{}.py".format(name) if main == None else main, + data = data + backend_data, + deps = deps + backend_deps + extra_dep + [name + "_lib"], + tags = test_tags + extra_tag, + exec_properties = tf_exec_properties({"tags": test_tags}), + **kwargs + ) + test_names.append(updated_name) + native.test_suite(name = name, tests = test_names) + +def tf_xla_py_strict_test(**kwargs): + tf_xla_py_test(**kwargs) + +def generate_backend_suites(backends = []): + """Generates per-backend test_suites that run all tests for a backend.""" + if not backends: + backends = all_backends + for backend in backends: + native.test_suite(name = "%s_tests" % backend, tags = ["tf_xla_%s" % backend]) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/case_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/case_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2c43557440c40c2d02d9eae884c901a59d1c4776 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/case_test.py @@ -0,0 +1,83 @@ +# Copyright 2020 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 case statements in XLA.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_function +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_switch_case +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.platform import test + + +class CaseTest(xla_test.XLATestCase): + + def testCaseBasic(self): + + @def_function.function(jit_compile=True) + def switch_case_test(branch_index): + + def f1(): + return array_ops.constant(17) + + def f2(): + return array_ops.constant(31) + + def f3(): + return array_ops.constant(-1) + + return control_flow_switch_case.switch_case( + branch_index, branch_fns={ + 0: f1, + 1: f2 + }, default=f3) + + with ops.device(self.device): + self.assertEqual(switch_case_test(array_ops.constant(0)).numpy(), 17) + self.assertEqual(switch_case_test(array_ops.constant(1)).numpy(), 31) + self.assertEqual(switch_case_test(array_ops.constant(2)).numpy(), -1) + self.assertEqual(switch_case_test(array_ops.constant(3)).numpy(), -1) + + def testBranchIsPruned(self): + + @def_function.function(jit_compile=True) + def switch_case_test(): + branch_index = array_ops.constant(0) + + def f1(): + return array_ops.constant(17) + + def f2(): + # Some operations that XLA cannot compile. + image_ops.decode_image(io_ops.read_file('/tmp/bmp')) + return array_ops.constant(31) + + # This tests that we do not try to compile all branches if the branch + # index in trivially constant. + return control_flow_switch_case.switch_case( + branch_index, branch_fns={ + 0: f1, + 1: f2 + }, default=f2) + + with ops.device(self.device): + self.assertEqual(switch_case_test().numpy(), 17) + + +if __name__ == '__main__': + ops.enable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/cast_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cast_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8ad5da768281ffa24722b77b520b03b1375dbbf5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cast_ops_test.py @@ -0,0 +1,58 @@ +# Copyright 2020 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 lowering of tf.bitcast""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +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 random_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import io_ops +from tensorflow.python.platform import test + + +class CastOpsTest(xla_test.XLATestCase): + + def testBitcastToLarger(self): + with ops.device('device:{}:0'.format(self.device)): + + def f(x): + t = array_ops.bitcast(x, dtypes.float32) + return math_ops.reduce_sum(t, axis=1) + + compiled_f = def_function.function(f, jit_compile=True) + + x = random_ops.random_normal([10, 10, 2], dtype=dtypes.float16) + with ops.device(self.device): + out = f(x) + compiled_out = compiled_f(x) + self.assertAllClose(out, compiled_out) + # 10,10,2--(bitcast-convert)-->10,10--(reduce)-->10 + self.assertEqual(out.shape[0], 10) + + hlo = compiled_f.experimental_get_compiler_ir(x)(stage='hlo') + self.assertIn('f32[10,10]{1,0} bitcast-convert(f16[10,10,2]{2,1,0}', hlo) + + def testBitcastToSmaller(self): + pass + + +if __name__ == '__main__': + ops.enable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/cast_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cast_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e8b622d1b397e4da124ea1dac757b6cf445461e1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cast_test.py @@ -0,0 +1,126 @@ +# Copyright 2025 The OpenXLA Authors. +# +# 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. +# ============================================================================== +import platform + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class CastTest(xla_test.XLATestCase): + + def test_cast(self): + types = { + dtypes.bool, + dtypes.float32, + dtypes.float64, + dtypes.complex64, + dtypes.int32, + dtypes.int64, + dtypes.uint32, + dtypes.uint64, + } + with self.session() as session: + for src_type in types: + for dst_type in types: + self._test_cast(src_type, dst_type, session) + + def test_cast_fp8(self): + if platform.system() == "Darwin": + # TODO(b/271327511): Fix issue where casts to FP8 very rarely result in + # NaN on Mac + self.skipTest("Casts to FP8 sometimes result in NaN on Mac") + fp8_types = { + dtypes.float8_e5m2, + dtypes.float8_e4m3fn, + dtypes.float8_e4m3fnuz, + dtypes.float8_e4m3b11fnuz, + dtypes.float8_e5m2fnuz, + } + other_types = { + dtypes.bool, + dtypes.float32, + dtypes.float64, + dtypes.complex64, + dtypes.int32, + dtypes.int64, + dtypes.uint32, + dtypes.uint64, + } + with self.session() as session: + for fp8_type in fp8_types: + for other_type in other_types | fp8_types: + self._test_cast(fp8_type, other_type, session) + self._test_cast(other_type, fp8_type, session) + + def _test_cast(self, src_type, dst_type, session): + with self.subTest(src_type=src_type, dst_type=dst_type): + shapes = [[], [4], [2, 3], [2, 0, 4]] + src_np_dtype = src_type.as_numpy_dtype + dst_np_dtype = dst_type.as_numpy_dtype + + for shape in shapes: + src = np.arange(np.prod(shape)).astype(src_np_dtype) + + if src_type in self.complex_tf_types: + src += (np.arange(np.prod(shape)) * 2j).astype(src_np_dtype) + src = src.reshape(shape) + dst = src.astype(dst_np_dtype) + self.assert_op_output_matches_expected( + lambda x, dst_type=dst_type: math_ops.cast(x, dst_type), + src, + expected=dst, + local_session=session, + ) + + # Check special values. + if src_type.is_integer: + imin = np.iinfo(src_np_dtype).min + imax = np.iinfo(src_np_dtype).max + if src_type.is_unsigned: + src = np.array([imin, imax, 0, 1], dtype=src_np_dtype) + else: + src = np.array([imin, imax, 0, 1, -1], dtype=src_np_dtype) + elif src_type in self.float_tf_types: + if dst_type.is_integer: + imin = np.iinfo(dst_np_dtype).min + imax = np.iinfo(dst_np_dtype).max // 2 + src = np.array([imin, imax, 0, 1], dtype=src_np_dtype) + elif dst_type in self.float_tf_types: + fmin = np.finfo(dst_np_dtype).min + fmax = np.finfo(dst_np_dtype).max + tiny = np.finfo(dst_np_dtype).tiny + eps = np.finfo(dst_np_dtype).eps + src = np.array( + [fmin, fmax, np.nan, eps, -eps, tiny, -tiny, np.inf, -np.inf], + dtype=src_np_dtype, + ) + dst = src.astype(dst_np_dtype) + self.assert_op_output_matches_expected( + lambda x, dst_type=dst_type: math_ops.cast(x, dst_type), + src, + expected=dst, + local_session=session, + ) + + def test_give_me_a_name(self): + pass + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/categorical_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/categorical_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9f37ca928fc8cdfeb98b2624db4301ab5f08b6e8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/categorical_op_test.py @@ -0,0 +1,195 @@ +# 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 multinomial generation ops in the XLA JIT compiler.""" + +import collections + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import random_seed +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import stateless_random_ops +from tensorflow.python.platform import googletest +from tensorflow.python.platform import test + + +# TODO(srvasude): Merge this with +# third_party/tensorflow/python/kernel_tests/random/multinomial_op_test.py. +class CategoricalTest(xla_test.XLATestCase): + """Test cases for random-number generating operators.""" + + def output_dtypes(self): + return set(self.int_types).intersection([np.int32, np.int64]) + + def _chi2(self, expected, actual): + """Returns Chi2 GOF statistic.""" + actual = np.asarray(actual) + expected = np.asarray(expected) + diff = actual - expected + chi2 = np.sum(diff * diff / expected) + return chi2 + + def _do_sampling(self, logits, num_samples): + """Categorical samples from given input. + + Args: + logits: Numpy ndarray of shape [batch_size, num_classes]. + num_samples: Int; number of samples to draw. + + Returns: + Frequencies from sampled classes; shape [batch_size, num_classes]. + """ + with self.session(), self.test_scope(): + random_seed.set_random_seed(1618) + op = random_ops.multinomial(logits, num_samples, + output_dtype=dtypes.int32) + d = self.evaluate(op) + + batch_size, num_classes = logits.shape + freqs_mat = [] + for i in range(batch_size): + cnts = dict(collections.Counter(d[i, :])) + + # Requires drawn class labels be in range. + self.assertLess(max(cnts.keys()), num_classes) + self.assertGreaterEqual(min(cnts.keys()), 0) + + freqs = [(cnts[k] * 1. / num_samples if k in cnts else 0) + for k in range(num_classes)] + freqs_mat.append(freqs) + + return freqs_mat + + def _testRngIsNotConstant(self, rng, dtype, output_dtype): + # Tests that 'rng' does not always return the same value. + with self.session(): + with self.test_scope(): + x = rng(dtype, output_dtype) + + # The random-number generator, if working correctly, should produce the + # same output multiple times with low probability. + y = self.evaluate(x) + z = self.evaluate(x) + w = self.evaluate(x) + + # We use exact equality here. If the random-number generator is producing + # deterministic output, all three outputs will be bitwise identical. + self.assertTrue((not np.array_equal(y, z)) or + (not np.array_equal(z, w)) or + (not np.array_equal(y, w))) + + def testCategoricalIsNotConstant(self): + def rng(dtype, output_dtype): + return random_ops.multinomial(np.array([[1., 1., 1.]], dtype=dtype), 10, + output_dtype=output_dtype) + + dtype = np.float32 + for output_dtype in self.output_dtypes(): + self._testRngIsNotConstant(rng, dtype, output_dtype) + + @test.disable_with_predicate( + pred=test.is_built_with_rocm, skip_message="Test fails on ROCm.") + def testCategoricalIsInRange(self): + for dtype in self.float_types: + for output_dtype in self.output_dtypes(): + with self.session(): + with self.test_scope(): + x = random_ops.multinomial( + array_ops.ones(shape=[1, 20], dtype=dtype), 1000, + output_dtype=output_dtype) + y = self.evaluate(x) + self.assertTrue((y >= 0).sum() == 1000) + self.assertTrue((y < 20).sum() == 1000) + + def testSamplingCorrectness(self): + np.random.seed(1618) # Make it reproducible. + num_samples = 40000 + + rand_probs = np.random.dirichlet([1., 1., 2., 3.]) + rand_probs2 = np.random.dirichlet([1., 4., 5.], size=3) # batched + for probs in [[.5, .5], [.85, .05, .1], rand_probs, rand_probs2]: + probs = np.asarray(probs) + if len(probs.shape) == 1: + probs = probs.reshape(1, probs.size) # singleton batch + + logits = np.log(probs).astype(np.float32) + freqs = self._do_sampling(logits, num_samples) + + # the test here is similar to + # python/kernel_tests/random/multinomial_op_test.py + # Note that df >= 1 in all these cases. Choosing a cutoff of 1e-3 + # corresponds to an alpha value of 2.5% for df = 1, and smaller for larger + # df. + chi2 = self._chi2(probs, freqs) + self.assertLess(chi2, 1e-3) + + def testStatelessMultinomialIsInRange(self): + for dtype in self.float_types.intersection( + [dtypes.float32, dtypes.bfloat16]): + for output_dtype in self.output_dtypes(): + with self.session() as sess: + with self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + x = stateless_random_ops.stateless_multinomial( + array_ops.ones(shape=[1, 20], dtype=dtype), + 1000, + seed_t, + output_dtype=output_dtype) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef12]}) + self.assertTrue((y >= 0).sum() == 1000) + self.assertTrue((y < 20).sum() == 1000) + + def testDeterminismMultinomial(self): + # Stateless values should be equal iff the seeds are equal (roughly) + num_samples = 10 + with self.session(), self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + seeds = [(x, y) for x in range(5) for y in range(5)] * 3 + for logits in ([[0.1, 0.25, 0.5, 0.15]], [[0.5, 0.5], [0.8, 0.2], + [0.25, 0.75]]): + pure = stateless_random_ops.stateless_multinomial( + logits, num_samples, seed=seed_t) + values = [(seed, pure.eval(feed_dict={seed_t: seed})) for seed in seeds] + for s0, v0 in values: + for s1, v1 in values: + self.assertEqual(s0 == s1, np.all(v0 == v1)) + + def testEmpty(self): + with self.session(): + with self.test_scope(): + x = random_ops.multinomial( + array_ops.zeros([42, 40]), 0, output_dtype=dtypes.int32) + y = self.evaluate(x) + self.assertEqual(y.shape, (42, 0)) + + def testEmptyStateless(self): + with self.session() as sess: + with self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + x = stateless_random_ops.stateless_multinomial( + array_ops.zeros([42, 40]), + 0, + seed=seed_t, + output_dtype=dtypes.int32) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + self.assertEqual(y.shape, (42, 0)) + + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/cholesky_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cholesky_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..70419dc8dd8ff76a661c162ce9bd9c344d266dee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cholesky_op_test.py @@ -0,0 +1,147 @@ +# 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.Cholesky.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.platform import test + + +class CholeskyOpTest(xla_test.XLATestCase): + + # Cholesky defined for float64, float32, complex64, complex128 + # (https://www.tensorflow.org/api_docs/python/tf/cholesky) + @property + def float_types(self): + return set(super(CholeskyOpTest, self).float_types).intersection( + (np.float64, np.float32, np.complex64, np.complex128)) + + def _verifyCholeskyBase(self, sess, placeholder, x, chol, verification, atol): + chol_np, verification_np = sess.run([chol, verification], {placeholder: x}) + self.assertAllClose(x, verification_np, atol=atol) + self.assertShapeEqual(x, chol) + # Check that the cholesky is lower triangular, and has positive diagonal + # elements. + if chol_np.shape[-1] > 0: + chol_reshaped = np.reshape(chol_np, (-1, chol_np.shape[-2], + chol_np.shape[-1])) + for chol_matrix in chol_reshaped: + self.assertAllClose(chol_matrix, np.tril(chol_matrix), atol=atol) + self.assertTrue((np.diag(chol_matrix) > 0.0).all()) + + def _verifyCholesky(self, x, atol=1e-6): + # Verify that LL^T == x. + with self.session() as sess: + placeholder = array_ops.placeholder( + dtypes.as_dtype(x.dtype), shape=x.shape) + with self.test_scope(): + chol = linalg_ops.cholesky(placeholder) + verification = test_util.matmul_without_tf32(chol, chol, adjoint_b=True) + self._verifyCholeskyBase(sess, placeholder, x, chol, verification, atol) + + def testBasic(self): + data = np.array([[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]) + for dtype in self.float_types: + self._verifyCholesky(data.astype(dtype)) + + def testBatch(self): + for dtype in self.float_types: + simple_array = np.array( + [[[1., 0.], [0., 5.]]], dtype=dtype) # shape (1, 2, 2) + self._verifyCholesky(simple_array) + self._verifyCholesky(np.vstack((simple_array, simple_array))) + odd_sized_array = np.array( + [[[4., -1., 2.], [-1., 6., 0], [2., 0., 5.]]], dtype=dtype) + self._verifyCholesky(np.vstack((odd_sized_array, odd_sized_array))) + + # Generate random positive-definite matrices. + matrices = np.random.rand(10, 5, 5).astype(dtype) + for i in range(10): + matrices[i] = np.dot(matrices[i].T, matrices[i]) + self._verifyCholesky(matrices, atol=1e-4) + + @test_util.run_v2_only + def testNonSquareMatrixV2(self): + for dtype in self.float_types: + with self.assertRaises(errors.InvalidArgumentError): + linalg_ops.cholesky(np.array([[1., 2., 3.], [3., 4., 5.]], dtype=dtype)) + with self.assertRaises(errors.InvalidArgumentError): + linalg_ops.cholesky( + np.array( + [[[1., 2., 3.], [3., 4., 5.]], [[1., 2., 3.], [3., 4., 5.]]], + dtype=dtype)) + + @test_util.run_v1_only("Different error types") + def testNonSquareMatrixV1(self): + for dtype in self.float_types: + with self.assertRaises(ValueError): + linalg_ops.cholesky(np.array([[1., 2., 3.], [3., 4., 5.]], dtype=dtype)) + with self.assertRaises(ValueError): + linalg_ops.cholesky( + np.array( + [[[1., 2., 3.], [3., 4., 5.]], [[1., 2., 3.], [3., 4., 5.]]], + dtype=dtype)) + + @test_util.run_v2_only + def testWrongDimensionsV2(self): + for dtype in self.float_types: + tensor3 = constant_op.constant([1., 2.], dtype=dtype) + with self.assertRaises(errors.InvalidArgumentError): + linalg_ops.cholesky(tensor3) + with self.assertRaises(errors.InvalidArgumentError): + linalg_ops.cholesky(tensor3) + + @test_util.run_v1_only("Different error types") + def testWrongDimensionsV1(self): + for dtype in self.float_types: + tensor3 = constant_op.constant([1., 2.], dtype=dtype) + with self.assertRaises(ValueError): + linalg_ops.cholesky(tensor3) + with self.assertRaises(ValueError): + linalg_ops.cholesky(tensor3) + + def testLarge2000x2000(self): + n = 2000 + shape = (n, n) + data = np.ones(shape).astype(np.float32) / (2.0 * n) + np.diag( + np.ones(n).astype(np.float32)) + self._verifyCholesky(data, atol=1e-4) + + def testMatrixConditionNumbers(self): + for dtype in self.float_types: + condition_number = 1000 + size = 20 + + # Generate random positive-definite symmetric matrices, and take their + # Eigendecomposition. + matrix = np.random.rand(size, size) + matrix = np.dot(matrix.T, matrix) + _, w = np.linalg.eigh(matrix) + + # Build new Eigenvalues exponentially distributed between 1 and + # 1/condition_number + v = np.exp(-np.log(condition_number) * np.linspace(0, size, size) / size) + matrix = np.dot(np.dot(w, np.diag(v)), w.T).astype(dtype) + self._verifyCholesky(matrix, atol=1e-4) + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/clustering_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/clustering_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8363d65c65e1bd35d0e90e05371195e0babcebdd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/clustering_test.py @@ -0,0 +1,98 @@ +# 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 the behavior of the auto-compilation pass.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_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 math_ops +from tensorflow.python.platform import googletest + +CPU_DEVICE = "/job:localhost/replica:0/task:0/cpu:0" + + +class ClusteringTest(xla_test.XLATestCase): + + def testAdd(self): + val1 = np.array([4, 3, 2, 1], dtype=np.float32) + val2 = np.array([5, 6, 7, 8], dtype=np.float32) + expected = val1 + val2 + with self.session(): + with self.test_scope(): + input1 = constant_op.constant(val1, name="const1") + input2 = constant_op.constant(val2, name="const2") + output = math_ops.add(input1, input2) + result = self.evaluate(output) + self.assertAllClose(result, expected, rtol=1e-3) + + def testAddFromCpuMultiple(self): + val1 = np.array([4, 3, 2, 1]).astype(np.float32) + val2 = np.array([5, 6, 7, 8]).astype(np.float32) + expected = val1 + val2 + with self.session(): + with ops.device(CPU_DEVICE): + input1 = constant_op.constant(val1, name="const1") + input2 = constant_op.constant(val2, name="const2") + with self.test_scope(): + output = math_ops.add(input1, input2) + for _ in range(10): + result = self.evaluate(output) + self.assertAllClose(result, expected, rtol=1e-3) + + def testDeadlock(self): + # Builds a graph of the form: + # x -> y + # | \ + # z -> w + # where x and z are placed on the CPU and y and w are placed on the XLA + # device. If y and w are clustered for compilation, then the graph will + # deadlock since the clustered graph will contain a self-loop. + with self.session() as sess: + with ops.device(CPU_DEVICE): + x = array_ops.placeholder(dtypes.float32, [2]) + with self.test_scope(): + y = x * 2 + with ops.device(CPU_DEVICE): + z = y * y + with self.test_scope(): + w = y + z + result = sess.run(w, {x: [1.5, 0.5]}) + self.assertAllClose(result, [12., 2.], rtol=1e-3) + + def testHostMemory(self): + with self.session() as sess: + x = array_ops.placeholder(dtypes.int32) + with self.test_scope(): + y = x + 1 + with ops.device(CPU_DEVICE): + # Place a computation on the CPU, so y and w cannot be merged into the + # same JIT compilation. + z = y * 2 + with self.test_scope(): + # Argument 'y' is a non-constant output of a previous cluster. Make sure + # it is properly copied to host memory so it can be used as a + # compile-time constant input for this cluster. + w = array_ops.reshape(z, y) + result = sess.run(w, {x: [1, 0]}) + expected = np.array([[4], [2]], dtype=np.int32) + self.assertAllClose(expected, result, rtol=1e-3) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/complex_div_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/complex_div_test.py new file mode 100644 index 0000000000000000000000000000000000000000..733f916e101b5cadf0144e303f0a76fb904280c0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/complex_div_test.py @@ -0,0 +1,176 @@ +# Copyright 2019 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. +# ============================================================================== +"""Test cases for complex numbers division.""" + +import os + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.platform import googletest + +os.environ["XLA_FLAGS"] = ("--xla_cpu_fast_math_honor_nans=true " + "--xla_cpu_fast_math_honor_infs=true") + + +class ComplexNumbersDivisionTest(xla_test.XLATestCase): + """Test cases for complex numbers division operators.""" + + def _testBinary(self, op, a, b, expected, equality_test=None): + with self.session() as session: + with self.test_scope(): + pa = array_ops.placeholder(dtypes.as_dtype(a.dtype), a.shape, name="a") + pb = array_ops.placeholder(dtypes.as_dtype(b.dtype), b.shape, name="b") + output = op(pa, pb) + result = session.run(output, {pa: a, pb: b}) + if equality_test is None: + equality_test = self.assertAllCloseAccordingToType + equality_test(np.real(result), np.real(expected), rtol=1e-3) + equality_test(np.imag(result), np.imag(expected), rtol=1e-3) + + def testComplexOps(self): + for dtype in self.complex_types: + # Test division by 0 scenarios. + self._testBinary( + gen_math_ops.real_div, + np.array([ + complex(1, 1), + complex(1, np.inf), + complex(1, np.nan), + complex(np.inf, 1), + complex(np.inf, np.inf), + complex(np.inf, np.nan), + complex(np.nan, 1), + complex(np.nan, np.inf), + complex(np.nan, np.nan), + complex(-np.inf, np.nan), + ], + dtype=dtype), + np.array([ + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0 + 0j, + 0.0 + 0j, + ], + dtype=dtype), + expected=np.array([ + complex(np.inf, np.inf), + complex(np.inf, np.inf), + complex(np.inf, np.nan), + complex(np.inf, np.inf), + complex(np.inf, np.inf), + complex(np.inf, np.nan), + complex(np.nan, np.inf), + complex(np.nan, np.inf), + complex(np.nan, np.nan), + complex(-np.inf, np.nan), + ], + dtype=dtype)) + + # Test division with finite numerator, inf/nan denominator. + self._testBinary( + gen_math_ops.real_div, + np.array([ + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + ], + dtype=dtype), + np.array( + [ + complex(1, np.inf), + complex(1, np.nan), + complex(np.inf, 1), + complex(np.inf, np.inf), # C++ and Python diverge here. + complex(np.inf, np.nan), # C++ and Python diverge here. + complex(np.nan, 1), + complex(np.nan, np.inf), # C++ and Python diverge here. + complex(np.nan, -np.inf), # C++ and Python diverge here. + complex(np.nan, np.nan), + ], + dtype=dtype), + expected=np.array( + [ + (1 + 1j) / complex(1, np.inf), + (1 + 1j) / complex(1, np.nan), + (1 + 1j) / complex(np.inf, 1), + complex(0 + 0j), # C++ and Python diverge here. + complex(0 + 0j), # C++ and Python diverge here. + (1 + 1j) / complex(np.nan, 1), + complex(0 + 0j), # C++ and Python diverge here. + complex(0 - 0j), # C++ and Python diverge here. + (1 + 1j) / complex(np.nan, np.nan), + ], + dtype=dtype)) + + # Test division with inf/nan numerator, infinite denominator. + self._testBinary( + gen_math_ops.real_div, + np.array([ + complex(1, np.inf), + complex(1, np.nan), + complex(np.inf, 1), + complex(np.inf, np.inf), + complex(np.inf, np.nan), + complex(np.nan, 1), + complex(np.nan, np.inf), + complex(np.nan, np.nan), + complex(np.nan, -np.inf), + ], + dtype=dtype), + np.array([ + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + 1 + 1j, + -1 - 1j, + ], + dtype=dtype), + expected=np.array( + [ + complex(np.inf, np.inf), # C++ and Python diverge here. + complex(1 / np.nan) / (1 + 1j), + complex(np.inf / 1) / (1 + 1j), + complex(np.inf, -np.nan), # C++ and Python diverge here. + complex(np.inf, -np.inf), # C++ and Python diverge here. + complex(np.nan / 1) / (1 + 1j), + complex(np.inf, np.inf), # C++ and Python diverge here. + complex(np.nan / np.nan) / (1 + 1j), + complex(np.inf, np.inf), # C++ and Python diverge here. + ], + dtype=dtype)) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/concat_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/concat_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ae3a6f33d164ec4accd9468ffde26ff98fc92c85 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/concat_ops_test.py @@ -0,0 +1,397 @@ +# 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. +# ============================================================================== +"""Functional tests for XLA Concat Op.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python import pywrap_sanitizers +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class ConcatTest(xla_test.XLATestCase): + + def testHStack(self): + with self.session(): + p1 = array_ops.placeholder(dtypes.float32, shape=[4, 4]) + p2 = array_ops.placeholder(dtypes.float32, shape=[4, 4]) + with self.test_scope(): + c = array_ops.concat([p1, p2], 0) + params = { + p1: np.random.rand(4, 4).astype("f"), + p2: np.random.rand(4, 4).astype("f") + } + result = c.eval(feed_dict=params) + + self.assertEqual(result.shape, c.get_shape()) + self.assertAllEqual(result[:4, :], params[p1]) + self.assertAllEqual(result[4:, :], params[p2]) + + def testVStack(self): + with self.session(): + p1 = array_ops.placeholder(dtypes.float32, shape=[4, 4]) + p2 = array_ops.placeholder(dtypes.float32, shape=[4, 4]) + with self.test_scope(): + c = array_ops.concat([p1, p2], 1) + params = { + p1: np.random.rand(4, 4).astype("f"), + p2: np.random.rand(4, 4).astype("f") + } + result = c.eval(feed_dict=params) + + self.assertEqual(result.shape, c.get_shape()) + self.assertAllEqual(result[:, :4], params[p1]) + self.assertAllEqual(result[:, 4:], params[p2]) + + def testInt32(self): + with self.session(): + p1 = np.random.rand(2, 3).astype("i") + p2 = np.random.rand(2, 3).astype("i") + x1 = constant_op.constant(p1) + x2 = constant_op.constant(p2) + with self.test_scope(): + c = array_ops.concat([x1, x2], 0) + result = self.evaluate(c) + self.assertAllEqual(result[:2, :], p1) + self.assertAllEqual(result[2:, :], p2) + + def testAxisInt64(self): + with self.session(): + p1 = np.random.rand(2, 3).astype("i") + p2 = np.random.rand(2, 3).astype("i") + x1 = constant_op.constant(p1) + x2 = constant_op.constant(p2) + axis = constant_op.constant(0, dtype=dtypes.int64) + with self.test_scope(): + c = array_ops.concat([x1, x2], axis) + result = self.evaluate(c) + self.assertAllEqual(result[:2, :], p1) + self.assertAllEqual(result[2:, :], p2) + + def _testRandom(self, dtype): + # Random dims of rank 5 + shape = np.random.randint(1, 5, size=5) + # Random number of tensors, but always > 1. + num_tensors = np.random.randint(2, 10) + # Random dim to concat on + concat_dim = np.random.randint(5) + params = {} + if dtype == dtypes.bfloat16: + dtype_feed = dtypes.float32 + else: + dtype_feed = dtype + with self.session(): + p = [] + for i in np.arange(num_tensors): + input_shape = shape + input_shape[concat_dim] = np.random.randint(1, 5) + placeholder = array_ops.placeholder(dtype_feed, shape=input_shape) + p.append(placeholder) + + t = dtype_feed.as_numpy_dtype + params[placeholder] = np.random.rand(*input_shape).astype(t) + + if dtype != dtype_feed: + concat_inputs = [math_ops.cast(p_i, dtype) for p_i in p] + else: + concat_inputs = p + with self.test_scope(): + c = array_ops.concat(concat_inputs, concat_dim) + if dtype != dtype_feed: + c = math_ops.cast(c, dtype_feed) + result = c.eval(feed_dict=params) + + self.assertEqual(result.shape, c.get_shape()) + cur_offset = 0 + + for i in np.arange(num_tensors): + # The index into the result is the ':' along all dimensions + # except the concat_dim. slice(0, size) is used for ':', and + # a list of slices is used to index into result. + ind = [slice(0, params[p[i]].shape[j]) for j in np.arange(5)] + ind[concat_dim] = slice(cur_offset, + cur_offset + params[p[i]].shape[concat_dim]) + cur_offset += params[p[i]].shape[concat_dim] + if dtype == dtype_feed: + self.assertAllEqual(result[tuple(ind)], params[p[i]]) + else: + self.assertAllClose(result[tuple(ind)], params[p[i]], 0.01) + + def testRandom(self): + self._testRandom(dtypes.float32) + self._testRandom(dtypes.int32) + + def _testGradientsSimple(self): + with self.session(): + inp = [] + inp_tensors = [] + with self.test_scope(): + for x in [1, 2, 6]: + shape = [10, x, 2] + t = np.random.rand(*shape).astype("f") + inp.append(t) + inp_tensors.append( + constant_op.constant( + [float(y) for y in t.flatten()], + shape=shape, + dtype=dtypes.float32)) + c = array_ops.concat(inp_tensors, 1) + output_shape = [10, 9, 2] + grad_inp = np.random.rand(*output_shape).astype("f") + grad_tensor = constant_op.constant( + [float(x) for x in grad_inp.flatten()], shape=output_shape) + grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor]) + concated_grad = array_ops.concat(grad, 1) + result = self.evaluate(concated_grad) + self.assertAllEqual(result, grad_inp) + + def testGradientsSimpleAll(self): + self._testGradientsSimple() + + def _testGradientsFirstDim(self): + with self.session(): + inp = [] + inp_tensors = [] + with self.test_scope(): + for x in [1, 2, 6]: + shape = [x, 10, 2] + t = np.random.rand(*shape).astype("f") + inp.append(t) + inp_tensors.append( + constant_op.constant( + [float(y) for y in t.flatten()], + shape=shape, + dtype=dtypes.float32)) + c = array_ops.concat(inp_tensors, 0) + output_shape = [9, 10, 2] + grad_inp = np.random.rand(*output_shape).astype("f") + grad_tensor = constant_op.constant( + [float(x) for x in grad_inp.flatten()], shape=output_shape) + grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor]) + concated_grad = array_ops.concat(grad, 0) + result = self.evaluate(concated_grad) + + self.assertAllEqual(result, grad_inp) + + def testGradientsFirstDimAll(self): + self._testGradientsFirstDim() + + def _testGradientsLastDim(self): + with self.session(): + inp = [] + inp_tensors = [] + with self.test_scope(): + for x in [1, 2, 6]: + shape = [10, 2, x] + t = np.random.rand(*shape).astype("f") + inp.append(t) + inp_tensors.append( + constant_op.constant( + [float(y) for y in t.flatten()], + shape=shape, + dtype=dtypes.float32)) + c = array_ops.concat(inp_tensors, 2) + output_shape = [10, 2, 9] + grad_inp = np.random.rand(*output_shape).astype("f") + grad_tensor = constant_op.constant( + [float(x) for x in grad_inp.flatten()], shape=output_shape) + grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor]) + concated_grad = array_ops.concat(grad, 2) + result = self.evaluate(concated_grad) + + self.assertAllEqual(result, grad_inp) + + def testGradientsLastDimAll(self): + self._testGradientsLastDim() + + def _RunAndVerifyGradientsRandom(self): + # Random dims of rank 5 + input_shape = np.random.randint(1, 5, size=5) + # Random number of tensors + num_tensors = np.random.randint(1, 10) + # Random dim to concat on + concat_dim = np.random.randint(5) + concat_dim_sizes = np.random.randint(1, 5, size=num_tensors) + with self.session(): + inp = [] + inp_tensors = [] + with self.test_scope(): + for x in concat_dim_sizes: + shape = input_shape + shape[concat_dim] = x + t = np.random.rand(*shape).astype("f") + inp.append(t) + inp_tensors.append( + constant_op.constant( + [float(y) for y in t.flatten()], + shape=shape, + dtype=dtypes.float32)) + c = array_ops.concat(inp_tensors, concat_dim) + output_shape = input_shape + output_shape[concat_dim] = concat_dim_sizes.sum() + grad_inp = np.random.rand(*output_shape).astype("f") + grad_tensor = constant_op.constant( + [float(x) for x in grad_inp.flatten()], shape=output_shape) + grad = gradients_impl.gradients([c], inp_tensors, [grad_tensor]) + concated_grad = array_ops.concat(grad, concat_dim) + result = self.evaluate(concated_grad) + + self.assertAllEqual(result, grad_inp) + + def testGradientsRandom(self): + for _ in range(5): + self._RunAndVerifyGradientsRandom() + + # Re-enable once zero-element Retvals are handled correctly. + def DISABLED_testZeroSize(self): + # Verify that concat doesn't crash and burn for zero size inputs + np.random.seed(7) + with self.session(): + with self.test_scope(): + for shape0 in (), (2,): + axis = len(shape0) + for shape1 in (), (3,): + for n0 in 0, 1, 2: + for n1 in 0, 1, 2: + x0 = np.random.randn(*(shape0 + (n0,) + shape1)) + x1 = np.random.randn(*(shape0 + (n1,) + shape1)) + correct = np.concatenate([x0, x1], axis=axis) + # TODO(irving): Make tf.concat handle map, then drop list(). + xs = list(map(constant_op.constant, [x0, x1])) + c = array_ops.concat(xs, axis) + self.assertAllEqual(c, correct) + # Check gradients + dc = np.random.randn(*c.get_shape().as_list()) + dxs = self.evaluate(gradients_impl.gradients(c, xs, dc)) + self.assertAllEqual(dc, np.concatenate(dxs, axis=axis)) + + def testConcatTuple(self): + c1 = np.random.rand(4, 4).astype(np.float32) + c2 = np.random.rand(4, 4).astype(np.float32) + with self.session(): + with self.test_scope(): + concat_list_t = array_ops.concat([c1, c2], 0) + concat_tuple_t = array_ops.concat((c1, c2), 0) + self.assertAllEqual(concat_list_t, self.evaluate(concat_tuple_t)) + + def testConcatNoScalars(self): + with self.session(): + with self.test_scope(): + scalar = constant_op.constant(7) + dim = array_ops.placeholder(dtypes.int32) + with self.assertRaisesRegex( + ValueError, r"Can't concatenate scalars \(use tf\.stack instead\)"): + array_ops.concat([scalar, scalar, scalar], dim) + + # The purpose of this is to ensure that XLA on GPU will not run out of memory + # with too many arguments. + def testConcatLargeNumberOfTensors(self): + if "CPU" in self.device: + self.skipTest("This test can time out on CPU, so we will just allow " + "other backends to catch this specific error.") + if (pywrap_sanitizers.is_asan_enabled() or + pywrap_sanitizers.is_tsan_enabled() or + pywrap_sanitizers.is_msan_enabled() or + pywrap_sanitizers.is_ubsan_enabled()): + self.skipTest("This test can time out on *SAN.") + with self.session(): + with self.test_scope(): + for concat_dim in range(2): + params = {} + p = [] + shape = np.array([7, 13]) + num_tensors = 1001 + for i in np.arange(num_tensors): + input_shape = shape + placeholder = array_ops.placeholder( + dtypes.float32, shape=input_shape) + p.append(placeholder) + params[placeholder] = np.random.rand(*input_shape).astype( + np.float32) + + concat_inputs = p + c = array_ops.concat(concat_inputs, concat_dim) + result = c.eval(feed_dict=params) + + self.assertEqual(result.shape, c.get_shape()) + cur_offset = 0 + + for i in np.arange(num_tensors): + # The index into the result is the ':' along all dimensions + # except the concat_dim. slice(0, size) is used for ':', and + # a list of slices is used to index into result. + index = [slice(0, params[p[i]].shape[j]) for j in np.arange(2)] + index[concat_dim] = slice( + cur_offset, cur_offset + params[p[i]].shape[concat_dim]) + cur_offset += params[p[i]].shape[concat_dim] + self.assertAllEqual(result[tuple(index)], params[p[i]]) + + +class ConcatOffsetTest(xla_test.XLATestCase): + + def testBasic(self): + with self.session(): + with self.test_scope(): + cdim = constant_op.constant(1, dtypes.int32) + s0 = constant_op.constant([2, 3, 5], dtypes.int32) + s1 = constant_op.constant([2, 7, 5], dtypes.int32) + s2 = constant_op.constant([2, 20, 5], dtypes.int32) + off = gen_array_ops.concat_offset(cdim, [s0, s1, s2]) + ans = self.evaluate(off) + self.assertAllEqual(ans, [[0, 0, 0], [0, 3, 0], [0, 10, 0]]) + + +class PackTest(xla_test.XLATestCase): + + def testBasic(self): + with self.session(): + with self.test_scope(): + s0 = constant_op.constant([2, 3, 5], dtypes.int32) + s1 = constant_op.constant([2, 7, 5], dtypes.int32) + s2 = constant_op.constant([2, 20, 5], dtypes.int32) + packed = array_ops_stack.stack([s0, s1, s2]) + ans = self.evaluate(packed) + self.assertAllEqual(ans, [[2, 3, 5], [2, 7, 5], [2, 20, 5]]) + + def testScalars(self): + with self.session(): + with self.test_scope(): + s0 = constant_op.constant(2, dtypes.int32) + s1 = constant_op.constant(3, dtypes.int32) + s2 = constant_op.constant(5, dtypes.int32) + packed = array_ops_stack.stack([s0, s1, s2]) + ans = self.evaluate(packed) + self.assertAllEqual(ans, [2, 3, 5]) + + def testEmpty(self): + with self.session(): + with self.test_scope(): + s0 = constant_op.constant([[]], dtypes.int32) + s1 = constant_op.constant([[]], dtypes.int32) + s2 = constant_op.constant([[]], dtypes.int32) + packed = array_ops_stack.stack([s0, s1, s2]) + ans = self.evaluate(packed) + self.assertAllEqual(ans, [[[]], [[]], [[]]]) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/cond_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cond_test.py new file mode 100644 index 0000000000000000000000000000000000000000..99600ab1a7cdd9b8624c2c7ccf2d148765f21109 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/cond_test.py @@ -0,0 +1,318 @@ +# Copyright 2019 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 tf.cond in XLA.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.client import session +from tensorflow.python.compiler.xla import xla +from tensorflow.python.eager import def_function +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.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import control_flow_switch_case +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.platform import test + + +@test_util.with_control_flow_v2 +class CondTest(xla_test.XLATestCase): + + def testCondAndTensorArrayInDefun(self): + # TODO(b/132430685): Make test more useful. Also b/129396295, b/127846988 + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + @def_function.function + def f(): + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=1) + output = cond.cond( + constant_op.constant(True), + lambda: ta.write(0, 5.), lambda: ta.write(0, 10.)) + + return output.stack() + + output_t = f() + self.assertAllEqual([5.], self.evaluate(output_t)) + + xla_context.Exit() + + def testCondAndTensorArrayInDefun_constFolding(self): + g = ops.Graph() + with session.Session(graph=g), g.as_default(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + @def_function.function + def f(): + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=1) + output = cond.cond( + constant_op.constant(False), + lambda: ta.write(0, 5.), lambda: ta.write(0, 10.)) + + return output.stack() + + output_t = f() + self.assertAllEqual([10.], self.evaluate(output_t)) + + xla_context.Exit() + + def testCondAndTensorArray_xlaCompile(self): + self.skipTest("b/127846988") + # Fails with "Uninitialized arguments" in XlaIfOp::Compile + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + def f(): + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=1) + output = cond.cond( + constant_op.constant(True), + lambda: ta.write(0, 5.), lambda: ta.write(0, 10.)) + + return output.stack() + + output_t, = xla.compile(f) + self.assertAllEqual([5.], self.evaluate(output_t)) + + xla_context.Exit() + + def testCondConstPropagation(self): + with self.session() as sess, self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + x = array_ops.placeholder(dtypes.float32) + p = array_ops.placeholder(dtypes.int32) + + # TODO(b/129021699): Wrapping this in a tf.function does not work. + def if_true(): + # This emits a StridedSlice op which expects the index to be a + # compile-time const. + return x[p] + + def if_false(): + return 5. + + output = cond.cond( + constant_op.constant(True), if_true, if_false) + + self.assertAllEqual(1., + sess.run(output, feed_dict={ + x: [0., 1., 2.], + p: 1 + })) + + xla_context.Exit() + + def testCondConstPropagation_xlaCompile(self): + self.skipTest("b/132430685") + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + x = array_ops.placeholder_with_default([0., 1., 2.], shape=[3]) + p = constant_op.constant(1) + + def f(): + # TODO(b/129021699): Wrapping this in a tf.function does not work. + def if_true(): + # This emits a StridedSlice op which expects the index to be a + # compile-time const. + return x[p] + + def if_false(): + return 5. + + return cond.cond( + constant_op.constant(True), if_true, if_false) + + output = xla.compile(f) + + self.assertAllEqual(1., self.evaluate(output)) + + xla_context.Exit() + + def testCondConstPropagation_errorMsg(self): + self.skipTest("b/132430685") + with self.session() as sess, self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + x = array_ops.placeholder(dtypes.float32) + p = random_ops.random_uniform([], minval=1, maxval=3, dtype=dtypes.int32) + + # TODO(b/129021699): Wrapping this in a tf.function does not work. + def if_true(): + # This emits a StridedSlice op which expects the index to be a + # compile-time const. + return x[:p] + + def if_false(): + return array_ops.fill([p], 5.) + + output = cond.cond( + constant_op.constant(True), if_true, if_false) + + with self.assertRaisesRegex(errors.InvalidArgumentError, + "must be a compile-time constant"): + sess.run( + output, feed_dict={ + x: [0., 1., 2.], + }) + + xla_context.Exit() + + def testCondConstPropagation_errorMsg_xlaCompile(self): + with self.session() as sess, self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + x = array_ops.placeholder(dtypes.float32) + p = random_ops.random_uniform([], minval=1, maxval=3, dtype=dtypes.int32) + condition = math_ops.cast( + random_ops.random_uniform([], minval=0, maxval=2, dtype=dtypes.int32), + dtypes.bool) + + def f(): + # TODO(b/129021699): Wrapping this in a tf.function does not work. + def if_true(): + # This emits a StridedSlice op which expects the index to be a + # compile-time const. + return x[:p] + + def if_false(): + return array_ops.fill([p], 5.) + + return cond.cond(condition, if_true, if_false) + + output = xla.compile(f) + + with self.assertRaisesRegex(errors.InvalidArgumentError, + "must be a compile-time constant"): + sess.run( + output, feed_dict={ + x: [0., 1., 2.], + }) + + xla_context.Exit() + + def testSwitchCaseAndTensorArrayInDefun(self): + self.skipTest("b/127846988") + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + @def_function.function + def f(): + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=1) + output = control_flow_switch_case.switch_case( + constant_op.constant(1), { + 0: lambda: ta.write(0, 5.), + 1: lambda: ta.write(0, 10.), + 2: lambda: ta.write(0, 15.), + }) + + return output.stack() + + output_t = f() + self.assertAllEqual([10.], self.evaluate(output_t)) + + xla_context.Exit() + + def testSwitchCaseAndTensorArray_xlaCompile(self): + self.skipTest("b/127846988") + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + def f(): + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=1) + output = control_flow_switch_case.switch_case( + constant_op.constant(1), { + 0: lambda: ta.write(0, 5.), + 1: lambda: ta.write(0, 10.), + 2: lambda: ta.write(0, 15.), + }) + + return output.stack() + + output_t, = xla.compile(f) + self.assertAllEqual([10.], self.evaluate(output_t)) + + xla_context.Exit() + + def testSwitchCaseConstPropagation(self): + self.skipTest("b/127846988") + with self.session() as sess, self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + x = array_ops.placeholder(dtypes.float32) + p = array_ops.placeholder(dtypes.int32) + + def branch0(): + return 5. + + def branch1(): + return 15. + + # TODO(b/129021699): Wrapping this in a tf.function does not work. + def branch2(): + # This emits a StridedSlice op which expects the index to be a + # compile-time const. + return x[p] + + output = control_flow_switch_case.switch_case( + constant_op.constant(2), { + 0: branch0, + 1: branch1, + 2: branch2, + }) + + self.assertAllEqual(7., + sess.run(output, feed_dict={ + x: [0., 1., 7.], + p: 2, + })) + + xla_context.Exit() + + def testCondNoInputs(self): + """Verifies against `Failed precondition: Expected one input shape`.""" + + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + + for pred in True, False: + cond_out = cond.cond( + array_ops.placeholder_with_default(pred, []), + lambda: constant_op.constant(2.), + lambda: constant_op.constant(1.)) + self.assertEqual(int(pred) + 1., self.evaluate(cond_out)) + + xla_context.Exit() + + +if __name__ == '__main__': + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/const_arg_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/const_arg_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ca86a26aa592618d20f60d1c7534b3cc9db9b564 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/const_arg_test.py @@ -0,0 +1,42 @@ +# Copyright 2021 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 compilation that involves constant arguments.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import googletest + + +class ConstArgTest(xla_test.XLATestCase): + # Pass constant value to XlaDynamicSlice's size parameter that must be found + # by xla::ValueInference. Most often, constants are passed to op kernels + # using XlaExpression with kind kConstant. To require value inference, this + # model obfuscates the constant using operations `>=` and `where_v2`. + + def testValueInference(self): + with self.session() as session: + with self.test_scope(): + a = array_ops.placeholder(dtypes.int32, [], name="a") + size = array_ops.reshape(array_ops.where_v2(a >= 0, 1, 0), [1]) + output = xla.dynamic_slice([11, 12, 13], [0], size) + result = session.run(output, {a: 1}) + expected = [11] + self.assertEqual(result, expected) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/const_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/const_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3d0feb51750c2cf5ce5dd9edacccdd95fea7449b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/const_test.py @@ -0,0 +1,81 @@ +# Copyright 2022 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 const op compilation.""" + +import numpy as np + +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import test_util +from tensorflow.python.platform import test + + +# This test doesn't use XLATestCase like the other tests in this directory. +# The Const op xla op kernel is compilation only and therefore is not executed +# with XLA in the on demand compilation mode. Instead we use +# tf.function(jit_compile=True) +class ConstOpTest(test_util.TensorFlowTestCase): + + # Verifies that the Const op works + # @test_util.run_v2_only + def testConst(self): + types = { + dtypes.bool, + dtypes.int8, + dtypes.int16, + dtypes.int32, + dtypes.int64, + dtypes.uint8, + dtypes.uint16, + dtypes.uint32, + dtypes.uint64, + dtypes.float16, + dtypes.bfloat16, + dtypes.float32, + dtypes.float64, + dtypes.float8_e5m2, + dtypes.float8_e4m3fn, + dtypes.float8_e4m3fnuz, + dtypes.float8_e4m3b11fnuz, + dtypes.float8_e5m2fnuz, + } + for dtype in types: + with self.subTest(dtype=dtype): + if dtype == dtypes.bool: + values = [True, False] + elif dtype in [ + dtypes.uint8, + dtypes.uint16, + dtypes.uint32, + dtypes.uint64, + ]: + values = [0., 1., dtype.min, dtype.max] + else: + values = [0., 1., -1., dtype.min, dtype.max] + if dtype.is_floating: + values.extend([float("Inf"), -float("Inf"), float("NaN")]) + values = np.array(values, dtype=dtype.as_numpy_dtype) + + @def_function.function(jit_compile=True) + def f(): + return constant_op.constant(values, dtype) # pylint: disable=cell-var-from-loop + + result = f() + self.assertAllEqual(self.evaluate(result), values) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv2d_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv2d_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ccbe09f7d47ed67defbc4bf26b936874bb6e1041 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv2d_test.py @@ -0,0 +1,963 @@ +# 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 Conv2D via the XLA JIT. + +The canned results in these tests are created by running each test using the +Tensorflow CPU device and saving the output. +""" + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import test_utils +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import googletest + +DATA_FORMATS = ( + ("_data_format_NHWC", "NHWC"), + ("_data_format_NCHW", "NCHW"), +) + +CONV_CONFIGS = ( + ("_Conv2D_data_format_NHWC", "NHWC", "Conv2D"), + ("_Conv2D_data_format_NCHW", "NCHW", "Conv2D"), + ("_Conv_data_format_NHWC", "NHWC", "Conv"), + ("_Conv_data_format_NCHW", "NCHW", "Conv"), +) + + +class Conv2DTest(xla_test.XLATestCase, parameterized.TestCase): + + def _VerifyValues( + self, + input_sizes=None, + filter_sizes=None, + strides=None, + dilations=None, + padding=None, + data_format_src="NHWC", + data_format_dst="NHWC", + expected=None, + op_name="Conv2D", + ): + """Tests that tf.nn.conv2d produces the expected value. + + Args: + input_sizes: Input tensor dimensions in [batch, input_rows, input_cols, + input_depth]. + filter_sizes: Filter tensor dimensions in [kernel_rows, kernel_cols, + input_depth, output_depth]. + strides: Strides. + dilations: RHS dilations. + padding: Padding type. + data_format_src: Data format input is in. + data_format_dst: Data format verification will run and input is converted + to. + expected: Expected output. + op_name: Name of operation to test (Conv/Conv2D) + """ + + total_size_1 = np.prod(input_sizes) + total_size_2 = np.prod(filter_sizes) + x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes) + x2 = np.arange(1, total_size_2 + 1, dtype=np.float32).reshape(filter_sizes) + strides = [1] + strides + [1] + if dilations is None: + dilations = [1, 1] + dilations = [1] + dilations + [1] + + # Convert between data formats. + expected = test_utils.ConvertBetweenDataFormats(expected, data_format_src, + data_format_dst) + x1 = test_utils.ConvertBetweenDataFormats(x1, data_format_src, + data_format_dst) + input_sizes = test_utils.PermuteDimsBetweenDataFormats( + input_sizes, data_format_src, data_format_dst) + strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src, + data_format_dst) + dilations = test_utils.PermuteDimsBetweenDataFormats( + dilations, data_format_src, data_format_dst) + + with self.session() as sess: + t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes) + t2 = array_ops.placeholder(dtypes.float32, shape=filter_sizes) + with self.test_scope(): + if op_name == "Conv": + conv_format = ( + "CHANNELS_LAST" if data_format_dst == "NHWC" else "CHANNELS_FIRST" + ) + out = gen_nn_ops.conv( + t1, + t2, + strides=strides, + padding=padding, + data_format=conv_format, + dilations=dilations, + ) + elif op_name == "Conv2D": + out = nn_ops.conv2d( + t1, + t2, + strides=strides, + padding=padding, + data_format=data_format_dst, + dilations=dilations, + ) + else: + raise ValueError("Invalid op name: %s" % op_name) + + value = sess.run(out, {t1: x1, t2: x2}) + self.assertAllClose(expected, value, 1e-3) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D1x1Filter(self, data_format, op_name): + expected_output = np.reshape([ + 30.0, 36.0, 42.0, 66.0, 81.0, 96.0, 102.0, 126.0, 150.0, 138.0, 171.0, + 204.0, 174.0, 216.0, 258.0, 210.0, 261.0, 312.0 + ], [1, 2, 3, 3]) + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[1, 1, 3, 3], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D2x2Filter(self, data_format, op_name): + expected_output = np.reshape( + [2271.0, 2367.0, 2463.0, 2901.0, 3033.0, 3165.0], [1, 1, 2, 3]) + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D2x2Filter2x1Dilation(self, data_format, op_name): + expected_output = np.array([[[[72], [82], [92]], [[112], [122], [132]]]]) + self._VerifyValues( + input_sizes=[1, 4, 4, 1], + filter_sizes=[2, 2, 1, 1], + strides=[1, 1], + dilations=[2, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D1x2Filter(self, data_format, op_name): + expected_output = np.reshape([ + 231.0, 252.0, 273.0, 384.0, 423.0, 462.0, 690.0, 765.0, 840.0, 843.0, + 936.0, 1029.0 + ], [1, 2, 2, 3]) + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[1, 2, 3, 3], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D2x2FilterStride2(self, data_format, op_name): + expected_output = np.reshape([2271.0, 2367.0, 2463.0], [1, 1, 1, 3]) + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + strides=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D2x2FilterStride2Same(self, data_format, op_name): + expected_output = np.reshape( + [2271.0, 2367.0, 2463.0, 1230.0, 1305.0, 1380.0], [1, 1, 2, 3]) + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + strides=[2, 2], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2DEmptyDilation(self, data_format, op_name): + self._VerifyValues( + input_sizes=[0, 2, 3, 3], + filter_sizes=[1, 1, 3, 3], + strides=[1, 1], + dilations=[2, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=np.zeros([0, 2, 3, 3]), + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D2x2FilterDilation(self, data_format, op_name): + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + strides=[1, 1], + dilations=[1, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=np.reshape([2667, 2781, 2895], [1, 1, 1, 3]), + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2D1x2FilterDilation(self, data_format, op_name): + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[1, 2, 3, 3], + strides=[1, 1], + dilations=[2, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=np.array([[ + [[231, 252, 273], [384, 423, 462]], + [[690, 765, 840], [843, 936, 1029]], + ]]), + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv2DKernelSizeMatchesInputSizeDilation(self, data_format, op_name): + self._VerifyValues( + input_sizes=[1, 3, 3, 1], + filter_sizes=[2, 2, 1, 2], + strides=[1, 1], + dilations=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=np.reshape([108, 128], [1, 1, 1, 2]), + op_name=op_name, + ) + + def testConvExpandedBatch(self): + tensor_in_sizes_batch = [10, 2, 3, 3] + tensor_in_sizes_expanded_batch = [2, 5, 2, 3, 3] + batch_dims = 2 + filter_in_sizes = [1, 1, 3, 3] + filter_in = np.arange( + 1, np.prod(filter_in_sizes) + 1, dtype=np.float32 + ).reshape(filter_in_sizes) + x1 = np.arange( + 1, np.prod(tensor_in_sizes_batch) + 1, dtype=np.float32 + ).reshape(tensor_in_sizes_batch) + x2 = x1.reshape(tensor_in_sizes_expanded_batch) + + with self.session() as sess: + t1 = array_ops.placeholder(dtypes.bfloat16, shape=tensor_in_sizes_batch) + t2 = array_ops.placeholder( + dtypes.bfloat16, shape=tensor_in_sizes_expanded_batch + ) + filter_t = array_ops.placeholder(dtypes.bfloat16, shape=filter_in_sizes) + + out1 = gen_nn_ops.conv( + t1, filter_t, strides=[1, 1, 1, 1], padding="VALID" + ) + out2 = gen_nn_ops.conv( + t2, + filter_t, + strides=[1, 1, 1, 1], + padding="VALID", + batch_dims=batch_dims, + ) + value1 = sess.run(out1, {t1: x1, filter_t: filter_in}) + value2 = sess.run(out2, {t2: x2, filter_t: filter_in}) + + self.assertEqual(list(value1.shape), tensor_in_sizes_batch) + self.assertEqual(list(value2.shape), tensor_in_sizes_expanded_batch) + self.assertAllCloseAccordingToType(value1, value2.reshape(value1.shape)) + + +class Conv2DBackpropInputTest(xla_test.XLATestCase, parameterized.TestCase): + + def _VerifyValues(self, + input_sizes=None, + filter_sizes=None, + out_backprop_sizes=None, + strides=None, + dilations=None, + padding=None, + data_format_src="NHWC", + data_format_dst="NHWC", + expected=None): + """Tests that gen_nn_ops.conv2d_backprop_input produces the expected output. + + Args: + input_sizes: Input tensor dimensions in + [batch, input_rows, input_cols, input_depth]. + filter_sizes: Filter tensor dimensions in + [kernel_rows, kernel_cols, input_depth, output_depth]. + out_backprop_sizes: Output gradients tensor dimensions. + strides: Strides. + dilations: Dilations. + padding: Padding type. + data_format_src: Data format input is in. + data_format_dst: Data format verification will run and input is converted + to. + expected: Expected output. + """ + + total_size_1 = np.prod(filter_sizes) + total_size_2 = np.prod(out_backprop_sizes) + x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(filter_sizes) + x2 = np.arange( + 1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes) + strides = [1] + strides + [1] + if dilations is not None: + dilations = [1] + dilations + [1] + + expected = np.reshape(expected, input_sizes) + + # Convert between data formats. + expected = test_utils.ConvertBetweenDataFormats(expected, data_format_src, + data_format_dst) + x2 = test_utils.ConvertBetweenDataFormats(x2, data_format_src, + data_format_dst) + input_sizes = test_utils.PermuteDimsBetweenDataFormats( + input_sizes, data_format_src, data_format_dst) + out_backprop_sizes = test_utils.PermuteDimsBetweenDataFormats( + out_backprop_sizes, data_format_src, data_format_dst) + strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src, + data_format_dst) + if dilations is not None: + dilations = test_utils.PermuteDimsBetweenDataFormats( + dilations, data_format_src, data_format_dst) + + with self.session() as sess: + t1 = array_ops.placeholder(dtypes.float32, shape=filter_sizes) + t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes) + with self.test_scope(): + out = gen_nn_ops.conv2d_backprop_input( + input_sizes=input_sizes, + filter=t1, + out_backprop=t2, + strides=strides, + dilations=dilations, + padding=padding, + data_format=data_format_dst) + + value = sess.run(out, {t1: x1, t2: x2}) + self.assertAllEqual(input_sizes, value.shape) + self.assertAllClose(expected, value, 1e-3) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x1Filter(self, data_format): + expected_output = [ + 5, 11, 17, 11, 25, 39, 17, 39, 61, 23, 53, 83, 29, 67, 105, 35, 81, 127, + 41, 95, 149, 47, 109, 171, 53, 123, 193, 59, 137, 215, 65, 151, 237, 71, + 165, 259, 77, 179, 281, 83, 193, 303, 89, 207, 325, 95, 221, 347. + ] + self._VerifyValues( + input_sizes=[1, 4, 4, 3], + filter_sizes=[1, 1, 3, 2], + out_backprop_sizes=[1, 4, 4, 2], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterStride3Width5(self, data_format): + expected_output = [1, 2, 0, 2, 4] + self._VerifyValues( + input_sizes=[1, 1, 5, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[3, 3], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterStride3Width6(self, data_format): + expected_output = [1, 2, 0, 2, 4, 0] + self._VerifyValues( + input_sizes=[1, 1, 6, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[3, 3], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterStride3Width7(self, data_format): + expected_output = [1, 2, 0, 2, 4, 0, 0] + self._VerifyValues( + input_sizes=[1, 1, 7, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[3, 3], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterC1Same(self, data_format): + expected_output = [1, 4, 7, 7, 23, 33] + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 2, 3, 1], + strides=[1, 1], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Filter(self, data_format): + expected_output = [ + 14, 32, 50, 100, 163, 226, 167, 212, 257, 122, 140, 158, 478, 541, 604, + 437, 482, 527 + ] + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + out_backprop_sizes=[1, 1, 2, 3], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterSame(self, data_format): + expected_output = [ + 14, 32, 50, 100, 163, 226, 217, 334, 451, 190, 307, 424, 929, 1217, + 1505, 1487, 1883, 2279 + ] + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + out_backprop_sizes=[1, 2, 3, 3], + strides=[1, 1], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2Filter(self, data_format): + expected_output = [1, 4, 4, 3, 10, 8, 5, 16, 12] + self._VerifyValues( + input_sizes=[1, 3, 3, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 3, 2, 1], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterSame(self, data_format): + expected_output = [1, 4, 7, 4, 13, 16, 7, 22, 25] + self._VerifyValues( + input_sizes=[1, 3, 3, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 3, 3, 1], + strides=[1, 1], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterStride2(self, data_format): + expected_output = [1, 2, 5, 4, 6, 0, 0, 0, 0, 0, 3, 6, 13, 8, 12] + self._VerifyValues( + input_sizes=[1, 3, 5, 1], + filter_sizes=[1, 3, 1, 1], + out_backprop_sizes=[1, 2, 2, 1], + strides=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterStride2Same(self, data_format): + expected_output = [1, 2, 2, 3, 4, 6] + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[2, 2], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Depth3ValidBackpropInputStride1x1Dilation2x1( + self, data_format): + self._VerifyValues( + input_sizes=[1, 3, 6, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 5, 1], + strides=[1, 1], + dilations=[2, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[1, 4, 7, 10, 13, 10, 0, 0, 0, 0, 0, 0, 3, 10, 17, 24, 31, 20]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Depth1ValidBackpropInputDilation1x2(self, data_format): + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 1, 1], + strides=[1, 1], + dilations=[1, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[1, 0, 2, 3, 0, 4]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2DEmptyBackpropInputDilation1x2(self, data_format): + self._VerifyValues( + input_sizes=[0, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[0, 1, 1, 1], + strides=[1, 1], + dilations=[1, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=np.zeros([0])) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Depth3ValidBackpropInputDilation2x1(self, data_format): + # The GPU version of this test is not very stable. So adjusting the + # error threshold to 1e-4. + self._VerifyValues( + input_sizes=[1, 3, 2, 3], + filter_sizes=[2, 2, 3, 3], + out_backprop_sizes=[1, 1, 1, 3], + strides=[1, 1], + dilations=[2, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[ + 14, 32, 50, 68, 86, 104, 0, 0, 0, 0, 0, 0, 122, 140, 158, 176, 194, + 212 + ]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2DKernelSizeMatchesInputSizeBackpropInputDilation2x2( + self, data_format): + self._VerifyValues( + input_sizes=[1, 3, 3, 1], + filter_sizes=[2, 2, 1, 2], + out_backprop_sizes=[1, 1, 1, 2], + strides=[1, 1], + dilations=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[5, 0, 11, 0, 0, 0, 17, 0, 23]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2DGroupedFilter(self, data_format): + expected_output = [ + 5, 17, 29, 25, 53, 81, 41, 53, 65, 109, 137, 165, 77, 89, 101, 193, 221, + 249, 113, 125, 137, 277, 305, 333 + ] + self._VerifyValues( + input_sizes=[1, 2, 2, 6], + filter_sizes=[2, 2, 3, 4], + out_backprop_sizes=[1, 1, 1, 4], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + +class Conv2DBackpropFilterTest(xla_test.XLATestCase, parameterized.TestCase): + + def _VerifyValues(self, + input_sizes=None, + filter_sizes=None, + out_backprop_sizes=None, + strides=None, + dilations=None, + padding=None, + data_format_src="NHWC", + data_format_dst="NHWC", + expected=None): + """Tests that gen_nn_ops.conv2d_backprop_filter produces the right output. + + Args: + input_sizes: Input tensor dimensions in + [batch, input_rows, input_cols, input_depth]. + filter_sizes: Filter tensor dimensions in + [kernel_rows, kernel_cols, input_depth, output_depth]. + out_backprop_sizes: Output gradients tensor dimensions. + strides: Stride. + dilations: Dilations. + padding: Padding type. + data_format_src: Data format input is in. + data_format_dst: Data format verification will run and input is converted + to. + expected: Expected output. + """ + + total_size_1 = np.prod(input_sizes) + total_size_2 = np.prod(out_backprop_sizes) + x1 = np.arange(1, total_size_1 + 1, dtype=np.float32).reshape(input_sizes) + x2 = np.arange( + 1, total_size_2 + 1, dtype=np.float32).reshape(out_backprop_sizes) + strides = [1] + strides + [1] + if dilations is not None: + dilations = [1] + dilations + [1] + + expected = np.reshape(expected, filter_sizes) + + # Convert between data formats. + x1 = test_utils.ConvertBetweenDataFormats(x1, data_format_src, + data_format_dst) + x2 = test_utils.ConvertBetweenDataFormats(x2, data_format_src, + data_format_dst) + input_sizes = test_utils.PermuteDimsBetweenDataFormats( + input_sizes, data_format_src, data_format_dst) + out_backprop_sizes = test_utils.PermuteDimsBetweenDataFormats( + out_backprop_sizes, data_format_src, data_format_dst) + strides = test_utils.PermuteDimsBetweenDataFormats(strides, data_format_src, + data_format_dst) + if dilations is not None: + dilations = test_utils.PermuteDimsBetweenDataFormats( + dilations, data_format_src, data_format_dst) + + with self.session() as sess: + t1 = array_ops.placeholder(dtypes.float32, shape=input_sizes) + t2 = array_ops.placeholder(dtypes.float32, shape=out_backprop_sizes) + with self.test_scope(): + tensor = gen_nn_ops.conv2d_backprop_filter( + input=t1, + filter_sizes=filter_sizes, + out_backprop=t2, + strides=strides, + dilations=dilations, + padding=padding, + data_format=data_format_dst) + + value = sess.run(tensor, {t1: x1, t2: x2}) + self.assertAllEqual(filter_sizes, value.shape) + self.assertAllClose(expected, value, 1e-3) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x1Filter(self, data_format): + expected_output = [8056, 8432, 8312, 8704, 8568, 8976] + self._VerifyValues( + input_sizes=[1, 4, 4, 3], + filter_sizes=[1, 1, 3, 2], + out_backprop_sizes=[1, 4, 4, 2], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2Filter(self, data_format): + expected_output = [120, 141] + self._VerifyValues( + input_sizes=[1, 3, 3, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 3, 2, 1], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterDepth1(self, data_format): + expected_output = [5, 8, 14, 17] + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Filter(self, data_format): + expected_output = [ + 17, 22, 27, 22, 29, 36, 27, 36, 45, 32, 43, 54, 37, 50, 63, 42, 57, 72, + 62, 85, 108, 67, 92, 117, 72, 99, 126, 77, 106, 135, 82, 113, 144, 87, + 120, 153 + ] + self._VerifyValues( + input_sizes=[1, 2, 3, 3], + filter_sizes=[2, 2, 3, 3], + out_backprop_sizes=[1, 1, 2, 3], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterStride3Width5(self, data_format): + expected_output = [9, 12] + self._VerifyValues( + input_sizes=[1, 1, 5, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[3, 3], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterStride3Width6(self, data_format): + expected_output = [9, 12] + self._VerifyValues( + input_sizes=[1, 1, 6, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[3, 3], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x2FilterStride3Width7(self, data_format): + expected_output = [9, 12] + self._VerifyValues( + input_sizes=[1, 1, 7, 1], + filter_sizes=[1, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[3, 3], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x3Filter(self, data_format): + expected_output = [5, 8, 11] + self._VerifyValues( + input_sizes=[1, 1, 4, 1], + filter_sizes=[1, 3, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x3FilterSame(self, data_format): + expected_output = [20, 30, 20] + self._VerifyValues( + input_sizes=[1, 1, 4, 1], + filter_sizes=[1, 3, 1, 1], + out_backprop_sizes=[1, 1, 4, 1], + strides=[1, 1], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D1x3FilterSameOutbackprop2(self, data_format): + expected_output = [7, 10, 3] + self._VerifyValues( + input_sizes=[1, 1, 4, 1], + filter_sizes=[1, 3, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[2, 2], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterC1Same(self, data_format): + expected_output = [91, 58, 32, 17] + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 2, 3, 1], + strides=[1, 1], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterStride2(self, data_format): + expected_output = [92, 102, 112] + self._VerifyValues( + input_sizes=[1, 3, 5, 1], + filter_sizes=[1, 3, 1, 1], + out_backprop_sizes=[1, 2, 2, 1], + strides=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2FilterStride2Same(self, data_format): + expected_output = [7, 2, 16, 5] + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 2, 1], + strides=[2, 2], + padding="SAME", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Depth3ValidBackpropFilterStride1x1Dilation2x1( + self, data_format): + self._VerifyValues( + input_sizes=[1, 3, 6, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 5, 1], + strides=[1, 1], + dilations=[2, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[55, 70, 235, 250]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Depth1ValidBackpropFilterDilation1x2(self, data_format): + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 1], + out_backprop_sizes=[1, 1, 1, 1], + strides=[1, 1], + dilations=[1, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[1, 3, 4, 6]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2DEmptyBackpropFilterDilation1x2(self, data_format): + self._VerifyValues( + input_sizes=[1, 2, 3, 1], + filter_sizes=[2, 2, 1, 0], + out_backprop_sizes=[1, 1, 1, 0], + strides=[1, 1], + dilations=[1, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=np.zeros([0])) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2D2x2Depth3ValidBackpropFilterDilation2x2(self, data_format): + self._VerifyValues( + input_sizes=[1, 3, 4, 3], + filter_sizes=[2, 2, 3, 3], + out_backprop_sizes=[1, 1, 2, 3], + strides=[1, 1], + dilations=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[ + 17, 22, 27, 22, 29, 36, 27, 36, 45, 47, 64, 81, 52, 71, 90, 57, 78, + 99, 137, 190, 243, 142, 197, 252, 147, 204, 261, 167, 232, 297, 172, + 239, 306, 177, 246, 315 + ]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2DKernelSizeMatchesInputSizeBackpropFilterDilation2x2( + self, data_format): + self._VerifyValues( + input_sizes=[1, 3, 3, 1], + filter_sizes=[2, 2, 1, 2], + out_backprop_sizes=[1, 1, 1, 2], + strides=[1, 1], + dilations=[2, 2], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=[1, 2, 3, 6, 7, 14, 9, 18]) + + @parameterized.named_parameters(*DATA_FORMATS) + def testConv2DGroupedFilter(self, data_format): + expected_output = [1, 4, 3, 8, 5, 12, 7, 16] + self._VerifyValues( + input_sizes=[1, 2, 2, 2], + filter_sizes=[2, 2, 1, 2], + out_backprop_sizes=[1, 1, 1, 2], + strides=[1, 1], + padding="VALID", + data_format_src="NHWC", + data_format_dst=data_format, + expected=expected_output) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv3d_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv3d_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6487540558ef02322b82c3c2d4647015f241ff42 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv3d_test.py @@ -0,0 +1,860 @@ +# 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 3D convolutions using the XLA JIT.""" + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import test_utils +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import googletest + + +CONV_CONFIGS = ( + ("_Conv3D_data_format_NDHWC", "NDHWC", "Conv3D"), + ("_Conv3D_data_format_NCDHW", "NCDHW", "Conv3D"), + ("_Conv_data_format_NDHWC", "NDHWC", "Conv"), + ("_Conv_data_format_NCDHW", "NCDHW", "Conv"), +) + + +# Test outputs computed in prod (colab) by running nn.conv3d on a GPU device +# with its GPU (non-xla) kernel. +class Conv3DTest(xla_test.XLATestCase, parameterized.TestCase): + + def _VerifyValues( + self, + input_sizes=None, + filter_sizes=None, + strides=None, + dilations=None, + padding=None, + data_format_src="NDHWC", + data_format_dst="NDHWC", + expected=None, + op_name="Conv3D", + ): + """Tests that tf.nn.conv3d produces the expected value. + + Args: + input_sizes: Input tensor dimensions in [batch, input_rows, input_cols, + input_depth]. + filter_sizes: Filter tensor dimensions in [kernel_rows, kernel_cols, + input_depth, output_depth]. + strides: Strides. + dilations: RHS dilations. + padding: Padding type. + data_format_src: Data format input is in. + data_format_dst: Data format verification will run and input is converted + to. + expected: Expected output. + op_name: Name of operation to test (Conv/Conv2D) + """ + + total_size_1 = np.prod(input_sizes) + total_size_2 = np.prod(filter_sizes) + x1 = np.reshape( + [f * 1.0 / total_size_1 for f in range(1, total_size_1 + 1)], + input_sizes, + ) + x2 = np.reshape( + [f * 1.0 / total_size_2 for f in range(1, total_size_2 + 1)], + filter_sizes, + ) + strides = [1] + strides + [1] + if dilations is None: + dilations = [1, 1, 1] + dilations = [1] + dilations + [1] + + # Convert between data formats. + expected = test_utils.ConvertBetweenDataFormats( + expected, data_format_src, data_format_dst + ) + x1 = test_utils.ConvertBetweenDataFormats( + x1, data_format_src, data_format_dst + ) + input_sizes = test_utils.PermuteDimsBetweenDataFormats( + input_sizes, data_format_src, data_format_dst + ) + strides = test_utils.PermuteDimsBetweenDataFormats( + strides, data_format_src, data_format_dst + ) + dilations = test_utils.PermuteDimsBetweenDataFormats( + dilations, data_format_src, data_format_dst + ) + + with self.session() as sess: + t1 = array_ops.placeholder(dtypes.bfloat16, shape=input_sizes) + t2 = array_ops.placeholder(dtypes.bfloat16, shape=filter_sizes) + with self.test_scope(): + if op_name == "Conv": + conv_format = ( + "CHANNELS_LAST" + if data_format_dst == "NDHWC" + else "CHANNELS_FIRST" + ) + out = gen_nn_ops.conv( + t1, + t2, + strides=strides, + padding=padding, + data_format=conv_format, + dilations=dilations, + ) + elif op_name == "Conv3D": + out = nn_ops.conv3d( + t1, + t2, + strides=strides, + padding=padding, + data_format=data_format_dst, + dilations=dilations, + ) + else: + raise ValueError("Invalid op name: %s" % op_name) + + value = sess.run(out, {t1: x1, t2: x2}) + self.assertAllCloseAccordingToType(expected, value) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3D1x1x1Filter(self, data_format, op_name): + expected_output = np.reshape( + [ + 0.18518518518518517, + 0.2222222222222222, + 0.25925925925925924, + 0.4074074074074074, + 0.5, + 0.5925925925925926, + 0.6296296296296297, + 0.7777777777777777, + 0.9259259259259259, + 0.8518518518518519, + 1.0555555555555556, + 1.259259259259259, + 1.074074074074074, + 1.3333333333333333, + 1.5925925925925926, + 1.2962962962962963, + 1.6111111111111112, + 1.9259259259259258, + ], + [1, 2, 3, 1, 3], + ) + + # These are equivalent to the Conv2D1x1 case. + self._VerifyValues( + input_sizes=[1, 2, 3, 1, 3], + filter_sizes=[1, 1, 1, 3, 3], + strides=[1, 1, 1], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + self._VerifyValues( + input_sizes=[1, 2, 1, 3, 3], + filter_sizes=[1, 1, 1, 3, 3], + strides=[1, 1, 1], + padding="VALID", + expected=np.reshape(expected_output, [1, 2, 1, 3, 3]), + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + self._VerifyValues( + input_sizes=[1, 1, 2, 3, 3], + filter_sizes=[1, 1, 1, 3, 3], + strides=[1, 1, 1], + padding="VALID", + expected=np.reshape(expected_output, [1, 1, 2, 3, 3]), + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3D1x1x1Filter2x1x1Dilation(self, data_format, op_name): + expected_output = np.reshape( + [ + 0.05555555555555555, + 0.1111111111111111, + 0.16666666666666666, + 0.2222222222222222, + 0.2777777777777778, + 0.3333333333333333, + 0.3888888888888889, + 0.4444444444444444, + 0.5, + 0.5555555555555556, + 0.6111111111111112, + 0.6666666666666666, + 0.7222222222222222, + 0.7777777777777778, + 0.8333333333333334, + 0.8888888888888888, + 0.9444444444444444, + 1.0, + ], + [1, 3, 6, 1, 1], + ) + + self._VerifyValues( + input_sizes=[1, 3, 6, 1, 1], + filter_sizes=[1, 1, 1, 1, 1], + strides=[1, 1, 1], + padding="VALID", + dilations=[2, 1, 1], + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + # Expected values computed using scipy's correlate function. + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3D2x2x2Filter(self, data_format, op_name): + expected_output = np.reshape( + [ + 3.7719907407407405, + 3.850694444444445, + 3.929398148148149, + 4.265046296296295, + 4.357638888888888, + 4.450231481481481, + 6.730324074074074, + 6.892361111111109, + 7.054398148148148, + 7.223379629629629, + 7.399305555555557, + 7.575231481481481, + 9.688657407407408, + 9.934027777777779, + 10.17939814814815, + 10.181712962962962, + 10.440972222222221, + 10.700231481481481, + ], + [1, 3, 1, 2, 3], + ) + # expected_shape = [1, 3, 1, 2, 5] + self._VerifyValues( + input_sizes=[1, 4, 2, 3, 3], # b, z, y, x, fin + filter_sizes=[2, 2, 2, 3, 3], # z, y, x, fin, fout + strides=[1, 1, 1], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3D2x2x2Filter1x2x1Dilation(self, data_format, op_name): + expected_output = np.reshape( + [ + 1.1388888888888888, + 1.2013888888888888, + 1.3263888888888888, + 1.3888888888888888, + 1.5138888888888888, + 1.5763888888888888, + 1.701388888888889, + 1.763888888888889, + 2.263888888888889, + 2.3263888888888893, + 2.451388888888889, + 2.513888888888889, + 2.6388888888888893, + 2.701388888888889, + 2.826388888888889, + 2.888888888888889, + 3.388888888888889, + 3.451388888888889, + 3.576388888888889, + 3.6388888888888884, + 3.7638888888888893, + 3.8263888888888893, + 3.9513888888888893, + 4.013888888888889, + ], + [1, 3, 4, 2, 1], + ) + + self._VerifyValues( + input_sizes=[1, 4, 6, 3, 1], + filter_sizes=[2, 2, 2, 1, 1], + strides=[1, 1, 1], + padding="VALID", + dilations=[1, 2, 1], + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3DStrides(self, data_format, op_name): + expected_output = np.reshape( + [ + 0.06071428571428571, + 0.08988095238095238, + 0.10238095238095238, + 0.11488095238095238, + 0.12738095238095237, + 0.13988095238095238, + 0.08452380952380953, + 0.26071428571428573, + 0.35238095238095235, + 0.36488095238095236, + 0.3773809523809524, + 0.3898809523809524, + 0.4023809523809524, + 0.23452380952380952, + 0.46071428571428574, + 0.6148809523809524, + 0.6273809523809524, + 0.6398809523809523, + 0.6523809523809524, + 0.6648809523809525, + 0.3845238095238095, + 1.1273809523809524, + 1.4898809523809524, + 1.5023809523809524, + 1.5148809523809523, + 1.5273809523809523, + 1.5398809523809525, + 0.8845238095238095, + 1.3273809523809526, + 1.7523809523809522, + 1.764880952380952, + 1.7773809523809523, + 1.7898809523809525, + 1.8023809523809526, + 1.0345238095238096, + 1.5273809523809525, + 2.0148809523809526, + 2.0273809523809523, + 2.0398809523809525, + 2.052380952380952, + 2.0648809523809524, + 1.1845238095238095, + 2.1940476190476192, + 2.8898809523809526, + 2.9023809523809527, + 2.9148809523809525, + 2.9273809523809526, + 2.9398809523809524, + 1.6845238095238095, + 2.394047619047619, + 3.1523809523809523, + 3.1648809523809525, + 3.177380952380952, + 3.1898809523809524, + 3.2023809523809526, + 1.8345238095238097, + 2.594047619047619, + 3.4148809523809525, + 3.427380952380952, + 3.4398809523809524, + 3.4523809523809526, + 3.4648809523809523, + 1.9845238095238096, + ], + [1, 3, 3, 7, 1], + ) + self._VerifyValues( + input_sizes=[1, 5, 8, 7, 1], + filter_sizes=[1, 2, 3, 1, 1], + strides=[2, 3, 1], # different stride for each spatial dimension + padding="SAME", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3D2x2x2FilterStride2(self, data_format, op_name): + expected_output = np.reshape( + [ + 3.7719907407407405, + 3.850694444444445, + 3.929398148148149, + 9.688657407407408, + 9.934027777777779, + 10.17939814814815, + ], + [1, 2, 1, 1, 3], + ) + self._VerifyValues( + input_sizes=[1, 4, 2, 3, 3], + filter_sizes=[2, 2, 2, 3, 3], + strides=[2, 2, 2], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3DStride3(self, data_format, op_name): + expected_output = np.reshape( + [ + 1.5114087301587302, + 1.5716765873015872, + 1.6319444444444446, + 1.5634920634920635, + 1.6267361111111112, + 1.6899801587301588, + 1.6155753968253967, + 1.681795634920635, + 1.748015873015873, + 1.9280753968253967, + 2.012152777777778, + 2.096230158730159, + 1.9801587301587302, + 2.067212301587302, + 2.154265873015873, + 2.0322420634920637, + 2.122271825396825, + 2.2123015873015874, + 4.428075396825396, + 4.65500992063492, + 4.881944444444444, + 4.480158730158729, + 4.710069444444444, + 4.939980158730158, + 4.532242063492063, + 4.7651289682539675, + 4.9980158730158735, + 4.844742063492064, + 5.095486111111112, + 5.346230158730158, + 4.896825396825397, + 5.150545634920635, + 5.4042658730158735, + 4.94890873015873, + 5.205605158730158, + 5.462301587301588, + ], + [1, 2, 2, 3, 3], + ) + self._VerifyValues( + input_sizes=[1, 6, 7, 8, 2], + filter_sizes=[3, 2, 1, 2, 3], + strides=[3, 3, 3], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testConv3D2x2x2FilterStride2Same(self, data_format, op_name): + expected_output = np.reshape( + [ + 3.7719907407407405, + 3.850694444444445, + 3.929398148148149, + 2.0162037037037037, + 2.0659722222222223, + 2.1157407407407405, + 9.688657407407408, + 9.934027777777779, + 10.17939814814815, + 4.599537037037037, + 4.732638888888889, + 4.8657407407407405, + ], + [1, 2, 1, 2, 3], + ) + self._VerifyValues( + input_sizes=[1, 4, 2, 3, 3], + filter_sizes=[2, 2, 2, 3, 3], + strides=[2, 2, 2], + padding="SAME", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testKernelSmallerThanStride(self, data_format, op_name): + expected_output = np.reshape( + [ + 0.037037037037037035, + 0.1111111111111111, + 0.25925925925925924, + 0.3333333333333333, + 0.7037037037037037, + 0.7777777777777778, + 0.9259259259259259, + 1.0, + ], + [1, 2, 2, 2, 1], + ) + + self._VerifyValues( + input_sizes=[1, 3, 3, 3, 1], + filter_sizes=[1, 1, 1, 1, 1], + strides=[2, 2, 2], + padding="SAME", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + self._VerifyValues( + input_sizes=[1, 3, 3, 3, 1], + filter_sizes=[1, 1, 1, 1, 1], + strides=[2, 2, 2], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + expected_output = np.reshape( + [ + 0.5408163265306123, + 0.5801749271137027, + 0.28061224489795916, + 0.8163265306122448, + 0.8556851311953353, + 0.4030612244897959, + 0.41873177842565595, + 0.43403790087463556, + 0.19642857142857142, + 2.4693877551020407, + 2.5087463556851315, + 1.1377551020408163, + 2.7448979591836733, + 2.7842565597667637, + 1.260204081632653, + 1.168731778425656, + 1.1840379008746356, + 0.5178571428571429, + 1.0951166180758019, + 1.1060495626822158, + 0.4464285714285714, + 1.1716472303206997, + 1.1825801749271136, + 0.4770408163265306, + 0.3691690962099125, + 0.37244897959183676, + 0.125, + ], + [1, 3, 3, 3, 1], + ) + self._VerifyValues( + input_sizes=[1, 7, 7, 7, 1], + filter_sizes=[2, 2, 2, 1, 1], + strides=[3, 3, 3], + padding="SAME", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + expected_output = np.reshape( + [ + 0.5408163265306123, + 0.5801749271137027, + 0.8163265306122448, + 0.8556851311953353, + 2.4693877551020407, + 2.5087463556851315, + 2.7448979591836733, + 2.7842565597667637, + ], + [1, 2, 2, 2, 1], + ) + self._VerifyValues( + input_sizes=[1, 7, 7, 7, 1], + filter_sizes=[2, 2, 2, 1, 1], + strides=[3, 3, 3], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + @parameterized.named_parameters(*CONV_CONFIGS) + def testKernelSizeMatchesInputSize(self, data_format, op_name): + expected_output = np.reshape([1.5625, 1.875], [1, 1, 1, 1, 2]) + self._VerifyValues( + input_sizes=[1, 2, 1, 2, 1], + filter_sizes=[2, 1, 2, 1, 2], + strides=[1, 1, 1], + padding="VALID", + expected=expected_output, + data_format_src="NDHWC", + data_format_dst=data_format, + op_name=op_name, + ) + + def testConvExpandedBatch(self): + tensor_in_sizes_batch = [10, 2, 3, 1, 3] + tensor_in_sizes_expanded_batch = [2, 5, 2, 3, 1, 3] + batch_dims = 2 + filter_in_sizes = [1, 1, 1, 3, 3] + filter_in = np.arange( + 1, np.prod(filter_in_sizes) + 1, dtype=np.float32 + ).reshape(filter_in_sizes) + x1 = np.arange( + 1, np.prod(tensor_in_sizes_batch) + 1, dtype=np.float32 + ).reshape(tensor_in_sizes_batch) + x2 = x1.reshape(tensor_in_sizes_expanded_batch) + + with self.session() as sess: + t1 = array_ops.placeholder(dtypes.bfloat16, shape=tensor_in_sizes_batch) + t2 = array_ops.placeholder( + dtypes.bfloat16, shape=tensor_in_sizes_expanded_batch + ) + filter_t = array_ops.placeholder(dtypes.bfloat16, shape=filter_in_sizes) + + out1 = gen_nn_ops.conv( + t1, filter_t, strides=[1, 1, 1, 1, 1], padding="VALID" + ) + out2 = gen_nn_ops.conv( + t2, + filter_t, + strides=[1, 1, 1, 1, 1], + padding="VALID", + batch_dims=batch_dims, + ) + value1 = sess.run(out1, {t1: x1, filter_t: filter_in}) + value2 = sess.run(out2, {t2: x2, filter_t: filter_in}) + + self.assertEqual(list(value1.shape), tensor_in_sizes_batch) + self.assertEqual(list(value2.shape), tensor_in_sizes_expanded_batch) + self.assertAllCloseAccordingToType(value1, value2.reshape(value1.shape)) + + +# Test cloned from +# tensorflow/python/kernel_tests/conv3d_backprop_filter_v2_grad_test.py +class Conv3DBackpropFilterV2GradTest(xla_test.XLATestCase): + + def testGradient(self): + with self.session(), self.test_scope(): + for padding in ["SAME", "VALID"]: + for stride in [1, 2]: + np.random.seed(1) + in_shape = [2, 4, 3, 3, 2] + in_val = constant_op.constant( + 2 * np.random.random_sample(in_shape) - 1, dtype=dtypes.float32) + filter_shape = [3, 3, 3, 2, 3] + strides = [1, stride, stride, stride, 1] + # Make a convolution op with the current settings, just to easily get + # the shape of the output. + conv_out = nn_ops.conv3d(in_val, + array_ops.zeros(filter_shape), strides, + padding) + out_backprop_shape = conv_out.get_shape().as_list() + out_backprop_val = constant_op.constant( + 2 * np.random.random_sample(out_backprop_shape) - 1, + dtype=dtypes.float32) + output = nn_ops.conv3d_backprop_filter_v2(in_val, filter_shape, + out_backprop_val, strides, + padding) + err = gradient_checker.compute_gradient_error( + [in_val, out_backprop_val], [in_shape, out_backprop_shape], + output, filter_shape) + print("conv3d_backprop_filter gradient err = %g " % err) + err_tolerance = 1e-3 + self.assertLess(err, err_tolerance) + + +# Test cloned from tensorflow/python/kernel_tests/conv3d_transpose_test.py +class Conv3DTransposeTest(xla_test.XLATestCase): + + def testConv3DTransposeSingleStride(self): + with self.session(), self.test_scope(): + strides = [1, 1, 1, 1, 1] + + # Input, output: [batch, depth, height, width, channel] + x_shape = [2, 5, 6, 4, 3] + y_shape = [2, 5, 6, 4, 2] + + # Filter: [kernel_depth, kernel_height, kernel_width, out_depth, in_depth] + f_shape = [3, 3, 3, 2, 3] + + x = constant_op.constant( + 1.0, shape=x_shape, name="x", dtype=dtypes.float32) + f = constant_op.constant( + 1.0, shape=f_shape, name="filter", dtype=dtypes.float32) + output = nn_ops.conv3d_transpose( + x, f, y_shape, strides=strides, padding="SAME") + value = self.evaluate(output) + + # We count the number of cells being added at the locations in the output. + # At the center, #cells = kernel_depth * kernel_height * kernel_width + # At the corners, #cells = ceil(kernel_depth/2) * ceil(kernel_height/2) + # * ceil(kernel_width/2) + # At the edges, #cells = + # kernel_depth * ceil(kernel_height/2) * ceil(kernel_width/2) or + # ceil(kernel_depth/2) * kernel_height * ceil(kernel_width/2) or + # ceil(kernel_depth/2) * ceil(kernel_height/2) * kernel_width + # At the borders, #cells = + # ceil(kernel_depth/2) * kernel_height * kernel_width or + # kernel_depth * ceil(kernel_height/2) * kernel_width or + # kernel_depth * kernel_height * ceil(kernel_width/2) + + for n in range(x_shape[0]): + for k in range(f_shape[3]): + for w in range(y_shape[3]): + for h in range(y_shape[2]): + for d in range(y_shape[1]): + d_in = d > 0 and d < y_shape[1] - 1 + h_in = h > 0 and h < y_shape[2] - 1 + w_in = w > 0 and w < y_shape[3] - 1 + if d_in + h_in + w_in == 3: + target = 27 * 3.0 + elif d_in + h_in + w_in == 2: + target = 18 * 3.0 + elif d_in or h_in or w_in: + target = 12 * 3.0 + else: + target = 8 * 3.0 + self.assertAllClose(target, value[n, d, h, w, k]) + + def testConv3DTransposeSame(self): + with self.session(), self.test_scope(): + strides = [1, 2, 2, 2, 1] + + # Input, output: [batch, depth, height, width, depth] + x_shape = [2, 5, 6, 4, 3] + y_shape = [2, 10, 12, 8, 2] + + # Filter: [kernel_depth, kernel_height, kernel_width, out_depth, in_depth] + f_shape = [3, 3, 3, 2, 3] + + x = constant_op.constant( + 1.0, shape=x_shape, name="x", dtype=dtypes.float32) + f = constant_op.constant( + 1.0, shape=f_shape, name="filter", dtype=dtypes.float32) + output = nn_ops.conv3d_transpose( + x, f, y_shape, strides=strides, padding="SAME") + value = self.evaluate(output) + + for n in range(x_shape[0]): + for k in range(f_shape[3]): + for w in range(y_shape[3]): + for h in range(y_shape[2]): + for d in range(y_shape[1]): + # We add a case for locations divisible by the stride. + d_in = d % strides[1] == 0 and 0 < d < y_shape[1] - 1 + h_in = h % strides[2] == 0 and 0 < h < y_shape[2] - 1 + w_in = w % strides[3] == 0 and 0 < w < y_shape[3] - 1 + if d_in + h_in + w_in == 3: + target = 8 * 3.0 + elif d_in + h_in + w_in == 2: + target = 4 * 3.0 + elif d_in or h_in or w_in: + target = 2 * 3.0 + else: + target = 3.0 + self.assertAllClose(target, value[n, d, h, w, k]) + + def testConv3DTransposeValid(self): + with self.session(), self.test_scope(): + strides = [1, 2, 2, 2, 1] + + # Input, output: [batch, depth, height, width, depth] + x_shape = [2, 5, 6, 4, 3] + y_shape = [2, 11, 13, 9, 2] + + # Filter: [kernel_depth, kernel_height, kernel_width, out_depth, in_depth] + f_shape = [3, 3, 3, 2, 3] + + x = constant_op.constant( + 1.0, shape=x_shape, name="x", dtype=dtypes.float32) + f = constant_op.constant( + 1.0, shape=f_shape, name="filter", dtype=dtypes.float32) + output = nn_ops.conv3d_transpose( + x, f, y_shape, strides=strides, padding="VALID") + value = self.evaluate(output) + + cache_values = np.zeros(y_shape, dtype=np.float32) + + # The amount of padding added + pad = 1 + + for n in range(x_shape[0]): + for k in range(f_shape[3]): + for w in range(y_shape[3]): + for h in range(y_shape[2]): + for d in range(y_shape[1]): + # We add a case for locations divisible by the stride. + d_in = d % strides[1] == 0 and pad < d < y_shape[1] - 1 - pad + h_in = h % strides[2] == 0 and pad < h < y_shape[2] - 1 - pad + w_in = w % strides[3] == 0 and pad < w < y_shape[3] - 1 - pad + if d_in + h_in + w_in == 3: + target = 8 * 3.0 + elif d_in + h_in + w_in == 2: + target = 4 * 3.0 + elif d_in or h_in or w_in: + target = 2 * 3.0 + else: + target = 3.0 + cache_values[n, d, h, w, k] = target + + # copy values in the border + cache_values[n, :, :, 0, k] = cache_values[n, :, :, 1, k] + cache_values[n, :, :, -1, k] = cache_values[n, :, :, -2, k] + cache_values[n, :, 0, :, k] = cache_values[n, :, 1, :, k] + cache_values[n, :, -1, :, k] = cache_values[n, :, -2, :, k] + cache_values[n, 0, :, :, k] = cache_values[n, 1, :, :, k] + cache_values[n, -1, :, :, k] = cache_values[n, -2, :, :, k] + + self.assertAllClose(cache_values, value) + + def testGradient(self): + x_shape = [2, 3, 4, 3, 2] + f_shape = [3, 3, 3, 2, 2] + y_shape = [2, 6, 8, 6, 2] + strides = [1, 2, 2, 2, 1] + np.random.seed(1) # Make it reproducible. + x_val = np.random.random_sample(x_shape).astype(np.float64) + f_val = np.random.random_sample(f_shape).astype(np.float64) + with self.session(), self.test_scope(): + x = constant_op.constant(x_val, name="x", dtype=dtypes.float32) + f = constant_op.constant(f_val, name="f", dtype=dtypes.float32) + output = nn_ops.conv3d_transpose( + x, f, y_shape, strides=strides, padding="SAME") + err = gradient_checker.compute_gradient_error([x, f], [x_shape, f_shape], + output, y_shape) + print("conv3d_transpose gradient err = %g " % err) + err_tolerance = 0.001 + self.assertLess(err, err_tolerance) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv_node_name_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv_node_name_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1c75605d08a4b48026183f539a78ceaacc241b4e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/conv_node_name_test.py @@ -0,0 +1,118 @@ +# 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 Convolution node name match via the XLA JIT. + +The canned results in these tests are created by running each test using the +Tensorflow CPU device and saving the output. +""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import ops +from tensorflow.python.layers import layers +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.platform import googletest + + +class ConvolutionNodeNameTest(xla_test.XLATestCase): + """Verify convolution node name match. + + Verify convolution node names on TPU and CPU match with dilation > 1. + """ + + def _verifyNodeNameMatch(self, layer, input_sizes, filter_sizes, strides, + dilations): + + def _GetNodeNames(use_xla): + with self.session(): + input_tensor = array_ops.placeholder(np.float32, shape=input_sizes) + + if use_xla: + with self.device_scope(): + # pylint: disable=protected-access + graph = ops.get_default_graph() + graph._set_control_flow_context( + control_flow_ops.XLAControlFlowContext()) + # pylint: enable=protected-access + conv2d_op = layer( + filters=64, + kernel_size=filter_sizes, + dilation_rate=dilations, + padding="same") + _ = conv2d_op(input_tensor) + return [n.name for n in ops.get_default_graph().as_graph_def().node] + else: + with ops.device("CPU"): + conv2d_op = layer( + filters=64, + kernel_size=filter_sizes, + dilation_rate=dilations, + padding="same") + _ = conv2d_op(input_tensor) + names = [ + n.name for n in ops.get_default_graph().as_graph_def().node + ] + # filter out space to depth ops. + return [ + name for name in names + if "space" not in name and "Space" not in name + ] + + xla_names = _GetNodeNames(use_xla=True) + no_xla_names = _GetNodeNames(use_xla=False) + + # CPU path creates some additional nodes to handle dilations. + # TODO(b/138804006): Remove this when CPU & GPU support dilations. + filtered_no_xla_names = [] + for name in no_xla_names: + if ("dilation_rate" in name or "filter_shape" in name or "stack" in name): + continue + else: + filtered_no_xla_names.append(name) + + self.assertListEqual(xla_names, filtered_no_xla_names) + + def testConv1DNodeNameMatch(self): + input_sizes = [8, 16, 3] + filter_sizes = [7] + strides = 1 + dilations = [2] + layer = layers.Conv1D + self._verifyNodeNameMatch(layer, input_sizes, filter_sizes, strides, + dilations) + + def testConv2DNodeNameMatch(self): + input_sizes = [8, 16, 16, 3] + filter_sizes = [7, 7] + strides = 1 + dilations = [2, 2] + layer = layers.Conv2D + self._verifyNodeNameMatch(layer, input_sizes, filter_sizes, strides, + dilations) + + def testConv3DNodeNameMatch(self): + input_sizes = [8, 16, 16, 16, 3] + filter_sizes = [7, 7, 7] + strides = 1 + dilations = [2, 2, 2] + layer = layers.Conv3D + self._verifyNodeNameMatch(layer, input_sizes, filter_sizes, strides, + dilations) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/data_format_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/data_format_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e021d55f4ac27db72407c78d6ef2d8d302e0464c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/data_format_ops_test.py @@ -0,0 +1,147 @@ +# 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 DataFormatVecPermute operator.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import test + + +class XlaDataFormatDimMapTest(xla_test.XLATestCase): + + def _test(self, input_data, src_format, dst_format, expected): + for dtype in {np.int32, np.int64}: + x = np.array(input_data, dtype=dtype) + with self.session() as session: + with self.test_scope(): + placeholder = array_ops.placeholder(dtypes.as_dtype(x.dtype), x.shape) + param = {placeholder: x} + output = nn_ops.data_format_dim_map( + placeholder, src_format=src_format, dst_format=dst_format) + result = session.run(output, param) + self.assertAllEqual(result, expected) + + def test(self): + self._test(0, "NHWC", "NCHW", 0) + self._test(1, "NHWC", "NCHW", 2) + self._test(2, "NHWC", "NCHW", 3) + self._test(3, "NHWC", "NCHW", 1) + self._test(-1, "NHWC", "NCHW", 1) + self._test(-2, "NHWC", "NCHW", 3) + self._test(-3, "NHWC", "NCHW", 2) + self._test(-4, "NHWC", "NCHW", 0) + self._test([1, 3], "NHWC", "NCHW", [2, 1]) + self._test([1, 3, -2], "NHWC", "NCHW", [2, 1, 3]) + self._test([1, -3, -2], "NHWC", "NCHW", [2, 2, 3]) + self._test([[1, -3], [1, -1]], "NHWC", "NCHW", [[2, 2], [2, 1]]) + + self._test([1, -3, -2], "NHWC", "NCHW", [2, 2, 3]) + self._test([-4, -3, -2, -1, 0, 1, 2, 3], "NHWC", "HWNC", + [2, 0, 1, 3, 2, 0, 1, 3]) + self._test([-4, -3, -2, -1, 0, 1, 2, 3], "NHWC", "WHCN", + [3, 1, 0, 2, 3, 1, 0, 2]) + self._test([-4, -3, -2, -1, 0, 1, 2, 3], "qwer", "rewq", + [3, 2, 1, 0, 3, 2, 1, 0]) + + self._test(0, "NDHWC", "NCDHW", 0) + self._test(1, "NDHWC", "NCDHW", 2) + self._test(2, "NDHWC", "NCDHW", 3) + self._test(3, "NDHWC", "NCDHW", 4) + self._test(4, "NDHWC", "NCDHW", 1) + self._test([1, 4], "NDHWC", "NCDHW", [2, 1]) + self._test([1, 4, -2], "NDHWC", "NCDHW", [2, 1, 4]) + self._test([1, -3, -2], "NDHWC", "NCDHW", [2, 3, 4]) + self._test([[1, -4], [1, -1]], "NDHWC", "NCDHW", [[2, 2], [2, 1]]) + + self._test([1, -3, -2], "NDHWC", "NCDHW", [2, 3, 4]) + self._test([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4], "NDHWC", "DHWNC", + [3, 0, 1, 2, 4, 3, 0, 1, 2, 4]) + self._test([-5, -4, -3, -2, -1, 0, 1, 2, 3, 4], "NDHWC", "WHDCN", + [4, 2, 1, 0, 3, 4, 2, 1, 0, 3]) + + +class XlaPermuteOpTest(xla_test.XLATestCase): + + def _runPermuteAndCompare(self, x, src_format, dst_format, expected): + with self.session() as session: + with self.test_scope(): + placeholder = array_ops.placeholder(dtypes.as_dtype(x.dtype), x.shape) + param = {placeholder: x} + output = nn_ops.data_format_vec_permute( + placeholder, src_format=src_format, dst_format=dst_format) + result = session.run(output, param) + self.assertAllEqual(result, expected) + + def testNHWCToNCHW(self): + for dtype in {np.int32, np.int64}: + x = np.array([7, 4, 9, 3], dtype=dtype) + self._runPermuteAndCompare(x, "NHWC", "NCHW", [7, 3, 4, 9]) + + def testNHWCToNCHW_Size2(self): + for dtype in {np.int32, np.int64}: + x = np.array([4, 9], dtype=dtype) + self._runPermuteAndCompare(x, "NHWC", "NCHW", [4, 9]) + + def testNCHWToNHWC(self): + for dtype in {np.int32, np.int64}: + x = np.array([7, 4, 9, 3], dtype=dtype) + self._runPermuteAndCompare(x, "NCHW", "NHWC", [7, 9, 3, 4]) + + def testNCHWToNHWC_Size2(self): + for dtype in {np.int32, np.int64}: + x = np.array([9, 3], dtype=dtype) + self._runPermuteAndCompare(x, "NCHW", "NHWC", [9, 3]) + + def testNHWCToHWNC(self): + for dtype in {np.int32, np.int64}: + x = np.array([7, 4, 9, 3], dtype=dtype) + self._runPermuteAndCompare(x, "NHWC", "HWNC", [4, 9, 7, 3]) + + def testHWNCToNHWC(self): + for dtype in {np.int32, np.int64}: + x = np.array([7, 4, 9, 3], dtype=dtype) + self._runPermuteAndCompare(x, "HWNC", "NHWC", [9, 7, 4, 3]) + + def testNHWCToNCHW2D(self): + for dtype in {np.int32, np.int64}: + x = np.array([[7, 4], [9, 3], [4, 5], [5, 1]], dtype=dtype) + self._runPermuteAndCompare(x, "NHWC", "NCHW", + [[7, 4], [5, 1], [9, 3], [4, 5]]) + + def testNHWCToHWNC2D(self): + for dtype in {np.int32, np.int64}: + x = np.array([[7, 4], [9, 3], [4, 5], [5, 1]], dtype=dtype) + self._runPermuteAndCompare(x, "NHWC", "HWNC", + [[9, 3], [4, 5], [7, 4], [5, 1]]) + + def testHWNCToNHWC2D(self): + for dtype in {np.int32, np.int64}: + x = np.array([[7, 4], [9, 3], [4, 5], [5, 1]], dtype=dtype) + self._runPermuteAndCompare(x, "HWNC", "NHWC", + [[4, 5], [7, 4], [9, 3], [5, 1]]) + + def testNCHWToNHWC2D(self): + for dtype in {np.int32, np.int64}: + x = np.array([[7, 4], [9, 3], [4, 5], [5, 1]], dtype=dtype) + self._runPermuteAndCompare(x, "NCHW", "NHWC", + [[7, 4], [4, 5], [5, 1], [9, 3]]) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/dense_layer_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/dense_layer_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b409c58e9e1af30bb3dea68361091da09d6d3870 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/dense_layer_test.py @@ -0,0 +1,141 @@ +# 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 DenseLayer JIT compilation on the CPU and GPU devices.""" + +import os + +import numpy as np + +from tensorflow.compiler.tests import test_utils +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.compiler.xla import jit +from tensorflow.python.framework import ops +from tensorflow.python.layers import layers +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + +jit_scope = jit.experimental_jit_scope + +def GetRunMetadataLabels(run_metadata): + """Returns all labels in run_metadata.""" + labels = [] + for dev_stats in run_metadata.step_stats.dev_stats: + for node_stats in dev_stats.node_stats: + labels.append(node_stats.timeline_label) + return labels + + +def InLabels(labels, substr): + """Returns true iff one of the labels contains substr.""" + return any(substr in x for x in labels) + + +class DenseLayerTest(test.TestCase): + + def countXlaOps(self, labels): + """Count how many XlaCompile/XlaRun labels are present.""" + xla_compile_count = sum("XlaCompile(" in x for x in labels) + xla_run_count = sum("XlaRun(" in x for x in labels) + self.assertEqual(xla_compile_count, xla_run_count) + return xla_run_count + + + def testDenseLayerAutoJit(self): + """Tests dense layer compilation in auto-jit mode. + + Dense layer should be compiled into a single XlaCompile/XlaRun op pair in + auto-jit mode. + """ + + os.environ["TF_XLA_FLAGS"] = ( + "--tf_xla_cpu_global_jit " + os.environ.get("TF_XLA_FLAGS", "")) + config = config_pb2.ConfigProto() + config.graph_options.optimizer_options.global_jit_level = ( + config_pb2.OptimizerOptions.ON_1) + + with self.session(config=config) as sess: + x = array_ops.placeholder(shape=[None, None, 3], dtype=np.float32) + y = layers.dense(x, 3) + + self.evaluate(variables.global_variables_initializer()) + run_metadata = config_pb2.RunMetadata() + test_utils.RunWithWarmup( + sess, + y, {x: np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + + labels = GetRunMetadataLabels(run_metadata) + self.assertEqual(1, self.countXlaOps(labels)) + self.assertFalse(InLabels(labels, "MatMult")) + + def testDenseLayerJitScopeDefinedShape(self): + """Tests that the dense layer node is properly compiled in jit scope. + + Dense layer with static shape input tensor should be compiled into a single + XlaCompile/XlaRun op pair by XLA. + """ + + with self.session() as sess: + x = array_ops.placeholder(shape=[2, 2, 3], dtype=np.float32) + with jit_scope(): + y = layers.dense(x, 3) + + self.evaluate(variables.global_variables_initializer()) + run_metadata = config_pb2.RunMetadata() + test_utils.RunWithWarmup( + sess, + y, {x: np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + + labels = GetRunMetadataLabels(run_metadata) + self.assertEqual(1, self.countXlaOps(labels)) + # No need to check whether ListDiff is compiled or not because ListDiff op + # is not used when input tensor shape is fully defined. + + def testDenseLayerJitScopeUndefinedShape(self): + """Tests that the dense layer node is properly compiled in jit scope. + """ + + with self.session() as sess: + x = array_ops.placeholder(shape=[None, None, 3], dtype=np.float32) + with jit_scope(): + y = layers.dense(x, 3) + + self.evaluate(variables.global_variables_initializer()) + run_metadata = config_pb2.RunMetadata() + test_utils.RunWithWarmup( + sess, + y, {x: np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + + labels = GetRunMetadataLabels(run_metadata) + self.assertEqual(1, self.countXlaOps(labels)) + self.assertFalse(InLabels(labels, "MatMult")) + + +if __name__ == "__main__": + os.environ["TF_XLA_FLAGS"] = ("--tf_xla_enable_lazy_compilation=true " + + os.environ.get("TF_XLA_FLAGS", "")) + # This test is using Tensorflow sessions which are not compatible with eager + # mode. + ops.disable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/depthwise_conv_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/depthwise_conv_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c9b460df17ebbf231aebfc0fdf70a722a296e5d4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/depthwise_conv_op_test.py @@ -0,0 +1,701 @@ +# 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. +# ============================================================================== +"""Functional tests for depthwise convolutional operations.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_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 array_ops +from tensorflow.python.ops import nn_impl +from tensorflow.python.ops import nn_ops +import tensorflow.python.ops.nn_grad # pylint: disable=unused-import +from tensorflow.python.platform import test + + +# Reference implementation of depthwise_conv2d +def ReferenceDepthwiseConv2D(input_tensor, filter_tensor, strides, padding, + data_format=None): + # Reference implementation of depthwise convolution that uses regular + # convolution. + convs = [] + in_channels = filter_tensor.shape[2] + # Use a custom implementation of depthwise conv2d using slicing. + for channel in range(in_channels): + # Slice the input along channel + if data_format == "NCHW": + input_slice = input_tensor[:, channel:channel+1, :, :] + else: + input_slice = input_tensor[:, :, :, channel:channel+1] + + # Slice the filters. Filters are H, W, InC, DepthMultiplier + filter_slice = filter_tensor[:, :, channel:channel+1, :] + # Do conv + convs.append(nn_ops.conv2d(input_slice, filter_slice, + strides, padding, + data_format=data_format, + name="depthwise_slice_%d" % channel)) + + # Concat along dimension. + if data_format == "NCHW": + return array_ops.concat(convs, 1) + else: + return array_ops.concat(convs, 3) + + +def ConfigsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + Yields: + Tuple (input_size, filter_size, out_size, stride, padding), the depthwise + convolution parameters. + """ + input_sizes = [[4, 5, 5, 48], [2, 5, 5, 48], [4, 8, 8, 84], [4, 17, 17, 48], + [4, 9, 27, 8], [4, 31, 31, 7], [4, 35, 35, 2], + [4, 147, 147, 2], [3, 299, 299, 3], [5, 183, 183, 1]] + filter_sizes = [[1, 1, 48, 2], [2, 2, 48, 8], [1, 3, 84, 1], [3, 1, 48, 4], + [3, 3, 8, 1], [3, 3, 7, 1], [5, 5, 2, 1], [3, 3, 2, 8], + [2, 2, 3, 8], [5, 5, 1, 2]] + out_sizes = [[4, 5, 5, 96], [2, 5, 5, 384], [4, 8, 8, 84], [4, 17, 17, 192], + [4, 9, 27, 8], [4, 31, 31, 7], [4, 35, 35, 2], [4, 49, 49, 16], + [3, 150, 150, 24], [5, 92, 92, 2]] + strides = [1, 1, 1, 1, 1, 1, 1, 3, 2, 2] + # pylint: disable=invalid-name + VALID = "VALID" + SAME = "SAME" + # pylint: enable=invalid-name + paddings = [SAME, SAME, SAME, SAME, SAME, SAME, SAME, VALID, SAME, SAME, SAME] + for i, f, o, s, p in zip(input_sizes, filter_sizes, out_sizes, strides, + paddings): + yield i, f, o, s, p + + +def ConfigsWithDilationsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + Yields: + Tuple (input_size, filter_size, out_size, stride, dilation, padding), the + depthwise + convolution parameters. + """ + input_sizes = [[4, 6, 6, 48], [4, 8, 8, 84], [4, 36, 36, 2], [4, 148, 148, 2], + [3, 300, 300, 3]] + filter_sizes = [[1, 1, 48, 2], [1, 3, 84, 1], [5, 5, 2, 1], [4, 4, 2, 8], + [2, 2, 3, 8]] + out_sizes = [[4, 6, 6, 96], [4, 8, 8, 84], [4, 36, 36, 2], [4, 74, 74, 16], + [3, 296, 296, 24]] + strides = [1, 1, 2, 2, 1] + dilations = [2, 2, 4, 2, 4] + # pylint: disable=invalid-name + VALID = "VALID" + SAME = "SAME" + # pylint: enable=invalid-name + paddings = [SAME, SAME, SAME, SAME, VALID] + for i, f, o, s, d, p in zip(input_sizes, filter_sizes, out_sizes, strides, + dilations, paddings): + yield i, f, o, s, d, p + + +def CheckGradConfigsToTest(): + """Iterator for different convolution shapes, strides and paddings. + + compute_gradient_error() is very expensive. So the configs should be + relatively small. + + Yields: + Tuple (input_size, filter_size, out_size, stride, padding), the depthwise + convolution parameters. + """ + input_sizes = [[2, 5, 8, 1], [4, 5, 5, 1], [2, 4, 4, 2], [1, 15, 15, 2], + [2, 15, 16, 1]] + filter_sizes = [[4, 4, 1, 2], [2, 2, 1, 2], [3, 1, 2, 2], [1, 3, 2, 1], + [3, 3, 1, 2]] + out_sizes = [[2, 5, 8, 2], [4, 2, 2, 2], [2, 4, 4, 4], [1, 15, 15, 2], + [2, 5, 5, 2]] + strides = [1, 2, 1, 1, 3] + # pylint: disable=invalid-name + VALID = "VALID" + SAME = "SAME" + # pylint: enable=invalid-name + paddings = [SAME, VALID, SAME, SAME, VALID] + for i, f, o, s, p in zip(input_sizes, filter_sizes, out_sizes, strides, + paddings): + yield i, f, o, s, p + + +class DepthwiseConv2DTest(xla_test.XLATestCase): + + # This is testing that depthwise_conv2d and depthwise_conv2d_native + # produce the same results. It also tests that NCHW and NWHC + # formats agree, by comparing the depthwise_conv2d_native with + # 'NCHW' format (with transposition) matches the 'NHWC' format using + # the higher level interface. + def _VerifyValues(self, + tensor_in_sizes, + filter_in_sizes, + stride, + padding, + data_type, + data_format="NHWC"): + """Verifies the output values of the convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in + [batch, input_rows, input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in + [filter_rows, filter_cols, input_depth, depth_multiplier]. + stride: Stride. + padding: Padding type. + data_type: The data type to use. + data_format: The data_format of the input. "NHWC" or "NCHW". + """ + total_size_1 = 1 + total_size_2 = 1 + for s in tensor_in_sizes: + total_size_1 *= s + for s in filter_in_sizes: + total_size_2 *= s + # Initializes the input and filter tensor with numbers incrementing from 1. + x1 = np.array([f * 1.0 for f in range(1, total_size_1 + 1)], + dtype=data_type).reshape(tensor_in_sizes) + x2 = np.array([f * 1.0 for f in range(1, total_size_2 + 1)], + dtype=data_type).reshape(filter_in_sizes) + with self.session() as sess: + if data_type == np.float32: + tolerance = 1e-4 + else: + self.assertEqual(data_type, np.float64) + tolerance = 1e-8 + + t1 = array_ops.placeholder(shape=tensor_in_sizes, dtype=data_type) + t2 = array_ops.placeholder(shape=filter_in_sizes, dtype=data_type) + + native_t1 = t1 + strides = [1, stride, stride, 1] + if data_format == "NCHW": + # Transpose from NWHC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + native_t1 = array_ops.transpose(t1, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + + with self.test_scope(): + conv_native = nn_ops.depthwise_conv2d_native( + native_t1, + t2, + strides=strides, + data_format=data_format, + padding=padding) + + if data_format == "NCHW": + # Transpose back from NCHW to NHWC + conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1]) + + with ops.device("CPU"): + conv_interface = ReferenceDepthwiseConv2D( + t1, t2, strides=[1, stride, stride, 1], padding=padding) + + native_result = sess.run(conv_native, {t1: x1, t2: x2}) + interface_result = sess.run(conv_interface, {t1: x1, t2: x2}) + + print("data_type:", data_type, "max diff = ", + np.amax(np.absolute(native_result - interface_result))) + self.assertAllClose( + np.ravel(native_result), np.ravel(interface_result), rtol=tolerance) + + @test_util.run_without_tensor_float_32( + "DepthwiseConv2D may use TF32 when available.") + def testDepthwiseConv2D(self): + for index, (input_size, filter_size, _, stride, + padding) in enumerate(ConfigsToTest()): + print("Testing DepthwiseConv2D,", index, "th config:", input_size, "*", + filter_size, "stride:", stride, "padding:", padding) + for data_type in self.float_types: + # TODO(phawkins): the reference implementation only supports float32. + if data_type == np.float32: + self._VerifyValues( + input_size, filter_size, stride, padding, data_type) + + @test_util.run_without_tensor_float_32( + "DepthwiseConv2D may use TF32 when available.") + def testDepthwiseConv2DFormat(self): + for index, (input_size, filter_size, _, stride, + padding) in enumerate(ConfigsToTest()): + print("Testing DepthwiseConv2DFormat,", index, "th config:", input_size, + "*", filter_size, "stride:", stride, "padding:", padding) + for data_type in self.float_types: + # TODO(phawkins): the reference implementation only supports float32. + if data_type == np.float32: + self._VerifyValues( + input_size, + filter_size, + stride, + padding, + data_type, + data_format="NCHW") + +# This is testing against hand calculated results. + + def _VerifyHandValues(self, tensor_in_sizes, filter_in_sizes, stride, padding, + expected): + """Verifies the output values of the depthwise convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in + [batch, input_rows, input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in + [filter_rows, filter_cols, input_depth, depth_multiplier]. + stride: Stride. + padding: Padding type. + expected: An array containing the expected operation outputs. + """ + total_size_1 = 1 + total_size_2 = 1 + for s in tensor_in_sizes: + total_size_1 *= s + for s in filter_in_sizes: + total_size_2 *= s + # Initializes the input tensor with array containing incrementing + # numbers from 1. + x1 = np.array([f * 1.0 for f in range(1, total_size_1 + 1)], + dtype=np.float32).reshape(tensor_in_sizes) + x2 = np.array([f * 1.0 for f in range(1, total_size_2 + 1)], + dtype=np.float32).reshape(filter_in_sizes) + with self.session() as sess: + t1 = array_ops.placeholder(shape=tensor_in_sizes, dtype=np.float32) + t2 = array_ops.placeholder(shape=filter_in_sizes, dtype=np.float32) + with self.test_scope(): + conv = nn_ops.depthwise_conv2d_native( + t1, t2, strides=[1, stride, stride, 1], padding=padding) + value = sess.run(conv, {t1: x1, t2: x2}) + print("value = ", value) + self.assertArrayNear(expected, np.ravel(value), 1e-4) + self.assertShapeEqual(value, conv) + + def testConv2D2x2Filter(self): + # The inputs look like this (it's a 3 x 2 matrix, each of depth 2): + # + # [ (1.0, 2.0), (3.0, 4.0), ( 5.0, 6.0) ] + # [ (7.0, 8.0), (9.0, 10.0), (11.0, 12.0) ] + # We can view this as two inputs + # + # input depth 0: + # + # [ 1.0, 3.0, 5.0 ] + # [ 7.0, 9.0, 11.0 ] + # + # input depth 1: + # + # [ 2.0, 4.0, 6.0 ] + # [ 8.0, 10.0, 12.0 ] + # + # The filter looks like this (it has two 2 x 2 patches, each generating 2 + # depths): + # + # filter #0: + # + # [ (1.0, 3.0), ( 5.0, 7.0)] + # [ (9.0, 11.0), (13.0, 15.0)] + # + # filter #1: + # + # [ ( 2.0, 4.0), ( 6.0, 8.0)] + # [ (10.0, 12.0), (14.0, 16.0)] + # + # So the outputs are: + # + # (position 0, 0: in_depth 0, output_depth 0 -- using filter #0) + # 1.0 * 1.0 + 7.0 * 9.0 + 3.0 * 5.0 + 9.0 * 13.0 = 196 + # (position 0, 0: in_depth 0, output_depth 1 -- using filter #1) + # 1.0 * 2.0 + 7.0 * 10.0 + 3.0 * 6.0 + 9.0 * 14.0 = 216 + # (position 0, 0: in_depth 1, output_depth 2 -- using filter #0) + # 2.0 * 3.0 + 8.0 * 11.0 + 4.0 * 7.0 + 10.0 * 15.0 = 272 + # (position 0, 0: in_depth 1, output_depth 3 -- using filter #1) + # 2.0 * 4.0 + 8.0 * 12.0 + 4.0 * 8.0 + 10.0 * 16.0 = 296 + # + # (position 1, 0: in_depth 0, output_depth 0 -- using filter #0) + # 3.0 * 1.0 + 9.0 * 9.0 + 5.0 * 5.0 + 11.0 * 13.0 = 252 + # (position 1, 0: in_depth 0, output_depth 1 -- using filter #1) + # 3.0 * 2.0 + 9.0 * 10.0 + 5.0 * 6.0 + 11.0 * 14.0 = 280 + # (position 1, 0: in_depth 1, output_depth 2 -- using filter #0) + # 4.0 * 3.0 + 10.0 * 11.0 + 6.0 * 7.0 + 12.0 * 15.0 = 344 + # (position 1, 0: in_depth 1, output_depth 3 -- using filter #1) + # 4.0 * 4.0 + 10.0 * 12.0 + 6.0 * 8.0 + 12.0 * 16.0 = 376 + expected_output = [196, 216, 272, 296, 252, 280, 344, 376] + self._VerifyHandValues( + tensor_in_sizes=[1, 2, 3, 2], + filter_in_sizes=[2, 2, 2, 2], + stride=1, + padding="VALID", + expected=expected_output) + + # This is testing that depthwise_conv2d with dilation produces + # the same results between CPU and TPU. It also tests that NCHW + # and NWHC formats agree. + def _VerifyValuesWithDilation(self, + tensor_in_sizes, + filter_in_sizes, + stride, + dilation, + padding, + data_type, + data_format="NHWC"): + """Verifies the output values of the convolution function. + + Args: + tensor_in_sizes: Input tensor dimensions in [batch, input_rows, + input_cols, input_depth]. + filter_in_sizes: Filter tensor dimensions in [filter_rows, filter_cols, + input_depth, depth_multiplier]. + stride: Stride. + dilation: Dilation. + padding: Padding type. + data_type: The data type to use. + data_format: The data_format of the input. "NHWC" or "NCHW". + """ + total_size_1 = 1 + total_size_2 = 1 + for s in tensor_in_sizes: + total_size_1 *= s + for s in filter_in_sizes: + total_size_2 *= s + # Initializes the input and filter tensor with numbers incrementing from 1. + x1 = np.array([f * 1.0 for f in range(1, total_size_1 + 1)], + dtype=data_type).reshape(tensor_in_sizes) + x2 = np.array([f * 1.0 for f in range(1, total_size_2 + 1)], + dtype=data_type).reshape(filter_in_sizes) + with self.session() as sess: + if data_type == np.float32: + # TODO(b/64210055): Tolerance for TPU is high. + tolerance = 1e-2 + else: + self.assertEqual(data_type, np.float64) + tolerance = 1e-8 + + t1 = array_ops.placeholder(shape=tensor_in_sizes, dtype=data_type) + t2 = array_ops.placeholder(shape=filter_in_sizes, dtype=data_type) + + native_t1 = t1 + strides = [1, stride, stride, 1] + dilations = [dilation, dilation] + if data_format == "NCHW": + # Transpose from NWHC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + native_t1 = array_ops.transpose(t1, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + + with self.test_scope(): + conv_native = nn_impl.depthwise_conv2d( + native_t1, + t2, + strides=strides, + rate=dilations, + data_format=data_format, + padding=padding) + + if data_format == "NCHW": + # Transpose back from NCHW to NHWC + conv_native = array_ops.transpose(conv_native, [0, 2, 3, 1]) + + with ops.device("CPU"): + # CPU only support NHWC format + strides = [1, stride, stride, 1] + conv_interface = nn_impl.depthwise_conv2d( + t1, t2, strides=strides, rate=dilations, padding=padding) + + native_result = sess.run(conv_native, {t1: x1, t2: x2}) + interface_result = sess.run(conv_interface, {t1: x1, t2: x2}) + + print("data_type:", data_type, "max diff = ", + np.amax(np.absolute(native_result - interface_result))) + self.assertAllClose( + np.ravel(native_result), np.ravel(interface_result), rtol=tolerance) + + def testDilationDepthwiseConv2DWith(self): + for index, (input_size, filter_size, _, stride, dilation, + padding) in enumerate(ConfigsWithDilationsToTest()): + print("Testing DilationDepthwiseConv2D,", index, "th config:", input_size, + "*", filter_size, "stride:", stride, "dilation: ", dilation, + "padding:", padding) + for data_type in self.float_types: + # TODO(phawkins): the reference implementation only supports float32. + if data_type == np.float32: + self._VerifyValuesWithDilation(input_size, filter_size, stride, + dilation, padding, data_type) + + def testDilationDepthwiseConv2DWithFormat(self): + for index, (input_size, filter_size, _, stride, dilation, + padding) in enumerate(ConfigsWithDilationsToTest()): + print("Testing DilationDepthwiseConv2DFormat,", index, "th config:", + input_size, "*", filter_size, "stride:", stride, "dilation:", + dilation, "padding:", padding) + for data_type in self.float_types: + # TODO(phawkins): the reference implementation only supports float32. + if data_type == np.float32: + self._VerifyValuesWithDilation( + input_size, + filter_size, + stride, + dilation, + padding, + data_type, + data_format="NCHW") + + def _CompareBackpropInput(self, input_sizes, filter_sizes, output_sizes, + stride, padding): + x1 = np.random.rand(*filter_sizes).astype(np.float32) + x2 = np.random.rand(*output_sizes).astype(np.float32) + + def _GetVal(use_xla): + with self.session(): + t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)]) + t1 = array_ops.placeholder(np.float32, shape=filter_sizes) + t2 = array_ops.placeholder(np.float32, shape=output_sizes) + if use_xla: + with self.test_scope(): + backprop = nn_ops.depthwise_conv2d_native_backprop_input( + t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) + else: + backprop = nn_ops.depthwise_conv2d_native_backprop_input( + t0, t1, t2, strides=[1, stride, stride, 1], padding=padding) + + ret = backprop.eval({t1: x1, t2: x2}) + self.assertShapeEqual(ret, backprop) + return ret + + gpu_value = _GetVal(use_xla=True) + cpu_value = _GetVal(use_xla=False) + self.assertAllClose(cpu_value, gpu_value, rtol=1e-3, atol=1e-3) + + def testDepthwiseConv2DInputGradCompare(self): + for index, (input_size, filter_size, output_size, stride, + padding) in enumerate(ConfigsToTest()): + print("Testing DepthwiseConv2DInputGradCompare,", index, "th config:", + input_size, "*", filter_size, "stride:", stride, "padding:", + padding) + self._CompareBackpropInput(input_size, filter_size, output_size, stride, + padding) + + def _CompareBackpropFilter(self, + input_sizes, + filter_sizes, + output_sizes, + stride, + padding, + data_format="NHWC"): + x0 = np.random.rand(*input_sizes).astype(np.float32) + x2 = np.random.rand(*output_sizes).astype(np.float32) + + def _GetVal(use_xla): + with self.session(): + t0 = array_ops.placeholder(np.float32, shape=input_sizes) + t1 = constant_op.constant(filter_sizes, shape=[len(filter_sizes)]) + t2 = array_ops.placeholder(np.float32, shape=output_sizes) + native_t0 = t0 + native_t2 = t2 + strides = [1, stride, stride, 1] + + if use_xla: + if data_format == "NCHW": + # Transpose from NWHC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + native_t0 = array_ops.transpose(t0, [0, 3, 1, 2]) + native_t2 = array_ops.transpose(t2, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + with self.test_scope(): + backprop = nn_ops.depthwise_conv2d_native_backprop_filter( + native_t0, + t1, + native_t2, + strides=strides, + padding=padding, + data_format=data_format) + else: + # For CPU, the format NCHW is not supported. Therefore we always use + # NHWC here. + backprop = nn_ops.depthwise_conv2d_native_backprop_filter( + native_t0, t1, native_t2, strides=strides, padding=padding) + ret = backprop.eval({t0: x0, t2: x2}) + self.assertShapeEqual(ret, backprop) + return ret + + gpu_value = _GetVal(use_xla=True) + cpu_value = _GetVal(use_xla=False) + self.assertAllClose(cpu_value, gpu_value, rtol=1e-4, atol=1e-4) + + @test_util.run_without_tensor_float_32( + "DepthwiseConv2DFilterGrad may use TF32 when available.") + def testDepthwiseConv2DFilterGradCompare(self): + for index, (input_size, filter_size, output_size, stride, + padding) in enumerate(ConfigsToTest()): + print("Testing DepthwiseConv2DFilterGradCompare,", index, "th config:", + input_size, "*", filter_size, "producing output", output_size, + "stride:", stride, "padding:", padding) + self._CompareBackpropFilter(input_size, filter_size, output_size, + stride, padding) + + @test_util.run_without_tensor_float_32( + "DepthwiseConv2DFilterGrad may use TF32 when available.") + def testDepthwiseConv2DFilterGradFormatNCHWCompare(self): + for index, (input_size, filter_size, output_size, stride, + padding) in enumerate(ConfigsToTest()): + print("Testing DepthwiseConv2DFilterGradFormatNCHWCompare,", index, + "th config:", input_size, "*", filter_size, "producing output", + output_size, "stride:", stride, "padding:", padding) + self._CompareBackpropFilter( + input_size, + filter_size, + output_size, + stride, + padding, + data_format="NCHW") + + def _CompareBackpropInputWithDilation(self, input_sizes, filter_sizes, + output_sizes, stride, dilation, + padding): + x1 = np.random.rand(*filter_sizes).astype(np.float32) + x2 = np.random.rand(*output_sizes).astype(np.float32) + + def _GetVal(use_xla): + with self.session(): + t1 = array_ops.placeholder(np.float32, shape=filter_sizes) + t2 = array_ops.placeholder(np.float32, shape=output_sizes) + if use_xla: + with self.test_scope(): + t0 = constant_op.constant(input_sizes, shape=[len(input_sizes)]) + backprop = nn_ops.depthwise_conv2d_native_backprop_input( + t0, + t1, + t2, + strides=[1, stride, stride, 1], + dilations=[1, dilation, dilation, 1], + padding=padding) + else: + # TODO(wangtao): figure out gradient with stride > 1. + # depthwise_conv2d_native_backprop_input on CPU doesn't support + # dilation. + t3 = array_ops.space_to_batch( + t2, block_size=dilation, paddings=[[0, 0], [0, 0]]) + input_sizes_transform = [ + input_sizes[0] * dilation * dilation, input_sizes[1] // dilation, + input_sizes[2] // dilation, input_sizes[3] + ] + t0 = constant_op.constant( + input_sizes_transform, shape=[len(input_sizes)]) + backprop_naive = nn_ops.depthwise_conv2d_native_backprop_input( + t0, t1, t3, strides=[1, stride, stride, 1], padding=padding) + backprop = array_ops.batch_to_space( + backprop_naive, [[0, 0], [0, 0]], block_size=dilation) + + ret = backprop.eval({t1: x1, t2: x2}) + self.assertShapeEqual(ret, backprop) + return ret + + gpu_value = _GetVal(use_xla=True) + cpu_value = _GetVal(use_xla=False) + + # TODO (b/64210055): Tolerance for TPU is high. + self.assertAllClose(cpu_value, gpu_value, rtol=1e-2, atol=1e-3) + + def testDilationDepthwiseConv2DInputGradWithCompare(self): + for index, (input_size, filter_size, output_size, stride, dilation, + padding) in enumerate(ConfigsWithDilationsToTest()): + print("Testing DilationDepthwiseConv2DInputGradWithDilationCompare,", + index, "th config:", input_size, "*", filter_size, "stride:", + stride, "dilation:", dilation, "padding:", padding) + # TODO(wangtao): implement CPU grad computation with stride > 1. + if stride == 1: + self._CompareBackpropInputWithDilation(input_size, filter_size, + output_size, stride, dilation, + padding) + + def _CompareBackpropFilterWithDilation(self, + input_sizes, + filter_sizes, + output_sizes, + stride, + dilation, + padding, + data_format="NHWC"): + x0 = np.random.rand(*input_sizes).astype(np.float32) + x2 = np.random.rand(*output_sizes).astype(np.float32) + + def _GetVal(use_xla): + with self.session(): + t0 = array_ops.placeholder(np.float32, shape=input_sizes) + t1 = constant_op.constant(filter_sizes, shape=[len(filter_sizes)]) + t2 = array_ops.placeholder(np.float32, shape=output_sizes) + native_t0 = t0 + native_t2 = t2 + strides = [1, stride, stride, 1] + dilations = [1, dilation, dilation, 1] + + if use_xla: + if data_format == "NCHW": + # Transpose from NWHC input to NCHW + # Ex. [4, 5, 5, 48] to [4, 48, 5, 5] + native_t0 = array_ops.transpose(t0, [0, 3, 1, 2]) + native_t2 = array_ops.transpose(t2, [0, 3, 1, 2]) + strides = [1, 1, stride, stride] + dilations = [1, 1, dilation, dilation] + with self.test_scope(): + backprop = nn_ops.depthwise_conv2d_native_backprop_filter( + native_t0, + t1, + native_t2, + strides=strides, + padding=padding, + dilations=dilations, + data_format=data_format) + else: + # For CPU, the format NCHW is not supported. Therefore we always use + # NHWC here. + # depthwise_conv2d_native_backprop_filter on CPU doesn't support + # dilation. + native_t3 = array_ops.space_to_batch( + native_t2, block_size=dilation, paddings=[[0, 0], [0, 0]]) + native_t0_transform = array_ops.space_to_batch( + native_t0, block_size=dilation, paddings=[[0, 0], [0, 0]]) + backprop = nn_ops.depthwise_conv2d_native_backprop_filter( + native_t0_transform, + t1, + native_t3, + strides=strides, + padding=padding) + ret = backprop.eval({t0: x0, t2: x2}) + self.assertShapeEqual(ret, backprop) + return ret + + gpu_value = _GetVal(use_xla=True) + cpu_value = _GetVal(use_xla=False) + # TODO(b/64210055): Tolerance for TPU is high. + self.assertAllClose(cpu_value, gpu_value, rtol=1e-3, atol=1e-4) + + def testDilationDepthwiseConv2DFilterGradCompare(self): + for index, (input_size, filter_size, output_size, stride, dilation, + padding) in enumerate(ConfigsWithDilationsToTest()): + print("Testing DilationDepthwiseConv2DFilterGradCompare,", index, + "th config:", input_size, "*", filter_size, "producing output", + output_size, "stride:", stride, "dilation:", dilation, "padding:", + padding) + if stride == 1: + # TODO(wangtao): implement CPU grad computation with stride > 1. + self._CompareBackpropFilterWithDilation(input_size, filter_size, + output_size, stride, dilation, + padding) + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/dynamic_slice_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/dynamic_slice_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..07d3ef99bc16f2ba8c5d58039428a4f236fa2a24 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/dynamic_slice_ops_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. +# ============================================================================== +"""Tests for XLA dynamic slicing ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class DynamicUpdateSliceOpsTest(xla_test.XLATestCase): + + def _assertOpOutputMatchesExpected(self, op, args, expected): + with self.session() as session: + with self.test_scope(): + placeholders = [ + array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape) + for arg in args + ] + feeds = {placeholders[i]: args[i] for i in range(0, len(args))} + output = op(*placeholders) + result = session.run(output, feeds) + self.assertAllClose(result, expected, rtol=1e-3) + + def testUpdateSlice(self): + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + xla.dynamic_update_slice, [ + np.array([], dtype=dtype), + np.array([], dtype=dtype), + np.array([0], dtype=np.int32) + ], + expected=np.array([], dtype=dtype)) + + self._assertOpOutputMatchesExpected( + xla.dynamic_update_slice, [ + np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], dtype=dtype), + np.array([11, 12, 13], dtype=dtype), + np.array([6], dtype=np.int32) + ], + expected=np.array([1, 2, 3, 4, 5, 6, 11, 12, 13, 10], dtype=dtype)) + + self._assertOpOutputMatchesExpected( + xla.dynamic_update_slice, [ + np.array( + [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=dtype), + np.array([[42, 43], [44, 45]], dtype=dtype), + np.array([1, 2], dtype=np.int32) + ], + expected=np.array( + [[1, 2, 3, 4], [5, 6, 42, 43], [9, 10, 44, 45]], dtype=dtype)) + + self._assertOpOutputMatchesExpected( + xla.dynamic_update_slice, [ + np.array( + [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=dtype), + np.array([[], []], dtype=dtype), + np.array([1, 2], dtype=np.int32) + ], + expected=np.array( + [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=dtype)) + + self._assertOpOutputMatchesExpected( + xla.dynamic_update_slice, [ + np.array( + [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]], dtype=dtype), + np.ones([3, 4], dtype=dtype), + np.array([0, 0], dtype=np.int32) + ], + expected=np.ones([3, 4], dtype=dtype)) + + +if __name__ == '__main__': + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/dynamic_stitch_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/dynamic_stitch_test.py new file mode 100644 index 0000000000000000000000000000000000000000..830cf75d93919e7525face40dfba15a29cf36c05 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/dynamic_stitch_test.py @@ -0,0 +1,91 @@ +# 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 tf.dynamic_stitch.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.platform import googletest + + +class DynamicStitchTest(xla_test.XLATestCase): + + def _AssertDynamicStitchResultIs(self, indices, data, expected): + with self.session() as session: + index_placeholders = [ + array_ops.placeholder(dtypes.as_dtype(arg.dtype)) for arg in indices + ] + data_placeholders = [ + array_ops.placeholder(dtypes.as_dtype(arg.dtype)) for arg in data + ] + with self.test_scope(): + output = data_flow_ops.dynamic_stitch(index_placeholders, + data_placeholders) + + feed_dict = {} + for placeholder, value in zip(index_placeholders, indices): + feed_dict[placeholder] = value + for placeholder, value in zip(data_placeholders, data): + feed_dict[placeholder] = value + result = session.run(output, feed_dict=feed_dict) + self.assertAllClose(expected, result, rtol=1e-3) + + def testSimpleEmpty(self): + idx1 = np.array([0, 2], dtype=np.int32) + idx2 = np.array([[1], [3]], dtype=np.int32) + val1 = np.array([[], []], dtype=np.int32) + val2 = np.array([[[]], [[]]], dtype=np.int32) + self._AssertDynamicStitchResultIs( + [idx1, idx2], [val1, val2], + expected=np.array([[], [], [], []], np.int32)) + + def testEmptyIndex(self): + idx1 = np.array([], dtype=np.int32) + idx2 = np.array([[], []], dtype=np.int32) + val1 = np.ndarray(shape=(0, 9), dtype=np.int32) + val2 = np.ndarray(shape=(2, 0, 9), dtype=np.int32) + self._AssertDynamicStitchResultIs([idx1, idx2], [val1, val2], + expected=np.ndarray( + shape=(0, 9), dtype=np.int32)) + + def testSimple1D(self): + val1 = np.array([0, 4, 7], dtype=np.int32) + val2 = np.array([1, 6, 2, 3, 5], dtype=np.int32) + val3 = np.array([0, 40, 70], dtype=np.float32) + val4 = np.array([10, 60, 20, 30, 50], dtype=np.float32) + expected = np.array([0, 10, 20, 30, 40, 50, 60, 70], dtype=np.float32) + self._AssertDynamicStitchResultIs( + [val1, val2], [val3, val4], expected=expected) + + def testSimple2D(self): + val1 = np.array([0, 4, 7], dtype=np.int32) + val2 = np.array([1, 6], dtype=np.int32) + val3 = np.array([2, 3, 5], dtype=np.int32) + val4 = np.array([[0, 1], [40, 41], [70, 71]], dtype=np.float32) + val5 = np.array([[10, 11], [60, 61]], dtype=np.float32) + val6 = np.array([[20, 21], [30, 31], [50, 51]], dtype=np.float32) + expected = np.array( + [[0, 1], [10, 11], [20, 21], [30, 31], [40, 41], [50, 51], [60, 61], + [70, 71]], + dtype=np.float32) + self._AssertDynamicStitchResultIs( + [val1, val2, val3], [val4, val5, val6], expected=expected) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/eager_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/eager_test.py new file mode 100644 index 0000000000000000000000000000000000000000..34cd222a154f7118a9a191895925c0802ada543a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/eager_test.py @@ -0,0 +1,803 @@ +# 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. +# ============================================================================== +"""Test cases for eager execution using XLA.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.eager import backprop +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import indexed_slices +from tensorflow.python.framework import ops +from tensorflow.python.layers import convolutional +from tensorflow.python.layers import pooling +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.ops import cond +from tensorflow.python.ops import embedding_ops +from tensorflow.python.ops import functional_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 +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.platform import googletest +from tensorflow.python.training import adam + + +class EagerTest(xla_test.XLATestCase): + + def testBasic(self): + with self.test_scope(): + three = constant_op.constant(3) + five = constant_op.constant(5) + product = three * five + self.assertAllEqual(15, product) + + def testGradientTape(self): + with self.test_scope(): + + x = constant_op.constant(1.0) + y = constant_op.constant(10.0) + with backprop.GradientTape(persistent=True) as tape: + tape.watch(x) + tape.watch(y) + a = x + y + x * y + da_dx = tape.gradient(a, x) + da_dy = tape.gradient(a, y) + + self.assertEqual(11.0, da_dx.numpy()) + self.assertEqual(2.0, da_dy.numpy()) + + def testExecuteListOutputLen0(self): + with self.test_scope(): + empty = constant_op.constant([], dtype=dtypes.float32) + result = array_ops_stack.unstack(empty, 0) + self.assertTrue(isinstance(result, list)) + self.assertEqual(0, len(result)) + + def testExecuteListOutputLen1(self): + with self.test_scope(): + split_dim = constant_op.constant(1) + value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]]) + result = array_ops.split(value, 1, axis=split_dim) + self.assertTrue(isinstance(result, list)) + self.assertEqual(1, len(result)) + self.assertAllEqual([[0, 1, 2], [3, 4, 5]], result[0]) + + def testExecuteListOutputLen3(self): + with self.test_scope(): + split_dim = constant_op.constant(1) + value = constant_op.constant([[0., 1., 2.], [3., 4., 5.]]) + result = array_ops.split(value, 3, axis=split_dim) + self.assertTrue(isinstance(result, list)) + self.assertEqual(3, len(result)) + self.assertAllEqual([[0], [3]], result[0]) + self.assertAllEqual([[1], [4]], result[1]) + self.assertAllEqual([[2], [5]], result[2]) + + def testBasicGraph(self): + # Run some ops eagerly + with self.test_scope(): + three = constant_op.constant(3) + five = constant_op.constant(5) + product = three * five + self.assertAllEqual(15, product) + + # Run some ops graphly + with context.graph_mode(), self.session(): + with self.test_scope(): + three = constant_op.constant(3) + five = constant_op.constant(5) + product = three * five + self.assertAllEqual(15, self.evaluate(product)) + + def testDegenerateSlices(self): + with self.test_scope(): + npt = np.arange(1, 19, dtype=np.float32).reshape(3, 2, 3) + t = constant_op.constant(npt) + # degenerate by offering a forward interval with a negative stride + self.assertAllEqual(npt[0:-1:-1, :, :], t[0:-1:-1, :, :]) + # degenerate with a reverse interval with a positive stride + self.assertAllEqual(npt[-1:0, :, :], t[-1:0, :, :]) + # empty interval in every dimension + self.assertAllEqual(npt[-1:0, 2:2, 2:3:-1], t[-1:0, 2:2, 2:3:-1]) + + def testIdentity(self): + 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) + i = array_ops.identity(v) + self.assertAllEqual(True, i.numpy()) + + def testAssignAddVariable(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(1.0) + v.assign_add(2.0) + self.assertEqual(3.0, v.numpy()) + + def testReadAssignRead(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(1.0) + val1 = v.read_value() + v.assign_add(2.0) + val2 = v.read_value() + self.assertEqual(1.0, val1.numpy()) + self.assertEqual(3.0, val2.numpy()) + + def testGradient(self): + def f(x): + return x + + with self.test_scope(): + grad_fn = backprop.gradients_function(f) + self.assertAllEqual(2., grad_fn(1., dy=2.)[0]) + + def testVariableGradient(self): + with self.test_scope(): + v0 = resource_variable_ops.ResourceVariable(1.0) + + def f(): + x = v0 * v0 + return x + + grads = backprop.implicit_grad(f)() + self.assertEqual(2., grads[0][0].numpy()) + + def testMultipleVariableReads(self): + # This test makes sure consecutive variable reads don't copy + # the underlying memory. + with self.test_scope(): + # Create 128MiB variables + var = resource_variable_ops.ResourceVariable( + array_ops.ones([32, 1024, 1024])) + + # Read the same variable 100 times. If the underlying tensor + # is not copied, this is a trivial operation. If it is copied, + # this will eat over 13GB and OOM. + values = [] + for _ in range(100): + values.append(var.value()) + + # The shape, shape_n, size, and rank are tested here because their + # execution kernels (as opposed to compilation only tf2xla kernels) + # are distincts from tf2xla kernels. + + def testShape(self): + def const(value): + return array_ops.shape( + constant_op.constant(value)).numpy() + + def ones(value): + return array_ops.shape( + array_ops.ones(value)).numpy() + + with self.test_scope(): + # Shapes of directly constructed tensors + self.assertAllEqual([], const(3)) + self.assertAllEqual([3], const([1.0, 2.0, 3.0])) + self.assertAllEqual([2, 2], const([[1.0, 2.0], [3.0, 4.0]])) + self.assertAllEqual([2, 1, 2], const([[[1.0, 2.0]], [[3.0, 4.0]]])) + + # Shapes of tensors created by op running on device + # We make this distinction because directly constructed tensors + # are treated differently in a few places that can influence shape: + # - they always have on_host_tensor + # - they and their shapes can be cached + # - they end up on device via a copy, instead of as program output + self.assertAllEqual([], ones([])) + self.assertAllEqual([3], ones([3])) + self.assertAllEqual([2, 2], ones([2, 2])) + self.assertAllEqual([2, 1, 2], ones([2, 1, 2])) + + def testShapeN(self): + with self.test_scope(): + # Shapes of directly constructed tensors + shapes = array_ops.shape_n([ + constant_op.constant(1.0), + constant_op.constant([1.0, 2.0, 3.0]), + constant_op.constant([[1.0, 2.0], [3.0, 4.0]])]) + self.assertAllEqual( + [[], [3], [2, 2]], + [x.numpy().tolist() for x in shapes]) + + # Shapes of tensors created by op running on device + shapes = array_ops.shape_n([ + array_ops.ones([]), + array_ops.ones([3]), + array_ops.ones([2, 2])]) + self.assertAllEqual( + [[], [3], [2, 2]], + [x.numpy().tolist() for x in shapes]) + + def testSize(self): + with self.test_scope(): + self.assertEqual( + 1, array_ops.size(constant_op.constant(1.0)).numpy()) + self.assertEqual( + 3, array_ops.size(constant_op.constant([1.0, 2.0, 3.0])).numpy()) + self.assertEqual( + 4, array_ops.size( + constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy()) + + def testRank(self): + with self.test_scope(): + self.assertEqual( + 0, array_ops.rank(constant_op.constant(1.0)).numpy()) + self.assertEqual( + 1, array_ops.rank(constant_op.constant([1.0, 2.0, 3.0])).numpy()) + self.assertEqual( + 2, array_ops.rank( + constant_op.constant([[1.0, 2.0], [3.0, 4.0]])).numpy()) + + def testAdam(self): + with self.test_scope(): + optimizer = adam.AdamOptimizer(0.1) + x = resource_variable_ops.ResourceVariable(10.0) + with backprop.GradientTape() as tape: + y = x * x + dy_dx = tape.gradient(y, x) + optimizer.apply_gradients([(dy_dx, x)]) + self.assertAlmostEqual(9.9, x.numpy(), places=3) + + def testAdamSparse(self): + with ops.device('/cpu:0'): + # Create 2-D embedding for 3 objects on CPU because sparse/sliced updates + # are not implemented on TPU. + embedding_matrix = resource_variable_ops.ResourceVariable( + array_ops.ones([3, 2])) + + with self.test_scope(): + with backprop.GradientTape() as tape: + embedding = embedding_ops.embedding_lookup(embedding_matrix, [1]) + y = math_ops.reduce_sum(embedding) + dy_dx = tape.gradient(y, embedding_matrix) + self.assertIsInstance(dy_dx, indexed_slices.IndexedSlices) + optimizer = adam.AdamOptimizer(0.1) + # The gradient application operations will run on CPU because optimizer + # updates are always collocated with the variable. + optimizer.apply_gradients([(dy_dx, embedding_matrix)]) + + # This assign_add will run on CPU because when an input to an + # operation is a resource, this operation is placed on the resource's + # device by the eager runtime. + embedding_matrix.assign_add(array_ops.ones([3, 2])) + + self.assertAllClose([[2.0, 2.0], + [1.9, 1.9], + [2.0, 2.0]], embedding_matrix.numpy()) + + +class EagerFunctionTest(xla_test.XLATestCase): + + def testBasic(self): + with self.test_scope(): + matmul = def_function.function(math_ops.matmul) + t = constant_op.constant([[1.0, 2.0], [3.0, 4.0]]) + sq = matmul(t, t, transpose_a=True) + self.assertAllEqual(sq.numpy().reshape(-1), [10, 14, 14, 20]) + + def testConv(self): + if 'GPU' in self.device: + # TODO(b/32333178) + self.skipTest('Current implementation of RandomStandardNormal kernel ' + 'is very slow on GPU, and has been denylisted.') + with self.test_scope(): + data_format = 'channels_last' + conv = convolutional.Conv2D( + filters=1, kernel_size=2, padding='VALID', + data_format=data_format, activation=nn_ops.relu, + kernel_initializer=init_ops.ones_initializer(), + bias_initializer=init_ops.zeros_initializer()) + pool = pooling.MaxPooling2D(2, 2, data_format=data_format) + + def model(x): + x = conv(x) + return pool(x) + model = def_function.function(model) + + x = array_ops.ones([1, 4, 4, 1]) + y = model(x) + self.assertAllEqual(y.numpy(), [[[[4.]]]]) + + def testReadVariable(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(1.0) + + @def_function.function + def f(): + return v.read_value() + + var = f() + self.assertEqual(1.0, var.numpy()) + + def testResourceVariableNoInlineReadWrite(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(1.0) + w = resource_variable_ops.ResourceVariable(0.0) + + @def_function.function(experimental_attributes={'_noinline': True}) + def g(x): + w.assign(w.read_value() + x) + return v.read_value() + x * w.read_value() + + @def_function.function(experimental_attributes={'_noinline': True}) + def f(): + return g(1.0) + g(2.0) + g(3.0) + g(4.0) + g(5.0) + + # 1 + 1*1 + 1 + 2*3 + 1 + 3*6 + 1 + 4*10 + 1 + 5*15 + self.assertEqual(145.0, f().numpy()) + self.assertEqual(15.0, w.read_value().numpy()) + + def testResourceVariableNoInlineReadOnly(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(10.0) + + @def_function.function(experimental_attributes={'_noinline': True}) + def g(): + return v.read_value() + + @def_function.function(experimental_attributes={'_noinline': True}) + def f(): + return g() + g() + g() + g() + g() + + self.assertEqual(50.0, f().numpy()) + + def testResourceVariableNoInlineWriteOnly(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(0.0) + + @def_function.function(experimental_attributes={'_noinline': True}) + def g(x): + v.assign(x) + + @def_function.function(experimental_attributes={'_noinline': True}) + def f(): + g(1.0) + g(2.0) + g(3.0) + g(4.0) + g(5.0) + + f() + self.assertEqual(5.0, v.read_value().numpy()) + + def testUpdateVariable(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable(1.0) + + def f(v): + v.assign_add(1.0) + return v + + f = def_function.function(f) + + var = f(v) + self.assertEqual(2.0, var.numpy()) + + def testReturnResourceHandle(self): + with self.test_scope(): + v = resource_variable_ops.ResourceVariable([[1.0, 2.0], [3.0, 4.0]]) + + def f(v): + return v.handle + + f = def_function.function(f) + handle = f(v) + self.assertAllEqual(v.numpy(), + resource_variable_ops.read_variable_op( + handle, dtypes.float32).numpy()) + + def testReturnMultipleResourceHandles(self): + with self.test_scope(): + v1 = resource_variable_ops.ResourceVariable(1.25) + v2 = resource_variable_ops.ResourceVariable(2.0) + + def f(v): + return v.handle, 3.0 * v, v2.handle, v + v2 + + f = def_function.function(f) + v1_handle, v1_times_3, v2_handle, variable_sum = f(v1) + self.assertAllEqual(v1.numpy(), + resource_variable_ops.read_variable_op( + v1_handle, dtypes.float32).numpy()) + self.assertEqual(3.75, v1_times_3.numpy()) + self.assertAllEqual(v2.numpy(), + resource_variable_ops.read_variable_op( + v2_handle, dtypes.float32).numpy()) + self.assertEqual(3.25, variable_sum.numpy()) + + def testAllArgumentKinds(self): + """Test a complex function that takes different argument kinds. + + tf2xla machinery that translates, compiles, and runs defuns + classifies arguments into: compile-time constants, regular tensors, + and resources. This test creates a function with a mix of all these + kinds. Moreover, the order of function arguments is intentionally mixed up. + + This also tests the case when the same argument is a compile-time constant + as well as used in an operation that normally expects its inputs to be + in device memory - addition in this case. + """ + with self.test_scope(): + def foo(c1, r1, v1, c2, v2, r2): + # c1 and c2 are compile-time constants + # r1 and r2 are regular tensors + # v1 and v2 are resource variables + a = c1 + r1 + b = math_ops.cast(c2, dtypes.float32) + v2 + c = array_ops.slice(v1, c1, c2) + d = r2 * v2 + return a, b, c, d + + foo = def_function.function(foo) + + c1 = [0, 0] + c2 = array_ops.ones([2], dtype=dtypes.int32) + + r1 = array_ops.ones([2]) + r2 = [[2., 2.], [3., 3.]] + + v1 = resource_variable_ops.ResourceVariable([[1., 2.], [3., 4.]]) + v2 = resource_variable_ops.ResourceVariable([[10., 20.], [30., 40.]]) + + a, b, c, d = foo(c1, r1, v1, c2, v2, r2) + + self.assertAllEqual([1, 1], a.numpy()) + self.assertAllEqual([[11., 21.], [31., 41.]], b.numpy()) + self.assertAllEqual([[1.]], c.numpy()) + self.assertAllEqual([[20., 40.], [90., 120.]], d.numpy()) + + def testDefunInGradientTape(self): + with self.test_scope(): + v0 = resource_variable_ops.ResourceVariable(5.0) + + @def_function.function + def f(x): + x = v0 * v0 * x + return x + + x = constant_op.constant(3.0) + with backprop.GradientTape() as tape: + y = f(x) + dy = tape.gradient(y, v0) + + self.assertEqual(75, y.numpy()) + self.assertEqual(30, dy.numpy()) + + def testGradientTapeInDefun(self): + with self.test_scope(): + v0 = resource_variable_ops.ResourceVariable(5.0) + + @def_function.function + def f(): + x = constant_op.constant(1.0) + with backprop.GradientTape() as tape: + y = v0 * x + dy = tape.gradient(y, v0) + return dy + + dy = f() + self.assertEqual(1.0, dy.numpy()) + + def testSliceInDefun(self): + with self.test_scope(): + + @def_function.function + def f(x, y): + return x[0::2, y:, ...] + + x = array_ops.ones([2, 3, 4], dtype=dtypes.float32) + y = array_ops.ones([], dtype=dtypes.int32) + with backprop.GradientTape() as tape: + tape.watch(x) + tape.watch(y) + z = f(x, y) + dz = tape.gradient(z, x) + + self.assertAllEqual(np.ones([1, 2, 4]), z.numpy()) + self.assertAllEqual((2, 3, 4), dz.shape.as_list()) + + def testNestedDefun(self): + with self.test_scope(): + + @def_function.function + def times_two(x): + return 2. * x + + @def_function.function + def two_x_plus_1(x): + return times_two(x) + 1. + + x = constant_op.constant([2., 3., 4.]) + y = two_x_plus_1(x) + self.assertAllEqual([5., 7., 9.], y.numpy()) + + def testNestedDefunWithVariable(self): + with self.test_scope(): + v0 = resource_variable_ops.ResourceVariable(5.0) + + @def_function.function + def g(x): + x = v0 * x + return x + + @def_function.function + def f(x): + x = g(v0 * x) + return x + + x = constant_op.constant(3.0) + y = f(x) + + self.assertEqual(75.0, y.numpy()) + + def testNestedDefunInGradientTape(self): + with self.test_scope(): + v0 = resource_variable_ops.ResourceVariable(5.0) + + @def_function.function + def g(x): + x = v0 * x + return x + + @def_function.function + def f(x): + x = g(v0 * x) + return x + + x = constant_op.constant(3.0) + with backprop.GradientTape() as tape: + y = f(x) + dy = tape.gradient(y, v0) + + self.assertEqual(75, y.numpy()) + self.assertEqual(30, dy.numpy()) + + def testNestedDefunInGradientTapeDifferentVars(self): + with self.test_scope(): + v0 = resource_variable_ops.ResourceVariable(5.0) + v1 = resource_variable_ops.ResourceVariable(3.0) + + @def_function.function + def g(x): + x = v1 * x + return x + + @def_function.function + def f(x): + x = g(v0 * x) + return x + + x = constant_op.constant(3.0) + with backprop.GradientTape(persistent=True) as tape: + y = f(x) + dy_v0 = tape.gradient(y, v0) + dy_v1 = tape.gradient(y, v1) + + self.assertEqual(45, y.numpy()) + self.assertEqual(9, dy_v0.numpy()) + self.assertEqual(15, dy_v1.numpy()) + + def testWhileInDefun(self): + with self.test_scope(): + @def_function.function + def f(start): + c = lambda x: math_ops.less(x, 13.0) + b = lambda x: math_ops.add(x, 1.0) + return while_loop.while_loop(c, b, [start]) + + y = f(constant_op.constant(3.0)) + self.assertEqual(13.0, y.numpy()) + + def testAutoGraphWhileInDefun(self): + with self.test_scope(): + @def_function.function + def f(start): + x = start + while x < 13.0: + x += 1.0 + return x + + y = f(constant_op.constant(3.0)) + self.assertEqual(13.0, y.numpy()) + + def testCondInDefun(self): + with self.test_scope(): + @def_function.function + def f(pred, value): + fn1 = lambda: math_ops.add(value, 1.0) + fn2 = lambda: math_ops.subtract(value, 1.0) + return cond.cond(pred, fn1, fn2) + + plus_one = f(constant_op.constant(True), constant_op.constant(10.0)) + minus_one = f(constant_op.constant(False), constant_op.constant(10.0)) + self.assertEqual(11.0, plus_one.numpy()) + self.assertEqual(9.0, minus_one.numpy()) + + def testAutoGraphCondInDefun(self): + with self.test_scope(): + @def_function.function + def f(pred, value): + if pred: + return value + 1.0 + else: + return value - 1.0 + + plus_one = f(constant_op.constant(True), constant_op.constant(10.0)) + minus_one = f(constant_op.constant(False), constant_op.constant(10.0)) + self.assertEqual(11.0, plus_one.numpy()) + self.assertEqual(9.0, minus_one.numpy()) + + def testScanInDefun(self): + with self.test_scope(): + elems = constant_op.constant([1.0, 2.0, 3.0, 4.0, 5.0, 6.0], name='data') + v = constant_op.constant(2.0, name='v') + + @def_function.function + def f(y): + # pylint: disable=unnecessary-lambda + return functional_ops.scan( + lambda a, x: math_ops.multiply(a, x), y, initializer=v) + # pylint: enable=unnecessary-lambda + + r = f(elems) + self.assertAllEqual([2., 4., 12., 48., 240., 1440.], self.evaluate(r)) + + def testFeedDeviceMemoryToOpExpectingHostMemory(self): + @def_function.function + def f(dims, value): + return array_ops.fill(dims, value) + + with self.test_scope(): + x = constant_op.constant([4], dtype=dtypes.int64) + + y = f(x, 3) + self.assertAllEqual([3, 3, 3, 3], y) + + def testRequestNotToCompile(self): + with self.test_scope(): + def f(x): + with ops.device('device:CPU:0'): + y = 2.0 * x + return x, y + + wholly_compiled_f = def_function.function(f) + op_by_op_f = def_function.function(f, jit_compile=False) + + x = array_ops.identity([0.0, 2.0], name='data') + + # When function is wholly compiled, all outputs will be on the + # device on which it is run. + r_x, r_y = wholly_compiled_f(x) + self.assertAllEqual([0.0, 2.0], r_x) + self.assertAllEqual([0.0, 4.0], r_y) + if context.executing_eagerly(): + # backing_device is only available for eager tensors. + self.assertRegex(r_x.backing_device, self.device) + self.assertRegex(r_y.backing_device, self.device) + + # When function is executed op-by-op, requested devices will be + # respected. + r_x, r_y = op_by_op_f(x) + self.assertAllEqual([0.0, 2.0], r_x) + self.assertAllEqual([0.0, 4.0], r_y) + if context.executing_eagerly(): + # backing_device is only available for eager tensors. + self.assertRegex(r_x.backing_device, self.device) + self.assertRegex(r_y.backing_device, 'device:CPU:0') + + +class ExcessivePaddingTest(xla_test.XLATestCase): + """Test that eager execution works with TPU flattened tensors. + + Tensors that would normally be excessively padded when written + to TPU memory are reshaped to 1-D flat tensors. + + This test case verifies that such tensors work with eager execution. + + The flattening currently only happens on TPU, but tests should work + fine with all backends as flattening is transparent. + """ + + def testFromConstant(self): + with self.test_scope(): + # Create constant of shape [100, 2, 1]. This tensor would be + # excessively padded on TPU. + tensor = constant_op.constant(100 * [[[10.0], [2.0]]]) + # Use reduce_sum since it requires correctly working with + # a particular dimension. + reduced = math_ops.reduce_sum(tensor, axis=1) + self.assertAllEqual(100 * [[12.0]], reduced) + + def testFromOperation(self): + with self.test_scope(): + tensor = array_ops.ones([3, 100, 2, 2]) + reduced = math_ops.reduce_sum(tensor, axis=[0, 2, 3]) + self.assertAllEqual(100 * [12.0], reduced) + + def testAsFunctionInput(self): + with self.test_scope(): + + @def_function.function + def f(x): + return math_ops.reduce_sum(x, axis=2) + + tensor = constant_op.constant(100 * [[[10.0, 2.0]]]) + reduced = f(tensor) + self.assertAllEqual(100 * [[12.0]], reduced) + + def testAsFunctionOutput(self): + with self.test_scope(): + + @def_function.function + def f(x): + return x * constant_op.constant(100 * [[[10.0, 2.0]]]) + + y = f(3) + reduced = math_ops.reduce_sum(y, axis=2) + self.assertAllEqual(100 * [[36.0]], reduced) + + +def multiple_tpus(): + devices = context.context().devices() + return len([d for d in devices if 'device:TPU:' in d]) > 1 + + +class MultiDeviceTest(xla_test.XLATestCase): + """Test running TPU computation on more than one core.""" + + def testBasic(self): + if not multiple_tpus(): + self.skipTest('MultiDeviceTest requires multiple TPU devices.') + + # Compute 10 on TPU core 0 + with ops.device('device:TPU:0'): + two = constant_op.constant(2) + five = constant_op.constant(5) + ten = two * five + self.assertAllEqual(10, ten) + + # Compute 6 on TPU core 1 + with ops.device('device:TPU:1'): + two = constant_op.constant(2) + three = constant_op.constant(3) + six = two * three + self.assertAllEqual(6, six) + + # Copy 10 and 6 to CPU and sum them + self.assertAllEqual(16, ten + six) + + +if __name__ == '__main__': + ops.enable_eager_execution( + config=config_pb2.ConfigProto(log_device_placement=True)) + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/einsum_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/einsum_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fb359e73458ed9b66252411766630ae82f154545 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/einsum_op_test.py @@ -0,0 +1,84 @@ +# Copyright 2019 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. +# ============================================================================== +"""Test cases for einsum op.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import special_math_ops +from tensorflow.python.platform import googletest + + +class EinsumOpTest(xla_test.XLATestCase): + """Test cases for einsum op.""" + + def _testUnary(self, op, inp, expected): + """Verifies that unary 'op' produces 'expected' when fed input 'inp'.""" + with self.session() as session: + with self.test_scope(): + pinp = array_ops.placeholder( + dtypes.as_dtype(inp.dtype), inp.shape, name='a') + output = op(pinp) + result = session.run(output, {pinp: inp}) + self.assertEqual(output.dtype, expected.dtype) + self.assertAllCloseAccordingToType( + expected, result, rtol=1e-3, atol=1e-5, bfloat16_rtol=0.03) + + def _testBinary(self, op, a, b, expected): + """Verifies that binary 'op' produces 'expected' when fed 'a' and 'b'.""" + with self.session() as session: + with self.test_scope(): + pa = array_ops.placeholder(dtypes.as_dtype(a.dtype), a.shape, name='a') + pb = array_ops.placeholder(dtypes.as_dtype(b.dtype), b.shape, name='b') + output = op(pa, pb) + result = session.run(output, {pa: a, pb: b}) + self.assertAllCloseAccordingToType(result, expected, rtol=1e-3) + + def testMatMul(self): + for dtype in self.float_types: + self._testBinary( + lambda x, y: special_math_ops.einsum('ij,jk->ik', x, y), + np.array([[-0.25]], dtype=dtype), + np.array([[8]], dtype=dtype), + expected=np.array([[-2]], dtype=dtype)) + + def testImplicitForm(self): + for dtype in self.float_types: + self._testBinary( + lambda x, y: special_math_ops.einsum('ijk,kji', x, y), + np.array([[[1, 3], [2, 5], [6, 8]]], dtype=dtype), + np.array([[[1], [3], [2]], [[5], [6], [8]]], dtype=dtype), + expected=np.array(128, dtype=dtype)) + + def testReducedIndices(self): + for dtype in self.float_types: + self._testBinary( + lambda x, y: special_math_ops.einsum('ij,j->', x, y), + np.array([[1, 3], [2, 5], [6, 8]], dtype=dtype), + np.array([3, 2], dtype=dtype), + expected=np.array(59, dtype=dtype)) + + def testUnary(self): + for dtype in self.float_types: + self._testUnary( + lambda x: special_math_ops.einsum('ijk->kji', x), + np.array([[[1, 3], [2, 5], [6, 8]]], dtype=dtype), + expected=np.array([[[1], [2], [6]], [[3], [5], [8]]], dtype=dtype)) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/ensure_shape_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ensure_shape_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b433303c8778e0084ad0296cc6750045a22f64dd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ensure_shape_op_test.py @@ -0,0 +1,47 @@ +# 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 ensure_shape_op.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import check_ops +from tensorflow.python.platform import test + + +class EnsureShapeOpTest(xla_test.XLATestCase): + + def testEnsureShape(self): + with self.session() as sess: + p = array_ops.placeholder(dtypes.int32) + with self.test_scope(): + op = check_ops.ensure_shape(p, (None, 3)) + expected_out = [[0, 1, 2], [3, 4, 5], [6, 7, 8]] + self.assertAllEqual(expected_out, + sess.run(op, {p: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]})) + + def testInvalidEnsureShape(self): + with self.session() as sess: + p = array_ops.placeholder(dtypes.int32) + with self.test_scope(): + op = check_ops.ensure_shape(p, (None, 3, 3)) + with self.assertRaisesRegex(errors_impl.InvalidArgumentError, + "is not compatible with expected shape"): + sess.run(op, {p: [[0, 1, 2], [3, 4, 5], [6, 7, 8]]}) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/extract_image_patches_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/extract_image_patches_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..112a09cd0f0c1fcd79fad96384a228da4ff27e48 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/extract_image_patches_op_test.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. +# ============================================================================== +"""Functional tests for ExtractImagePatches op.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class ExtractImagePatches(xla_test.XLATestCase): + """Functional tests for ExtractImagePatches op.""" + + def _VerifyValues(self, image, ksizes, strides, rates, padding, patches): + """Tests input-output pairs for the ExtractImagePatches op. + + Args: + image: Input tensor with shape: [batch, in_rows, in_cols, depth]. + ksizes: Patch size specified as: [ksize_rows, ksize_cols]. + strides: Output strides, specified as [stride_rows, stride_cols]. + rates: Atrous rates, specified as [rate_rows, rate_cols]. + padding: Padding type. + patches: Expected output. + """ + ksizes = [1] + ksizes + [1] + strides = [1] + strides + [1] + rates = [1] + rates + [1] + + with self.session(): + image_placeholder = array_ops.placeholder(dtypes.float32) + with self.test_scope(): + out_tensor = array_ops.extract_image_patches( + image_placeholder, + ksizes=ksizes, + strides=strides, + rates=rates, + padding=padding, + name="im2col") + feed_dict = {image_placeholder: image} + self.assertAllClose(patches, out_tensor.eval(feed_dict=feed_dict)) + + def testKsize1x1Stride1x1Rate1x1(self): + """Verifies that for 1x1 kernel the output equals the input.""" + # [2, 3, 4, 5] + image = np.reshape(range(120), [2, 3, 4, 5]) + # [2, 3, 4, 5] + patches = np.reshape(range(120), [2, 3, 4, 5]) + for padding in ["VALID", "SAME"]: + self._VerifyValues( + image, + ksizes=[1, 1], + strides=[1, 1], + rates=[1, 1], + padding=padding, + patches=patches) + + def testKsize1x1Stride2x3Rate1x1(self): + """Test for 1x1 kernel and strides.""" + # [2, 4, 5, 3] + image = np.reshape(range(120), [2, 4, 5, 3]) + # [2, 2, 2, 3] + patches = image[:, ::2, ::3, :] + for padding in ["VALID", "SAME"]: + self._VerifyValues( + image, + ksizes=[1, 1], + strides=[2, 3], + rates=[1, 1], + padding=padding, + patches=patches) + + def testKsize2x2Stride1x1Rate1x1Valid(self): + """Test for 2x2 kernel with VALID padding.""" + # [1, 2, 2, 1] + image = [[[[1], [2]], [[3], [4]]]] + # [1, 1, 1, 4] + patches = [[[[1, 2, 3, 4]]]] + self._VerifyValues( + image, + ksizes=[2, 2], + strides=[1, 1], + rates=[1, 1], + padding="VALID", + patches=patches) + + def testKsize2x2Stride1x1Rate1x1Same(self): + """Test for 2x2 kernel with SAME padding.""" + # [1, 2, 2, 1] + image = [[[[1], [2]], [[3], [4]]]] + # [1, 2, 2, 4] + patches = [[[[1, 2, 3, 4], [2, 0, 4, 0]], [[3, 4, 0, 0], [4, 0, 0, 0]]]] + self._VerifyValues( + image, + ksizes=[2, 2], + strides=[1, 1], + rates=[1, 1], + padding="SAME", + patches=patches) + + def testKsize2x2Stride1x1Rate2x2Valid(self): + """Test for 2x2 kernel with 2x2 dilation.""" + # [1, 2, 2, 1] + image = np.arange(16).reshape(1, 4, 4, 1).astype(np.float32) + # [1, 2, 2, 4] + patches = [[[[0, 2, 8, 10], [1, 3, 9, 11]], + [[4, 6, 12, 14], [5, 7, 13, 15]]]] + self._VerifyValues( + image, + ksizes=[2, 2], + strides=[1, 1], + rates=[2, 2], + padding="VALID", + patches=patches) + + def testKsize2x2Stride1x1Rate1x1ValidDepth2(self): + """Test for 2x2 kernel with VALID padding.""" + # [1, 2, 2, 2] + image = [[[[1, 5], [2, 6]], [[3, 7], [4, 8]]]] + # [1, 1, 1, 8] + patches = [[[[1, 5, 2, 6, 3, 7, 4, 8]]]] + self._VerifyValues( + image, + ksizes=[2, 2], + strides=[1, 1], + rates=[1, 1], + padding="VALID", + patches=patches) + + def testInvalidKernelSize(self): + """Test that zero kernel size raises an error in XLA mode.""" + with self.session(): + image_placeholder = array_ops.placeholder(dtypes.float32) + with self.test_scope(): + out_tensor = array_ops.extract_image_patches( + image_placeholder, + ksizes=[1, 0, 2, 1], + strides=[1, 1, 1, 1], + rates=[1, 1, 1, 1], + padding="VALID", + ) + feed_dict = {image_placeholder: np.zeros([1, 4, 4, 1])} + with self.assertRaisesRegex( + errors_impl.OutOfRangeError, "Kernel size values must be positive" + ): + out_tensor.eval(feed_dict=feed_dict) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/fake_quant_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fake_quant_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..315abb5abcc735a476f9489645d480771b3b8f93 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fake_quant_ops_test.py @@ -0,0 +1,695 @@ +# 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. +# ============================================================================== +import numpy as np +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.platform import googletest + + +class FakeQuantWithMinMaxArgsTest(xla_test.XLATestCase): + """Test cases for FakeQuantWithMinMaxArgs operation.""" + + # 8 bits, wide range. + def testOp_with8BitsNoScalingNoNudging(self): + self._TestOp(0.0, 255.0, 8, False, 0.0, 255.0, 1.0) + + def testOp_with8BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 128.0, 8, False, 0.0, 127.5, 0.5) + + def testOp_with8BitsScalingAndNudgingUp(self): + self._TestOp(-128.0, -0.5, 8, False, -127.5, 0.0, 0.5) + + def testOp_with8BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 127.4, 8, False, 0.0, 127.5, 0.5) + + def testOp_with8BitsRoundingHalfWayZeroPoint(self): + # zero_point_from_min lands at exactly 0.5 (half-integer boundary). + # Scale = (509.0 - (-1.0)) / (255 - 0) = 510.0 / 255.0 = 2.0 + # zero_point_from_min = 0 - (-1.0) / 2.0 = 0.5 + # Under round-half-away-from-zero: nudged_zero_point = 1.0 + # nudged_min = (0 - 1.0) * 2.0 = -2.0 + # nudged_max = (255 - 1.0) * 2.0 = 508.0 + self._TestOp(-1.0, 509.0, 8, False, -2.0, 508.0, 2.0) + + # 8 bits, narrow range. + def testOp_with8BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 254.0, 8, True, 0.0, 254.0, 1.0) + + def testOp_with8BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 127.1, 8, True, 0.0, 127.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-127.1, -0.1, 8, True, -127.0, 0.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 126.9, 8, True, 0.0, 127.0, 0.5) + + # 7 bits, wide range. + def testOp_with7BitsNoScalingNoNudging(self): + self._TestOp(0.0, 127.0, 7, False, 0.0, 127.0, 1.0) + + def testOp_with7BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 64.0, 7, False, 0.0, 63.5, 0.5) + + def testOp_with7BitsScalingAndNudgingUp(self): + self._TestOp(-64.0, -0.5, 7, False, -63.5, 0.0, 0.5) + + def testOp_with7BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 63.4, 7, False, 0.0, 63.5, 0.5) + + # 7 bits, narrow range. + def testOp_with7BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 126.0, 7, True, 0.0, 126.0, 1.0) + + def testOp_with7BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 63.1, 7, True, 0.0, 63.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-63.1, -0.1, 7, True, -63.0, 0.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 62.9, 7, True, 0.0, 63.0, 0.5) + + def _TestOp(self, input_min, input_max, num_bits, narrow_range, + expected_nudged_input_min, expected_nudged_input_max, + expected_step): + inputs = np.array( + [ + expected_nudged_input_min - expected_step, + expected_nudged_input_min - 0.01, expected_nudged_input_min, + expected_nudged_input_min + 0.01, + expected_nudged_input_min + expected_step - 0.01, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step + 0.01, + expected_nudged_input_max - 0.01, expected_nudged_input_max, + expected_nudged_input_max + 0.01, + expected_nudged_input_max + expected_step + ], + dtype=np.float32) + expected = np.array( + [ + expected_nudged_input_min, expected_nudged_input_min, + expected_nudged_input_min, expected_nudged_input_min, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step, + expected_nudged_input_max, expected_nudged_input_max, + expected_nudged_input_max, expected_nudged_input_max + ], + dtype=np.float32) + + with self.session() as session: + with self.test_scope(): + input_placeholder = array_ops.placeholder( + dtypes.float32, inputs.shape, name="inputs") + outputs = array_ops.fake_quant_with_min_max_args( + input_placeholder, + min=input_min, + max=input_max, + num_bits=num_bits, + narrow_range=narrow_range) + result = session.run(outputs, {input_placeholder: inputs}) + self.assertAllCloseAccordingToType( + result, expected, rtol=1e-3, atol=1e-5, bfloat16_rtol=0.03) + + +class FakeQuantWithMinMaxArgsGradientTest(xla_test.XLATestCase): + """Test cases for FakeQuantWithMinMaxArgsGradient operation.""" + + # 8 bits, wide range. + def testOp_with8BitsNoScalingNoNudging(self): + self._TestOp(0.0, 255.0, 8, False, 0.0, 255.0, 1.0) + + def testOp_with8BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 128.0, 8, False, 0.0, 127.5, 0.5) + + def testOp_with8BitsScalingAndNudgingUp(self): + self._TestOp(-128.0, -0.5, 8, False, -127.5, 0.0, 0.5) + + def testOp_with8BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 127.4, 8, False, 0.0, 127.5, 0.5) + + # 8 bits, narrow range. + def testOp_with8BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 254.0, 8, True, 0.0, 254.0, 1.0) + + def testOp_with8BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 127.1, 8, True, 0.0, 127.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-127.1, -0.1, 8, True, -127.0, 0.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 126.9, 8, True, 0.0, 127.0, 0.5) + + # 7 bits, wide range. + def testOp_with7BitsNoScalingNoNudging(self): + self._TestOp(0.0, 127.0, 7, False, 0.0, 127.0, 1.0) + + def testOp_with7BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 64.0, 7, False, 0.0, 63.5, 0.5) + + def testOp_with7BitsScalingAndNudgingUp(self): + self._TestOp(-64.0, -0.5, 7, False, -63.5, 0.0, 0.5) + + def testOp_with7BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 63.4, 7, False, 0.0, 63.5, 0.5) + + # 7 bits, narrow range. + def testOp_with7BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 126.0, 7, True, 0.0, 126.0, 1.0) + + def testOp_with7BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 63.1, 7, True, 0.0, 63.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-63.1, -0.1, 7, True, -63.0, 0.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 62.9, 7, True, 0.0, 63.0, 0.5) + + def _TestOp(self, input_min, input_max, num_bits, narrow_range, + expected_nudged_input_min, expected_nudged_input_max, + expected_step): + inputs = np.array( + [ + expected_nudged_input_min - expected_step, + expected_nudged_input_min - 0.01, expected_nudged_input_min, + expected_nudged_input_min + 0.01, + expected_nudged_input_min + expected_step - 0.01, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step + 0.01, + expected_nudged_input_max - 0.01, expected_nudged_input_max, + expected_nudged_input_max + 0.01, + expected_nudged_input_max + expected_step + ], + dtype=np.float32) + gradients = np.arange(1, len(inputs) + 1, dtype=np.float32) + expected_backprops = np.array( + [0.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 0.0], + dtype=np.float32) + + with self.session() as session: + with self.test_scope(): + gradient_placeholder = array_ops.placeholder( + dtypes.float32, gradients.shape, name="gradients") + input_placeholder = array_ops.placeholder( + dtypes.float32, inputs.shape, name="inputs") + outputs = gen_array_ops.fake_quant_with_min_max_args_gradient( + gradient_placeholder, + input_placeholder, + min=input_min, + max=input_max, + num_bits=num_bits, + narrow_range=narrow_range) + backprops = session.run(outputs, { + gradient_placeholder: gradients, + input_placeholder: inputs + }) + self.assertAllCloseAccordingToType( + backprops, + expected_backprops, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + + +class FakeQuantWithMinMaxVarsTest(xla_test.XLATestCase): + """Test cases for FakeQuantWithMinMaxVars operation.""" + + # 8 bits, wide range. + def testOp_with8BitsNoScalingNoNudging(self): + self._TestOp(0.0, 255.0, 8, False, 0.0, 255.0, 1.0) + + def testOp_with8BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 128.0, 8, False, 0.0, 127.5, 0.5) + + def testOp_with8BitsScalingAndNudgingUp(self): + self._TestOp(-128.0, -0.5, 8, False, -127.5, 0.0, 0.5) + + def testOp_with8BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 127.4, 8, False, 0.0, 127.5, 0.5) + + # 8 bits, narrow range. + def testOp_with8BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 254.0, 8, True, 0.0, 254.0, 1.0) + + def testOp_with8BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 127.1, 8, True, 0.0, 127.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-127.1, -0.1, 8, True, -127.0, 0.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 126.9, 8, True, 0.0, 127.0, 0.5) + + # 7 bits, wide range. + def testOp_with7BitsNoScalingNoNudging(self): + self._TestOp(0.0, 127.0, 7, False, 0.0, 127.0, 1.0) + + def testOp_with7BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 64.0, 7, False, 0.0, 63.5, 0.5) + + def testOp_with7BitsScalingAndNudgingUp(self): + self._TestOp(-64.0, -0.5, 7, False, -63.5, 0.0, 0.5) + + def testOp_with7BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 63.4, 7, False, 0.0, 63.5, 0.5) + + # 7 bits, narrow range. + def testOp_with7BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 126.0, 7, True, 0.0, 126.0, 1.0) + + def testOp_with7BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 63.1, 7, True, 0.0, 63.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-63.1, -0.1, 7, True, -63.0, 0.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 62.9, 7, True, 0.0, 63.0, 0.5) + + def _TestOp(self, input_min, input_max, num_bits, narrow_range, + expected_nudged_input_min, expected_nudged_input_max, + expected_step): + inputs = np.array( + [ + expected_nudged_input_min - expected_step, + expected_nudged_input_min - 0.01, expected_nudged_input_min, + expected_nudged_input_min + 0.01, + expected_nudged_input_min + expected_step - 0.01, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step + 0.01, + expected_nudged_input_max - 0.01, expected_nudged_input_max, + expected_nudged_input_max + 0.01, + expected_nudged_input_max + expected_step + ], + dtype=np.float32) + expected = np.array( + [ + expected_nudged_input_min, expected_nudged_input_min, + expected_nudged_input_min, expected_nudged_input_min, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step, + expected_nudged_input_max, expected_nudged_input_max, + expected_nudged_input_max, expected_nudged_input_max + ], + dtype=np.float32) + + with self.session() as session: + with self.test_scope(): + input_placeholder = array_ops.placeholder( + dtypes.float32, inputs.shape, name="inputs") + min_placeholder = array_ops.placeholder(dtypes.float32, (), name="min") + max_placeholder = array_ops.placeholder(dtypes.float32, (), name="max") + outputs = array_ops.fake_quant_with_min_max_vars( + input_placeholder, + min_placeholder, + max_placeholder, + num_bits=num_bits, + narrow_range=narrow_range) + result = session.run( + outputs, { + input_placeholder: inputs, + min_placeholder: input_min, + max_placeholder: input_max + }) + self.assertAllCloseAccordingToType( + result, expected, rtol=1e-3, atol=1e-5, bfloat16_rtol=0.03) + + +class FakeQuantWithMinMaxVarsGradientTest(xla_test.XLATestCase): + """Test cases for FakeQuantWithMinMaxVarsGradient operation.""" + + # 8 bits, wide range. + def testOp_with8BitsNoScalingNoNudging(self): + self._TestOp(0.0, 255.0, 8, False, 0.0, 255.0, 1.0) + + def testOp_with8BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 128.0, 8, False, 0.0, 127.5, 0.5) + + def testOp_with8BitsScalingAndNudgingUp(self): + self._TestOp(-128.0, -0.5, 8, False, -127.5, 0.0, 0.5) + + def testOp_with8BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 127.4, 8, False, 0.0, 127.5, 0.5) + + # 8 bits, narrow range. + def testOp_with8BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 254.0, 8, True, 0.0, 254.0, 1.0) + + def testOp_with8BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 127.1, 8, True, 0.0, 127.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-127.1, -0.1, 8, True, -127.0, 0.0, 0.5) + + def testOp_with8BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 126.9, 8, True, 0.0, 127.0, 0.5) + + # 7 bits, wide range. + def testOp_with7BitsNoScalingNoNudging(self): + self._TestOp(0.0, 127.0, 7, False, 0.0, 127.0, 1.0) + + def testOp_with7BitsScalingAndNudgingDown(self): + self._TestOp(0.5, 64.0, 7, False, 0.0, 63.5, 0.5) + + def testOp_with7BitsScalingAndNudgingUp(self): + self._TestOp(-64.0, -0.5, 7, False, -63.5, 0.0, 0.5) + + def testOp_with7BitsScalingAndNudgingBetween(self): + self._TestOp(-0.1, 63.4, 7, False, 0.0, 63.5, 0.5) + + # 7 bits, narrow range. + def testOp_with7BitsNarrowRangeNoScalingNoNudging(self): + self._TestOp(0.0, 126.0, 7, True, 0.0, 126.0, 1.0) + + def testOp_with7BitsNarrowRangeScalingAndNudgingDown(self): + self._TestOp(0.1, 63.1, 7, True, 0.0, 63.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingUp(self): + self._TestOp(-63.1, -0.1, 7, True, -63.0, 0.0, 0.5) + + def testOp_with7BitsNarrowRangeScalingAndNudgingBetween(self): + self._TestOp(-0.1, 62.9, 7, True, 0.0, 63.0, 0.5) + + def _TestOp(self, input_min, input_max, num_bits, narrow_range, + expected_nudged_input_min, expected_nudged_input_max, + expected_step): + inputs = np.array( + [ + expected_nudged_input_min - expected_step, + expected_nudged_input_min - 0.01, expected_nudged_input_min, + expected_nudged_input_min + 0.01, + expected_nudged_input_min + expected_step - 0.01, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step + 0.01, + expected_nudged_input_max - 0.01, expected_nudged_input_max, + expected_nudged_input_max + 0.01, + expected_nudged_input_max + expected_step + ], + dtype=np.float32) + gradients = np.arange(1, len(inputs) + 1, dtype=np.float32) + expected_backprops_wrt_input = np.array( + [0.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 0.0], + dtype=np.float32) + expected_backprops_wrt_min = 1.0 + 2.0 + expected_backprops_wrt_max = 10.0 + 11.0 + + with self.session() as session: + with self.test_scope(): + gradient_placeholder = array_ops.placeholder( + dtypes.float32, gradients.shape, name="gradients") + input_placeholder = array_ops.placeholder( + dtypes.float32, inputs.shape, name="inputs") + min_placeholder = array_ops.placeholder(dtypes.float32, (), name="min") + max_placeholder = array_ops.placeholder(dtypes.float32, (), name="max") + outputs = array_ops.fake_quant_with_min_max_vars_gradient( + gradient_placeholder, + input_placeholder, + min_placeholder, + max_placeholder, + num_bits=num_bits, + narrow_range=narrow_range) + backprops_wrt_input, backprops_wrt_min, backprops_wrt_max = session.run( + outputs, { + gradient_placeholder: gradients, + input_placeholder: inputs, + min_placeholder: input_min, + max_placeholder: input_max + }) + self.assertAllCloseAccordingToType( + backprops_wrt_input, + expected_backprops_wrt_input, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + self.assertAllCloseAccordingToType( + backprops_wrt_min, + expected_backprops_wrt_min, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + self.assertAllCloseAccordingToType( + backprops_wrt_max, + expected_backprops_wrt_max, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + + +class FakeQuantWithMinMaxVarsPerChannelTest(xla_test.XLATestCase): + """Test cases for FakeQuantWithMinMaxVarsPerChannel operation.""" + + # 8 bits, wide range. + def testOp_with8Bits(self): + self._TestOp( + [0.0, 0.5, -128.0, -0.1], + [255.0, 128.0, -0.5, 127.4], + 8, + False, + [0.0, 0.0, -127.5, 0.0], + [255.0, 127.5, 0.0, 127.5], + [1.0, 0.5, 0.5, 0.5]) + + # 8 bits, narrow range. + def testOp_with8BitsNarrowRange(self): + self._TestOp( + [0.0, 0.1, -127.1, -0.1], + [254.0, 127.1, -0.1, 126.9], + 8, + True, + [0.0, 0.0, -127.0, 0.0], + [254.0, 127.0, 0.0, 127.0], + [1.0, 0.5, 0.5, 0.5]) + + # 7 bits, wide range. + def testOp_with7Bits(self): + self._TestOp( + [0.0, 0.5, -64.0, -0.1], + [127.0, 64.0, -0.5, 63.4], + 7, + False, + [0.0, 0.0, -63.5, 0.0], + [127.0, 63.5, 0.0, 63.5], + [1.0, 0.5, 0.5, 0.5]) + + # 7 bits, narrow range. + def testOp_with7BitsNarrowRange(self): + self._TestOp( + [0.0, 0.1, -63.1, -0.1], + [126.0, 63.1, -0.1, 62.9], + 7, + True, + [0.0, 0.0, -63.0, 0.0], + [126.0, 63.0, 0.0, 63.0], + [1.0, 0.5, 0.5, 0.5]) + + def _TestOp(self, input_mins, input_maxs, num_bits, narrow_range, + expected_nudged_input_mins, expected_nudged_input_maxs, + expected_steps): + num_channels = len(input_mins) + inputs_list = [] + expected_list = [] + for i in range(num_channels): + expected_nudged_input_min = expected_nudged_input_mins[i] + expected_nudged_input_max = expected_nudged_input_maxs[i] + expected_step = expected_steps[i] + + inputs_list.append( + [ + expected_nudged_input_min - expected_step, + expected_nudged_input_min - 0.01, expected_nudged_input_min, + expected_nudged_input_min + 0.01, + expected_nudged_input_min + expected_step - 0.01, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step + 0.01, + expected_nudged_input_max - 0.01, expected_nudged_input_max, + expected_nudged_input_max + 0.01, + expected_nudged_input_max + expected_step + ]) + expected_list.append( + [ + expected_nudged_input_min, expected_nudged_input_min, + expected_nudged_input_min, expected_nudged_input_min, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step, + expected_nudged_input_max, expected_nudged_input_max, + expected_nudged_input_max, expected_nudged_input_max + ]) + inputs = np.transpose(np.array(inputs_list, dtype=np.float32)) + expected = np.transpose(np.array(expected_list, dtype=np.float32)) + + with self.session() as session: + with self.test_scope(): + input_placeholder = array_ops.placeholder( + dtypes.float32, inputs.shape, name="inputs") + min_placeholder = array_ops.placeholder( + dtypes.float32, (num_channels), name="min") + max_placeholder = array_ops.placeholder( + dtypes.float32, (num_channels), name="max") + outputs = array_ops.fake_quant_with_min_max_vars_per_channel( + input_placeholder, + min_placeholder, + max_placeholder, + num_bits=num_bits, + narrow_range=narrow_range) + result = session.run( + outputs, { + input_placeholder: inputs, + min_placeholder: input_mins, + max_placeholder: input_maxs + }) + self.assertAllCloseAccordingToType( + result, expected, rtol=1e-3, atol=1e-5, bfloat16_rtol=0.03) + + +class FakeQuantWithMinMaxVarsPerChannelGradientTest(xla_test.XLATestCase): + """Test cases for FakeQuantWithMinMaxVarsPerChannelGradient operation.""" + + # 8 bits, wide range. + def testOp_with8Bits(self): + self._TestOp( + [0.0, 0.5, -128.0, -0.1], + [255.0, 128.0, -0.5, 127.4], + 8, + False, + [0.0, 0.0, -127.5, 0.0], + [255.0, 127.5, 0.0, 127.5], + [1.0, 0.5, 0.5, 0.5]) + + # 8 bits, narrow range. + def testOp_with8BitsNarrowRange(self): + self._TestOp( + [0.0, 0.1, -127.1, -0.1], + [254.0, 127.1, -0.1, 126.9], + 8, + True, + [0.0, 0.0, -127.0, 0.0], + [254.0, 127.0, 0.0, 127.0], + [1.0, 0.5, 0.5, 0.5]) + + # 7 bits, wide range. + def testOp_with7Bits(self): + self._TestOp( + [0.0, 0.5, -64.0, -0.1], + [127.0, 64.0, -0.5, 63.4], + 7, + False, + [0.0, 0.0, -63.5, 0.0], + [127.0, 63.5, 0.0, 63.5], + [1.0, 0.5, 0.5, 0.5]) + + # 7 bits, narrow range. + def testOp_with7BitsNarrowRange(self): + self._TestOp( + [0.0, 0.1, -63.1, -0.1], + [126.0, 63.1, -0.1, 62.9], + 7, + True, + [0.0, 0.0, -63.0, 0.0], + [126.0, 63.0, 0.0, 63.0], + [1.0, 0.5, 0.5, 0.5]) + + def _TestOp(self, input_mins, input_maxs, num_bits, narrow_range, + expected_nudged_input_mins, expected_nudged_input_maxs, + expected_steps): + num_channels = len(input_mins) + inputs_list = [] + gradients_list = [] + expected_backprops_wrt_input_list = [] + expected_backprops_wrt_min_list = [] + expected_backprops_wrt_max_list = [] + for i in range(num_channels): + expected_nudged_input_min = expected_nudged_input_mins[i] + expected_nudged_input_max = expected_nudged_input_maxs[i] + expected_step = expected_steps[i] + inputs = [ + expected_nudged_input_min - expected_step, + expected_nudged_input_min - 0.01, expected_nudged_input_min, + expected_nudged_input_min + 0.01, + expected_nudged_input_min + expected_step - 0.01, + expected_nudged_input_min + expected_step, + expected_nudged_input_min + expected_step + 0.01, + expected_nudged_input_max - 0.01, expected_nudged_input_max, + expected_nudged_input_max + 0.01, + expected_nudged_input_max + expected_step + ] + inputs_list.append(inputs) + gradients_list.append(list(range(1, len(inputs) + 1))) + expected_backprops_wrt_input_list.append( + [0.0, 0.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 0.0]) + expected_backprops_wrt_min_list.append(1.0 + 2.0) + expected_backprops_wrt_max_list.append(10.0 + 11.0) + + inputs = np.transpose(np.array(inputs_list, dtype=np.float32)) + gradients = np.transpose(np.array(gradients_list, dtype=np.float32)) + expected_backprops_wrt_input = np.transpose(np.array( + expected_backprops_wrt_input_list, dtype=np.float32)) + expected_backprops_wrt_min = np.array( + expected_backprops_wrt_min_list, dtype=np.float32) + expected_backprops_wrt_max = np.array( + expected_backprops_wrt_max_list, dtype=np.float32) + + with self.session() as session: + with self.test_scope(): + gradient_placeholder = array_ops.placeholder( + dtypes.float32, gradients.shape, name="gradients") + input_placeholder = array_ops.placeholder( + dtypes.float32, inputs.shape, name="inputs") + min_placeholder = array_ops.placeholder( + dtypes.float32, (num_channels), name="min") + max_placeholder = array_ops.placeholder( + dtypes.float32, (num_channels), name="max") + outputs = array_ops.fake_quant_with_min_max_vars_per_channel_gradient( + gradient_placeholder, + input_placeholder, + min_placeholder, + max_placeholder, + num_bits=num_bits, + narrow_range=narrow_range) + backprops_wrt_input, backprops_wrt_min, backprops_wrt_max = session.run( + outputs, { + gradient_placeholder: gradients, + input_placeholder: inputs, + min_placeholder: input_mins, + max_placeholder: input_maxs + }) + self.assertAllCloseAccordingToType( + backprops_wrt_input, + expected_backprops_wrt_input, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + self.assertAllCloseAccordingToType( + backprops_wrt_min, + expected_backprops_wrt_min, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + self.assertAllCloseAccordingToType( + backprops_wrt_max, + expected_backprops_wrt_max, + rtol=1e-3, + atol=1e-5, + bfloat16_rtol=0.03) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/fft_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fft_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a2e2f5cb406d52399e168b91adc10b79bcaee8d9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fft_test.py @@ -0,0 +1,247 @@ +# 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 FFT via the XLA JIT.""" + +import itertools + +import numpy as np +import scipy.signal as sps + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops.signal import signal +from tensorflow.python.platform import googletest + +BATCH_DIMS = (3, 5) +RTOL = 0.009 # Eigen/cuFFT differ widely from np, especially for FFT3D +ATOL = 1e-4 +RTOL_3D = 0.07 +ATOL_3D = 4e-4 + + +def pick_10(x): + x = list(x) + np.random.seed(123) + np.random.shuffle(x) + return x[:10] + + +def to_32bit(x): + if x.dtype == np.complex128: + return x.astype(np.complex64) + if x.dtype == np.float64: + return x.astype(np.float32) + return x + + +POWS_OF_2 = 2**np.arange(3, 12) +INNER_DIMS_1D = list((x,) for x in POWS_OF_2) +POWS_OF_2 = 2**np.arange(3, 8) # To avoid OOM on GPU. +INNER_DIMS_2D = pick_10(itertools.product(POWS_OF_2, POWS_OF_2)) +INNER_DIMS_3D = pick_10(itertools.product(POWS_OF_2, POWS_OF_2, POWS_OF_2)) + + +class FFTTest(xla_test.XLATestCase): + + def _VerifyFftMethod(self, + inner_dims, + complex_to_input, + input_to_expected, + tf_method, + atol=ATOL, + rtol=RTOL): + for indims in inner_dims: + print("nfft =", indims) + shape = BATCH_DIMS + indims + data = np.arange(np.prod(shape) * 2) / np.prod(indims) + np.random.seed(123) + np.random.shuffle(data) + data = np.reshape(data.astype(np.float32).view(np.complex64), shape) + data = to_32bit(complex_to_input(data)) + expected = to_32bit(input_to_expected(data)) + with self.session() as sess: + with self.test_scope(): + ph = array_ops.placeholder( + dtypes.as_dtype(data.dtype), shape=data.shape) + out = tf_method(ph) + value = sess.run(out, {ph: data}) + self.assertAllClose(expected, value, rtol=rtol, atol=atol) + + def testContribSignalSTFT(self): + ws = 512 + hs = 128 + dims = (ws * 20,) + shape = BATCH_DIMS + dims + data = np.arange(np.prod(shape)) / np.prod(dims) + np.random.seed(123) + np.random.shuffle(data) + data = np.reshape(data.astype(np.float32), shape) + window = sps.get_window("hann", ws) + expected = sps.stft( + data, nperseg=ws, noverlap=ws - hs, boundary=None, window=window)[2] + expected = np.swapaxes(expected, -1, -2) + expected *= window.sum() # scipy divides by window sum + with self.session() as sess: + with self.test_scope(): + ph = array_ops.placeholder( + dtypes.as_dtype(data.dtype), shape=data.shape) + out = signal.stft(ph, ws, hs) + grad = gradients_impl.gradients(out, ph, + grad_ys=array_ops.ones_like(out)) + + # For gradients, we simply verify that they compile & execute. + value, _ = sess.run([out, grad], {ph: data}) + self.assertAllClose(expected, value, rtol=RTOL, atol=ATOL) + + def testFFT(self): + self._VerifyFftMethod(INNER_DIMS_1D, lambda x: x, np.fft.fft, + signal.fft) + + def testFFT2D(self): + self._VerifyFftMethod(INNER_DIMS_2D, lambda x: x, np.fft.fft2, + signal.fft2d) + + def testFFT3D(self): + self._VerifyFftMethod(INNER_DIMS_3D, lambda x: x, + lambda x: np.fft.fftn(x, axes=(-3, -2, -1)), + signal.fft3d, ATOL_3D, RTOL_3D) + + def testIFFT(self): + self._VerifyFftMethod(INNER_DIMS_1D, lambda x: x, np.fft.ifft, + signal.ifft) + + def testIFFT2D(self): + self._VerifyFftMethod(INNER_DIMS_2D, lambda x: x, np.fft.ifft2, + signal.ifft2d) + + def testIFFT3D(self): + self._VerifyFftMethod(INNER_DIMS_3D, lambda x: x, + lambda x: np.fft.ifftn(x, axes=(-3, -2, -1)), + signal.ifft3d, ATOL_3D, RTOL_3D) + + def testRFFT(self): + + def _to_expected(x): + return np.fft.rfft(x, n=x.shape[-1]) + + def _tf_fn(x): + return signal.rfft(x, fft_length=[x.shape[-1]]) + + self._VerifyFftMethod(INNER_DIMS_1D, np.real, _to_expected, _tf_fn) + + def testRFFT2D(self): + + def _tf_fn(x): + return signal.rfft2d(x, fft_length=[x.shape[-2], x.shape[-1]]) + + self._VerifyFftMethod( + INNER_DIMS_2D, np.real, + lambda x: np.fft.rfft2(x, s=[x.shape[-2], x.shape[-1]]), _tf_fn) + + def testRFFT3D(self): + + def _to_expected(x): + return np.fft.rfftn( + x, axes=(-3, -2, -1), s=[x.shape[-3], x.shape[-2], x.shape[-1]]) + + def _tf_fn(x): + return signal.rfft3d( + x, fft_length=[x.shape[-3], x.shape[-2], x.shape[-1]]) + + self._VerifyFftMethod(INNER_DIMS_3D, np.real, _to_expected, _tf_fn, ATOL_3D, + RTOL_3D) + + def testRFFT3DMismatchedSize(self): + + def _to_expected(x): + return np.fft.rfftn( + x, + axes=(-3, -2, -1), + s=[x.shape[-3] // 2, x.shape[-2], x.shape[-1] * 2]) + + def _tf_fn(x): + return signal.rfft3d( + x, fft_length=[x.shape[-3] // 2, x.shape[-2], x.shape[-1] * 2]) + + self._VerifyFftMethod(INNER_DIMS_3D, np.real, _to_expected, _tf_fn) + + def testIRFFT(self): + + def _tf_fn(x): + return signal.irfft(x, fft_length=[2 * (x.shape[-1] - 1)]) + + self._VerifyFftMethod( + INNER_DIMS_1D, lambda x: np.fft.rfft(np.real(x), n=x.shape[-1]), + lambda x: np.fft.irfft(x, n=2 * (x.shape[-1] - 1)), _tf_fn) + + def testIRFFT2D(self): + + def _tf_fn(x): + return signal.irfft2d(x, fft_length=[x.shape[-2], 2 * (x.shape[-1] - 1)]) + + self._VerifyFftMethod( + INNER_DIMS_2D, + lambda x: np.fft.rfft2(np.real(x), s=[x.shape[-2], x.shape[-1]]), + lambda x: np.fft.irfft2(x, s=[x.shape[-2], 2 * (x.shape[-1] - 1)]), + _tf_fn) + + def testIRFFT3D(self): + + def _to_input(x): + return np.fft.rfftn( + np.real(x), + axes=(-3, -2, -1), + s=[x.shape[-3], x.shape[-2], x.shape[-1]]) + + def _to_expected(x): + return np.fft.irfftn( + x, + axes=(-3, -2, -1), + s=[x.shape[-3], x.shape[-2], 2 * (x.shape[-1] - 1)]) + + def _tf_fn(x): + return signal.irfft3d( + x, fft_length=[x.shape[-3], x.shape[-2], 2 * (x.shape[-1] - 1)]) + + self._VerifyFftMethod(INNER_DIMS_3D, _to_input, _to_expected, _tf_fn, + ATOL_3D, RTOL_3D) + + def testIRFFT3DMismatchedSize(self): + + def _to_input(x): + return np.fft.rfftn( + np.real(x), + axes=(-3, -2, -1), + s=[x.shape[-3] // 2, x.shape[-2], x.shape[-1] * 2]) + + def _to_expected(x): + return np.fft.irfftn( + x, + axes=(-3, -2, -1), + s=[x.shape[-3] // 2, x.shape[-2], x.shape[-1] * 2]) + + def _tf_fn(x): + return signal.irfft3d( + x, fft_length=[x.shape[-3] // 2, x.shape[-2], x.shape[-1] * 2]) + + self._VerifyFftMethod(INNER_DIMS_3D, _to_input, _to_expected, _tf_fn, + ATOL_3D, RTOL_3D) + + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/fifo_queue_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fifo_queue_test.py new file mode 100644 index 0000000000000000000000000000000000000000..945d0df19fcae7ac2b8dd94116f20f3ae533b28d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fifo_queue_test.py @@ -0,0 +1,195 @@ +# 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.data_flow_ops.FIFOQueue.""" + +import time + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes as dtypes_lib +from tensorflow.python.ops import data_flow_ops +from tensorflow.python.platform import test + + +class FIFOQueueTest(xla_test.XLATestCase): + + def testEnqueue(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + enqueue_op = q.enqueue((10.0,)) + enqueue_op.run() + + def testEnqueueWithShape(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32, shapes=(3, 2)) + enqueue_correct_op = q.enqueue(([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]],)) + enqueue_correct_op.run() + with self.assertRaises(ValueError): + q.enqueue(([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]],)) + self.assertEqual(1, self.evaluate(q.size())) + + def testMultipleDequeues(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, [dtypes_lib.int32], shapes=[()]) + self.evaluate(q.enqueue([1])) + self.evaluate(q.enqueue([2])) + self.evaluate(q.enqueue([3])) + a, b, c = self.evaluate([q.dequeue(), q.dequeue(), q.dequeue()]) + self.assertAllEqual(set([1, 2, 3]), set([a, b, c])) + + def testQueuesDontShare(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, [dtypes_lib.int32], shapes=[()]) + self.evaluate(q.enqueue(1)) + q2 = data_flow_ops.FIFOQueue(10, [dtypes_lib.int32], shapes=[()]) + self.evaluate(q2.enqueue(2)) + self.assertAllEqual(self.evaluate(q2.dequeue()), 2) + self.assertAllEqual(self.evaluate(q.dequeue()), 1) + + def testEnqueueDictWithoutNames(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + with self.assertRaisesRegex(ValueError, "must have names"): + q.enqueue({"a": 12.0}) + + def testParallelEnqueue(self): + with self.session() as sess, self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0] + enqueue_ops = [q.enqueue((x,)) for x in elems] + dequeued_t = q.dequeue() + + # Run one producer thread for each element in elems. + def enqueue(enqueue_op): + sess.run(enqueue_op) + + threads = [ + self.checkedThread(target=enqueue, args=(e,)) for e in enqueue_ops + ] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + + # Dequeue every element using a single thread. + results = [] + for _ in range(len(elems)): + results.append(self.evaluate(dequeued_t)) + self.assertItemsEqual(elems, results) + + def testParallelDequeue(self): + with self.session() as sess, self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + elems = [10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0] + enqueue_ops = [q.enqueue((x,)) for x in elems] + dequeued_t = q.dequeue() + + # Enqueue every element using a single thread. + for enqueue_op in enqueue_ops: + enqueue_op.run() + + # Run one consumer thread for each element in elems. + results = [] + + def dequeue(): + results.append(sess.run(dequeued_t)) + + threads = [self.checkedThread(target=dequeue) for _ in enqueue_ops] + for thread in threads: + thread.start() + for thread in threads: + thread.join() + self.assertItemsEqual(elems, results) + + def testDequeue(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + elems = [10.0, 20.0, 30.0] + enqueue_ops = [q.enqueue((x,)) for x in elems] + dequeued_t = q.dequeue() + + for enqueue_op in enqueue_ops: + enqueue_op.run() + + for i in range(len(elems)): + vals = self.evaluate(dequeued_t) + self.assertEqual([elems[i]], vals) + + def testEnqueueAndBlockingDequeue(self): + with self.session() as sess, self.test_scope(): + q = data_flow_ops.FIFOQueue(3, dtypes_lib.float32) + elems = [10.0, 20.0, 30.0] + enqueue_ops = [q.enqueue((x,)) for x in elems] + dequeued_t = q.dequeue() + + def enqueue(): + # The enqueue_ops should run after the dequeue op has blocked. + # TODO(mrry): Figure out how to do this without sleeping. + time.sleep(0.1) + for enqueue_op in enqueue_ops: + sess.run(enqueue_op) + + results = [] + + def dequeue(): + for _ in range(len(elems)): + results.append(sess.run(dequeued_t)) + + enqueue_thread = self.checkedThread(target=enqueue) + dequeue_thread = self.checkedThread(target=dequeue) + enqueue_thread.start() + dequeue_thread.start() + enqueue_thread.join() + dequeue_thread.join() + + for elem, result in zip(elems, results): + self.assertEqual([elem], result) + + def testMultiEnqueueAndDequeue(self): + with self.session() as sess, self.test_scope(): + q = data_flow_ops.FIFOQueue(10, (dtypes_lib.int32, dtypes_lib.float32)) + elems = [(5, 10.0), (10, 20.0), (15, 30.0)] + enqueue_ops = [q.enqueue((x, y)) for x, y in elems] + dequeued_t = q.dequeue() + + for enqueue_op in enqueue_ops: + enqueue_op.run() + + for i in range(len(elems)): + x_val, y_val = sess.run(dequeued_t) + x, y = elems[i] + self.assertEqual([x], x_val) + self.assertEqual([y], y_val) + + def testQueueSizeEmpty(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + self.assertEqual([0], self.evaluate(q.size())) + + def testQueueSizeAfterEnqueueAndDequeue(self): + with self.session(), self.test_scope(): + q = data_flow_ops.FIFOQueue(10, dtypes_lib.float32) + enqueue_op = q.enqueue((10.0,)) + dequeued_t = q.dequeue() + size = q.size() + self.assertEqual([], size.get_shape()) + + enqueue_op.run() + self.assertEqual(1, self.evaluate(size)) + dequeued_t.op.run() + self.assertEqual(0, self.evaluate(size)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/float_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/float_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6fc1acb0795c56f66065a3504170f94dde7dfc14 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/float_ops_test.py @@ -0,0 +1,545 @@ +# Copyright 2025 The OpenXLA Authors. +# +# 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. +# ============================================================================== +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import googletest + + +class FloatOpsTest(xla_test.XLATestCase): + + def test_float_ops(self): + with self.session() as session: + for dtype in self.float_types: + x = np.arange(-0.90, 0.90, 0.25) + self.assert_op_output_matches_expected( + math_ops.acos, + x.astype(dtype), + expected=np.arccos(x).astype(dtype), + local_session=session, + ) + self.assert_op_output_matches_expected( + math_ops.asin, + x.astype(dtype), + expected=np.arcsin(x).astype(dtype), + local_session=session, + ) + x = np.arange(-3, 3).reshape(1, 3, 2) + self.assert_op_output_matches_expected( + math_ops.atan, + x.astype(dtype), + expected=np.arctan(x).astype(dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.acosh, + np.array([1, 2, 3, 4], dtype=dtype), + expected=np.array( + [0, 1.3169579, 1.76274717, 2.06343707], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.asinh, + np.array([1, 2, 3, 4], dtype=dtype), + expected=np.array( + [0.88137359, 1.44363548, 1.81844646, 2.09471255], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.atanh, + np.array([0.1, 0.2, 0.3, 0.4], dtype=dtype), + expected=np.array( + [0.10033535, 0.20273255, 0.3095196, 0.42364893], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.ceil, + np.array([[-1.7, 1.2]], dtype=dtype), + expected=np.array([[-1, 2]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.cosh, + np.array([1, 2, 3, 4], dtype=dtype), + expected=np.array( + [1.54308063, 3.76219569, 10.067662, 27.30823284], dtype=dtype + ), + local_session=session, + ) + + # Disable float16 testing for now + if dtype != np.float16: + x = np.arange(-10, 10, 1).astype(dtype) + erf_x = session.run(math_ops.erf(x)) + erfc_x = session.run(math_ops.erfc(x)) + + self.assert_op_output_matches_expected( + math_ops.erf, + x, + expected=erf_x, + local_session=session, + ) + self.assert_op_output_matches_expected( + math_ops.erfc, + x, + expected=erfc_x, + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.exp, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[0.36787945, 2.7182817]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.expm1, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[-0.63212056, 1.71828183]], dtype=dtype), + local_session=session, + rtol=1e-5, + ) + + self.assert_op_output_matches_expected( + math_ops.floor, + np.array([[-1.7, 1.2]], dtype=dtype), + expected=np.array([[-2, 1]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.is_finite, + np.array( + [[-np.inf, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]], dtype=dtype + ), + expected=np.array([[0, 1, 1, 1, 1, 1, 1, 0, 0]], dtype=np.bool_), + local_session=session, + ) + + # Tests for tf.nn ops. + self.assert_op_output_matches_expected( + nn_ops.l2_loss, + np.array([[[]]], dtype=dtype), + expected=dtype(0), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.l2_loss, + dtype(4), + dtype(8), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.l2_loss, + np.array([[-2, 4]], dtype=dtype), + expected=dtype(10), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.reciprocal, + np.array([[1, 2]], dtype=dtype), + expected=np.array([[1, 0.5]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.log, + np.array([[1, 2]], dtype=dtype), + expected=np.array([[0, 0.69314718]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.sin, + np.array([[1, 2]], dtype=dtype), + expected=np.array([[0.841478, 0.909302]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.cos, + np.array([[1, 2]], dtype=dtype), + expected=np.array([[0.540297, -0.41614]], dtype=dtype), + local_session=session, + ) + + # Confirm that log1p will remain precise across a range of small values. + self.assert_op_output_matches_expected( + math_ops.log1p, + np.array( + [[1e-14, 1e-15, 0.6, 2] + [x * 1e-5 for x in range(1, 20)]], + dtype=dtype, + ), + expected=np.log1p( + np.array( + [[1e-14, 1e-15, 0.6, 2] + [x * 1e-5 for x in range(1, 20)]], + dtype=dtype, + ) + ).astype(dtype), + local_session=session, + rtol=1e-15 if dtype == np.float64 else 1e-4, + atol=1e-15 if dtype == np.float64 else 1e-4, + ) + + self.assert_op_output_matches_expected( + math_ops.rint, + np.array( + [ + [-1.7, 1.2, 4.0, 0.0], + [-3.5, -2.5, -1.5, -0.5], + [0.5, 1.5, 2.5, 3.5], + ], + dtype=dtype, + ), + expected=np.array( + [[-2, 1, 4, 0], [-4, -2, -2, 0], [0, 2, 2, 4]], dtype=dtype + ), + local_session=session, + ) + self.assert_op_output_matches_expected( + math_ops.round, + np.array( + [ + [-1.7, 1.2, 4.0, 0.0], + [-3.5, -2.5, -1.5, -0.5], + [0.5, 1.5, 2.5, 3.5], + ], + dtype=dtype, + ), + expected=np.array( + [[-2, 1, 4, 0], [-4, -2, -2, 0], [0, 2, 2, 4]], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.rsqrt, + np.array([[4, 16]], dtype=dtype), + expected=np.array([[0.5, 0.25]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.sigmoid, + np.array([[1, 1, 1, 1], [1, 2, 3, 4]], dtype=dtype), + expected=np.array( + [ + [0.7310586, 0.7310586, 0.7310586, 0.7310586], + [0.7310586, 0.880797, 0.95257413, 0.98201376], + ], + dtype=dtype, + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.sigmoid, + np.array([-300, -150, 0, 150, 300], dtype=dtype), + expected=np.array([0, 0, 0.5, 1, 1], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.sinh, + np.array([1, 2, 3, 4], dtype=dtype), + expected=np.array( + [1.17520119, 3.62686041, 10.01787493, 27.2899172], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.sqrt, + np.array([[4, 9]], dtype=dtype), + expected=np.array([[2, 3]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.tan, + np.array([1, 2, 3, 4], dtype=dtype), + expected=np.array( + [1.55740772, -2.18503986, -0.14254654, 1.15782128], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.tanh, + np.array( + [ + [1, 2, 3, 4], + [np.inf, -np.inf, np.nan, 20], + [19, -19, 22, -22], + ], + dtype=dtype, + ), + expected=np.array( + [ + [0.76159418, 0.96402758, 0.99505478, 0.99932933], + [1.0, -1.0, np.nan, 1.0], + [1.0, -1.0, 1.0, -1.0], + ], + dtype=dtype, + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.log_softmax, + np.array([[1, 1, 1, 1], [1, 2, 3, 4]], dtype=dtype), + expected=np.array( + [ + [-1.3862944, -1.3862944, -1.3862944, -1.3862944], + [-3.4401896, -2.4401896, -1.4401897, -0.44018969], + ], + dtype=dtype, + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.elu, + np.array([[-1, 0, 1, -1e-6]], dtype=dtype), + expected=np.array( + [[-0.63212056, 0, 1, -9.999995e-07]], dtype=dtype + ), + rtol=1e-5, + atol=1e-6, + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.selu, + np.array([[-1, 0, 1, -1e-5]], dtype=dtype), + expected=np.array( + [[-1.11133074, 0.0, 1.05070099, -1.758090550379974e-05]], + dtype=dtype, + ), + rtol=1e-5, + atol=1e-6, + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.relu, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[0, 1]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.relu6, + np.array([[-0.05, 6.05, 5]], dtype=dtype), + expected=np.array([[0, 6, 5]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.leaky_relu, + np.array([[-2, -1, 0, 1, 2]], dtype=dtype), + expected=np.array([[-0.4, -0.2, 0.0, 1.0, 2.0]], dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.softmax, + np.array([1, 2, 3, 4], dtype=dtype), + expected=np.array( + [0.032058604, 0.087144323, 0.23688284, 0.64391428], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.softmax, + np.array([[1, 1, 1, 1], [1, 2, 3, 4]], dtype=dtype), + expected=np.array( + [ + [0.25, 0.25, 0.25, 0.25], + [0.032058604, 0.087144323, 0.23688284, 0.64391428], + ], + dtype=dtype, + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.softmax, + np.array([[[1, 1], [1, 1]], [[1, 2], [3, 4]]], dtype=dtype), + expected=np.array( + [ + [[0.5, 0.5], [0.5, 0.5]], + [[0.26894142, 0.73105858], [0.26894142, 0.73105858]], + ], + dtype=dtype, + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + nn_ops.softsign, + np.array([[-2, -1, 0, 1, 2]], dtype=dtype), + expected=np.array( + [[-0.66666669, -0.5, 0, 0.5, 0.66666669]], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.sign, + np.array( + [[-2.0, -1.0, -0.0, +0.0, 1.0, 2.0, float("nan")]], dtype=dtype + ), + expected=np.array( + [[-1.0, -1.0, -0.0, +0.0, 1.0, 1.0, float("nan")]], dtype=dtype + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.is_finite, + np.array( + [[42, float("inf"), -123], [float("nan"), 0, -0.0]], dtype=dtype + ), + expected=np.array( + [[True, False, True], [False, True, True]], dtype=np.bool_ + ), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.lgamma, + np.array(0.5, dtype=dtype), + expected=np.array(np.log(np.pi) / 2, dtype=dtype), + local_session=session, + ) + + self.assert_op_output_matches_expected( + math_ops.lgamma, + np.array( + [ + [1, 2, 3], + [4, 5, 6], + [1 / 2, 3 / 2, 5 / 2], + [-3 / 2, -7 / 2, -11 / 2], + ], + dtype=dtype, + ), + expected=np.array( + [ + [0, 0, np.log(2.0)], + [np.log(6.0), np.log(24.0), np.log(120)], + [ + np.log(np.pi) / 2, + np.log(np.pi) / 2 - np.log(2), + np.log(np.pi) / 2 - np.log(4) + np.log(3), + ], + [ + np.log(np.pi) / 2 - np.log(3) + np.log(4), + np.log(np.pi) / 2 - np.log(105) + np.log(16), + np.log(np.pi) / 2 - np.log(10395) + np.log(64), + ], + ], + dtype=dtype, + ), + local_session=session, + ) + + # The actual result is complex. Take the real part. + self.assert_op_output_matches_expected( + 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, + ), + local_session=session, + atol=1e-4, + ) + + self.assert_op_output_matches_expected( + math_ops.digamma, + np.array( + [ + [1.0, 0.5, 1 / 3.0], + [0.25, 1 / 6.0, 0.125], + [2.0, 3.0, 4.0], + [6.0, 8.0, 9.0], + ], + dtype=dtype, + ), + expected=np.array( + [ + [ + -np.euler_gamma, + -2 * np.log(2) - np.euler_gamma, + -np.pi / 2 / np.sqrt(3) + - 3 * np.log(3) / 2 + - np.euler_gamma, + ], + [ + -np.pi / 2 - 3 * np.log(2) - np.euler_gamma, + -np.pi * np.sqrt(3) / 2 + - 2 * np.log(2) + - 3 * np.log(3) / 2 + - np.euler_gamma, + -np.pi / 2 + - 4 * np.log(2) + - ( + np.pi + + np.log(2 + np.sqrt(2)) + - np.log(2 - np.sqrt(2)) + ) + / np.sqrt(2) + - np.euler_gamma, + ], + [ + 1 - np.euler_gamma, + 1.5 - np.euler_gamma, + 11 / 6.0 - np.euler_gamma, + ], + [ + 137 / 60.0 - np.euler_gamma, + 363 / 140.0 - np.euler_gamma, + 761 / 280.0 - np.euler_gamma, + ], + ], + dtype=dtype, + ), + local_session=session, + ) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/ftrl_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ftrl_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..817661fbfef2448b17e8a43f8a9dc07361a45e6b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ftrl_ops_test.py @@ -0,0 +1,198 @@ +# Copyright 2019 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. +# ============================================================================== +"""Test cases for ftrl ("follow the regularized leader") operations.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import test_util +from tensorflow.python.ops import gen_training_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.platform import googletest + + +class ResourceApplyFtrlTest(xla_test.XLATestCase): + """Test cases for ftrl ops.""" + + def setUp(self): + super().setUp() + self.rewrite_ops_for_tpu = ("TPU" in self.device and + test_util.is_mlir_bridge_enabled()) + + def _eval(self, var, accum, linear, grad, lr, l1, l2, l2_shrinkage=0, + lr_power=1, multiply_linear_by_lr=False): + dtype = np.float32 + var = np.array(var, dtype=dtype) + accum = np.array(accum, dtype=dtype) + linear = np.array(linear, dtype=dtype) + grad = np.array(grad, dtype=dtype) + use_v2 = bool(l2_shrinkage) + with self.session() as session: + with self.test_scope(): + lr = constant_op.constant(lr, dtype=dtype) + l1 = constant_op.constant(l1, dtype=dtype) + l2 = constant_op.constant(l2, dtype=dtype) + l2_shrinkage = constant_op.constant(l2_shrinkage, dtype=dtype) + lr_power = constant_op.constant(lr_power, dtype=dtype) + v_var = resource_variable_ops.ResourceVariable(var, dtype=dtype) + v_accum = resource_variable_ops.ResourceVariable(accum, dtype=dtype) + v_linear = resource_variable_ops.ResourceVariable(linear, dtype=dtype) + session.run(v_var.create) + session.run(v_accum.create) + session.run(v_linear.create) + assert not (use_v2 and multiply_linear_by_lr) + if use_v2: + session.run(gen_training_ops.resource_apply_ftrl_v2( + v_var.handle, v_accum.handle, v_linear.handle, + grad, lr, l1, l2, l2_shrinkage, lr_power, + multiply_linear_by_lr=multiply_linear_by_lr)) + else: + session.run(gen_training_ops.resource_apply_ftrl( + v_var.handle, v_accum.handle, v_linear.handle, + grad, lr, l1, l2, lr_power, + multiply_linear_by_lr=multiply_linear_by_lr)) + return (v_var.read_value().eval().reshape(var.shape), + v_accum.read_value().eval().reshape(accum.shape), + v_linear.read_value().eval().reshape(linear.shape)) + + def testAccum(self): + """Test that accum is updated with grad^2.""" + accum = np.array([[[1, 3], [2, 5], [6, 8]]]) + grad = np.array([[[1, 3], [2, 5], [6, 8]]]) + _, new_accum, _ = self._eval( + var=np.zeros((1, 3, 2)), + accum=accum, + linear=np.zeros((1, 3, 2)), + grad=grad, + lr=7, l1=3, l2=7, lr_power=2) + self.assertAllClose(accum + grad*grad, new_accum) + + def testLinearNoGradient(self): + """Test that if accum_new == accum, linear doesn't change.""" + _, _, linear = self._eval( + var=np.ones((1, 3, 2)), + accum=[[[1, 3], [2, 5], [6, 8]]], + linear=[[[1, 2], [3, 4], [5, 6]]], + grad=np.zeros((1, 3, 2)), # make accum_new == acum + lr=1, l1=3, l2=7, lr_power=2) + self.assertAllClose([[[1, 2], [3, 4], [5, 6]]], linear) + + def testLinear(self): + """Test the linear update for new_linear=2 and linear=1.""" + _, _, linear = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=1, l1=3, l2=7, lr_power=2) + self.assertAllClose(1.75 * np.ones((1, 3, 2)), linear) + + def testLR(self): + """Test that the linear update is divided by lr.""" + _, _, linear = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=5, l1=3, l2=7, lr_power=-1) + self.assertAllClose(0.8 * np.ones((1, 3, 2)), linear) + + def testVar(self): + """Test computation of var with linear=1.5, quadratic=1.""" + var, _, _ = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=1, l1=1, l2=0.25, lr_power=1) + self.assertAllClose(-0.5 * np.ones((1, 3, 2)), var) + + def testVarClipped(self): + """Test that var becomes 0 if |linear| < l1.""" + var, _, _ = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=1, l1=1.6, l2=0.25, lr_power=1) + self.assertAllClose(np.zeros((1, 3, 2)), var) + + def testQuadratic(self): + """Test that quadratic (here: -2) is the divisor of var.""" + var, _, _ = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=1, l1=1, l2=-1.25, lr_power=1) + self.assertAllClose(0.25 * np.ones((1, 3, 2)), var) + + def testL2Shrinkage(self): + """Test that 2 * l2_shrinkage * var is *not* added to the gradient.""" + _, accum, _ = self._eval( + var=np.ones((1, 3, 2)), + accum=np.zeros((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.zeros((1, 3, 2)), + lr=7, l1=3, l2=7, lr_power=2, l2_shrinkage=0.5) + self.assertAllClose(np.zeros((1, 3, 2)), accum) + + def testL2ShrinkageOnLinear(self): + """Test that 2 * l2_shrinkage * var is added to linear.""" + _, _, linear = self._eval( + var=np.ones((1, 3, 2)), + accum=np.zeros((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.zeros((1, 3, 2)), + lr=2, l1=3, l2=7, lr_power=0, l2_shrinkage=11) + self.assertAllClose(22 * np.ones((1, 3, 2)), linear) + + def testMultiplyLinearByLR(self): + """Test multiply_linear_by_lr = true for the linear variable.""" + _, _, linear = self._eval( + var=np.zeros((1, 3, 2)), + accum=np.zeros((1, 3, 2)), + linear=np.ones((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=6, l1=1, l2=-1.25, lr_power=0, + multiply_linear_by_lr=True) + self.assertAllClose(7 * np.ones((1, 3, 2)), linear) + + def testMultiplyLinearByLRClipping(self): + """Test that multiply_linear_by_lr = true scales the clip margins.""" + var, _, _ = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=3, l1=1.0, l2=0.25, lr_power=1, + multiply_linear_by_lr=True) + self.assertAllClose(-0.25 * np.ones((1, 3, 2)), var) + + def testMultiplyLinearByLRClipZero(self): + """Test that multiply_linear_by_lr = true still clips to 0.""" + var, _, _ = self._eval( + var=np.ones((1, 3, 2)), + accum=np.ones((1, 3, 2)), + linear=np.zeros((1, 3, 2)), + grad=np.ones((1, 3, 2)), + lr=3, l1=1.2, l2=0.25, lr_power=1, + multiply_linear_by_lr=True) + self.assertAllClose(np.zeros((1, 3, 2)), var) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/ftrl_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ftrl_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2117d38dccedb0186c21c9f1809791f3016e2b96 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ftrl_test.py @@ -0,0 +1,352 @@ +# 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 Ftrl optimizer.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import adagrad +from tensorflow.python.training import ftrl +from tensorflow.python.training import gradient_descent + +class FtrlOptimizerTest(xla_test.XLATestCase): + + def initVariableAndGradient(self, dtype): + var0 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.02, 0.04], dtype=dtype) + + return var0, var1, grads0, grads1 + + def equivAdagradTest_FtrlPart(self, steps, dtype): + var0, var1, grads0, grads1 = self.initVariableAndGradient(dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + learning_rate_power=-0.5, # using Adagrad learning rate + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run Ftrl for a few steps + for _ in range(steps): + ftrl_update.run() + + return self.evaluate(var0), self.evaluate(var1) + + def equivAdagradTest_AdagradPart(self, steps, dtype): + var0, var1, grads0, grads1 = self.initVariableAndGradient(dtype) + opt = adagrad.AdagradOptimizer(3.0, initial_accumulator_value=0.1) + adagrad_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run Adagrad for a few steps + for _ in range(steps): + adagrad_update.run() + + return self.evaluate(var0), self.evaluate(var1) + + def equivGradientDescentTest_FtrlPart(self, steps, dtype): + var0, var1, grads0, grads1 = self.initVariableAndGradient(dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + learning_rate_power=-0.0, # using Fixed learning rate + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run Ftrl for a few steps + for _ in range(steps): + ftrl_update.run() + + return self.evaluate(var0), self.evaluate(var1) + + def equivGradientDescentTest_GradientDescentPart(self, steps, dtype): + var0, var1, grads0, grads1 = self.initVariableAndGradient(dtype) + opt = gradient_descent.GradientDescentOptimizer(3.0, name="sgd") + sgd_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run GradientDescent for a few steps + for _ in range(steps): + sgd_update.run() + + return self.evaluate(var0), self.evaluate(var1) + + def testFtrlwithoutRegularization(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([0.0, 0.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run 3 steps FTRL + for _ in range(3): + ftrl_update.run() + + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-2.60260963, -4.29698515]), + self.evaluate(var0), + float_rtol=1e-4, + half_rtol=1e-2) + self.assertAllCloseAccordingToType( + np.array([-0.28432083, -0.56694895]), + self.evaluate(var1), + float_rtol=1e-5, + half_rtol=1e-2) + + def testFtrlwithoutRegularization2(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 3 steps FTRL + for _ in range(3): + ftrl_update.run() + + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-2.55607247, -3.98729396]), + self.evaluate(var0), + 1e-5, + 1e-5, + float_rtol=1e-4) + self.assertAllCloseAccordingToType( + np.array([-0.28232238, -0.56096673]), self.evaluate(var1), 1e-5, + 1e-5) + + def testFtrlWithL1(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=0.0) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps FTRL + for _ in range(10): + ftrl_update.run() + + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-7.66718769, -10.91273689]), + self.evaluate(var0), + rtol=1e-4, + bfloat16_rtol=1e-1, + bfloat16_atol=1e-1) + self.assertAllCloseAccordingToType( + np.array([-0.93460727, -1.86147261]), + self.evaluate(var1), + rtol=1e-4) + + def testFtrlWithL1_L2(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=2.0) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps FTRL + for _ in range(10): + ftrl_update.run() + + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-0.24059935, -0.46829352]), + self.evaluate(var0), + rtol=1e-5) + self.assertAllCloseAccordingToType( + np.array([-0.02406147, -0.04830509]), + self.evaluate(var1), + rtol=1e-5) + + def testFtrlWithL1_L2_L2Shrinkage(self): + """Test the new FTRL op with support for l2 shrinkage. + + The addition of this parameter which places a constant pressure on weights + towards the origin causes the gradient descent trajectory to differ. The + weights will tend to have smaller magnitudes with this parameter set. + """ + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.02], dtype=dtype) + opt = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=2.0, + l2_shrinkage_regularization_strength=0.1) + ftrl_update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Fetch params to validate initial values + self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) + self.assertAllCloseAccordingToType([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps FTRL + for _ in range(10): + ftrl_update.run() + + # Validate updated params + self.assertAllCloseAccordingToType( + np.array([-0.22578996, -0.44345799]), + self.evaluate(var0), + rtol=1e-4) + self.assertAllCloseAccordingToType( + np.array([-0.14378493, -0.13229476]), + self.evaluate(var1), + rtol=1e-4) + + def testFtrlWithL2ShrinkageDoesNotChangeLrSchedule(self): + """Verifies that l2 shrinkage in FTRL does not change lr schedule.""" + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.2], dtype=dtype) + grads1 = constant_op.constant([0.1, 0.2], dtype=dtype) + + opt0 = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=2.0, + l2_shrinkage_regularization_strength=0.1) + opt1 = ftrl.FtrlOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=2.0) + update0 = opt0.apply_gradients([(grads0, var0)]) + update1 = opt1.apply_gradients([(grads1, var1)]) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var0)) + self.assertAllCloseAccordingToType([1.0, 2.0], self.evaluate(var1)) + + # Run 10 steps FTRL + for _ in range(10): + update0.run() + update1.run() + + # var0 is experiencing L2 shrinkage so it should be smaller than var1 + # in magnitude. + self.assertTrue((var0.eval()**2 < self.evaluate(var1)**2).all()) + accum0 = list(opt0._slots["accum"].values())[0].eval() + accum1 = list(opt1._slots["accum"].values())[0].eval() + # L2 shrinkage should not change how we update grad accumulator. + self.assertAllCloseAccordingToType(accum0, accum1) + + # When variables are initialized with Zero, FTRL-Proximal has two properties: + # 1. Without L1&L2 but with fixed learning rate, FTRL-Proximal is identical + # with GradientDescent. + # 2. Without L1&L2 but with adaptive learning rate, FTRL-Proximal is identical + # with Adagrad. + # So, basing on these two properties, we test if our implementation of + # FTRL-Proximal performs same updates as Adagrad or GradientDescent. + def testEquivAdagradwithoutRegularization(self): + steps = 5 + for dtype in self.float_types: + with self.session(), self.test_scope(): + val0, val1 = self.equivAdagradTest_FtrlPart(steps, dtype) + with self.session(), self.test_scope(): + val2, val3 = self.equivAdagradTest_AdagradPart(steps, dtype) + + self.assertAllCloseAccordingToType(val0, val2, rtol=1e-4, half_rtol=1e-2) + self.assertAllCloseAccordingToType(val1, val3, rtol=1e-4, half_rtol=1e-2) + + def testEquivGradientDescentwithoutRegularization(self): + steps = 5 + for dtype in self.float_types: + with self.session(), self.test_scope(): + val0, val1 = self.equivGradientDescentTest_FtrlPart(steps, dtype) + with self.session(), self.test_scope(): + val2, val3 = self.equivGradientDescentTest_GradientDescentPart( + steps, dtype) + + self.assertAllCloseAccordingToType(val0, val2, rtol=1e-5) + self.assertAllCloseAccordingToType(val1, val3, rtol=1e-5) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/function_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/function_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7853c17098bad43e3fdd996bf6ecd6e6135a6d5b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/function_test.py @@ -0,0 +1,149 @@ +# 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. +# ============================================================================== +"""Test cases for Tensorflow functions.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import googletest + + +class FunctionTest(xla_test.XLATestCase): + + def testFunction(self): + """Executes a simple TensorFlow function.""" + + def APlus2B(a, b): + return a + b * 2 + + aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) + bval = np.array([5, 6, 7, 8]).reshape([2, 2]).astype(np.float32) + expected = APlus2B(aval, bval) + + with self.session(): + + @function.Defun(dtypes.float32, dtypes.float32) + def Foo(a, b): + return APlus2B(a, b) + + a = constant_op.constant(aval, name="a") + b = constant_op.constant(bval, name="b") + with self.test_scope(): + call_f = Foo(a, b) + result = self.evaluate(call_f) + self.assertAllClose(result, expected, rtol=1e-3) + + def testNestedFunctions(self): + """Executes two nested TensorFlow functions.""" + + def TimesTwo(x): + return x * 2 + + def APlus2B(a, b): + return a + TimesTwo(b) + + aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) + bval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) + expected = APlus2B(aval, bval) + + with self.session(): + + @function.Defun(dtypes.float32, dtypes.float32) + def Foo(a, b): + return APlus2B(a, b) + + a = constant_op.constant(aval, name="a") + b = constant_op.constant(bval, name="b") + with self.test_scope(): + call_g = Foo(a, b) + result = self.evaluate(call_g) + self.assertAllClose(result, expected, rtol=1e-3) + + def testFunctionMultipleRetvals(self): + """Executes a function with multiple return values.""" + + # This function will run on the XLA device + def Func(a, b): + return a + b, a - b + + aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) + bval = np.array([5, 6, 7, 8]).reshape([2, 2]).astype(np.float32) + expected = Func(aval, bval) + + with self.session(): + + @function.Defun(dtypes.float32, dtypes.float32) + def Foo(a, b): + return Func(a, b) + + a = constant_op.constant(aval, name="a") + b = constant_op.constant(bval, name="b") + with self.test_scope(): + call_f = Foo(a, b) + result = self.evaluate(call_f) + self.assertAllClose(result, expected, rtol=1e-3) + + def testCompileTimeConstantsInDefun(self): + """Tests that XLA handles compile-time constants in defuns.""" + with self.session() as sess: + + @function.Defun(dtypes.float32, dtypes.int32, dtypes.int32) + def Foo(a, c, d): + # c and d must be known at compile time + x = array_ops.slice(a, c, d) + return x + + a = array_ops.placeholder(dtypes.float32) + c = array_ops.placeholder(dtypes.int32, shape=[4]) + d = array_ops.placeholder(dtypes.int32, shape=[4]) + with self.test_scope(): + call_f = Foo(a, c, d) + result = sess.run(call_f, feed_dict={ + a: np.ones([1, 4, 4, 1]), + c: [0, 0, 0, 0], + d: [1, 2, 2, 1]}) + + self.assertAllEqual(np.ones([1, 2, 2, 1]), result) + + # TODO(b/36139787): Re-enable this test when noinline works again. + def DISABLED_testFunctionsNoInline(self): + + @function.Defun(dtypes.float32, noinline=True) + def TimesTwo(x): + return x * 2 + + @function.Defun(dtypes.float32, dtypes.float32) + def APlus2B(a, b): + return a + TimesTwo(b) + + aval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) + bval = np.array([4, 3, 2, 1]).reshape([2, 2]).astype(np.float32) + expected = aval + bval * 2 + + with self.session() as sess: + with self.test_scope(): + a = array_ops.placeholder(dtypes.float32, name="a") + b = array_ops.placeholder(dtypes.float32, name="b") + call = APlus2B(a, b) + result = sess.run(call, {a: aval, b: bval}) + self.assertAllClose(result, expected, rtol=1e-3) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/fused_batchnorm_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fused_batchnorm_test.py new file mode 100644 index 0000000000000000000000000000000000000000..75ed0f8fcde12dcc4b0f47e2a04f1f361d49ab44 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/fused_batchnorm_test.py @@ -0,0 +1,355 @@ +# 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. +# ============================================================================== +"""Functional tests for fused batch norm operations.""" + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import test_utils +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import gradient_checker +from tensorflow.python.ops import nn +from tensorflow.python.platform import test + +DATA_FORMATS = ( + ("_data_format_NHWC", "NHWC"), + ("_data_format_NCHW", "NCHW"), +) + +DATA_FORMATS_AND_AVG_FACTORS = ( + ("_data_format_NHWC_no_averaging", "NHWC", 1.0), + ("_data_format_NHWC_averaging", "NHWC", 0.6), + ("_data_format_NCHW_no_averaging", "NCHW", 1.0), + ("_data_format_NCHW_averaging", "NCHW", 0.6), +) + + +class FusedBatchNormTest(xla_test.XLATestCase, parameterized.TestCase): + + def _reference_training(self, x, scale, offset, old_mean, old_var, epsilon, + exponential_avg_factor, data_format): + if data_format != "NHWC": + raise ValueError("data_format must be NHWC, got %s." % data_format) + x_square = x * x + x_square_sum = np.sum(x_square, (0, 1, 2)) + x_sum = np.sum(x, axis=(0, 1, 2)) + element_count = np.size(x) / int(np.shape(x)[-1]) + mean = x_sum / element_count + var = x_square_sum / element_count - mean * mean + factor = element_count / max(element_count - 1, 1) + corrected_var = var * factor + normalized = (x - mean) / np.sqrt(var + epsilon) + if exponential_avg_factor != 1.0: + mean = (1.0 - + exponential_avg_factor) * old_mean + exponential_avg_factor * mean + corrected_var = (1.0 - exponential_avg_factor + ) * old_var + exponential_avg_factor * corrected_var + return (normalized * scale + offset), mean, var, corrected_var + + def _reference_grad(self, x, grad_y, scale, mean, var, epsilon, data_format): + # Use the following formulas to calculate gradients: + # grad_scale = + # sum(grad_y * (x - mean)) * rsqrt(var + epsilon) + # + # grad_offset = sum(output_y) + # + # grad_x = + # 1/N * scale * rsqrt(var + epsilon) * (N * grad_y - sum(grad_y) - + # (x - mean) * sum(grad_y * (x - mean)) / (var + epsilon)) + if data_format != "NHWC": + raise ValueError("data_format must be NHWC, got %s." % data_format) + grad_x = scale * (grad_y - np.mean(grad_y, axis=(0, 1, 2)) - + (x - mean) * np.mean(grad_y * + (x - mean), axis=(0, 1, 2)) / + (var + epsilon)) / np.sqrt(var + epsilon) + grad_scale = np.sum( + grad_y * (x - mean) / np.sqrt(var + epsilon), axis=(0, 1, 2)) + grad_offset = np.sum(grad_y, axis=(0, 1, 2)) + return grad_x, grad_scale, grad_offset + + @parameterized.named_parameters(*DATA_FORMATS) + def testInference(self, data_format): + channel = 3 + x_shape = [2, 2, 6, channel] + scale_shape = [channel] + x_val = np.random.random_sample(x_shape).astype(np.float32) + scale_val = np.random.random_sample(scale_shape).astype(np.float32) + offset_val = np.random.random_sample(scale_shape).astype(np.float32) + epsilon = 0.001 + exponential_avg_factor = 1.0 + data_format_src = "NHWC" + y_ref, mean_ref, var_ref, _ = self._reference_training( + x_val, scale_val, offset_val, None, None, epsilon, + exponential_avg_factor, data_format_src) + + with self.session() as sess, self.test_scope(): + # To avoid constant folding + x_val_converted = test_utils.ConvertBetweenDataFormats( + x_val, data_format_src, data_format) + y_ref_converted = test_utils.ConvertBetweenDataFormats( + y_ref, data_format_src, data_format) + + t_val = array_ops.placeholder( + np.float32, shape=x_val_converted.shape, name="x") + scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") + offset = array_ops.placeholder( + np.float32, shape=scale_shape, name="offset") + y, mean, variance = nn.fused_batch_norm( + t_val, + scale, + offset, + mean=mean_ref, + variance=var_ref, + epsilon=epsilon, + data_format=data_format, + is_training=False) + + y_val, _, _ = sess.run([y, mean, variance], { + t_val: x_val_converted, + scale: scale_val, + offset: offset_val + }) + self.assertAllClose(y_val, y_ref_converted, atol=1e-3) + + def _testLearning(self, use_gradient_checker, data_format, + exponential_avg_factor): + channel = 3 + x_shape = [2, 2, 6, channel] + scale_shape = [channel] + x_val = np.random.random_sample(x_shape).astype(np.float32) + scale_val = np.random.random_sample(scale_shape).astype(np.float32) + offset_val = np.random.random_sample(scale_shape).astype(np.float32) + mean_val = np.random.random_sample(scale_shape).astype(np.float32) + var_val_corr = np.random.random_sample(scale_shape).astype(np.float32) + epsilon = 0.001 + data_format_src = "NHWC" + # When in training mode, fused_batchnorm applies an implicit Bessel's + # correction. So we have to use the corrected variance here, as well. + y_ref, mean_ref, _, var_ref_corr = self._reference_training( + x_val, scale_val, offset_val, mean_val, var_val_corr, epsilon, + exponential_avg_factor, data_format_src) + + with self.session() as sess, self.test_scope(): + # To avoid constant folding + x_val_converted = test_utils.ConvertBetweenDataFormats( + x_val, data_format_src, data_format) + y_ref_converted = test_utils.ConvertBetweenDataFormats( + y_ref, data_format_src, data_format) + + t_val = array_ops.placeholder( + np.float32, shape=x_val_converted.shape, name="x") + scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") + offset = array_ops.placeholder( + np.float32, shape=scale_shape, name="offset") + if exponential_avg_factor == 1.0: + old_mean = None + old_var = None + else: + old_mean = array_ops.placeholder( + np.float32, shape=scale_shape, name="old_mean") + old_var = array_ops.placeholder( + np.float32, shape=scale_shape, name="old_var") + y, mean, var = nn.fused_batch_norm( + t_val, + scale, + offset, + mean=old_mean, + variance=old_var, + epsilon=epsilon, + exponential_avg_factor=exponential_avg_factor, + data_format=data_format, + is_training=True) + if exponential_avg_factor == 1.0: + feed_dict = { + t_val: x_val_converted, + scale: scale_val, + offset: offset_val, + } + else: + feed_dict = { + t_val: x_val_converted, + scale: scale_val, + offset: offset_val, + old_mean: mean_val, + old_var: var_val_corr + } + # Check gradient. + if use_gradient_checker: + err = gradient_checker.compute_gradient_error( + t_val, + x_val_converted.shape, + y, + x_val_converted.shape, + extra_feed_dict=feed_dict) + self.assertLess(err, 1e-3) + + y_tf, mean_tf, var_tf = sess.run([y, mean, var], feed_dict) + self.assertAllClose(y_tf, y_ref_converted, atol=1e-3) + self.assertAllClose(mean_tf, mean_ref, atol=1e-3) + self.assertAllClose(var_tf, var_ref_corr, atol=1e-3) + + @parameterized.named_parameters(*DATA_FORMATS_AND_AVG_FACTORS) + def testLearning(self, data_format, exponential_avg_factor): + self._testLearning(False, data_format, exponential_avg_factor) + + @parameterized.named_parameters(*DATA_FORMATS_AND_AVG_FACTORS) + def testLearningWithGradientChecker(self, data_format, + exponential_avg_factor): + self._testLearning(True, data_format, exponential_avg_factor) + + @parameterized.named_parameters(*DATA_FORMATS) + def testGradientTraining(self, data_format): + # disable_mlir_bridge for GPUs as there is no legalization for GPU with + # MLIR. + # TODO(b/189039456): Customize FusedBatchNorm legalization for GPU in MLIR. + if test_util.is_mlir_bridge_enabled() and self.device == "XLA_GPU": + self.skipTest("b/189039456") + + # TODO(b/64270657): Use gradient_checker here in addition to comparing with + # this reference implementation. + channel = 3 + x_shape = [2, 2, 6, channel] + scale_shape = [channel] + grad_val = np.random.random_sample(x_shape).astype(np.float32) + x_val = np.random.random_sample(x_shape).astype(np.float32) + scale_val = np.random.random_sample(scale_shape).astype(np.float32) + mean_val = np.random.random_sample(scale_shape).astype(np.float32) + var_val = np.random.random_sample(scale_shape).astype(np.float32) + epsilon = 0.001 + + # The TensorFlow FusedBatchNormGrad training operation takes two inputs with + # implementation defined values. In theory the only correct value these + # inputs are the corresponding reserve_space_{1|2} outputs from the + # FusedBatchNorm training operation. However, in practice, we rely on the + # first one being mean on {C|G}PU, and the second one being variance on CPU + # and inverse(sqrt(variance + epsilon)) on GPU (we test this assumption + # separately). + reserve_space_1_val = mean_val + if self.device == "XLA_GPU": + reserve_space_2_val = np.reciprocal(np.sqrt(var_val + epsilon)) + else: + reserve_space_2_val = var_val + + data_format_src = "NHWC" + grad_x_ref, grad_scale_ref, grad_offset_ref = self._reference_grad( + x_val, grad_val, scale_val, mean_val, var_val, epsilon, data_format_src) + + with self.session() as sess, self.test_scope(): + grad_val_converted = test_utils.ConvertBetweenDataFormats( + grad_val, data_format_src, data_format) + x_val_converted = test_utils.ConvertBetweenDataFormats( + x_val, data_format_src, data_format) + grad_x_ref_converted = test_utils.ConvertBetweenDataFormats( + grad_x_ref, data_format_src, data_format) + + grad = array_ops.placeholder( + np.float32, shape=x_val_converted.shape, name="grad") + x = array_ops.placeholder( + np.float32, shape=x_val_converted.shape, name="x") + reserve_space_1 = array_ops.placeholder( + np.float32, shape=scale_shape, name="reserve_space_1") + reserve_space_2 = array_ops.placeholder( + np.float32, shape=scale_shape, name="reserve_space_2") + scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") + grad_x, grad_scale, grad_offset, _, _ = gen_nn_ops.fused_batch_norm_grad( + grad, + x, + scale, + reserve_space_1, + reserve_space_2, + data_format=data_format, + is_training=True) + + grad_x_val, grad_scale_val, grad_offset_val = sess.run( + [grad_x, grad_scale, grad_offset], { + grad: grad_val_converted, + x: x_val_converted, + reserve_space_1: reserve_space_1_val, + reserve_space_2: reserve_space_2_val, + scale: scale_val + }) + + self.assertAllClose(grad_x_val, grad_x_ref_converted, atol=1e-2) + self.assertAllClose(grad_scale_val, grad_scale_ref, atol=1e-2) + self.assertAllClose(grad_offset_val, grad_offset_ref, atol=1e-3) + + @parameterized.named_parameters(*DATA_FORMATS) + def testGradientInference(self, data_format): + # TODO(b/64270657): Use gradient_checker here in addition to comparing with + # this reference implementation. + channel = 3 + x_shape = [2, 2, 6, channel] + scale_shape = [channel] + grad_val = np.random.random_sample(x_shape).astype(np.float32) + x_val = np.random.random_sample(x_shape).astype(np.float32) + scale_val = np.random.random_sample(scale_shape).astype(np.float32) + mean_val = np.random.random_sample(scale_shape).astype(np.float32) + var_val = np.random.random_sample(scale_shape).astype(np.float32) + data_format_src = "NHWC" + + with self.session() as sess, self.test_scope(): + grad_val_converted = test_utils.ConvertBetweenDataFormats( + grad_val, data_format_src, data_format) + x_val_converted = test_utils.ConvertBetweenDataFormats( + x_val, data_format_src, data_format) + + grad = array_ops.placeholder( + np.float32, shape=x_val_converted.shape, name="grad") + x = array_ops.placeholder( + np.float32, shape=x_val_converted.shape, name="x") + mean = array_ops.placeholder(np.float32, shape=scale_shape, name="mean") + var = array_ops.placeholder(np.float32, shape=scale_shape, name="var") + scale = array_ops.placeholder(np.float32, shape=scale_shape, name="scale") + with self.test_scope(): + out = gen_nn_ops.fused_batch_norm_grad( + grad, + x, + scale, + mean, + var, + data_format=data_format, + is_training=False) + grad_x, grad_scale, grad_offset, _, _ = out + + ref_x, ref_scale, ref_offset, _, _ = gen_nn_ops.fused_batch_norm_grad( + grad, x, scale, mean, var, data_format=data_format, is_training=False) + + grad_x_val, grad_scale_val, grad_offset_val, = sess.run( + [grad_x, grad_scale, grad_offset], { + grad: grad_val_converted, + x: x_val_converted, + mean: mean_val, + var: var_val, + scale: scale_val + }) + grad_x_ref, grad_scale_ref, grad_offset_ref, = sess.run( + [ref_x, ref_scale, ref_offset], { + grad: grad_val_converted, + x: x_val_converted, + mean: mean_val, + var: var_val, + scale: scale_val + }) + + self.assertAllClose(grad_x_val, grad_x_ref, atol=1e-2) + self.assertAllClose(grad_scale_val, grad_scale_ref, atol=1e-2) + self.assertAllClose(grad_offset_val, grad_offset_ref, atol=1e-3) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/gather_nd_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/gather_nd_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b5419652ea490f10084266cace8b493cd84c06e0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/gather_nd_op_test.py @@ -0,0 +1,175 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for tensorflow.ops.tf.gather_nd.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class GatherNdTest(xla_test.XLATestCase): + + def _runGather(self, params, indices, bad_indices_policy=""): + with self.session(): + paramsp = array_ops.placeholder(params.dtype) + indicesp = array_ops.placeholder(indices.dtype) + with self.test_scope(): + gather_nd_t = array_ops.gather_nd( + paramsp, indicesp, bad_indices_policy=bad_indices_policy + ) + feed_dict = {paramsp: params, indicesp: indices} + return gather_nd_t.eval(feed_dict=feed_dict) + + def testSimpleDtype(self): + for dtype in self.numeric_types: + self.assertAllEqual( + np.array([7, 7, 8], dtype=dtype), + self._runGather( + np.array([8, 1, 2, 3, 7, 5], dtype=dtype), + np.array([[4], [4], [0]], np.int32))) + + @test_util.disable_mlir_bridge("Error handling") + def testEmptyIndicesAndParamstAndEmptyParamsOk(self): + with self.session(): + params = np.ones((3, 3), dtype=np.float32) + + indices_empty = np.empty((0, 2), dtype=np.int32) + gather_nd_ok_val = self._runGather(params, indices_empty) + self.assertAllClose(np.empty((0,), dtype=np.float32), gather_nd_ok_val) + + indices_empty = np.empty((0, 1), dtype=np.int32) + gather_nd_ok_val = self._runGather(params, indices_empty) + self.assertAllClose(np.empty((0, 3), dtype=np.float32), gather_nd_ok_val) + + params_empty = np.empty((0, 3), dtype=np.float32) + indices_empty = np.empty((0, 2), dtype=np.int32) + gather_nd_ok_val = self._runGather(params_empty, indices_empty) + self.assertAllClose(np.empty((0,), dtype=np.float32), gather_nd_ok_val) + + # Zero sized indices results in a constant of 0 + params_empty = np.empty((0, 3), dtype=np.float32) + indices_nonempty = np.zeros((1, 2), dtype=np.int32) + gather_nd_ok_val = self._runGather(params_empty, indices_nonempty) + self.assertAllEqual(gather_nd_ok_val, np.zeros([3])) + + def testIndexScalar(self): + params = np.array( + [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T + indices = np.array([4, 1], dtype=np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(np.array(7), gather_nd_val) + + def testParamsRankLargerThanIndexIndexScalarSlices(self): + params = np.array( + [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T + indices = np.array( + [ + 4, + ], dtype=np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(np.array([-7, 7]), gather_nd_val) + + def testParamsRankLargerThanIndexSlices(self): + params = np.array( + [[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], dtype=np.float32).T + indices = np.array([[4], [4], [0]], np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(np.array([[-7, 7], [-7, 7], [-8, 8]]), gather_nd_val) + + def testHigherRankParamsLargerThanIndexSlices(self): + params = np.array( + [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], + [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]], + dtype=np.float32).T + indices = np.array([[4], [4], [0]], np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(params[[4, 4, 0]], gather_nd_val) + + def testEmptyIndicesLastRankMeansCopyEntireTensor(self): + params = np.array( + [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], + [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]], + dtype=np.float32).T + indices = np.array([[], []], dtype=np.int32) # Size (2, 0) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual( + np.vstack((params[np.newaxis, :], params[np.newaxis, :])), + gather_nd_val) + + def testHigherRankParamsAndIndicesLargerThanIndexSlices(self): + params = np.array( + [[[-8, -1, -2, -3, -7, -5], [8, 1, 2, 3, 7, 5]], + [[-80, -10, -20, -30, -70, -50], [80, 10, 20, 30, 70, 50]]], + dtype=np.float32).T + indices = np.array([[[3], [2], [1]], [[4], [4], [0]]], np.int32) + gather_nd_val = self._runGather(params, indices) + self.assertAllEqual(params[[3, 2, 1, 4, 4, 0]].reshape(2, 3, 2, 2), + gather_nd_val) + + def testHigherRankParams(self): + shape = (10, 20, 5, 1, 17) + params = np.random.rand(*shape).astype(np.float32) + indices = np.vstack( + [np.random.randint(0, s, size=2000, dtype=np.int32) for s in shape]).T + gather_nd_val = self._runGather(params, indices) + + expected = params[tuple(indices.T)] + self.assertAllEqual(expected, gather_nd_val) + + def testHigherRankParamsAndIndices(self): + shape = (10, 20, 5, 1, 17) + params = np.random.rand(*shape).astype(np.float32) + indices = np.vstack( + [np.random.randint(0, s, size=2000, dtype=np.int32) for s in shape]).T + indices_reshaped = indices.reshape([10, 10, 20, 5]) + gather_nd_val = self._runGather(params, indices_reshaped) + expected = params[tuple(indices.T)] + self.assertAllEqual(expected.reshape([10, 10, 20]), gather_nd_val) + + def testIgnoreBadIndices(self): + shape = (3, 4, 5) + params = np.arange(np.prod(shape), dtype=np.int32).reshape(shape) + indices = np.array([[[0, 0], [-1, 3]], [[2, 4], [2, 3]]], dtype=np.int32) + gather_nd_val = self._runGather( + params, indices, bad_indices_policy="IGNORE" + ) + expected = np.array( + [ + [[0, 1, 2, 3, 4], [0, 0, 0, 0, 0]], + [[0, 0, 0, 0, 0], [55, 56, 57, 58, 59]], + ], + dtype=np.int32, + ) + self.assertAllEqual(expected, gather_nd_val) + + def testIgnoreBadIndicesNoFeatureDim(self): + shape = (3, 4) + params = np.arange(np.prod(shape), dtype=np.int32).reshape(shape) + indices = np.array([[[0, 0], [-1, 3]], [[2, 4], [2, 3]]], dtype=np.int32) + gather_nd_val = self._runGather( + params, indices, bad_indices_policy="IGNORE" + ) + expected = np.array( + [[0, 0], [0, 11]], + dtype=np.int32, + ) + self.assertAllEqual(expected, gather_nd_val) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/gather_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/gather_test.py new file mode 100644 index 0000000000000000000000000000000000000000..74c427bd3b81e13e14b929d2ee1028bab17c5ed9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/gather_test.py @@ -0,0 +1,217 @@ +# 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. +# ============================================================================== +"""Functional tests for XLA Gather Op.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import flags +from tensorflow.python.platform import test + +FLAGS = flags.FLAGS + + +class GatherTest(xla_test.XLATestCase): + + def _buildParams(self, data, dtype): + data = data.astype(dtype.as_numpy_dtype) + # For complex types, adds 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 testScalar1D(self): + with self.session() as session, self.test_scope(): + data = np.array([0, 1, 2, 3, 7, 5]) + for dtype in self.all_tf_types: + for indices in 4, [4], [1, 2, 2, 4, 5]: + params_np = self._buildParams(data, dtype) + params = array_ops.placeholder(dtype=dtype) + indices_tf = constant_op.constant(indices) + gather_t = array_ops.gather(params, indices_tf) + gather_val = session.run(gather_t, feed_dict={params: params_np}) + np_val = constant_op.constant(params_np[indices]) + self.assertAllEqual(np_val, gather_val) + + def testScalar2D(self): + with self.session() as session, self.test_scope(): + data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], + [12, 13, 14]]) + for dtype in self.all_tf_types: + for axis in 0, 1, -1: + params_np = self._buildParams(data, dtype) + params = array_ops.placeholder(dtype=dtype) + indices = constant_op.constant(2) + gather_t = array_ops.gather(params, indices, axis=axis) + gather_val = session.run(gather_t, feed_dict={params: params_np}) + expected = constant_op.constant( + np.take(params_np, 2, axis=axis), dtype) + self.assertAllEqual(expected, gather_val) + + def testSimpleTwoD32(self): + with self.session() as session, self.test_scope(): + data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], + [12, 13, 14]]) + for dtype in self.all_tf_types: + for axis in 0, 1, -1: + params_np = self._buildParams(data, dtype) + params = array_ops.placeholder(dtype=dtype) + # The indices must be in bounds for any axis. + indices = constant_op.constant([0, 1, 0, 2]) + gather_t = array_ops.gather(params, indices, axis=axis) + gather_val = session.run(gather_t, feed_dict={params: params_np}) + expected = constant_op.constant( + np.take(params_np, [0, 1, 0, 2], axis=axis), dtype) + self.assertAllEqual(expected, gather_val) + + def testSimpleTwoD32_Int64Indices(self): + if np.int64 not in self.int_types: + return + + with self.session() as session, self.test_scope(): + data = np.array([[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 10, 11], + [12, 13, 14]]) + # The indices must be in bounds for any axis. + indices_np = np.array([0, 1, 0, 2]) + for dtype in self.all_tf_types: + for axis in 0, 1, -1: + params_np = self._buildParams(data, dtype) + params = array_ops.placeholder(dtype=dtype) + indices = array_ops.placeholder(dtype=dtypes.int64) + gather_t = array_ops.gather(params, indices, axis=axis) + gather_val = session.run( + gather_t, feed_dict={ + params: params_np, + indices: indices_np + }) + expected = constant_op.constant( + np.take(params_np, [0, 1, 0, 2], axis=axis), dtype) + self.assertAllEqual(expected, gather_val) + + def testHigherRank(self): + """Check that scalar and empty indices shapes work as well.""" + shape = (2, 1, 3, 2) + for indices_shape in (), (0,), (2, 0), (2, 3): + for dtype in self.all_tf_types: + for axis in 0, 1, 2, 3, -1, -2: + params = self._buildParams(np.random.randn(*shape), dtype) + indices = np.random.randint(shape[axis], size=indices_shape) + with self.session() as sess, self.test_scope(): + tf_params = array_ops.placeholder(dtype=dtype) + tf_indices = constant_op.constant(indices, dtype=dtypes.int32) + gather = array_ops.gather(tf_params, tf_indices, axis=axis) + gather_value = sess.run(gather, feed_dict={tf_params: params}) + gather_np = constant_op.constant( + np.take(params, indices, axis=axis), dtype) + self.assertAllEqual(gather_np, gather_value) + + def testIndicesWithDifferentDimensions(self): + with self.session(): + for dtype in self.numeric_tf_types: + params = array_ops.placeholder(dtype=dtype) + indices = array_ops.placeholder(dtype=np.int32) + with self.test_scope(): + gather = array_ops.gather(params, indices) + self.assertAllEqual( + 7, gather.eval(feed_dict={params: [4, 7, 2], indices: 1})) + self.assertAllEqual( + [7], gather.eval(feed_dict={params: [4, 7, 2], indices: [1]})) + self.assertAllEqual( + [[7]], gather.eval(feed_dict={params: [4, 7, 2], indices: [[1]]})) + + def testGatherPrecision(self): + with self.session() as session, self.test_scope(): + data = np.array([[0, 0, 0, 0], [0, 2 * (1 + np.exp2(-8)), 0, 0], + [0, 0, 0, 0], [0.015789, 0.0985, 0.55789, 0.3842]]) + indices = np.array([1, 2, 3, 1]) + dtype = dtypes.float32 + params_np = self._buildParams(data, dtype) + params = array_ops.placeholder(dtype=dtype) + indices_tf = constant_op.constant(indices) + gather_t = array_ops.gather(params, indices_tf) + gather_val = session.run(gather_t, feed_dict={params: params_np}) + np_val = params_np[indices] + self.assertAllEqual(np_val, gather_val) + + +class GatherBenchmark(test.Benchmark): + """Microbenchmarks for the gather op.""" + + def _benchmarkGather(self, name, axis, gather_indices, use_xla_jit): + + def BuilderFn(): + inputs = variables.Variable( + array_ops.zeros([100, 100, 10, 100, 50], dtype=dtypes.float32), + dtype=dtypes.float32, + name='input') + indices = variables.Variable( + gather_indices, dtype=dtypes.int32, name='indices') + gather_t = array_ops.gather(inputs, indices, axis=axis) + return '%s.axis%d' % (name, axis), [gather_t] + + xla_test.Benchmark(self, BuilderFn, use_xla_jit=use_xla_jit, device='cpu') + + def _benchmarkSliceGather(self, axis, use_xla_jit): + """Benchmarks a gather op that's really a dynamic slice.""" + self._benchmarkGather('slice_gather', axis, [1], use_xla_jit) + + def _benchmarkNontrivialGather(self, axis, use_xla_jit): + self._benchmarkGather('nontrivial_gather', axis, [9, 1, 0, 2] * 4, + use_xla_jit) + + def benchmarkSliceGatherAxis0(self): + self._benchmarkSliceGather(axis=0, use_xla_jit=False) + + def benchmarkSliceGatherAxis0XLA(self): + self._benchmarkSliceGather(axis=0, use_xla_jit=True) + + def benchmarkSliceGatherAxis1(self): + self._benchmarkSliceGather(axis=1, use_xla_jit=False) + + def benchmarkSliceGatherAxis1XLA(self): + self._benchmarkSliceGather(axis=1, use_xla_jit=True) + + def benchmarkSliceGatherAxis4(self): + self._benchmarkSliceGather(axis=4, use_xla_jit=False) + + def benchmarkSliceGatherAxis4XLA(self): + self._benchmarkSliceGather(axis=4, use_xla_jit=True) + + def benchmarkNontrivialGatherAxis0(self): + self._benchmarkNontrivialGather(axis=0, use_xla_jit=False) + + def benchmarkNontrivialGatherAxis0XLA(self): + self._benchmarkNontrivialGather(axis=0, use_xla_jit=True) + + def benchmarkNontrivialGatherAxis1(self): + self._benchmarkNontrivialGather(axis=1, use_xla_jit=False) + + def benchmarkNontrivialGatherAxis1XLA(self): + self._benchmarkNontrivialGather(axis=1, use_xla_jit=True) + + def benchmarkNontrivialGatherAxis4(self): + self._benchmarkNontrivialGather(axis=4, use_xla_jit=False) + + def benchmarkNontrivialGatherAxis4XLA(self): + self._benchmarkNontrivialGather(axis=4, use_xla_jit=True) + + +if __name__ == '__main__': + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/giant_const_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/giant_const_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..a4ef7176bfce1974f9a56e5ef9d3a96ab3548b52 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/giant_const_op_test.py @@ -0,0 +1,109 @@ +# Copyright 2021 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 giant const op compilation.""" + +import os +import numpy as np + +from tensorflow.python.distribute import tpu_strategy as tpu_lib +from tensorflow.python.distribute.cluster_resolver import tpu_cluster_resolver +from tensorflow.python.eager import def_function +from tensorflow.python.eager import remote +from tensorflow.python.eager import test +from tensorflow.python.framework import config +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.platform import flags + +FLAGS = flags.FLAGS +flags.DEFINE_string("tpu", "", "Name of TPU to connect to.") +flags.DEFINE_string("project", None, "Name of GCP project with TPU.") +flags.DEFINE_string("zone", None, "Name of GCP zone with TPU.") + + +def get_tpu_cluster_resolver(): + resolver = tpu_cluster_resolver.TPUClusterResolver( + tpu=FLAGS.tpu, + zone=FLAGS.zone, + project=FLAGS.project, + ) + return resolver + + +def get_tpu_strategy(): + resolver = get_tpu_cluster_resolver() + remote.connect_to_cluster(resolver) + tpu_cluster_resolver.initialize_tpu_system(resolver) + return tpu_lib.TPUStrategyV2(resolver) + + +# This test doesn't use XLATestCase like the other tests in this directory. +# The Const op xla op kernel is compilation only and therefore is not executed +# with XLA in the on demand compilation mode. Also, here we want to feed the +# full program to XLA to verify handling of programs with giant constant +# tensors. +class GiantConstOp(test.TestCase): + + # Verifies that graphs containing giant const tensors that won't fit in memory + # are compiled correctly to HLO. + def testGiantConst(self): + # Disabling Mlir bridge since using the tf2xla implementation of + # StridedSliceop which would get executed in this GiantConst test. + config.disable_mlir_bridge() + strategy = get_tpu_strategy() + types = { + dtypes.bool, + dtypes.int8, dtypes.int16, dtypes.int32, dtypes.int64, + dtypes.uint8, dtypes.uint16, dtypes.uint32, dtypes.uint64, + dtypes.float16, dtypes.bfloat16, + dtypes.float32, dtypes.float64, + } + for dtype in types: + values = [True if dtype is dtypes.bool else 1] + + if dtype is dtypes.bool: + values.append(False) + elif dtype is not dtypes.float64: + # TPUs don't follow IEEE 754 float64 standard for 64 bit floating point + # numbers so it could return different output even with just data + # transformation ops without any arithmetic operations. + values.extend([dtype.min, dtype.max]) + + for value in values: + + @def_function.function + def train_step(): + + # pylint: disable=cell-var-from-loop + def computation(): + const = constant_op.constant(value, dtype=dtype, shape=[1024]*4) + return const[:1, :1, :1, :1] + + return strategy.run(computation, args=()) + + output = strategy.experimental_local_results(train_step())[0] + expected = np.full((1, 1, 1, 1), value) + self.assertAllEqual(output, expected) + +if __name__ == "__main__": + # Make sure TF_XLA_FLAGS is not already set to avoid dropping the existing + # value silently. + assert "TF_XLA_FLAGS" not in os.environ + + # Disable tfxla constant folding that always creates full Tensors and will + # fail for giant tensors. + os.environ["TF_XLA_FLAGS"] = "--tf_xla_disable_constant_folding=true" + + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/image_ops_jit_compile_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/image_ops_jit_compile_test.py new file mode 100644 index 0000000000000000000000000000000000000000..27fdb24438ab739dbe4b0d944333b22e3c03fdfb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/image_ops_jit_compile_test.py @@ -0,0 +1,61 @@ +# Copyright 2022 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.array_ops.repeat.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import backprop +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import image_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +class ImageOpsTest(xla_test.XLATestCase): + + def testGradImageResize(self): + """Tests that the gradient of image.resize is compilable.""" + with ops.device("device:{}:0".format(self.device)): + img_width = 2048 + var = variables.Variable(array_ops.ones(1, dtype=dtypes.float32)) + + def model(x): + x = var * x + x = image_ops.resize_images( + x, + size=[img_width, img_width], + method=image_ops.ResizeMethod.BILINEAR) + return x + + def train(x, y): + with backprop.GradientTape() as tape: + output = model(x) + loss_value = math_ops.reduce_mean((y - output)**2) + grads = tape.gradient(loss_value, [var]) + return grads + + compiled_train = def_function.function(train, jit_compile=True) + x = array_ops.zeros((1, img_width // 2, img_width // 2, 1), + dtype=dtypes.float32) + y = array_ops.zeros((1, img_width, img_width, 1), dtype=dtypes.float32) + self.assertAllClose(train(x, y), compiled_train(x, y)) + + +if __name__ == "__main__": + ops.enable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/image_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/image_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..82f3971fd23716182044bb191ae50e6bd39b1d28 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/image_ops_test.py @@ -0,0 +1,1517 @@ +# 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 image ops.""" + +import colorsys +import math +import os + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.ops import gen_image_ops +from tensorflow.python.ops import image_ops +from tensorflow.python.platform import test + + +def _generate_numpy_random_rgb(shape): + # Only generate floating points that are fractions like n / 256, since they + # are RGB pixels. Some low-precision floating point types in this test can't + # handle arbitrary precision floating points well. + return np.random.randint(0, 256, shape) / 256. + + +class RGBToHSVTest(xla_test.XLATestCase): + + def testBatch(self): + # Build an arbitrary RGB image + np.random.seed(7) + batch_size = 5 + shape = (batch_size, 2, 7, 3) + + for nptype in self.float_types: + inp = _generate_numpy_random_rgb(shape).astype(nptype) + + # Convert to HSV and back, as a batch and individually + with self.session() as sess: + batch0 = array_ops.placeholder(nptype, shape=shape) + with self.test_scope(): + batch1 = image_ops.rgb_to_hsv(batch0) + batch2 = image_ops.hsv_to_rgb(batch1) + split0 = array_ops_stack.unstack(batch0) + with self.test_scope(): + split1 = list(map(image_ops.rgb_to_hsv, split0)) + split2 = list(map(image_ops.hsv_to_rgb, split1)) + join1 = array_ops_stack.stack(split1) + join2 = array_ops_stack.stack(split2) + batch1, batch2, join1, join2 = sess.run([batch1, batch2, join1, join2], + {batch0: inp}) + + # Verify that processing batch elements together is the same as separate + self.assertAllCloseAccordingToType(batch1, join1, half_rtol=0.000002) + self.assertAllCloseAccordingToType(batch2, join2, half_rtol=0.000002) + self.assertAllCloseAccordingToType( + batch2, inp, bfloat16_atol=0.03, half_rtol=0.02) + + def testRGBToHSVRoundTrip(self): + data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] + for nptype in self.float_types: + rgb_np = np.array(data, dtype=nptype).reshape([2, 2, 3]) / 255. + with self.session(): + placeholder = array_ops.placeholder(nptype) + with self.test_scope(): + hsv = image_ops.rgb_to_hsv(placeholder) + rgb = image_ops.hsv_to_rgb(hsv) + rgb_tf = rgb.eval(feed_dict={placeholder: rgb_np}) + self.assertAllCloseAccordingToType(rgb_tf, rgb_np, bfloat16_atol=0.03) + + def testRGBToHSVNumpy(self): + """Tests the RGB to HSV conversion matches a reference implementation.""" + for nptype in self.float_types: + rgb_flat = _generate_numpy_random_rgb((64, 3)).astype(nptype) + rgb_np = rgb_flat.reshape(4, 4, 4, 3) # pylint: disable=too-many-function-args + hsv_np = np.array([ + colorsys.rgb_to_hsv( + r.astype(np.float64), g.astype(np.float64), b.astype(np.float64)) + for r, g, b in rgb_flat + ]) + hsv_np = hsv_np.reshape(4, 4, 4, 3) # pylint: disable=too-many-function-args + with self.session(): + placeholder = array_ops.placeholder(nptype) + with self.test_scope(): + hsv_op = image_ops.rgb_to_hsv(placeholder) + hsv_tf = hsv_op.eval(feed_dict={placeholder: rgb_np}) + self.assertAllCloseAccordingToType(hsv_tf, hsv_np) + + +class AdjustContrastTest(xla_test.XLATestCase): + + def _testContrast(self, x_np, y_np, contrast_factor): + with self.session(): + x = array_ops.placeholder(x_np.dtype, shape=x_np.shape) + flt_x = image_ops.convert_image_dtype(x, dtypes.float32) + with self.test_scope(): + y = image_ops.adjust_contrast(flt_x, contrast_factor) + y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) + y_tf = y.eval({x: x_np}) + self.assertAllClose(y_tf, y_np, 1e-6) + + def testFloatContrast(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.float32).reshape(x_shape) / 255. + + y_data = [ + -45.25, -90.75, -92.5, 62.75, 169.25, 333.5, 28.75, -84.75, 349.5, + 134.75, 409.25, -116.5 + ] + y_np = np.array(y_data, dtype=np.float32).reshape(x_shape) / 255. + + self._testContrast(x_np, y_np, contrast_factor=2.0) + + def testBatchContrast(self): + x_shape = [2, 1, 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) + + y_data = [0, 0, 0, 81, 200, 255, 10, 0, 255, 116, 255, 0] + y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) + + self._testContrast(x_np, y_np, contrast_factor=2.0) + + def _adjustContrastNp(self, x_np, contrast_factor): + mean = np.mean(x_np, (1, 2), keepdims=True) + y_np = mean + contrast_factor * (x_np - mean) + return y_np + + def _adjustContrastTf(self, x_np, contrast_factor): + with self.session(): + x = array_ops.placeholder(np.float32) + with self.test_scope(): + y = image_ops.adjust_contrast(x, contrast_factor) + y_tf = y.eval({x: x_np}) + return y_tf + + def testRandomContrast(self): + x_shapes = [ + [1, 2, 2, 3], + [2, 1, 2, 3], + [1, 2, 2, 3], + [2, 5, 5, 3], + [2, 1, 1, 3], + ] + for x_shape in x_shapes: + x_np = np.random.rand(*x_shape) * 255. + contrast_factor = np.random.rand() * 2.0 + 0.1 + y_np = self._adjustContrastNp(x_np, contrast_factor) + y_tf = self._adjustContrastTf(x_np, contrast_factor) + self.assertAllClose(y_tf, y_np, rtol=1e-5, atol=1e-5) + + +class AdjustHueTest(xla_test.XLATestCase): + + def testAdjustNegativeHue(self): + x_shape = [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) + + delta = -0.25 + y_data = [0, 13, 1, 54, 226, 59, 8, 234, 150, 255, 39, 1] + y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) + + with self.session(): + x = array_ops.placeholder(x_np.dtype, shape=x_shape) + flt_x = image_ops.convert_image_dtype(x, dtypes.float32) + with self.test_scope(): + y = gen_image_ops.adjust_hue(flt_x, delta) + y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) + y_tf = y.eval({x: x_np}) + self.assertAllEqual(y_tf, y_np) + + def testAdjustPositiveHue(self): + x_shape = [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) + + delta = 0.25 + y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] + y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) + + with self.session(): + x = array_ops.placeholder(x_np.dtype, shape=x_shape) + flt_x = image_ops.convert_image_dtype(x, dtypes.float32) + with self.test_scope(): + y = gen_image_ops.adjust_hue(flt_x, delta) + y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) + y_tf = y.eval({x: x_np}) + self.assertAllEqual(y_tf, y_np) + + def testBatchAdjustHue(self): + x_shape = [2, 1, 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) + + delta = 0.25 + y_data = [13, 0, 11, 226, 54, 221, 234, 8, 92, 1, 217, 255] + y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) + + with self.session(): + x = array_ops.placeholder(x_np.dtype, shape=x_shape) + flt_x = image_ops.convert_image_dtype(x, dtypes.float32) + with self.test_scope(): + y = gen_image_ops.adjust_hue(flt_x, delta) + y = image_ops.convert_image_dtype(y, x.dtype, saturate=True) + y_tf = y.eval({x: x_np}) + self.assertAllEqual(y_tf, y_np) + + def _adjustHueNp(self, x_np, delta_h): + self.assertEqual(x_np.shape[-1], 3) + x_v = x_np.reshape([-1, 3]) + y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) + channel_count = x_v.shape[0] + for i in range(channel_count): + r = x_v[i][0] + g = x_v[i][1] + b = x_v[i][2] + h, s, v = colorsys.rgb_to_hsv(r, g, b) + h += delta_h + h = math.fmod(h + 10.0, 1.0) + r, g, b = colorsys.hsv_to_rgb(h, s, v) + y_v[i][0] = r + y_v[i][1] = g + y_v[i][2] = b + return y_v.reshape(x_np.shape) + + def _adjustHueTf(self, x_np, delta_h): + with self.session(): + x = array_ops.placeholder(dtypes.float32) + with self.test_scope(): + y = gen_image_ops.adjust_hue(x, delta_h) + y_tf = y.eval({x: x_np}) + return y_tf + + def testAdjustRandomHue(self): + x_shapes = [ + [2, 2, 3], + [4, 2, 3], + [2, 4, 3], + [2, 5, 3], + [1000, 1, 3], + ] + test_styles = [ + "all_random", + "rg_same", + "rb_same", + "gb_same", + "rgb_same", + ] + for x_shape in x_shapes: + for test_style in test_styles: + x_np = np.random.rand(*x_shape) * 255. + delta_h = np.random.rand() * 2.0 - 1.0 + if test_style == "all_random": + pass + elif test_style == "rg_same": + x_np[..., 1] = x_np[..., 0] + elif test_style == "rb_same": + x_np[..., 2] = x_np[..., 0] + elif test_style == "gb_same": + x_np[..., 2] = x_np[..., 1] + elif test_style == "rgb_same": + x_np[..., 1] = x_np[..., 0] + x_np[..., 2] = x_np[..., 0] + else: + raise AssertionError("Invalid test style: %s" % (test_style)) + y_np = self._adjustHueNp(x_np, delta_h) + y_tf = self._adjustHueTf(x_np, delta_h) + self.assertAllClose(y_tf, y_np, rtol=2e-5, atol=1e-4) + + def testInvalidShapes(self): + fused = False + if not fused: + # The tests are known to pass with the fused adjust_hue. We will enable + # them when the fused implementation is the default. + return + x_np = np.random.rand(2, 3) * 255. + delta_h = np.random.rand() * 2.0 - 1.0 + fused = False + with self.assertRaisesRegex(ValueError, "Shape must be at least rank 3"): + self._adjustHueTf(x_np, delta_h) + x_np = np.random.rand(4, 2, 4) * 255. + delta_h = np.random.rand() * 2.0 - 1.0 + with self.assertRaisesOpError("input must have 3 channels"): + self._adjustHueTf(x_np, delta_h) + + +class AdjustSaturationTest(xla_test.XLATestCase): + + def _adjust_saturation(self, image, saturation_factor): + image = ops.convert_to_tensor(image, name="image") + orig_dtype = image.dtype + flt_image = image_ops.convert_image_dtype(image, dtypes.float32) + with self.test_scope(): + saturation_adjusted_image = gen_image_ops.adjust_saturation( + flt_image, saturation_factor) + return image_ops.convert_image_dtype(saturation_adjusted_image, orig_dtype) + + def testHalfSaturation(self): + x_shape = [2, 2, 3] + x_rgb_data = [0, 5, 13, 54, 135, 226, 37, 8, 234, 90, 255, 1] + x_np = np.array(x_rgb_data, dtype=np.uint8).reshape(x_shape) + + saturation_factor = 0.5 + y_rgb_data = [6, 9, 13, 140, 180, 226, 135, 121, 234, 172, 255, 128] + y_np = np.array(y_rgb_data, dtype=np.uint8).reshape(x_shape) + + with self.session(): + x = array_ops.placeholder(x_np.dtype, shape=x_shape) + y = self._adjust_saturation(x, saturation_factor) + y_tf = y.eval({x: x_np}) + self.assertAllEqual(y_tf, y_np) + + def testTwiceSaturation(self): + x_shape = [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) + + saturation_factor = 2.0 + y_data = [0, 5, 13, 0, 106, 226, 30, 0, 234, 89, 255, 0] + y_np = np.array(y_data, dtype=np.uint8).reshape(x_shape) + + with self.session(): + x = array_ops.placeholder(x_np.dtype, shape=x_shape) + y = self._adjust_saturation(x, saturation_factor) + y_tf = y.eval({x: x_np}) + self.assertAllEqual(y_tf, y_np) + + def _adjustSaturationNp(self, x_np, scale): + self.assertEqual(x_np.shape[-1], 3) + x_v = x_np.reshape([-1, 3]) + y_v = np.ndarray(x_v.shape, dtype=x_v.dtype) + channel_count = x_v.shape[0] + for i in range(channel_count): + r = x_v[i][0] + g = x_v[i][1] + b = x_v[i][2] + h, s, v = colorsys.rgb_to_hsv(r, g, b) + s *= scale + s = min(1.0, max(0.0, s)) + r, g, b = colorsys.hsv_to_rgb(h, s, v) + y_v[i][0] = r + y_v[i][1] = g + y_v[i][2] = b + return y_v.reshape(x_np.shape) + + def testAdjustRandomSaturation(self): + x_shapes = [ + [2, 2, 3], + [4, 2, 3], + [2, 4, 3], + [2, 5, 3], + [1000, 1, 3], + ] + test_styles = [ + "all_random", + "rg_same", + "rb_same", + "gb_same", + "rgb_same", + ] + with self.session(): + for x_shape in x_shapes: + for test_style in test_styles: + x_np = np.random.rand(*x_shape) * 255. + scale = np.random.rand() + if test_style == "all_random": + pass + elif test_style == "rg_same": + x_np[..., 1] = x_np[..., 0] + elif test_style == "rb_same": + x_np[..., 2] = x_np[..., 0] + elif test_style == "gb_same": + x_np[..., 2] = x_np[..., 1] + elif test_style == "rgb_same": + x_np[..., 1] = x_np[..., 0] + x_np[..., 2] = x_np[..., 0] + else: + raise AssertionError("Invalid test style: %s" % (test_style)) + y_baseline = self._adjustSaturationNp(x_np, scale) + x = array_ops.placeholder(dtypes.float32, shape=x_shape) + with self.test_scope(): + y_fused = self._adjust_saturation(x, + scale).eval(feed_dict={x: x_np}) + self.assertAllClose(y_fused, y_baseline, rtol=2e-5, atol=1e-5) + + +class ResizeNearestNeighborTest(xla_test.XLATestCase): + # TODO(ilch): Wrap each test with `for dtype in self.float_types:` + # Some work to understand how that should be done was presented here: + # cl/227850213 + + def _assertForwardOpMatchesExpected(self, + image_np, + target_shape, + expected=None, + large_tolerance=False, + align_corners=True): + if expected is None: + self.fail("expected must be specified") + with self.session() as sess, self.test_scope(): + image = array_ops.placeholder(image_np.dtype) + resized = gen_image_ops.resize_nearest_neighbor( + image, target_shape, align_corners=align_corners) + out = sess.run(resized, {image: image_np[np.newaxis, :, :, np.newaxis]}) + if large_tolerance: + self.assertAllClose( + expected[np.newaxis, :, :, np.newaxis], out, rtol=2e-4, atol=2e-4) + else: + self.assertAllClose(expected[np.newaxis, :, :, np.newaxis], out) + + def testAlignCorners2x2To1x1(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2], [3, 4]], dtype=np.float32), [1, 1], + expected=np.array([[1]], dtype=np.float32)) + + def testAlignCorners1x1To2x2(self): + self._assertForwardOpMatchesExpected( + np.array([[1]], dtype=np.float32), [2, 2], + expected=np.array([[1, 1], [1, 1]], dtype=np.float32)) + + def testAlignCorners1x1To3x3(self): + self._assertForwardOpMatchesExpected( + np.array([[1]], dtype=np.float32), [3, 3], + expected=np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], dtype=np.float32)) + + def testAlignCorners2x2To3x3(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2], [3, 4]], dtype=np.float32), [3, 3], + expected=np.array([[1, 2, 2], [3, 4, 4], [3, 4, 4]], dtype=np.float32)) + + def testAlignCorners2x2To4x4(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2], [3, 4]], dtype=np.float32), [4, 4], + expected=np.array( + [[1, 1, 2, 2], [1, 1, 2, 2], [3, 3, 4, 4], [3, 3, 4, 4]], + dtype=np.float32), + large_tolerance=True) + + def testAlignCorners3x3To2x2(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), [2, 2], + expected=np.array([[1, 3], [7, 9]], dtype=np.float32)) + + def testAlignCorners4x4To3x3(self): + self._assertForwardOpMatchesExpected( + np.array( + [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]], + dtype=np.float32), [3, 3], + expected=np.array([[1, 3, 4], [9, 11, 12], [13, 15, 16]], + dtype=np.float32)) + + def testAlignCorners3x3To4x4(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), [4, 4], + expected=np.array( + [[1, 2, 2, 3], [4, 5, 5, 6], [4, 5, 5, 6], [7, 8, 8, 9]], + dtype=np.float32)) + + def testAlignCorners3x3To6x6(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), [6, 6], + expected=np.array( + [[1, 1, 2, 2, 3, 3], [1, 1, 2, 2, 3, 3], [4, 4, 5, 5, 6, 6], + [4, 4, 5, 5, 6, 6], [7, 7, 8, 8, 9, 9], [7, 7, 8, 8, 9, 9]], + dtype=np.float32)) + + def testAlignCorners3x3To9x9(self): + # The expected matrix might look uneven in terms of how many of each number + # there is, but this is an artifact of doing the dilation and convolution + # iteratively. The behavior is less esoteric in the 3x3To12x12 case below. + self._assertForwardOpMatchesExpected( + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), [9, 9], + expected=np.array( + [[1, 1, 2, 2, 2, 2, 3, 3, 3], [1, 1, 2, 2, 2, 2, 3, 3, 3], + [4, 4, 5, 5, 5, 5, 6, 6, 6], [4, 4, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 5, 5, 5, 5, 6, 6, 6], [4, 4, 5, 5, 5, 5, 6, 6, 6], + [7, 7, 8, 8, 8, 8, 9, 9, 9], [7, 7, 8, 8, 8, 8, 9, 9, 9], + [7, 7, 8, 8, 8, 8, 9, 9, 9]], + dtype=np.float32)) + + def testAlignCorners3x3To12x12(self): + self._assertForwardOpMatchesExpected( + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.float32), [12, 12], + expected=np.array([[1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3], + [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3], + [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9], + [7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9], + [7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9]], + dtype=np.float32)) + + def testBFloat16(self): + img = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + dtype=dtypes.bfloat16.as_numpy_dtype) + self._assertForwardOpMatchesExpected( + img, [4, 4], + expected=np.array( + [[1, 2, 2, 3], [4, 5, 5, 6], [4, 5, 5, 6], [7, 8, 8, 9]], + dtype=np.float32)) + + def testAlignCorners3x3To12x12_uint8(self): + # Ensure that resize with convolution works on XLA/GPU for integer types + self._assertForwardOpMatchesExpected( + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.uint8), [12, 12], + expected=np.array([[1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3], + [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3], + [1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [4, 4, 4, 5, 5, 5, 5, 5, 5, 6, 6, 6], + [7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9], + [7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9], + [7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9]], + dtype=np.uint8)) + + +class ResizeNearestNeighborNonAlignCornersTest(xla_test.XLATestCase): + + def _assertForwardOpMatchesExpected(self, + image_np, + target_shape, + expected=None, + large_tolerance=False, + align_corners=False, + half_pixel_centers=True): + if expected is None: + self.fail("expected must be specified") + with self.session() as sess, self.test_scope(): + image = array_ops.placeholder(image_np.dtype) + resized = gen_image_ops.resize_nearest_neighbor( + image, + target_shape, + align_corners=align_corners, + half_pixel_centers=half_pixel_centers) + out = sess.run(resized, {image: image_np[np.newaxis, :, :, np.newaxis]}) + if large_tolerance: + self.assertAllClose( + expected[np.newaxis, :, :, np.newaxis], out, rtol=2e-4, atol=2e-4) + else: + self.assertAllClose(expected[np.newaxis, :, :, np.newaxis], out) + + def testNonAlignCorners1x1To2x2(self): + input_data = [[64]] + expected_data = [[64, 64], [64, 64]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [2, 2], + expected=np.array(expected_data, dtype=np.float32)) + + def testNonAlignCorners2x2To1x1(self): + input_data = [[64, 32], [8, 16]] + expected_data = [[16]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [1, 1], + expected=np.array(expected_data, dtype=np.float32)) + + def testNonAlignCorners3x3To2x2(self): + input_data = [[64, 32, 128], [4, 8, 16]] + expected_data = [[64, 128], [4, 16]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [2, 2], + expected=np.array(expected_data, dtype=np.float32)) + + def testNonAlignCorners2x2To3x3(self): + input_data = [[64, 32], [8, 16]] + expected_data = [[64.0, 32.0, 32.0], [8.0, 16.0, 16.0], [8.0, 16.0, 16.0]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [3, 3], + expected=np.array(expected_data, dtype=np.float32)) + + def testNonAlignCorners2x2To4x4(self): + input_data = [[64, 32], [8, 16]] + expected_data = [[64.0, 64.0, 32.0, 32.0], [64.0, 64.0, 32.0, 32.0], + [8.0, 8.0, 16.0, 16.0], [8.0, 8.0, 16.0, 16.0]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [4, 4], + expected=np.array(expected_data, dtype=np.float32)) + + def testNonAlignCorners3x2To5x3(self): + input_data = [[64, 32], [8, 16], [50, 100]] + expected_data = [[64.0, 32.0, 32.0], [64.0, 32.0, 32.0], [8.0, 16.0, 16.0], + [50.0, 100.0, 100.0], [50.0, 100.0, 100.0]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [5, 3], + expected=np.array(expected_data, dtype=np.float32)) + + def testNonAlignCornersNonHalfPixelCorners2x2To1x1(self): + input_data = [[64, 32], [8, 16]] + expected_data = [[64]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [1, 1], + expected=np.array(expected_data, dtype=np.float32), + half_pixel_centers=False) + + def testNonAlignCornersNonHalfPixelCorners3x2To5x3(self): + input_data = [[64, 32], [8, 16], [50, 100]] + expected_data = [[64.0, 64.0, 32.0], [64.0, 64.0, 32.0], [8.0, 8.0, 16.0], + [8.0, 8.0, 16.0], [50.0, 50.0, 100.0]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [5, 3], + expected=np.array(expected_data, dtype=np.float32), + half_pixel_centers=False) + + def testNonAlignCorners3x2To6x4Batch2(self): + input_data = [[[64, 32], [32, 64], [50, 100]], [[32, 16], [16, 32], + [25, 50]]] + expected_data = [[[64.0, 64.0, 32.0, 32.0], [64.0, 64.0, 32.0, 32.0], + [32.0, 32.0, 64.0, 64.0], [32.0, 32.0, 64.0, 64.0], + [50.0, 50.0, 100.0, 100.0], [50.0, 50.0, 100.0, 100.0]], + [[32.0, 32.0, 16.0, 16.0], [32.0, 32.0, 16.0, 16.0], + [16.0, 16.0, 32.0, 32.0], [16.0, 16.0, 32.0, 32.0], + [25.0, 25.0, 50.0, 50.0], [25.0, 25.0, 50.0, 50.0]]] + + for dtype in self.float_types: + input_image = np.array(input_data, dtype=dtype) + expected = np.array(expected_data, dtype=dtype) + with self.session() as sess, self.test_scope(): + image = array_ops.placeholder(input_image.dtype) + resized = gen_image_ops.resize_nearest_neighbor( + image, [6, 4], align_corners=False, half_pixel_centers=True) + out = sess.run(resized, {image: input_image[:, :, :, np.newaxis]}) + self.assertAllClose(expected[:, :, :, np.newaxis], out) + + +class ResizeBilinearTest(parameterized.TestCase, xla_test.XLATestCase): + + def _assertForwardOpMatchesExpected(self, + image_np, + target_shape, + expected=None, + large_tolerance=False, + align_corners=True): + if expected is None: + self.fail("expected must be specified") + with self.session() as sess, self.test_scope(): + image = array_ops.placeholder(image_np.dtype) + resized = gen_image_ops.resize_bilinear( + image, target_shape, align_corners=align_corners) + out = sess.run(resized, {image: image_np[np.newaxis, :, :, np.newaxis]}) + if large_tolerance: + self.assertAllClose( + expected[np.newaxis, :, :, np.newaxis], out, rtol=0.1, atol=0.01) + else: + self.assertAllClose(expected[np.newaxis, :, :, np.newaxis], out) + + @parameterized.named_parameters( + [("1x2To3x3", 1, 2, 3, 3), ("2x2To1x1", 2, 2, 1, 1), + ("2x2To3x3", 2, 2, 3, 3), ("3x3To2x2", 3, 3, 2, 2), + ("4x4To3x3", 4, 4, 3, 3), ("3x3To9x9", 3, 3, 9, 9), + ("4x4To8x8", 4, 4, 8, 8), ("8x8To16x16", 8, 8, 16, 16), + ("64x64To512x512", 64, 64, 512, 512), + ("80x80To512x512", 80, 80, 512, 512), + ("96x96To512x512", 96, 96, 512, 512), + ("112x112To512x512", 112, 112, 512, 512), + ("256x48To2048x384", 256, 48, 2048, 384), + ("320x60To2048x384", 320, 60, 2048, 384), + ("448x84To2048x384", 448, 84, 2048, 384), + ("69x69To545x545", 69, 69, 545, 545), + ("86x86To545x545", 86, 86, 545, 545), + ("103x103To545x545", 103, 103, 545, 545), + ("120x120To545x545", 120, 120, 545, 545), + ("57x57To456x456", 57, 57, 456, 456), + ("72x72To456x456", 72, 72, 456, 456), + ("86x86To456x456", 86, 86, 456, 456), + ("100x100To456x456", 100, 100, 456, 456), + ("64x64To224x224", 64, 64, 224, 224), + ("128x128To224x224", 128, 128, 224, 224), + ("256x256To224x224", 256, 256, 224, 224), + ("512x512To224x224", 512, 512, 224, 224), + ("64x64To299x299", 64, 64, 299, 299), + ("128x128To299x299", 128, 128, 299, 299), + ("256x256To299x299", 256, 256, 299, 299), + ("512x512To299x299", 512, 512, 299, 299), + ("224x224To224x224", 224, 224, 224, 224)] + + # On windows, initialization of the following or any larger np.arrays + # where we set the dtype explicitly fails with: + # TypeError: expected number, got int + ([] if os.name == "nt" else [("224x224To224x224-bfloat", 224, 224, 224, + 224, dtypes.bfloat16.as_numpy_dtype)]), + # This test is disabled because it is very slow. It is slow because + # 383 is prime, 383 and 2047 are coprime, and 2048 is large. + # ("Disabled_384x72To2048x384", 384, 72, 2048, 384), + ) + def test(self, src_y, src_x, dst_y, dst_x, dtype=np.float32): + max_y = max(src_y - 1, 1) * (dst_y - 1) + 1 + max_x = max(src_x - 1, 1) * (dst_x - 1) + 1 + + input_data = [ + range(y * max_x, (y + 1) * max_x, max(dst_x - 1, 1)) + for y in range(0, max_y, max(dst_y - 1, 1)) + ] + + result = [ + range(y * max_x, (y + 1) * max_x, max(src_x - 1, 1)) + for y in range(0, max_y, max(src_y - 1, 1)) + ] + + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [dst_y, dst_x], + expected=np.array(result, dtype=np.float32), + large_tolerance=True) + + +class ResizeBilinearGradTest(parameterized.TestCase, xla_test.XLATestCase): + + def _assertBackwardOpMatchesExpected(self, + grads_np, + input_shape=None, + dtype=None, + expected=None, + large_tolerance=False): + if input_shape is None: + self.fail("input_shape must be specified") + if expected is None: + self.fail("expected must be specified") + with self.session() as sess, self.test_scope(): + dtype = dtype or np.float32 + grads = array_ops.placeholder(np.float32) + resized = gen_image_ops.resize_bilinear_grad( + grads, + np.zeros([1, input_shape[0], input_shape[1], 1], dtype=dtype), + align_corners=True) + out = sess.run(resized, {grads: grads_np[np.newaxis, :, :, np.newaxis]}) + if large_tolerance: + self.assertAllClose( + expected[np.newaxis, :, :, np.newaxis], out, rtol=0.1, atol=0.01) + else: + self.assertAllCloseAccordingToType( + expected[np.newaxis, :, :, np.newaxis], out) + + @parameterized.named_parameters( + ("1x3To1x3", 1, 2, 1, 3), + ("1x2To3x2", 1, 2, 3, 2), + ("1x2To3x3", 1, 2, 3, 3), + ("1x1To4x1", 1, 1, 4, 1), + ("1x1To5x1", 1, 1, 5, 1), + ("2x2To1x1", 2, 2, 1, 1), + ("2x2To3x3", 2, 2, 3, 3), + ("3x3To2x2", 3, 3, 2, 2), + ("4x4To3x3", 4, 4, 3, 3), + ("3x3To9x9", 3, 3, 9, 9), + ("4x4To8x8", 4, 4, 8, 8), + ("8x8To16x16", 8, 8, 16, 16), + ("2x64To2x512", 2, 64, 2, 512), + ("64x64To512x512", 64, 64, 512, 512), + ("80x80To512x512", 80, 80, 512, 512), + ("96x96To512x512", 96, 96, 512, 512), + ("112x112To512x512", 112, 112, 512, 512), + # ("Disabled_256x48To2048x384", 256, 48, 2048, 384), + # ("Disabled_320x60To2048x384", 320, 60, 2048, 384), + # ("Disabled_448x84To2048x384", 448, 84, 2048, 384), + ("69x69To545x545", 69, 69, 545, 545), + ("86x86To545x545", 86, 86, 545, 545), + ("103x103To545x545", 103, 103, 545, 545), + ("120x120To545x545", 120, 120, 545, 545), + ("57x57To456x456", 57, 57, 456, 456), + ("72x72To456x456", 72, 72, 456, 456), + ("86x86To456x456", 86, 86, 456, 456), + ("100x100To456x456", 100, 100, 456, 456), + # This test is disabled because it is very slow. It is slow because + # 383 is prime, 383 and 2047 are coprime, and 2048 is large. + # ("Disabled_384x72To2048x384", 384, 72, 2048, 384), + ) + def test(self, src_y, src_x, dst_y, dst_x): + + def GetRow(src, dst): + if src == 1: + return np.array([[max(dst**2 - dst, 1)]]) + row = [0] * src + for i in range(0, (dst - 1) * max(src - 1, 1) + 1, src - 1): + prev = int(math.floor(i / max(dst - 1, 1))) + row[prev] += max(dst - 1, 1) - i % max(dst - 1, 1) + if prev + 1 < src: + row[prev + 1] += i % max(dst - 1, 1) + return np.array([row]) + + input_element = max(dst_x - 1, 1) * max(dst_y - 1, 1) + input_data = [[input_element] * dst_x] * dst_y + result = GetRow(src_x, dst_x) * np.transpose(GetRow(src_y, dst_y)) + self._assertBackwardOpMatchesExpected( + np.array(input_data, dtype=np.float32), [src_y, src_x], + expected=np.array(result, dtype=np.float32), + large_tolerance=True) + + +class ResizeBilinearNonAlignCornersTest(xla_test.XLATestCase): + + def _assertForwardOpMatchesExpected(self, + image_np, + target_shape, + expected=None, + large_tolerance=False, + align_corners=True): + if expected is None: + self.fail("expected must be specified") + with self.session() as sess, self.test_scope(): + image = array_ops.placeholder(image_np.dtype) + resized = gen_image_ops.resize_bilinear( + image, target_shape, align_corners=align_corners) + out = sess.run(resized, {image: image_np[np.newaxis, :, :, np.newaxis]}) + if large_tolerance: + self.assertAllClose( + expected[np.newaxis, :, :, np.newaxis], out, rtol=0.1, atol=0.01) + else: + self.assertAllClose(expected[np.newaxis, :, :, np.newaxis], out) + + def testNonAlignCorners3x2To6x4(self): + input_data = [[64, 32], [32, 64], [50, 100]] + expected_data = [[64.0, 48.0, 32.0, 32.0], [48.0, 48.0, 48.0, 48.0], + [32.0, 48.0, 64.0, 64.0], [41.0, 61.5, 82.0, 82.0], + [50.0, 75.0, 100.0, 100.0], [50.0, 75.0, 100.0, 100.0]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [6, 4], + expected=np.array(expected_data, dtype=np.float32), + align_corners=False) + + def testNonAlignCorners6x4To3x2(self): + input_data = [[127, 127, 64, 64], [127, 127, 64, 64], [64, 64, 127, 127], + [64, 64, 127, 127], [50, 50, 100, 100], [50, 50, 100, 100]] + expected_data = [[127, 64], [64, 127], [50, 100]] + for dtype in self.float_types: + self._assertForwardOpMatchesExpected( + np.array(input_data, dtype=dtype), [3, 2], + expected=np.array(expected_data, dtype=dtype), + align_corners=False) + + def testNonAlignCorners3x2To6x4Batch2(self): + input_data = [[[64, 32], [32, 64], [50, 100]], [[32, 16], [16, 32], + [25, 50]]] + expected_data = [[[64.0, 48.0, 32.0, 32.0], [48.0, 48.0, 48.0, 48.0], + [32.0, 48.0, 64.0, 64.0], [41.0, 61.5, 82.0, 82.0], + [50.0, 75.0, 100.0, 100.0], [50.0, 75.0, 100.0, 100.0]], + [[32.0, 24.0, 16.0, 16.0], [24.0, 24.0, 24.0, 24.0], + [16.0, 24.0, 32.0, 32.0], [20.5, 30.75, 41.0, 41.0], + [25.0, 37.5, 50.0, 50.0], [25.0, 37.5, 50.0, 50.0]]] + + for dtype in self.float_types: + input_image = np.array(input_data, dtype=dtype) + expected = np.array(expected_data, dtype=dtype) + with self.session() as sess, self.test_scope(): + image = array_ops.placeholder(input_image.dtype) + resized = gen_image_ops.resize_bilinear( + image, [6, 4], align_corners=False) + out = sess.run(resized, {image: input_image[:, :, :, np.newaxis]}) + self.assertAllClose(expected[:, :, :, np.newaxis], out) + + +class ResizeBilinearGradHalfPixelCentersTest( + parameterized.TestCase, xla_test.XLATestCase +): + + def _assertBackwardOpMatchesExpected(self, grads_np, expected): + with self.session() as sess, self.test_scope(): + grads = array_ops.placeholder(np.float32) + resized = gen_image_ops.resize_bilinear_grad( + grads, + np.zeros(expected.shape, dtype=np.float32), + align_corners=False, + half_pixel_centers=True, + ) + out = sess.run(resized, {grads: grads_np}) + self.assertAllCloseAccordingToType(expected, out) + + def test3x2To6x4(self): + grad_data = [ + [0, 1, 2, 3], + [4, 5, 6, 7], + [8, 9, 10, 11], + [12, 13, 14, 15], + [16, 17, 18, 19], + [20, 21, 22, 23], + ] + expected_data = [[12.5, 19.5], [42.5, 49.5], [72.5, 79.5]] + self._assertBackwardOpMatchesExpected( + np.array(grad_data, dtype=np.float32)[np.newaxis, :, :, np.newaxis], + expected=np.array(expected_data, dtype=np.float32)[ + np.newaxis, :, :, np.newaxis + ], + ) + + def test6x4To3x2(self): + grad_data = [[0, 1], [2, 3], [4, 5]] + expected_data = [ + [0.0, 0.0, 0.25, 0.25], + [0.0, 0.0, 0.25, 0.25], + [0.5, 0.5, 0.75, 0.75], + [0.5, 0.5, 0.75, 0.75], + [1.0, 1.0, 1.25, 1.25], + [1.0, 1.0, 1.25, 1.25], + ] + self._assertBackwardOpMatchesExpected( + np.array(grad_data, dtype=np.float32)[np.newaxis, :, :, np.newaxis], + expected=np.array(expected_data, dtype=np.float32)[ + np.newaxis, :, :, np.newaxis + ], + ) + + def test3x2To6x4Batch2(self): + dst_y = 6 + dst_x = 4 + grad_data = np.arange(2 * dst_y * dst_x).reshape(2, dst_y, dst_x, 1) + expected_data = [ + [[[12.5], [19.5]], [[42.5], [49.5]], [[72.5], [79.5]]], + [[[108.5], [115.5]], [[138.5], [145.5]], [[168.5], [175.5]]], + ] + self._assertBackwardOpMatchesExpected( + np.array(grad_data, dtype=np.float32), + expected=np.array(expected_data, dtype=np.float32), + ) + + def test3x2To6x4Batch2Channel3(self): + dst_y = 6 + dst_x = 4 + grad_data = np.arange(2 * dst_y * dst_x * 3).reshape(2, dst_y, dst_x, 3) + expected_data = [ + [ + [[37.5, 41.5, 45.5], [58.5, 62.5, 66.5]], + [[127.5, 131.5, 135.5], [148.5, 152.5, 156.5]], + [[217.5, 221.5, 225.5], [238.5, 242.5, 246.5]], + ], + [ + [[325.5, 329.5, 333.5], [346.5, 350.5, 354.5]], + [[415.5, 419.5, 423.5], [436.5, 440.5, 444.5]], + [[505.5, 509.5, 513.5], [526.5, 530.5, 534.5]], + ], + ] + self._assertBackwardOpMatchesExpected( + np.array(grad_data, dtype=np.float32), + expected=np.array(expected_data, dtype=np.float32), + ) + + +class NonMaxSuppressionTest(xla_test.XLATestCase): + + def testNMSV3(self): + boxes_data = [[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]] + boxes_np = np.array(boxes_data, dtype=np.float32) + + scores_data = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] + scores_np = np.array(scores_data, dtype=np.float32) + max_output_size = 6 + iou_threshold_np = np.array(0.5, dtype=np.float32) + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + iou_threshold = array_ops.placeholder(iou_threshold_np.dtype, + iou_threshold_np.shape) + with self.test_scope(): + selected_indices = image_ops.non_max_suppression_v3( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=float("-inf")) + inputs_feed = { + boxes: boxes_np, + scores: scores_np, + iou_threshold: iou_threshold_np + } + (indices_tf) = sess.run(selected_indices, feed_dict=inputs_feed) + + self.assertEqual(indices_tf.size, 3) + self.assertAllClose(indices_tf[:3], [3, 0, 5]) + + def testNMS128From1024(self): + num_boxes = 1024 + boxes_np = np.random.normal(50, 10, (num_boxes, 4)).astype("f4") + scores_np = np.random.normal(0.5, 0.1, (num_boxes,)).astype("f4") + + max_output_size = 128 + iou_threshold_np = np.array(0.5, dtype=np.float32) + score_threshold_np = np.array(0.0, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + iou_threshold = array_ops.placeholder(iou_threshold_np.dtype, + iou_threshold_np.shape) + score_threshold = array_ops.placeholder(score_threshold_np.dtype, + score_threshold_np.shape) + with self.test_scope(): + selected_indices = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_to_max_output_size=True) + inputs_feed = { + boxes: boxes_np, + scores: scores_np, + score_threshold: score_threshold_np, + iou_threshold: iou_threshold_np + } + (indices_tf, _) = sess.run(selected_indices, feed_dict=inputs_feed) + + self.assertEqual(indices_tf.size, max_output_size) + + def testNMS3From6Boxes(self): + # Three boxes are selected based on IOU. + boxes_data = [[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]] + boxes_np = np.array(boxes_data, dtype=np.float32) + + scores_data = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] + scores_np = np.array(scores_data, dtype=np.float32) + + max_output_size = 3 + iou_threshold_np = np.array(0.5, dtype=np.float32) + score_threshold_np = np.array(0.0, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + iou_threshold = array_ops.placeholder(iou_threshold_np.dtype, + iou_threshold_np.shape) + score_threshold = array_ops.placeholder(score_threshold_np.dtype, + score_threshold_np.shape) + with self.test_scope(): + selected_indices = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_to_max_output_size=True) + inputs_feed = { + boxes: boxes_np, + scores: scores_np, + score_threshold: score_threshold_np, + iou_threshold: iou_threshold_np + } + (indices_tf, num_valid) = sess.run( + selected_indices, feed_dict=inputs_feed) + + self.assertEqual(indices_tf.size, max_output_size) + self.assertEqual(num_valid, 3) + self.assertAllClose(indices_tf[:num_valid], [3, 0, 5]) + + def testNMS3Then2WithScoreThresh(self): + # Three boxes are selected based on IOU. + # One is filtered out by score threshold. + + boxes_data = [[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]] + boxes_np = np.array(boxes_data, dtype=np.float32) + + scores_data = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] + scores_np = np.array(scores_data, dtype=np.float32) + max_output_size = 3 + iou_threshold_np = np.array(0.5, dtype=np.float32) + score_threshold_np = np.array(0.4, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + iou_threshold = array_ops.placeholder(iou_threshold_np.dtype, + iou_threshold_np.shape) + score_threshold = array_ops.placeholder(score_threshold_np.dtype, + score_threshold_np.shape) + with self.test_scope(): + selected_indices = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_to_max_output_size=True) + inputs_feed = { + boxes: boxes_np, + scores: scores_np, + iou_threshold: iou_threshold_np, + score_threshold: score_threshold_np + } + (indices_tf, num_valid) = sess.run( + selected_indices, feed_dict=inputs_feed) + + self.assertEqual(indices_tf.size, max_output_size) + self.assertEqual(num_valid, 2) + self.assertAllClose(indices_tf[:num_valid], [3, 0]) + + def testNMS3Then1WithScoreMaxThresh(self): + # Three boxes are selected based on IOU. + # One is filtered out by score threshold. + # One is filtered out by max_output_size. + + boxes_data = [[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]] + boxes_np = np.array(boxes_data, dtype=np.float32) + + scores_data = [0.9, 0.75, 0.6, 0.95, 0.5, 0.3] + scores_np = np.array(scores_data, dtype=np.float32) + max_output_size = 1 + iou_threshold_np = np.array(0.5, dtype=np.float32) + score_threshold_np = np.array(0.4, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + iou_threshold = array_ops.placeholder(iou_threshold_np.dtype, + iou_threshold_np.shape) + score_threshold = array_ops.placeholder(score_threshold_np.dtype, + score_threshold_np.shape) + with self.test_scope(): + selected_indices = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_to_max_output_size=True) + inputs_feed = { + boxes: boxes_np, + scores: scores_np, + iou_threshold: iou_threshold_np, + score_threshold: score_threshold_np + } + (indices_tf, num_valid) = sess.run( + selected_indices, feed_dict=inputs_feed) + + self.assertEqual(indices_tf.size, max_output_size) + self.assertEqual(num_valid, 1) + self.assertAllClose(indices_tf[:num_valid], [3]) + + def testSelectFromContinuousOverLap(self): + # Tests that a suppressed box does not itself suppress other boxes. + + boxes_data = [[0, 0, 1, 1], [0, 0.2, 1, 1.2], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 3]] + boxes_np = np.array(boxes_data, dtype=np.float32) + + scores_data = [0.9, 0.75, 0.6, 0.5, 0.4, 0.3] + scores_np = np.array(scores_data, dtype=np.float32) + max_output_size = 3 + iou_threshold_np = np.array(0.5, dtype=np.float32) + score_threshold_np = np.array(0.1, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + iou_threshold = array_ops.placeholder(iou_threshold_np.dtype, + iou_threshold_np.shape) + score_threshold = array_ops.placeholder(score_threshold_np.dtype, + score_threshold_np.shape) + with self.test_scope(): + selected_indices = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=score_threshold, + pad_to_max_output_size=True) + inputs_feed = { + boxes: boxes_np, + scores: scores_np, + iou_threshold: iou_threshold_np, + score_threshold: score_threshold_np + } + (indices_tf, num_valid) = sess.run( + selected_indices, feed_dict=inputs_feed) + + self.assertEqual(indices_tf.size, max_output_size) + self.assertEqual(num_valid, 3) + self.assertAllClose(indices_tf[:num_valid], [0, 2, 4]) + + +class BatchedNonMaxSuppressionCorrectnessTest(xla_test.XLATestCase): + + def testBatchedNMSFrom6(self): + boxes_data = [[[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]], + [[0, 2, 1, 2], [0, 0.8, 1, 1.8], [0, 0.6, 1, 1.6], + [0, 0.4, 1, 1.4], [0, 0.2, 1, 1.2], [0, 0, 1, 1]]] + scores_data = [[0.9, 0.7, 0.6, 0.5, 0.4, 0.3], + [0.8, 0.7, 0.6, 0.5, 0.4, 0.3]] + max_output_size = 6 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + invalid_index = 0 + self.assertAllEqual([[0, 1, 2, 4, 5, invalid_index], + [0, 1, 3, 5, invalid_index, invalid_index]], + indices_output) + self.assertAllEqual([5, 4], num_valid_output) + + def testBatchedNMSFrom6Max3(self): + boxes_data = [[[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]], + [[0, 2, 1, 2], [0, 0.8, 1, 1.8], [0, 0.6, 1, 1.6], + [0, 0.4, 1, 1.4], [0, 0.2, 1, 1.2], [0, 0, 1, 1]]] + scores_data = [[0.9, 0.7, 0.6, 0.5, 0.4, 0.3], + [0.8, 0.7, 0.6, 0.5, 0.4, 0.3]] + max_output_size = 3 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + self.assertAllEqual([[0, 1, 2], [0, 1, 3]], indices_output) + self.assertAllEqual([3, 3], num_valid_output) + + def testBatchedNMSSingleFrom6Max3(self): + boxes_data = [[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]] + scores_data = [0.9, 0.7, 0.6, 0.5, 0.4, 0.3] + max_output_size = 3 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + self.assertAllEqual([0, 1, 2], indices_output) + self.assertAllEqual(3, num_valid_output) + + def testBatchedNMSSingleFrom6NoPad(self): + boxes_data = [[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]] + scores_data = [0.9, 0.7, 0.6, 0.5, 0.4, 0.3] + max_output_size = 6 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + self.assertAllEqual([0, 1, 2, 4, 5], indices_output) + self.assertAllEqual(5, num_valid_output) + + def testBatchedNMSBatchDimsFrom6Max3(self): + boxes_data = [[[[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]], + [[0, 2, 1, 2], [0, 0.8, 1, 1.8], [0, 0.6, 1, 1.6], + [0, 0.4, 1, 1.4], [0, 0.2, 1, 1.2], [0, 0, 1, 1]]]] + scores_data = [[[0.9, 0.7, 0.6, 0.5, 0.4, 0.3], + [0.8, 0.7, 0.6, 0.5, 0.4, 0.3]]] + max_output_size = 3 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + self.assertAllEqual([[[0, 1, 2], [0, 1, 3]]], indices_output) + self.assertAllEqual([[3, 3]], num_valid_output) + + def testBatchedNMSScoreThresholdFrom6Max3(self): + boxes_data = [[[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]], + [[0, 2, 1, 2], [0, 0.8, 1, 1.8], [0, 0.6, 1, 1.6], + [0, 0.4, 1, 1.4], [0, 0.2, 1, 1.2], [0, 0, 1, 1]]] + scores_data = [[0.9, 0.7, 0.6, 0.4, 0.3, 0.2], + [0.8, 0.7, 0.6, 0.4, 0.3, 0.1]] + max_output_size = 3 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=0.5, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + invalid_index = 0 + self.assertAllEqual([3, 2], num_valid_output) + self.assertAllEqual([[0, 1, 2], [0, 1, invalid_index]], indices_output) + + def testBatchedNMSUnsortedInputFrom6(self): + boxes_data = [[[0, 2, 1, 2], [3, 3, 4, 4], [0, 0, 1, 1], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8]], + [[0, 0.4, 1, 1.4], [0, 2, 1, 2], [0, 0.2, 1, 1.2], + [0, 0, 1, 1], [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8]]] + scores_data = [[0.3, 0.7, 0.9, 0.6, 0.5, 0.4], + [0.5, 0.8, 0.4, 0.3, 0.6, 0.7]] + max_output_size = 6 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + invalid_index = 0 + self.assertAllEqual([[2, 1, 3, 5, 0, invalid_index], + [1, 5, 0, 3, invalid_index, invalid_index]], + indices_output) + self.assertAllEqual([5, 4], num_valid_output) + + def testBatchedNMSNoncanonicalizedInputFrom6(self): + boxes_data = [[[1, 0, 0, 1], [4, 3, 3, 4], [1, 0.4, 0, 1.4], + [1, 0.6, 0, 1.6], [1, 0.8, 0, 1.8], [1, 2, 0, 2]], + [[1, 2, 0, 2], [1, 0.8, 0, 1.8], [1, 0.6, 0, 1.6], + [1, 0.4, 0, 1.4], [1, 0.2, 0, 1.2], [1, 0, 0, 1]]] + + scores_data = [[0.9, 0.7, 0.6, 0.5, 0.4, 0.3], + [0.8, 0.7, 0.6, 0.5, 0.4, 0.3]] + max_output_size = 6 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + sorted_input=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + invalid_index = 0 + self.assertAllEqual([[0, 1, 2, 4, 5, invalid_index], + [0, 1, 3, 5, invalid_index, invalid_index]], + indices_output) + self.assertAllEqual([5, 4], num_valid_output) + + def testBatchedNMSScoreThresholdCanInputsFrom6Max3(self): + boxes_data = [[[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]], + [[0, 2, 1, 2], [0, 0.8, 1, 1.8], [0, 0.6, 1, 1.6], + [0, 0.4, 1, 1.4], [0, 0.2, 1, 1.2], [0, 0, 1, 1]]] + scores_data = [[0.9, 0.7, 0.6, 0.4, 0.3, 0.2], + [0.8, 0.7, 0.6, 0.4, 0.3, 0.1]] + max_output_size = 3 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype, shape=boxes_np.shape) + scores = array_ops.placeholder(scores_np.dtype, shape=scores_np.shape) + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + score_threshold=0.5, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=False) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + invalid_index = 0 + self.assertAllEqual([3, 2], num_valid_output) + self.assertAllEqual([[0, 1, 2], [0, 1, invalid_index]], indices_output) + + def testBatchedNMSFrom6DynamicInput(self): + boxes_data = [[[0, 0, 1, 1], [3, 3, 4, 4], [0, 0.4, 1, 1.4], + [0, 0.6, 1, 1.6], [0, 0.8, 1, 1.8], [0, 2, 1, 2]], + [[0, 2, 1, 2], [0, 0.8, 1, 1.8], [0, 0.6, 1, 1.6], + [0, 0.4, 1, 1.4], [0, 0.2, 1, 1.2], [0, 0, 1, 1]]] + scores_data = [[0.9, 0.7, 0.6, 0.5, 0.4, 0.3], + [0.8, 0.7, 0.6, 0.5, 0.4, 0.3]] + max_output_size = 6 + iou_threshold = 0.5 + boxes_np = np.array(boxes_data, dtype=np.float32) + scores_np = np.array(scores_data, dtype=np.float32) + + with self.session() as sess: + boxes = array_ops.placeholder(boxes_np.dtype) + scores = array_ops.placeholder(scores_np.dtype) + + with self.test_scope(): + (indices, num_valid) = image_ops.non_max_suppression_padded( + boxes=boxes, + scores=scores, + max_output_size=max_output_size, + iou_threshold=iou_threshold, + pad_to_max_output_size=True, + sorted_input=True, + canonicalized_coordinates=True) + + inputs = {boxes: boxes_np, scores: scores_np} + indices_output, num_valid_output = sess.run([indices, num_valid], inputs) + invalid_index = 0 + self.assertAllEqual([[0, 1, 2, 4, 5, invalid_index], + [0, 1, 3, 5, invalid_index, invalid_index]], + indices_output) + self.assertAllEqual([5, 4], num_valid_output) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/jit_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/jit_test.py new file mode 100644 index 0000000000000000000000000000000000000000..acb385f27884078de7e4ec39a3881615e5021005 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/jit_test.py @@ -0,0 +1,651 @@ +# 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 JIT compilation on the CPU and GPU devices.""" + +import os + +import numpy as np + +from tensorflow.compiler.tests import test_utils +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.client import session as session_lib +from tensorflow.python.compiler.xla import jit +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import cond +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.platform import test + + +jit_scope = jit.experimental_jit_scope + +# Disable rewrites to make sure we don't end up having to update this test +# whenever we implement new ones. +def NoRewriteSessionConfig(): + rewriter_config = rewriter_config_pb2.RewriterConfig( + disable_model_pruning=True, + arithmetic_optimization=rewriter_config_pb2.RewriterConfig.OFF, + dependency_optimization=rewriter_config_pb2.RewriterConfig.OFF, + function_optimization=rewriter_config_pb2.RewriterConfig.OFF) + graph_options = config_pb2.GraphOptions(rewrite_options=rewriter_config) + return config_pb2.ConfigProto(graph_options=graph_options) + + +def CompiledKernel(fn, *inputs, **kwargs): + """Execute 'fn' as a compiled XLA kernel, with 'inputs'.""" + name = kwargs.pop("name", None) + noinline = kwargs.pop("noinline", None) + + @function.Defun(func_name=name, noinline=noinline, compiled=True) + def Compiled(*args): + return fn(*args) + + return Compiled(*inputs) + + +def RunMetadataLabels(run_metadata): + """Returns all labels in run_metadata.""" + labels = [] + for dev_stats in run_metadata.step_stats.dev_stats: + for node_stats in dev_stats.node_stats: + labels.append(node_stats.timeline_label) + return labels + + +def InLabels(labels, substr): + """Returns true iff one of the labels contains substr.""" + return any(substr in x for x in labels) + + +def MetadataHasXlaRunOp(run_metadata): + """Returns true if there are XlaRun kernels in run_metadata's timeline.""" + + # TODO(phawkins): find a less hacky way to test whether a kernel ran. + return InLabels(RunMetadataLabels(run_metadata), "_XlaRun") + + +class JitLaunchTest(test.TestCase): + + # Evaluates 'fn' on 'args' both directly and as a compiled XLA kernel. + # Verifies that the outputs match and that XLA was invoked. 'fn' must take + # the same number of tensors as arguments that are in 'args', and must return + # a tuple of output tensors. + # + # If 'require_kernel_launch' is True, then we verify that an XlaCompile/XlaRun + # node actually ran. However, it is sometimes possible for XlaCompile/XlaRun + # ops to be constant-folded away, so the check is optional. + def _compare(self, + fn, + args, + require_kernel_launch=True, + name=None, + noinline=None): + with session_lib.Session(config=NoRewriteSessionConfig()) as sess: + placeholders = [] + feeds = {} + for arg in args: + placeholder = array_ops.placeholder( + dtypes.as_dtype(arg.dtype), list(arg.shape)) + placeholders.append(placeholder) + feeds[placeholder] = arg + + compiled_op = CompiledKernel( + fn, *placeholders, name=name, noinline=noinline) + direct_op = fn(*placeholders) + + run_metadata = config_pb2.RunMetadata() + compiled = test_utils.RunWithWarmup( + sess, compiled_op, feeds, + config_pb2.RunOptions(trace_level=config_pb2.RunOptions.FULL_TRACE), + run_metadata) + print("Compiled Result {}".format(compiled)) + + if require_kernel_launch: + self.assertTrue(MetadataHasXlaRunOp(run_metadata)) + + direct = sess.run(direct_op, feeds) + print("Direct Result {}".format(direct)) + + if (isinstance(compiled, (tuple, list)) and + (isinstance(direct, (tuple, list)))): + for (x, y) in zip(compiled, direct): + self.assertAllClose(x, y, rtol=1e-1) + else: + self.assertAllClose(compiled, direct, rtol=1e-2) + + def testNoOutputs(self): + with session_lib.Session() as sess: + + # Check that calling the result as a compiled kernel doesn't crash. + @function.Defun(compiled=True) + def KernelWithNoOutputs(): + a = constant_op.constant(100) # pylint: disable=unused-variable + + call = KernelWithNoOutputs() # pylint: disable=assignment-from-no-return + test_utils.RunWithWarmup(sess, call, {}) + + def testAliasing(self): + """Regression test for compiled functions that return an aliased buffer. + + XLA returns aliased buffers if outputs are identical. Tests that + we handle that case. + """ + + def AddOnceReturnTwice(x): + y = math_ops.add(x, x) + return y, y + + # Exercises compiling a function (say, Foo) which calls another function + # (say, Bar) which is not inlined. When the compiler compiles Foo, it needs + # to symbolically execute Bar correctly regardless of whether Bar is inlined + # or not. + + # Tests compiled=True and noinline=True. + self._compare( + AddOnceReturnTwice, [np.array([[[0.5, -1.0]]], dtype=np.float32)], + name="AddOnceReturnTwice_inline", + noinline=True) + + # Tests compiled=True and noinline=False. + self._compare( + AddOnceReturnTwice, [np.array([[[0.5, -1.0]]], dtype=np.float32)], + name="AddOnceReturnTwice_noinline", + noinline=False) + + def testOneConstOutput(self): + """Test consisting of a single constant return value.""" + + def OneConstOutput(): + return constant_op.constant([-3, 44, 99]) + + self._compare(OneConstOutput, [], require_kernel_launch=False) + + def testConstZeroElementOutput(self): + """Test consisting of a constant zero element return value.""" + + def ConstZeroElementOutput(): + return array_ops.fill([7, 0], 3.0) + + self._compare(ConstZeroElementOutput, [], require_kernel_launch=False) + + def testSomeConstOutputs(self): + """Test kernels that return a mixture of const and non-const outputs.""" + + def SomeConstOutputs(x): + return constant_op.constant( + [-2, 7]), array_ops.identity(x), constant_op.constant(3.5) + + self._compare( + SomeConstOutputs, [np.array( + [[1, 2, 3], [4, 5, 6]], dtype=np.float32)]) + + def testInt32Input(self): + """Test an int32-typed input. + + On a GPU, int32 tensors will be placed in host memory. + """ + + def AddToSelf(x): + return math_ops.add(x, x) + + self._compare(AddToSelf, [np.array([7, 1, 3], dtype=np.int32)]) + + def testMandatoryConstantInput(self): + """Tests an operator that has a mandatory-constant shape input.""" + + def FillWithFloat(x): + return array_ops.fill(x, 9.5) + + self._compare(FillWithFloat, [np.array([3, 2], dtype=np.int32)]) + + def testMnistForwardFunc(self): + """Compute inference function from MNIST beginners tutorial.""" + batch_size = 16 + image_size = 28 * 28 + num_classes = 10 + + # Define a TensorFlow function to compute the forward pass. + def MnistForward(w, b, x): + return nn_ops.softmax(math_ops.matmul(x, w) + b) + + w = np.random.random_sample((image_size, num_classes)).astype(np.float32) + b = np.random.random_sample((num_classes)).astype(np.float32) + x = np.random.random_sample((batch_size, image_size)).astype(np.float32) + self._compare(MnistForward, [w, b, x]) + + def testExplicitMarking(self): + """Test explicit marking of operators to compile.""" + batch_size = 16 + image_size = 28 * 28 + num_classes = 10 + + with ops.Graph().as_default(): + x = array_ops.placeholder(dtypes.float32) + w = array_ops.placeholder(dtypes.float32) + b = array_ops.placeholder(dtypes.float32) + with jit_scope(): + y1 = math_ops.matmul(x, w) + y2 = math_ops.add(y1, b) + with jit_scope(): + y = math_ops.square(y2) + + dw = np.random.random_sample((image_size, num_classes)).astype(np.float32) + db = np.random.random_sample((num_classes)).astype(np.float32) + dx = np.random.random_sample((batch_size, image_size)).astype(np.float32) + with session_lib.Session() as sess: + run_metadata = config_pb2.RunMetadata() + output = test_utils.RunWithWarmup( + sess, + y, { + x: dx, + w: dw, + b: db + }, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + + # TODO(phawkins): really we would like to test that there were exactly + # two kernel launches. However, we have no reliable way to determine + # that. + self.assertTrue(MetadataHasXlaRunOp(run_metadata)) + + expected = np.square(np.dot(dx, dw) + db) + self.assertAllClose(expected, output, rtol=1e-1) + + +class XlaCompilationTest(test.TestCase): + """Tests for auto-compilation on CPU/GPU devices.""" + + def testReshape(self): + """Tests an operator with compile-time constant and non-constant inputs.""" + + with self.session(config=NoRewriteSessionConfig()) as sess: + x = array_ops.placeholder(dtypes.float32) + y = array_ops.placeholder(dtypes.int32) + with jit_scope(): + # Reshape's first argument is non-constant in the JIT, but its second + # (shape) argument will be treated as a compile-time constant for + # each JIT compilation. + # We do not use a tf.const() argument since we want to ensure the + # shape is still a run-time argument to the JIT, and not + # statically known as part of the JIT compilation's input graph. + z = array_ops.reshape(x, y) + run_metadata = config_pb2.RunMetadata() + out = test_utils.RunWithWarmup( + sess, + z, { + x: np.array([1, 2, 3, 4, 5, 6], np.float32), + y: [-1, 3] + }, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue(MetadataHasXlaRunOp(run_metadata)) + self.assertAllClose(np.array([[1, 2, 3], [4, 5, 6]], np.float32), out) + + def testIgnoredArguments(self): + """Tests that JIT computations can ignore formal parameters.""" + + with self.session(config=NoRewriteSessionConfig()) as sess: + x = array_ops.placeholder(dtypes.int32) + y = array_ops.placeholder(dtypes.int32) + with jit_scope(): + z = math_ops.add(x, x) + w = math_ops.add(y, y) + # Pulls 'w' into the same compilation via control dependencies. + with ops.control_dependencies([w]): + n = control_flow_ops.no_op() + with ops.control_dependencies([n]): + t = math_ops.add(z, z) + + run_metadata = config_pb2.RunMetadata() + out = test_utils.RunWithWarmup( + sess, + t, { + x: np.int32(7), + y: np.int32(404) + }, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue(MetadataHasXlaRunOp(run_metadata)) + self.assertAllClose(28, out) + + def testLoops(self): + """Tests that compilation accepts computations containing loops.""" + + with self.session(config=NoRewriteSessionConfig()) as session: + x = array_ops.placeholder(dtypes.float32) + with jit_scope(): + c = lambda i, _: math_ops.less(i, 5) + b = lambda i, x: (i + 1, x * 2.0 + 1.0) + _, y = while_loop.while_loop(c, b, (constant_op.constant(0), x)) + + run_metadata = config_pb2.RunMetadata() + result = session.run(y, {x: np.float32(2)}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue(MetadataHasXlaRunOp(run_metadata)) + self.assertAllClose(result, np.float32(95), rtol=1e-1) + + def testCond(self): + """Tests that compilation handles switch operators.""" + + with self.session(config=NoRewriteSessionConfig()) as session: + x = array_ops.placeholder(dtypes.float32) + y = array_ops.placeholder(dtypes.float32) + c = array_ops.placeholder(dtypes.bool) + with jit_scope(): + z = x + 1.0 + w = cond.cond(c, lambda: z, lambda: y) + t = math_ops.add(z, w) + + # If JIT compilation chooses to cluster z and t, then execution will + # deadlock. + + run_metadata = config_pb2.RunMetadata() + result = test_utils.RunWithWarmup( + session, + t, { + x: np.float32(2), + y: np.float32(4), + c: True + }, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue(MetadataHasXlaRunOp(run_metadata)) + self.assertAllClose(result, np.float32(6), rtol=1e-1) + + def testNestedFunction(self): + g = ops.Graph() + with g.as_default(): + + @function.Defun(compiled=True) + def Bar(x, y): + return x + 2 * y + + @function.Defun(compiled=True) + def Foo(x): + return Bar(x * x, x * x * x) + + @function.Defun() + def Entry(x): + return Foo(x) + + inp = array_ops.placeholder(dtypes.float32) + out = Entry(inp) + + with self.session( + config=NoRewriteSessionConfig(), graph=g, use_gpu=True) as sess: + run_metadata = config_pb2.RunMetadata() + val = sess.run(out, + feed_dict={inp: [2., 10.]}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertAllClose(val, [20., 2100.]) + + def testLoopDeadlock(self): + """Regression test for bug that caused deadlocks in graphs with loops.""" + + with self.session(config=NoRewriteSessionConfig()) as session: + x = array_ops.placeholder(dtypes.float32) + with jit_scope(): + y = x + 1.0 + c = lambda i, _x, _y: math_ops.less(i, 5) + b = lambda i, x, _y: (i + 1, x * 2.0 + 1.0, x - 3.0) + _, _, w = while_loop.while_loop(c, b, (constant_op.constant(0), y, x)) + u = w + y + result = session.run(u, {x: np.float32(2)}) + self.assertAllClose(result, np.float32(63), rtol=1e-1) + + def testGradient(self): + """Tests that the backprop function is properly compiled.""" + + def _Run(compiled): + + @function.Defun(compiled=compiled) + def Forward(x): + return math_ops.log(x) + + g = ops.Graph() + with g.as_default(): + x = array_ops.placeholder(dtypes.float32) + y = Forward(x) + dx, = gradients_impl.gradients(y, [x], 1.0) + + cfg = NoRewriteSessionConfig() + cfg.graph_options.optimizer_options.opt_level = ( + config_pb2.OptimizerOptions.L1) + cfg.graph_options.optimizer_options.do_function_inlining = True + with session_lib.Session(graph=g, config=cfg) as sess: + run_metadata = config_pb2.RunMetadata() + dx_val = test_utils.RunWithWarmup( + sess, + dx, + feed_dict={x: 100.}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertAllClose(dx_val, 0.01) + return RunMetadataLabels(run_metadata) + + # SymGrad[f=log(x)](x, dy) = 1/x * dy + # + # Note: we don't need to compute log(x) for dx due to graph pruning. + + # Do not compile the backprop. We should see one Reciprocal and one Mul. + labels = _Run(compiled=False) + self.assertFalse(InLabels(labels, "Log")) + self.assertTrue(InLabels(labels, "Reciprocal")) + self.assertTrue(InLabels(labels, "Mul")) + self.assertFalse(InLabels(labels, "XlaCompile")) + self.assertFalse(InLabels(labels, "XlaRun")) + + # Compile the backprop. One XlaCompile/XlaRun pair. + labels = _Run(compiled=True) + self.assertFalse(InLabels(labels, "Log")) + self.assertFalse(InLabels(labels, "Reciprocal")) + self.assertFalse(InLabels(labels, "Mul")) + self.assertTrue(InLabels(labels, "XlaCompile")) + self.assertTrue(InLabels(labels, "XlaRun")) + + +class ElementWiseFusionTest(test.TestCase): + + # Runs a simple test with the input jit_level and fusion_only flag. + def simpleTest(self, arg0, arg1, global_jit_level): + config = config_pb2.ConfigProto() + config.graph_options.optimizer_options.global_jit_level = global_jit_level + + with session_lib.Session(config=config) as sess: + a1 = array_ops.placeholder(dtypes.float32, [2, 2], name="a1") + a2 = array_ops.placeholder(dtypes.float32, [2, 2], name="a2") + # Two element-wise ops. We need at least two ops since single + # element clusters are not passed to XLA in fusion_only mode. + a3 = a1 * a2 + a4 = a3 + a1 + # A matmul to break XLA clustering. + a5 = math_ops.matmul(a4, a1) + # Two more element-wise ops. + a6 = a5 - a4 + a7 = a6 + a2 + + run_metadata = config_pb2.RunMetadata() + output = test_utils.RunWithWarmup( + sess, + a7, { + a1: arg0, + a2: arg1 + }, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + + labels = RunMetadataLabels(run_metadata) + + xla_compile_count = sum("XlaCompile(" in x for x in labels) + xla_run_count = sum("XlaRun(" in x for x in labels) + self.assertEqual(xla_compile_count, xla_run_count) + + return output, xla_run_count + + +class LazyCompilationTest(test.TestCase): + + def testLazyCompilation(self): + + @function.Defun(compiled=True) + def CompiledFunction(x): + return math_ops.log(x) + + with session_lib.Session(config=NoRewriteSessionConfig()) as sess: + x = array_ops.placeholder(dtypes.float32) + y = CompiledFunction(x) + + # The very first run of the cluster is always compiled (non-lazily). + run_metadata_for_first_run = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [2., 10., 19., 77., 100.]}, + run_metadata=run_metadata_for_first_run, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue( + InLabels( + RunMetadataLabels(run_metadata_for_first_run), "_XlaCompile")) + self.assertTrue( + InLabels(RunMetadataLabels(run_metadata_for_first_run), "_XlaRun")) + + run_metadata_before_warmup = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [2., 10.]}, + run_metadata=run_metadata_before_warmup, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue( + InLabels( + RunMetadataLabels(run_metadata_before_warmup), "_XlaCompile")) + self.assertFalse( + InLabels(RunMetadataLabels(run_metadata_before_warmup), "_XlaRun")) + + # We compile when we see the same shape a second time. + + run_metadata_after_warmup = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [2., 10.]}, + run_metadata=run_metadata_after_warmup, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue( + InLabels(RunMetadataLabels(run_metadata_after_warmup), "_XlaCompile")) + self.assertTrue( + InLabels(RunMetadataLabels(run_metadata_after_warmup), "_XlaRun")) + + run_metadata_for_new_shape = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [2., 10., 12.]}, + run_metadata=run_metadata_for_new_shape, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue( + InLabels( + RunMetadataLabels(run_metadata_for_new_shape), "_XlaCompile")) + self.assertFalse( + InLabels(RunMetadataLabels(run_metadata_for_new_shape), "_XlaRun")) + + def testIsMegamorphic(self): + + @function.Defun(compiled=True) + def CompiledFunction(x): + return math_ops.log(x) + + with session_lib.Session(config=NoRewriteSessionConfig()) as sess: + x = array_ops.placeholder(dtypes.float32) + y = CompiledFunction(x) + + # Make the cluster go megamorphic by running it with lots of shape + # signatures where the cluster is executed with each signature only a few + # times. Then check that we don't compile the cluster ever again. + + for shape in range(10, 50): + for _ in range(0, 49): + sess.run(y, feed_dict={x: [0.] * shape}) + + for _ in range(0, 50): + run_metadata = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [0.] * 60}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue( + InLabels(RunMetadataLabels(run_metadata), "_XlaCompile")) + self.assertFalse(InLabels(RunMetadataLabels(run_metadata), "_XlaRun")) + + def testIsNotMegamorphic(self): + + @function.Defun(compiled=True) + def CompiledFunction(x): + return math_ops.log(x) + + with session_lib.Session(config=NoRewriteSessionConfig()) as sess: + x = array_ops.placeholder(dtypes.float32) + y = CompiledFunction(x) + + # Run the cluster with lots of shape signatures, but in a way that it + # isn't megamorphic (i.e. each shape signature sees a lot of executions). + # Then check that the cluster has not been marked as megamorphic. + + for shape in range(10, 50): + for _ in range(0, 1000): + sess.run(y, feed_dict={x: [0.] * shape}) + + for _ in range(0, 10): + sess.run(y, feed_dict={x: [0.] * 60}) + + run_metadata = config_pb2.RunMetadata() + sess.run( + y, + feed_dict={x: [0.] * 60}, + run_metadata=run_metadata, + options=config_pb2.RunOptions( + trace_level=config_pb2.RunOptions.FULL_TRACE)) + self.assertTrue(InLabels(RunMetadataLabels(run_metadata), "_XlaCompile")) + self.assertTrue(InLabels(RunMetadataLabels(run_metadata), "_XlaRun")) + + +if __name__ == "__main__": + os.environ["TF_XLA_FLAGS"] = ("--tf_xla_enable_lazy_compilation=true " + + os.environ.get("TF_XLA_FLAGS", "")) + # This test is using Tensorflow sessions which are not compatible with eager + # mode. + ops.disable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/listdiff_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/listdiff_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..064a669c5b29718bb95d51b1798e0264be6814e2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/listdiff_op_test.py @@ -0,0 +1,96 @@ +# 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 XLA listdiff operator.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class ListDiffTest(xla_test.XLATestCase): + + def _testListDiff(self, x, y, out, idx): + for dtype in [dtypes.int32, dtypes.int64]: + for index_dtype in [dtypes.int32, dtypes.int64]: + with self.session(): + x_tensor = ops.convert_to_tensor(x, dtype=dtype) + y_tensor = ops.convert_to_tensor(y, dtype=dtype) + with self.test_scope(): + out_tensor, idx_tensor = array_ops.listdiff( + x_tensor, y_tensor, out_idx=index_dtype) + tf_out, tf_idx = self.evaluate([out_tensor, idx_tensor]) + self.assertAllEqual(out, tf_out) + self.assertAllEqual(idx, tf_idx) + self.assertEqual(1, out_tensor.get_shape().ndims) + self.assertEqual(1, idx_tensor.get_shape().ndims) + + def testBasic1(self): + self._testListDiff(x=[1, 2, 3, 4], y=[1, 2], out=[3, 4], idx=[2, 3]) + + def testBasic2(self): + self._testListDiff(x=[1, 2, 3, 4], y=[2], out=[1, 3, 4], idx=[0, 2, 3]) + + def testBasic3(self): + self._testListDiff(x=[1, 4, 3, 2], y=[4, 2], out=[1, 3], idx=[0, 2]) + + def testDuplicates(self): + self._testListDiff(x=[1, 2, 4, 3, 2, 3, 3, 1], + y=[4, 2], + out=[1, 3, 3, 3, 1], + idx=[0, 3, 5, 6, 7]) + + def testRandom(self): + num_random_tests = 10 + int_low = -7 + int_high = 8 + max_size = 50 + for _ in range(num_random_tests): + x_size = np.random.randint(max_size + 1) + x = np.random.randint(int_low, int_high, size=x_size) + y_size = np.random.randint(max_size + 1) + y = np.random.randint(int_low, int_high, size=y_size) + out_idx = [(entry, pos) for pos, entry in enumerate(x) if entry not in y] + if out_idx: + out, idx = map(list, zip(*out_idx)) + else: + out = [] + idx = [] + self._testListDiff(list(x), list(y), out, idx) + + def testFullyOverlapping(self): + self._testListDiff(x=[1, 2, 3, 4], y=[1, 2, 3, 4], out=[], idx=[]) + + def testNonOverlapping(self): + self._testListDiff(x=[1, 2, 3, 4], + y=[5, 6], + out=[1, 2, 3, 4], + idx=[0, 1, 2, 3]) + + def testEmptyX(self): + self._testListDiff(x=[], y=[1, 2], out=[], idx=[]) + + def testEmptyY(self): + self._testListDiff(x=[1, 2, 3, 4], y=[], out=[1, 2, 3, 4], idx=[0, 1, 2, 3]) + + def testEmptyXY(self): + self._testListDiff(x=[], y=[], out=[], idx=[]) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/lrn_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lrn_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..05148c667af67603bde50d8db7830a9a47aaeba7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lrn_ops_test.py @@ -0,0 +1,137 @@ +# 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 Local Response Normalization ops.""" + +import copy + +import numpy as np + +from tensorflow.compiler.tests import xla_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_nn_ops +from tensorflow.python.ops import nn +from tensorflow.python.platform import googletest + +CPU_DEVICE = "/job:localhost/replica:0/task:0/cpu:0" + + +# Local response normalization tests. The forward tests are copied from +# tensorflow/python/kernel_tests/lrn_op_test.py +class LRNTest(xla_test.XLATestCase): + + def _LRN(self, input_image, lrn_depth_radius=5, bias=1.0, alpha=1.0, + beta=0.5): + """Compute expected result.""" + output = copy.deepcopy(input_image) + batch_size = input_image.shape[0] + rows = input_image.shape[1] + cols = input_image.shape[2] + depth = input_image.shape[3] + for b in range(batch_size): + for r in range(rows): + for c in range(cols): + for d in range(depth): + begin = max(0, d - lrn_depth_radius) + end = min(depth, d + lrn_depth_radius + 1) + patch = input_image[b, r, c, begin:end] + output[b, r, c, d] /= ( + np.power(bias + alpha * np.sum(patch * patch), beta)) + return output + + def _RunAndVerify(self, dtype): + with self.session(): + # random shape + shape = np.random.randint(1, 16, size=4) + # Make depth at least 2 to make it meaningful + shape[3] += 1 + p = array_ops.placeholder(dtype, shape=shape) + # random depth_radius, bias, alpha, beta + lrn_depth_radius = np.random.randint(1, shape[3]) + bias = 1.0 + np.random.rand() + alpha = 2.0 * np.random.rand() + beta = 2.0 * np.random.rand() + with self.test_scope(): + lrn_t = nn.local_response_normalization( + p, + name="lrn", + depth_radius=lrn_depth_radius, + bias=bias, + alpha=alpha, + beta=beta) + params = {p: np.random.rand(*shape).astype("f")} + result = lrn_t.eval(feed_dict=params) + expected = self._LRN( + params[p], + lrn_depth_radius=lrn_depth_radius, + bias=bias, + alpha=alpha, + beta=beta) + err = np.amax(np.abs(result - expected)) + print("LRN error for bias ", bias, "alpha ", alpha, " beta ", beta, " is ", + err) + if dtype == dtypes.float32: + self.assertTrue(err < 1e-4) + else: + self.assertTrue(err < 1e-2) + self.assertShapeEqual(expected, lrn_t) + + def testCompute(self): + for dtype in [dtypes.float32, dtypes.float16, dtypes.bfloat16]: + for _ in range(2): + self._RunAndVerify(dtype) + + def testLrnGrad(self): + # Test for LRNGrad that compares against the CPU implementation. + # Note: TF CPU implementation for LRNGrad supports float32 and float16. + for dtype in [dtypes.float32, dtypes.float16]: + shape = [1, 2, 3, 4] + total_size = np.prod(shape) + np_dtype = dtype.as_numpy_dtype + in_image_vals = np.arange(1, total_size + 1, dtype=np_dtype) + out_image_vals = np.arange(1, total_size + 1, dtype=np_dtype) + out_grads_vals = np.arange(1, total_size + 1, dtype=np_dtype) + depth_radius = np.random.randint(1, shape[3]) + bias = 1.0 + np.random.rand() + alpha = 1.0 * np.random.rand() + beta = 1.0 * np.random.rand() + + with self.session(): + in_image = constant_op.constant(in_image_vals, shape=shape, dtype=dtype) + out_image = constant_op.constant( + out_image_vals, shape=shape, dtype=dtype + ) + out_grads = constant_op.constant( + out_grads_vals, shape=shape, dtype=dtype + ) + with ops.device(CPU_DEVICE): + expected = gen_nn_ops.lrn_grad( + out_grads, in_image, out_image, depth_radius, bias, alpha, beta + ) + with self.test_scope(): + actual = gen_nn_ops.lrn_grad( + out_grads, in_image, out_image, depth_radius, bias, alpha, beta + ) + expected_val = self.evaluate(expected) + actual_val = self.evaluate(actual) + rtol = 1e-3 if dtype == dtypes.float32 else 1e-2 + atol = 1e-6 if dtype == dtypes.float32 else 2e-3 + self.assertAllClose(actual_val, expected_val, rtol=rtol, atol=atol) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm.py new file mode 100644 index 0000000000000000000000000000000000000000..b98e5126aad937a2e4311c3aa86a1056711569b8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm.py @@ -0,0 +1,156 @@ +# 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. +# ============================================================================== +"""A simple LSTM layer with benchmarks. + +This sets up a simple LSTM (Long Short Term Memory) layer, unrolled to a fixed +length sequence. The only deviation from standard LSTM cells is that +activations are clipped, inspired by the GNMT machine translation model. +The GNMT paper has more details: https://arxiv.org/abs/1609.08144 +""" + +from six.moves import range + +from tensorflow.python.framework import dtypes +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 random_ops +from tensorflow.python.ops import variable_v1 + + +def Clip(x): + """Clips x to the range [-1., 1.].""" + return math_ops.maximum(math_ops.minimum(x, 1.), -1.) + + +def LSTMCellWeightsShape(num_inputs, num_nodes): + """Returns the shape of the weights for a single LSTM cell.""" + # Dimension 0 accounts for combining x with the previous m state. + # Dimension 1 accounts for the in value and the (in, forget, out) gates. + return [num_inputs + num_nodes, 4 * num_nodes] + + +def LSTMCell(weights, m_prev, c_prev, x, pad): + """Unrolls a single LSTM cell with clipped activations forward by one step. + + Args: + weights: Weight matrix with shape LSTMCellWeightsShape. + m_prev: Previous m states with shape [batch_size, num_nodes]. + c_prev: Previous c states with shape [batch_size, num_nodes]. + x: Input with shape [batch_size, num_inputs]. + pad: Padding with shape [batch_size, 1]. Each padding value is either + 0 or 1, where 1 indicates padding; i.e. the input is shorter than the + sequence length, and the (m, c) states should simply be passed through + from the previous states. + Returns: + The next (m, c) states, each with shape [batch_size, num_nodes]. + """ + # Apply weights to the input and previous hidden state. + # The matmul here is the "big" operation. + xm = array_ops.concat([x, m_prev], 1) + xmw = math_ops.matmul(xm, weights) + + # Element-wise ops for the standard LSTM cell, with clipped activations. + # XLA can fuse these operations into a single loop. + in_value, in_gate, forget_gate, out_gate = array_ops.split( + value=xmw, num_or_size_splits=4, axis=1) + in_value = math_ops.tanh(in_value) + in_gate = math_ops.sigmoid(in_gate) + forget_gate = math_ops.sigmoid(forget_gate) + out_gate = math_ops.sigmoid(out_gate) + c_next = Clip(Clip(forget_gate * c_prev) + Clip(in_gate * in_value)) + m_next = Clip(out_gate * c_next) + + # Account for padding. + c_next = c_prev * pad + c_next * (1.0 - pad) + m_next = m_prev * pad + m_next * (1.0 - pad) + + return m_next, c_next + + +def LSTMLayer(cell_name, weights, m, c, x_seq, pad_seq): + """Unrolls a layer of LSTM cells forward by the sequence length. + + The sequence length is determined by the length of x_seq and pad_seq, which + must be the same. + + Args: + cell_name: Base name of each cell. + weights: Weight matrix with shape LSTMCellWeightsShape. + m: Initial m states with shape [batch_size, num_nodes]. + c: Initial c states with shape [batch_size, num_nodes]. + x_seq: List of inputs, each with shape [batch_size, num_inputs]. + The length of the list is the sequence length. + pad_seq: List of paddings, each with shape [batch_size, 1]. + The length of the list is the sequence length. + Each padding value is either 0 or 1, where 1 indicates padding; + i.e. the input is shorter than the sequence length. + Returns: + List of per-sequence-step outputs, each with shape [batch_size, num_nodes]. + Raises: + ValueError: If len(x_seq) != len(pad_seq). + """ + if len(x_seq) != len(pad_seq): + raise ValueError('length of x_seq(%d) != pad_seq(%d)' % + (len(x_seq), len(pad_seq))) + out_seq = [] + for seq in range(len(x_seq)): + with ops.name_scope('%s_%d' % (cell_name, seq)): + m, c = LSTMCell(weights, m, c, x_seq[seq], pad_seq[seq]) + out_seq.append(array_ops.identity(m, name='out')) + return out_seq + + +def RandomVar(shape, name=None): + """Returns a variable of the given shape initialized to random values.""" + return variable_v1.VariableV1( + random_ops.random_uniform(shape), dtype=dtypes.float32, name=name) + + +def RandomInputs(batch_size, seq_length, num_inputs): + """Returns randomly initialized (x_seq, pad_seq) sequences.""" + x_seq = [] + pad_seq = [] + with ops.name_scope('inputs'): + for seq in range(seq_length): + x_seq.append(RandomVar([batch_size, num_inputs], name='x_seq_%d' % seq)) + # Real padding values are always a sequence of 0 followed by a + # sequence of 1, but random values are fine for benchmarking. + pad_seq.append(RandomVar([batch_size, 1], name='pad_seq_%d' % seq)) + return x_seq, pad_seq + + +def BuildLSTMLayer(batch_size, seq_length, num_inputs, num_nodes): + """Builds a single LSTM layer with random weights and inputs. + + Args: + batch_size: Inputs are fed in batches of this size. + seq_length: The sequence length to unroll the LSTM layer. + num_inputs: Dimension of inputs that are fed into each LSTM cell. + num_nodes: The number of nodes in each LSTM cell. + + Returns: + (out_seq, weights) pair. The out_seq is a list of per-sequence-step + outputs, each with shape [batch_size, num_nodes]. The weights are a list of + weight variables that may be trained. + """ + weights = RandomVar( + LSTMCellWeightsShape(num_inputs, num_nodes), name='weights') + m = array_ops.zeros([batch_size, num_nodes], name='init_m') + c = array_ops.zeros([batch_size, num_nodes], name='init_c') + x_seq, pad_seq = RandomInputs(batch_size, seq_length, num_inputs) + + out_seq = LSTMLayer('lstm', weights, m, c, x_seq, pad_seq) + return out_seq, [weights] diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_layer_inference.config.pbtxt b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_layer_inference.config.pbtxt new file mode 100644 index 0000000000000000000000000000000000000000..05c40b3fa9a419f8a9fc7e44efa704fe9ae2d673 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_layer_inference.config.pbtxt @@ -0,0 +1,20 @@ +# Text form of tensorflow.tf2xla.Config proto. +feed{ id{node_name:"inputs/x_seq_0/read"} shape{dim{size:128}dim{size:1024}} } +feed{ id{node_name:"inputs/x_seq_1/read"} shape{dim{size:128}dim{size:1024}} } +feed{ id{node_name:"inputs/x_seq_2/read"} shape{dim{size:128}dim{size:1024}} } +feed{ id{node_name:"inputs/x_seq_3/read"} shape{dim{size:128}dim{size:1024}} } +feed{ id{node_name:"inputs/x_seq_4/read"} shape{dim{size:128}dim{size:1024}} } +feed{ id{node_name:"inputs/pad_seq_0/read"} shape{dim{size:128}dim{size:1}} } +feed{ id{node_name:"inputs/pad_seq_1/read"} shape{dim{size:128}dim{size:1}} } +feed{ id{node_name:"inputs/pad_seq_2/read"} shape{dim{size:128}dim{size:1}} } +feed{ id{node_name:"inputs/pad_seq_3/read"} shape{dim{size:128}dim{size:1}} } +feed{ id{node_name:"inputs/pad_seq_4/read"} shape{dim{size:128}dim{size:1}} } +feed{ id{node_name:"weights/read"} shape{dim{size:2048}dim{size:4096}} } +feed{ id{node_name:"init_c"} shape{dim{size:128}dim{size:1024}} } +feed{ id{node_name:"init_m"} shape{dim{size:128}dim{size:1024}} } + +fetch{ id{node_name:"lstm_0/out"} } +fetch{ id{node_name:"lstm_1/out"} } +fetch{ id{node_name:"lstm_2/out"} } +fetch{ id{node_name:"lstm_3/out"} } +fetch{ id{node_name:"lstm_4/out"} } diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_layer_inference.pbtxt b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_layer_inference.pbtxt new file mode 100644 index 0000000000000000000000000000000000000000..91d1c40f7a5a01d8e9c3e000ab21ed4267fe35a3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_layer_inference.pbtxt @@ -0,0 +1,5828 @@ +# Generated by running lstm_test, setting --dump_graph_dir. + +node { + name: "random_uniform/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\000\010\000\000\000\020\000\000" + } + } + } +} +node { + name: "random_uniform/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "random_uniform/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "random_uniform/RandomUniform" + op: "RandomUniform" + input: "random_uniform/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "random_uniform/sub" + op: "Sub" + input: "random_uniform/max" + input: "random_uniform/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "random_uniform/mul" + op: "Mul" + input: "random_uniform/RandomUniform" + input: "random_uniform/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "random_uniform" + op: "Add" + input: "random_uniform/mul" + input: "random_uniform/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "weights" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 2048 + } + dim { + size: 4096 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "weights/Assign" + op: "Assign" + input: "weights" + input: "random_uniform" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@weights" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "weights/read" + op: "Identity" + input: "weights" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@weights" + } + } + } +} +node { + name: "init_m" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + float_val: 0.0 + } + } + } +} +node { + name: "init_c" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\000\004\000\000" + } + } + } +} +node { + name: "inputs/random_uniform/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform/sub" + op: "Sub" + input: "inputs/random_uniform/max" + input: "inputs/random_uniform/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform/mul" + op: "Mul" + input: "inputs/random_uniform/RandomUniform" + input: "inputs/random_uniform/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform" + op: "Add" + input: "inputs/random_uniform/mul" + input: "inputs/random_uniform/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/x_seq_0" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/x_seq_0/Assign" + op: "Assign" + input: "inputs/x_seq_0" + input: "inputs/random_uniform" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_0" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/x_seq_0/read" + op: "Identity" + input: "inputs/x_seq_0" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_0" + } + } + } +} +node { + name: "inputs/random_uniform_1/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\001\000\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_1/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_1/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_1/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_1/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_1/sub" + op: "Sub" + input: "inputs/random_uniform_1/max" + input: "inputs/random_uniform_1/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_1/mul" + op: "Mul" + input: "inputs/random_uniform_1/RandomUniform" + input: "inputs/random_uniform_1/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_1" + op: "Add" + input: "inputs/random_uniform_1/mul" + input: "inputs/random_uniform_1/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/pad_seq_0" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/pad_seq_0/Assign" + op: "Assign" + input: "inputs/pad_seq_0" + input: "inputs/random_uniform_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_0" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/pad_seq_0/read" + op: "Identity" + input: "inputs/pad_seq_0" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_0" + } + } + } +} +node { + name: "inputs/random_uniform_2/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\000\004\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_2/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_2/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_2/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_2/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_2/sub" + op: "Sub" + input: "inputs/random_uniform_2/max" + input: "inputs/random_uniform_2/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_2/mul" + op: "Mul" + input: "inputs/random_uniform_2/RandomUniform" + input: "inputs/random_uniform_2/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_2" + op: "Add" + input: "inputs/random_uniform_2/mul" + input: "inputs/random_uniform_2/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/x_seq_1" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/x_seq_1/Assign" + op: "Assign" + input: "inputs/x_seq_1" + input: "inputs/random_uniform_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_1" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/x_seq_1/read" + op: "Identity" + input: "inputs/x_seq_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_1" + } + } + } +} +node { + name: "inputs/random_uniform_3/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\001\000\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_3/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_3/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_3/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_3/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_3/sub" + op: "Sub" + input: "inputs/random_uniform_3/max" + input: "inputs/random_uniform_3/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_3/mul" + op: "Mul" + input: "inputs/random_uniform_3/RandomUniform" + input: "inputs/random_uniform_3/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_3" + op: "Add" + input: "inputs/random_uniform_3/mul" + input: "inputs/random_uniform_3/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/pad_seq_1" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/pad_seq_1/Assign" + op: "Assign" + input: "inputs/pad_seq_1" + input: "inputs/random_uniform_3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_1" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/pad_seq_1/read" + op: "Identity" + input: "inputs/pad_seq_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_1" + } + } + } +} +node { + name: "inputs/random_uniform_4/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\000\004\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_4/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_4/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_4/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_4/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_4/sub" + op: "Sub" + input: "inputs/random_uniform_4/max" + input: "inputs/random_uniform_4/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_4/mul" + op: "Mul" + input: "inputs/random_uniform_4/RandomUniform" + input: "inputs/random_uniform_4/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_4" + op: "Add" + input: "inputs/random_uniform_4/mul" + input: "inputs/random_uniform_4/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/x_seq_2" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/x_seq_2/Assign" + op: "Assign" + input: "inputs/x_seq_2" + input: "inputs/random_uniform_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_2" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/x_seq_2/read" + op: "Identity" + input: "inputs/x_seq_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_2" + } + } + } +} +node { + name: "inputs/random_uniform_5/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\001\000\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_5/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_5/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_5/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_5/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_5/sub" + op: "Sub" + input: "inputs/random_uniform_5/max" + input: "inputs/random_uniform_5/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_5/mul" + op: "Mul" + input: "inputs/random_uniform_5/RandomUniform" + input: "inputs/random_uniform_5/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_5" + op: "Add" + input: "inputs/random_uniform_5/mul" + input: "inputs/random_uniform_5/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/pad_seq_2" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/pad_seq_2/Assign" + op: "Assign" + input: "inputs/pad_seq_2" + input: "inputs/random_uniform_5" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_2" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/pad_seq_2/read" + op: "Identity" + input: "inputs/pad_seq_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_2" + } + } + } +} +node { + name: "inputs/random_uniform_6/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\000\004\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_6/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_6/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_6/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_6/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_6/sub" + op: "Sub" + input: "inputs/random_uniform_6/max" + input: "inputs/random_uniform_6/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_6/mul" + op: "Mul" + input: "inputs/random_uniform_6/RandomUniform" + input: "inputs/random_uniform_6/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_6" + op: "Add" + input: "inputs/random_uniform_6/mul" + input: "inputs/random_uniform_6/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/x_seq_3" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/x_seq_3/Assign" + op: "Assign" + input: "inputs/x_seq_3" + input: "inputs/random_uniform_6" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_3" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/x_seq_3/read" + op: "Identity" + input: "inputs/x_seq_3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_3" + } + } + } +} +node { + name: "inputs/random_uniform_7/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\001\000\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_7/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_7/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_7/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_7/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_7/sub" + op: "Sub" + input: "inputs/random_uniform_7/max" + input: "inputs/random_uniform_7/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_7/mul" + op: "Mul" + input: "inputs/random_uniform_7/RandomUniform" + input: "inputs/random_uniform_7/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_7" + op: "Add" + input: "inputs/random_uniform_7/mul" + input: "inputs/random_uniform_7/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/pad_seq_3" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/pad_seq_3/Assign" + op: "Assign" + input: "inputs/pad_seq_3" + input: "inputs/random_uniform_7" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_3" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/pad_seq_3/read" + op: "Identity" + input: "inputs/pad_seq_3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_3" + } + } + } +} +node { + name: "inputs/random_uniform_8/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\000\004\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_8/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_8/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_8/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_8/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_8/sub" + op: "Sub" + input: "inputs/random_uniform_8/max" + input: "inputs/random_uniform_8/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_8/mul" + op: "Mul" + input: "inputs/random_uniform_8/RandomUniform" + input: "inputs/random_uniform_8/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_8" + op: "Add" + input: "inputs/random_uniform_8/mul" + input: "inputs/random_uniform_8/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/x_seq_4" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1024 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/x_seq_4/Assign" + op: "Assign" + input: "inputs/x_seq_4" + input: "inputs/random_uniform_8" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_4" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/x_seq_4/read" + op: "Identity" + input: "inputs/x_seq_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/x_seq_4" + } + } + } +} +node { + name: "inputs/random_uniform_9/shape" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + dim { + size: 2 + } + } + tensor_content: "\200\000\000\000\001\000\000\000" + } + } + } +} +node { + name: "inputs/random_uniform_9/min" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 0.0 + } + } + } +} +node { + name: "inputs/random_uniform_9/max" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "inputs/random_uniform_9/RandomUniform" + op: "RandomUniform" + input: "inputs/random_uniform_9/shape" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_INT32 + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "seed" + value { + i: 0 + } + } + attr { + key: "seed2" + value { + i: 0 + } + } +} +node { + name: "inputs/random_uniform_9/sub" + op: "Sub" + input: "inputs/random_uniform_9/max" + input: "inputs/random_uniform_9/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_9/mul" + op: "Mul" + input: "inputs/random_uniform_9/RandomUniform" + input: "inputs/random_uniform_9/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/random_uniform_9" + op: "Add" + input: "inputs/random_uniform_9/mul" + input: "inputs/random_uniform_9/min" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "inputs/pad_seq_4" + op: "Variable" + device: "/device:GPU:*" + attr { + key: "container" + value { + s: "" + } + } + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "shape" + value { + shape { + dim { + size: 128 + } + dim { + size: 1 + } + } + } + } + attr { + key: "shared_name" + value { + s: "" + } + } +} +node { + name: "inputs/pad_seq_4/Assign" + op: "Assign" + input: "inputs/pad_seq_4" + input: "inputs/random_uniform_9" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_4" + } + } + } + attr { + key: "use_locking" + value { + b: true + } + } + attr { + key: "validate_shape" + value { + b: true + } + } +} +node { + name: "inputs/pad_seq_4/read" + op: "Identity" + input: "inputs/pad_seq_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "_class" + value { + list { + s: "loc:@inputs/pad_seq_4" + } + } + } +} +node { + name: "lstm_0/concat/axis" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_0/concat" + op: "ConcatV2" + input: "inputs/x_seq_0/read" + input: "init_m" + input: "lstm_0/concat/axis" + device: "/device:GPU:*" + attr { + key: "N" + value { + i: 2 + } + } + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "Tidx" + value { + type: DT_INT32 + } + } +} +node { + name: "lstm_0/MatMul" + op: "MatMul" + input: "lstm_0/concat" + input: "weights/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "transpose_a" + value { + b: false + } + } + attr { + key: "transpose_b" + value { + b: false + } + } +} +node { + name: "lstm_0/split/split_dim" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_0/split" + op: "Split" + input: "lstm_0/split/split_dim" + input: "lstm_0/MatMul" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "num_split" + value { + i: 4 + } + } +} +node { + name: "lstm_0/Tanh" + op: "Tanh" + input: "lstm_0/split" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Sigmoid" + op: "Sigmoid" + input: "lstm_0/split:1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Sigmoid_1" + op: "Sigmoid" + input: "lstm_0/split:2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Sigmoid_2" + op: "Sigmoid" + input: "lstm_0/split:3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul" + op: "Mul" + input: "lstm_0/Sigmoid_1" + input: "init_c" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Minimum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_0/Minimum" + op: "Minimum" + input: "lstm_0/mul" + input: "lstm_0/Minimum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Maximum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_0/Maximum" + op: "Maximum" + input: "lstm_0/Minimum" + input: "lstm_0/Maximum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul_1" + op: "Mul" + input: "lstm_0/Sigmoid" + input: "lstm_0/Tanh" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Minimum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_0/Minimum_1" + op: "Minimum" + input: "lstm_0/mul_1" + input: "lstm_0/Minimum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Maximum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_0/Maximum_1" + op: "Maximum" + input: "lstm_0/Minimum_1" + input: "lstm_0/Maximum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/add" + op: "Add" + input: "lstm_0/Maximum" + input: "lstm_0/Maximum_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Minimum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_0/Minimum_2" + op: "Minimum" + input: "lstm_0/add" + input: "lstm_0/Minimum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Maximum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_0/Maximum_2" + op: "Maximum" + input: "lstm_0/Minimum_2" + input: "lstm_0/Maximum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul_2" + op: "Mul" + input: "lstm_0/Sigmoid_2" + input: "lstm_0/Maximum_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Minimum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_0/Minimum_3" + op: "Minimum" + input: "lstm_0/mul_2" + input: "lstm_0/Minimum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/Maximum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_0/Maximum_3" + op: "Maximum" + input: "lstm_0/Minimum_3" + input: "lstm_0/Maximum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul_3" + op: "Mul" + input: "init_c" + input: "inputs/pad_seq_0/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/sub/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_0/sub" + op: "Sub" + input: "lstm_0/sub/x" + input: "inputs/pad_seq_0/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul_4" + op: "Mul" + input: "lstm_0/Maximum_2" + input: "lstm_0/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/add_1" + op: "Add" + input: "lstm_0/mul_3" + input: "lstm_0/mul_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul_5" + op: "Mul" + input: "init_m" + input: "inputs/pad_seq_0/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/sub_1/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_0/sub_1" + op: "Sub" + input: "lstm_0/sub_1/x" + input: "inputs/pad_seq_0/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/mul_6" + op: "Mul" + input: "lstm_0/Maximum_3" + input: "lstm_0/sub_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/add_2" + op: "Add" + input: "lstm_0/mul_5" + input: "lstm_0/mul_6" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_0/out" + op: "Identity" + input: "lstm_0/add_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/concat/axis" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_1/concat" + op: "ConcatV2" + input: "inputs/x_seq_1/read" + input: "lstm_0/add_2" + input: "lstm_1/concat/axis" + device: "/device:GPU:*" + attr { + key: "N" + value { + i: 2 + } + } + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "Tidx" + value { + type: DT_INT32 + } + } +} +node { + name: "lstm_1/MatMul" + op: "MatMul" + input: "lstm_1/concat" + input: "weights/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "transpose_a" + value { + b: false + } + } + attr { + key: "transpose_b" + value { + b: false + } + } +} +node { + name: "lstm_1/split/split_dim" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_1/split" + op: "Split" + input: "lstm_1/split/split_dim" + input: "lstm_1/MatMul" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "num_split" + value { + i: 4 + } + } +} +node { + name: "lstm_1/Tanh" + op: "Tanh" + input: "lstm_1/split" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Sigmoid" + op: "Sigmoid" + input: "lstm_1/split:1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Sigmoid_1" + op: "Sigmoid" + input: "lstm_1/split:2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Sigmoid_2" + op: "Sigmoid" + input: "lstm_1/split:3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul" + op: "Mul" + input: "lstm_1/Sigmoid_1" + input: "lstm_0/add_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Minimum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_1/Minimum" + op: "Minimum" + input: "lstm_1/mul" + input: "lstm_1/Minimum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Maximum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_1/Maximum" + op: "Maximum" + input: "lstm_1/Minimum" + input: "lstm_1/Maximum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul_1" + op: "Mul" + input: "lstm_1/Sigmoid" + input: "lstm_1/Tanh" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Minimum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_1/Minimum_1" + op: "Minimum" + input: "lstm_1/mul_1" + input: "lstm_1/Minimum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Maximum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_1/Maximum_1" + op: "Maximum" + input: "lstm_1/Minimum_1" + input: "lstm_1/Maximum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/add" + op: "Add" + input: "lstm_1/Maximum" + input: "lstm_1/Maximum_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Minimum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_1/Minimum_2" + op: "Minimum" + input: "lstm_1/add" + input: "lstm_1/Minimum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Maximum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_1/Maximum_2" + op: "Maximum" + input: "lstm_1/Minimum_2" + input: "lstm_1/Maximum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul_2" + op: "Mul" + input: "lstm_1/Sigmoid_2" + input: "lstm_1/Maximum_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Minimum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_1/Minimum_3" + op: "Minimum" + input: "lstm_1/mul_2" + input: "lstm_1/Minimum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/Maximum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_1/Maximum_3" + op: "Maximum" + input: "lstm_1/Minimum_3" + input: "lstm_1/Maximum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul_3" + op: "Mul" + input: "lstm_0/add_1" + input: "inputs/pad_seq_1/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/sub/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_1/sub" + op: "Sub" + input: "lstm_1/sub/x" + input: "inputs/pad_seq_1/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul_4" + op: "Mul" + input: "lstm_1/Maximum_2" + input: "lstm_1/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/add_1" + op: "Add" + input: "lstm_1/mul_3" + input: "lstm_1/mul_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul_5" + op: "Mul" + input: "lstm_0/add_2" + input: "inputs/pad_seq_1/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/sub_1/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_1/sub_1" + op: "Sub" + input: "lstm_1/sub_1/x" + input: "inputs/pad_seq_1/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/mul_6" + op: "Mul" + input: "lstm_1/Maximum_3" + input: "lstm_1/sub_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/add_2" + op: "Add" + input: "lstm_1/mul_5" + input: "lstm_1/mul_6" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_1/out" + op: "Identity" + input: "lstm_1/add_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/concat/axis" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_2/concat" + op: "ConcatV2" + input: "inputs/x_seq_2/read" + input: "lstm_1/add_2" + input: "lstm_2/concat/axis" + device: "/device:GPU:*" + attr { + key: "N" + value { + i: 2 + } + } + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "Tidx" + value { + type: DT_INT32 + } + } +} +node { + name: "lstm_2/MatMul" + op: "MatMul" + input: "lstm_2/concat" + input: "weights/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "transpose_a" + value { + b: false + } + } + attr { + key: "transpose_b" + value { + b: false + } + } +} +node { + name: "lstm_2/split/split_dim" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_2/split" + op: "Split" + input: "lstm_2/split/split_dim" + input: "lstm_2/MatMul" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "num_split" + value { + i: 4 + } + } +} +node { + name: "lstm_2/Tanh" + op: "Tanh" + input: "lstm_2/split" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Sigmoid" + op: "Sigmoid" + input: "lstm_2/split:1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Sigmoid_1" + op: "Sigmoid" + input: "lstm_2/split:2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Sigmoid_2" + op: "Sigmoid" + input: "lstm_2/split:3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul" + op: "Mul" + input: "lstm_2/Sigmoid_1" + input: "lstm_1/add_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Minimum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_2/Minimum" + op: "Minimum" + input: "lstm_2/mul" + input: "lstm_2/Minimum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Maximum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_2/Maximum" + op: "Maximum" + input: "lstm_2/Minimum" + input: "lstm_2/Maximum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul_1" + op: "Mul" + input: "lstm_2/Sigmoid" + input: "lstm_2/Tanh" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Minimum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_2/Minimum_1" + op: "Minimum" + input: "lstm_2/mul_1" + input: "lstm_2/Minimum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Maximum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_2/Maximum_1" + op: "Maximum" + input: "lstm_2/Minimum_1" + input: "lstm_2/Maximum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/add" + op: "Add" + input: "lstm_2/Maximum" + input: "lstm_2/Maximum_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Minimum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_2/Minimum_2" + op: "Minimum" + input: "lstm_2/add" + input: "lstm_2/Minimum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Maximum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_2/Maximum_2" + op: "Maximum" + input: "lstm_2/Minimum_2" + input: "lstm_2/Maximum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul_2" + op: "Mul" + input: "lstm_2/Sigmoid_2" + input: "lstm_2/Maximum_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Minimum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_2/Minimum_3" + op: "Minimum" + input: "lstm_2/mul_2" + input: "lstm_2/Minimum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/Maximum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_2/Maximum_3" + op: "Maximum" + input: "lstm_2/Minimum_3" + input: "lstm_2/Maximum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul_3" + op: "Mul" + input: "lstm_1/add_1" + input: "inputs/pad_seq_2/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/sub/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_2/sub" + op: "Sub" + input: "lstm_2/sub/x" + input: "inputs/pad_seq_2/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul_4" + op: "Mul" + input: "lstm_2/Maximum_2" + input: "lstm_2/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/add_1" + op: "Add" + input: "lstm_2/mul_3" + input: "lstm_2/mul_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul_5" + op: "Mul" + input: "lstm_1/add_2" + input: "inputs/pad_seq_2/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/sub_1/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_2/sub_1" + op: "Sub" + input: "lstm_2/sub_1/x" + input: "inputs/pad_seq_2/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/mul_6" + op: "Mul" + input: "lstm_2/Maximum_3" + input: "lstm_2/sub_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/add_2" + op: "Add" + input: "lstm_2/mul_5" + input: "lstm_2/mul_6" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_2/out" + op: "Identity" + input: "lstm_2/add_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/concat/axis" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_3/concat" + op: "ConcatV2" + input: "inputs/x_seq_3/read" + input: "lstm_2/add_2" + input: "lstm_3/concat/axis" + device: "/device:GPU:*" + attr { + key: "N" + value { + i: 2 + } + } + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "Tidx" + value { + type: DT_INT32 + } + } +} +node { + name: "lstm_3/MatMul" + op: "MatMul" + input: "lstm_3/concat" + input: "weights/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "transpose_a" + value { + b: false + } + } + attr { + key: "transpose_b" + value { + b: false + } + } +} +node { + name: "lstm_3/split/split_dim" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_3/split" + op: "Split" + input: "lstm_3/split/split_dim" + input: "lstm_3/MatMul" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "num_split" + value { + i: 4 + } + } +} +node { + name: "lstm_3/Tanh" + op: "Tanh" + input: "lstm_3/split" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Sigmoid" + op: "Sigmoid" + input: "lstm_3/split:1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Sigmoid_1" + op: "Sigmoid" + input: "lstm_3/split:2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Sigmoid_2" + op: "Sigmoid" + input: "lstm_3/split:3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul" + op: "Mul" + input: "lstm_3/Sigmoid_1" + input: "lstm_2/add_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Minimum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_3/Minimum" + op: "Minimum" + input: "lstm_3/mul" + input: "lstm_3/Minimum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Maximum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_3/Maximum" + op: "Maximum" + input: "lstm_3/Minimum" + input: "lstm_3/Maximum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul_1" + op: "Mul" + input: "lstm_3/Sigmoid" + input: "lstm_3/Tanh" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Minimum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_3/Minimum_1" + op: "Minimum" + input: "lstm_3/mul_1" + input: "lstm_3/Minimum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Maximum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_3/Maximum_1" + op: "Maximum" + input: "lstm_3/Minimum_1" + input: "lstm_3/Maximum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/add" + op: "Add" + input: "lstm_3/Maximum" + input: "lstm_3/Maximum_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Minimum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_3/Minimum_2" + op: "Minimum" + input: "lstm_3/add" + input: "lstm_3/Minimum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Maximum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_3/Maximum_2" + op: "Maximum" + input: "lstm_3/Minimum_2" + input: "lstm_3/Maximum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul_2" + op: "Mul" + input: "lstm_3/Sigmoid_2" + input: "lstm_3/Maximum_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Minimum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_3/Minimum_3" + op: "Minimum" + input: "lstm_3/mul_2" + input: "lstm_3/Minimum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/Maximum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_3/Maximum_3" + op: "Maximum" + input: "lstm_3/Minimum_3" + input: "lstm_3/Maximum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul_3" + op: "Mul" + input: "lstm_2/add_1" + input: "inputs/pad_seq_3/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/sub/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_3/sub" + op: "Sub" + input: "lstm_3/sub/x" + input: "inputs/pad_seq_3/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul_4" + op: "Mul" + input: "lstm_3/Maximum_2" + input: "lstm_3/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/add_1" + op: "Add" + input: "lstm_3/mul_3" + input: "lstm_3/mul_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul_5" + op: "Mul" + input: "lstm_2/add_2" + input: "inputs/pad_seq_3/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/sub_1/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_3/sub_1" + op: "Sub" + input: "lstm_3/sub_1/x" + input: "inputs/pad_seq_3/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/mul_6" + op: "Mul" + input: "lstm_3/Maximum_3" + input: "lstm_3/sub_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/add_2" + op: "Add" + input: "lstm_3/mul_5" + input: "lstm_3/mul_6" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_3/out" + op: "Identity" + input: "lstm_3/add_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/concat/axis" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_4/concat" + op: "ConcatV2" + input: "inputs/x_seq_4/read" + input: "lstm_3/add_2" + input: "lstm_4/concat/axis" + device: "/device:GPU:*" + attr { + key: "N" + value { + i: 2 + } + } + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "Tidx" + value { + type: DT_INT32 + } + } +} +node { + name: "lstm_4/MatMul" + op: "MatMul" + input: "lstm_4/concat" + input: "weights/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "transpose_a" + value { + b: false + } + } + attr { + key: "transpose_b" + value { + b: false + } + } +} +node { + name: "lstm_4/split/split_dim" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_INT32 + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_INT32 + tensor_shape { + } + int_val: 1 + } + } + } +} +node { + name: "lstm_4/split" + op: "Split" + input: "lstm_4/split/split_dim" + input: "lstm_4/MatMul" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } + attr { + key: "num_split" + value { + i: 4 + } + } +} +node { + name: "lstm_4/Tanh" + op: "Tanh" + input: "lstm_4/split" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Sigmoid" + op: "Sigmoid" + input: "lstm_4/split:1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Sigmoid_1" + op: "Sigmoid" + input: "lstm_4/split:2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Sigmoid_2" + op: "Sigmoid" + input: "lstm_4/split:3" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul" + op: "Mul" + input: "lstm_4/Sigmoid_1" + input: "lstm_3/add_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Minimum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_4/Minimum" + op: "Minimum" + input: "lstm_4/mul" + input: "lstm_4/Minimum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Maximum/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_4/Maximum" + op: "Maximum" + input: "lstm_4/Minimum" + input: "lstm_4/Maximum/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul_1" + op: "Mul" + input: "lstm_4/Sigmoid" + input: "lstm_4/Tanh" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Minimum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_4/Minimum_1" + op: "Minimum" + input: "lstm_4/mul_1" + input: "lstm_4/Minimum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Maximum_1/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_4/Maximum_1" + op: "Maximum" + input: "lstm_4/Minimum_1" + input: "lstm_4/Maximum_1/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/add" + op: "Add" + input: "lstm_4/Maximum" + input: "lstm_4/Maximum_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Minimum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_4/Minimum_2" + op: "Minimum" + input: "lstm_4/add" + input: "lstm_4/Minimum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Maximum_2/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_4/Maximum_2" + op: "Maximum" + input: "lstm_4/Minimum_2" + input: "lstm_4/Maximum_2/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul_2" + op: "Mul" + input: "lstm_4/Sigmoid_2" + input: "lstm_4/Maximum_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Minimum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_4/Minimum_3" + op: "Minimum" + input: "lstm_4/mul_2" + input: "lstm_4/Minimum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/Maximum_3/y" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: -1.0 + } + } + } +} +node { + name: "lstm_4/Maximum_3" + op: "Maximum" + input: "lstm_4/Minimum_3" + input: "lstm_4/Maximum_3/y" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul_3" + op: "Mul" + input: "lstm_3/add_1" + input: "inputs/pad_seq_4/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/sub/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_4/sub" + op: "Sub" + input: "lstm_4/sub/x" + input: "inputs/pad_seq_4/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul_4" + op: "Mul" + input: "lstm_4/Maximum_2" + input: "lstm_4/sub" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/add_1" + op: "Add" + input: "lstm_4/mul_3" + input: "lstm_4/mul_4" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul_5" + op: "Mul" + input: "lstm_3/add_2" + input: "inputs/pad_seq_4/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/sub_1/x" + op: "Const" + device: "/device:GPU:*" + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + attr { + key: "value" + value { + tensor { + dtype: DT_FLOAT + tensor_shape { + } + float_val: 1.0 + } + } + } +} +node { + name: "lstm_4/sub_1" + op: "Sub" + input: "lstm_4/sub_1/x" + input: "inputs/pad_seq_4/read" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/mul_6" + op: "Mul" + input: "lstm_4/Maximum_3" + input: "lstm_4/sub_1" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/add_2" + op: "Add" + input: "lstm_4/mul_5" + input: "lstm_4/mul_6" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +node { + name: "lstm_4/out" + op: "Identity" + input: "lstm_4/add_2" + device: "/device:GPU:*" + attr { + key: "T" + value { + type: DT_FLOAT + } + } +} +versions { + producer: 19 +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_test.py new file mode 100644 index 0000000000000000000000000000000000000000..3dde220aaa724d2655edad47c417dca6753881a9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/lstm_test.py @@ -0,0 +1,328 @@ +# 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 the LSTM cell and layer.""" + +import argparse +import os +import sys + +import numpy as np + +from tensorflow.compiler.tests import lstm +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +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 gradients_impl +from tensorflow.python.ops import init_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +def _DumpGraph(graph, basename): + if FLAGS.dump_graph_dir: + name = os.path.join(FLAGS.dump_graph_dir, basename + '.pbtxt') + with open(name, 'w') as f: + f.write(str(graph.as_graph_def())) + + +def _Sigmoid(x): + return 1. / (1. + np.exp(-x)) + + +def _Clip(x): + return np.maximum(np.minimum(x, 1.), -1.) + + +class LSTMTest(test.TestCase): + + def setUp(self): + # The tests for a single LSTM cell and LSTM layer use these values as + # inputs. We always set the dimensionality of num_inputs=1; thus batch_size + # actually represents the different input cases. + self._inputs = np.array([[-1.], [-.5], [0.], [.5], [1.]], np.float32) + self._batch_size = len(self._inputs) + + def _NextC(self, inputs, weight, m_prev, c_prev): + """Returns the next c states of an LSTM cell.""" + x = (inputs + m_prev) * weight + return _Clip(_Clip(_Sigmoid(x) * c_prev) + _Clip(_Sigmoid(x) * np.tanh(x))) + + def _NextM(self, inputs, weight, m_prev, c_prev): + """Returns the next m states of an LSTM cell.""" + x = (inputs + m_prev) * weight + return _Clip(_Sigmoid(x) * self._NextC(inputs, weight, m_prev, c_prev)) + + def _RunLSTMCell(self, basename, init_weights, m_prev_scalar, c_prev_scalar, + pad_scalar): + with self.session() as sess: + num_inputs = 1 + num_nodes = 1 + + weights = init_weights(lstm.LSTMCellWeightsShape(num_inputs, num_nodes)) + m_prev = constant_op.constant([[m_prev_scalar]] * self._batch_size) + c_prev = constant_op.constant([[c_prev_scalar]] * self._batch_size) + x = constant_op.constant(self._inputs) + pad = constant_op.constant([[pad_scalar]] * self._batch_size) + + m, c = lstm.LSTMCell(weights, m_prev, c_prev, x, pad) + _DumpGraph(sess.graph, 'lstm_cell_%s_%d_%d_%d' % + (basename, m_prev_scalar, c_prev_scalar, pad_scalar)) + + # Initialize variables and run the unrolled LSTM step. + self.evaluate(variables.global_variables_initializer()) + return self.evaluate([m, c]) + + @test_util.run_without_tensor_float_32('TF32 capable devices fail the test' + ' due to reduced matmul precision') + def testLSTMCell(self): + # Run with all-0 weights, no padding. + m, c = self._RunLSTMCell('zeros', init_ops.zeros_initializer(), 0., 0., 0.) + self.assertAllClose(m, [[0.]] * self._batch_size) + self.assertAllClose(c, [[0.]] * self._batch_size) + m, c = self._RunLSTMCell('zeros', init_ops.zeros_initializer(), 0., 1., 0.) + self.assertAllClose(m, [[.25]] * self._batch_size) + self.assertAllClose(c, [[.5]] * self._batch_size) + m, c = self._RunLSTMCell('zeros', init_ops.zeros_initializer(), 1., 0., 0.) + self.assertAllClose(m, [[.0]] * self._batch_size) + self.assertAllClose(c, [[.0]] * self._batch_size) + m, c = self._RunLSTMCell('zeros', init_ops.zeros_initializer(), 1., 1., 0.) + self.assertAllClose(m, [[.25]] * self._batch_size) + self.assertAllClose(c, [[.5]] * self._batch_size) + + # Run with all-1 weights, no padding. + for m_prev in [0., 1.]: + for c_prev in [0., 1.]: + m, c = self._RunLSTMCell('ones', + init_ops.ones_initializer(), m_prev, c_prev, + 0.) + self.assertAllClose(m, self._NextM(self._inputs, 1., m_prev, c_prev)) + self.assertAllClose(c, self._NextC(self._inputs, 1., m_prev, c_prev)) + + # Run with random weights. + for weight in np.random.rand(3): + weight_tf = constant_op.constant(weight, dtypes.float32) + random_weight = lambda shape, w=weight_tf: array_ops.fill(shape, w) + + # No padding. + for m_prev in [0., 1.]: + for c_prev in [0., 1.]: + m, c = self._RunLSTMCell('random', random_weight, m_prev, c_prev, 0.) + self.assertAllClose(m, + self._NextM(self._inputs, weight, m_prev, c_prev)) + self.assertAllClose(c, + self._NextC(self._inputs, weight, m_prev, c_prev)) + + # Set padding. + for m_prev in [0., 1.]: + for c_prev in [0., 1.]: + m, c = self._RunLSTMCell('random', random_weight, m_prev, c_prev, 1.) + self.assertAllClose(m, [[m_prev]] * self._batch_size) + self.assertAllClose(c, [[c_prev]] * self._batch_size) + + def testLSTMLayerErrors(self): + num_inputs = 1 + num_nodes = 1 + seq_length = 3 + + weights = array_ops.zeros(lstm.LSTMCellWeightsShape(num_inputs, num_nodes)) + m = constant_op.constant([[0.]] * self._batch_size) + c = constant_op.constant([[0.]] * self._batch_size) + x_seq = [constant_op.constant(self._inputs)] * seq_length + pad = constant_op.constant([[0.]] * self._batch_size) + + with self.assertRaisesWithPredicateMatch(ValueError, 'length of x_seq'): + lstm.LSTMLayer('lstm', weights, m, c, x_seq, [pad]) + with self.assertRaisesWithPredicateMatch(ValueError, 'length of x_seq'): + lstm.LSTMLayer('lstm', weights, m, c, x_seq, [pad] * 2) + with self.assertRaisesWithPredicateMatch(ValueError, 'length of x_seq'): + lstm.LSTMLayer('lstm', weights, m, c, x_seq, [pad] * 4) + + def _RunLSTMLayer(self, basename, init_weights, m_init_scalar, c_init_scalar, + pad_scalar): + with self.session() as sess: + num_inputs = 1 + num_nodes = 1 + seq_length = 3 + + weights = init_weights(lstm.LSTMCellWeightsShape(num_inputs, num_nodes)) + m_init = constant_op.constant([[m_init_scalar]] * self._batch_size) + c_init = constant_op.constant([[c_init_scalar]] * self._batch_size) + x_seq = [constant_op.constant(self._inputs)] * seq_length + pad_seq = [constant_op.constant([[pad_scalar]] * self._batch_size) + ] * seq_length + + out_seq = lstm.LSTMLayer('lstm', weights, m_init, c_init, x_seq, pad_seq) + _DumpGraph(sess.graph, 'lstm_layer_%s_%d_%d_%d' % + (basename, m_init_scalar, c_init_scalar, pad_scalar)) + + # Initialize variables and run the unrolled LSTM layer. + self.evaluate(variables.global_variables_initializer()) + return self.evaluate(out_seq) + + @test_util.run_without_tensor_float_32('TF32 capable devices fail the test' + ' due to reduced matmul precision') + def testLSTMLayer(self): + # Run with all-0 weights, no padding. + o = self._RunLSTMLayer('zeros', init_ops.zeros_initializer(), 0., 0., 0.) + self.assertAllClose(o, [[[0.]] * self._batch_size] * 3) + o = self._RunLSTMLayer('zeros', init_ops.zeros_initializer(), 0., 1., 0.) + self.assertAllClose(o, [[[.25]] * self._batch_size, + [[.125]] * self._batch_size, + [[.0625]] * self._batch_size]) + o = self._RunLSTMLayer('zeros', init_ops.zeros_initializer(), 1., 0., 0.) + self.assertAllClose(o, [[[0.]] * self._batch_size] * 3) + o = self._RunLSTMLayer('zeros', init_ops.zeros_initializer(), 1., 1., 0.) + self.assertAllClose(o, [[[.25]] * self._batch_size, + [[.125]] * self._batch_size, + [[.0625]] * self._batch_size]) + + # Run with all-1 weights, no padding. + weight1 = 1. + for m_init in [0., 1.]: + for c_init in [0., 1.]: + o = self._RunLSTMLayer('ones', + init_ops.ones_initializer(), m_init, c_init, 0.) + m0 = self._NextM(self._inputs, weight1, m_init, c_init) + c0 = self._NextC(self._inputs, weight1, m_init, c_init) + self.assertAllClose(o[0], m0) + m1 = self._NextM(self._inputs, weight1, m0, c0) + c1 = self._NextC(self._inputs, weight1, m0, c0) + self.assertAllClose(o[1], m1) + m2 = self._NextM(self._inputs, weight1, m1, c1) + self.assertAllClose(o[2], m2) + + # Run with random weights. + for weight in np.random.rand(3): + weight_tf = constant_op.constant(weight, dtypes.float32) + random_weight = lambda shape, w=weight_tf: array_ops.fill(shape, w) + + # No padding. + for m_init in [0., 1.]: + for c_init in [0., 1.]: + o = self._RunLSTMLayer('random', random_weight, m_init, c_init, 0.) + m0 = self._NextM(self._inputs, weight, m_init, c_init) + c0 = self._NextC(self._inputs, weight, m_init, c_init) + self.assertAllClose(o[0], m0) + m1 = self._NextM(self._inputs, weight, m0, c0) + c1 = self._NextC(self._inputs, weight, m0, c0) + self.assertAllClose(o[1], m1) + m2 = self._NextM(self._inputs, weight, m1, c1) + self.assertAllClose(o[2], m2) + + # Set padding. + o = self._RunLSTMLayer('random', random_weight, 0., 0., 1.) + self.assertAllClose(o, [[[0.]] * self._batch_size] * 3) + o = self._RunLSTMLayer('random', random_weight, 0., 1., 1.) + self.assertAllClose(o, [[[0.]] * self._batch_size] * 3) + o = self._RunLSTMLayer('random', random_weight, 1., 0., 1.) + self.assertAllClose(o, [[[1.]] * self._batch_size] * 3) + o = self._RunLSTMLayer('random', random_weight, 1., 1., 1.) + self.assertAllClose(o, [[[1.]] * self._batch_size] * 3) + + +class LSTMBenchmark(test.Benchmark): + """Mcro-benchmarks for a single layer of LSTM cells.""" + + def _LayerBuilder(self, do_training): + out_seq, weights = lstm.BuildLSTMLayer(FLAGS.batch_size, FLAGS.seq_length, + FLAGS.num_inputs, FLAGS.num_nodes) + name, fetches = ('lstm_layer_inference', out_seq) + if do_training: + # Not a real loss function, but good enough for benchmarking backprop. + loss = math_ops.reduce_sum(math_ops.add_n(out_seq)) + dw = gradients_impl.gradients(loss, weights) + name, fetches = ('lstm_layer_training', dw) + + _DumpGraph(ops.get_default_graph(), + '%s_%d_%d_%d_%d' % (name, FLAGS.batch_size, FLAGS.seq_length, + FLAGS.num_inputs, FLAGS.num_nodes)) + return name, fetches + + def benchmarkLayerInference(self): + xla_test.Benchmark(self, lambda: self._LayerBuilder(False), False, + FLAGS.device) + + def benchmarkLayerInferenceXLA(self): + xla_test.Benchmark(self, lambda: self._LayerBuilder(False), True, + FLAGS.device) + + def benchmarkLayerTraining(self): + xla_test.Benchmark(self, lambda: self._LayerBuilder(True), False, + FLAGS.device) + + def benchmarkLayerTrainingXLA(self): + xla_test.Benchmark(self, lambda: self._LayerBuilder(True), True, + FLAGS.device) + + +if __name__ == '__main__': + parser = argparse.ArgumentParser() + parser.register('type', 'bool', lambda v: v.lower() == 'true') + parser.add_argument( + '--batch_size', + type=int, + default=128, + help="""\ + Inputs are fed in batches of this size, for both inference and training. + Larger values cause the matmul in each LSTM cell to have higher + dimensionality.\ + """ + ) + parser.add_argument( + '--seq_length', + type=int, + default=60, + help="""\ + Length of the unrolled sequence of LSTM cells in a layer.Larger values + cause more LSTM matmuls to be run.\ + """ + ) + parser.add_argument( + '--num_inputs', + type=int, + default=1024, + help='Dimension of inputs that are fed into each LSTM cell.' + ) + parser.add_argument( + '--num_nodes', + type=int, + default=1024, + help='Number of nodes in each LSTM cell.' + ) + parser.add_argument( + '--device', + type=str, + default='gpu', + help="""\ + TensorFlow device to assign ops to, e.g. "gpu", "cpu". For details see + documentation for tf.Graph.device.\ + """ + ) + parser.add_argument( + '--dump_graph_dir', + type=str, + default='', + help='If non-empty, dump graphs in *.pbtxt format to this directory.' + ) + global FLAGS # pylint:disable=global-at-module-level + FLAGS, unparsed = parser.parse_known_args() + # This test is using Tensorflow sessions which are not compatible with eager + # mode. + ops.disable_eager_execution() + test.main(argv=[sys.argv[0]] + unparsed) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/manip_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/manip_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..69d49f4136df27c33dfee80082342bdbe1e3fb9d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/manip_ops_test.py @@ -0,0 +1,64 @@ +# Copyright 2019 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. +# ============================================================================== +"""Test cases for manip ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import manip_ops +from tensorflow.python.platform import googletest + + +class ManipOpsTest(xla_test.XLATestCase): + """Test cases for manip ops.""" + + def _testRoll(self, a, shift, axis): + with self.session() as session: + with self.test_scope(): + p = array_ops.placeholder(dtypes.as_dtype(a.dtype), a.shape, name="a") + output = manip_ops.roll(a, shift, axis) + result = session.run(output, {p: a}) + self.assertAllEqual(result, np.roll(a, shift, axis)) + + def testNumericTypes(self): + for t in self.numeric_types: + self._testRoll(np.random.randint(-100, 100, (5)).astype(t), 3, 0) + self._testRoll( + np.random.randint(-100, 100, (4, 4, 3)).astype(t), [1, -6, 6], + [0, 1, 2]) + self._testRoll( + np.random.randint(-100, 100, (4, 2, 1, 3)).astype(t), [0, 1, -2], + [1, 2, 3]) + + def testFloatTypes(self): + for t in self.float_types: + self._testRoll(np.random.rand(5).astype(t), 2, 0) + self._testRoll(np.random.rand(3, 4).astype(t), [1, 2], [1, 0]) + self._testRoll(np.random.rand(1, 3, 4).astype(t), [1, 0, -3], [0, 1, 2]) + + def testComplexTypes(self): + for t in self.complex_types: + x = np.random.rand(4, 4).astype(t) + self._testRoll(x + 1j * x, 2, 0) + x = np.random.rand(2, 5).astype(t) + self._testRoll(x + 1j * x, [1, 2], [1, 0]) + x = np.random.rand(3, 2, 1, 1).astype(t) + self._testRoll(x + 1j * x, [2, 1, 1, 0], [0, 3, 1, 2]) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_band_part_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_band_part_test.py new file mode 100644 index 0000000000000000000000000000000000000000..45de7b2951a8544142683f43f0db5b56352cb7ef --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_band_part_test.py @@ -0,0 +1,195 @@ +# 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 absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +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 + + +class MatrixBandPartTest(xla_test.XLATestCase, parameterized.TestCase): + + @parameterized.parameters( + { + 'batch_shape': [], + 'rows': 1, + 'cols': 1 + }, + { + 'batch_shape': [], + 'rows': 1, + 'cols': 2 + }, + { + 'batch_shape': [], + 'rows': 1, + 'cols': 7 + }, + { + 'batch_shape': [], + 'rows': 2, + 'cols': 1 + }, + { + 'batch_shape': [], + 'rows': 2, + 'cols': 2 + }, + { + 'batch_shape': [], + 'rows': 2, + 'cols': 7 + }, + { + 'batch_shape': [], + 'rows': 7, + 'cols': 1 + }, + { + 'batch_shape': [], + 'rows': 7, + 'cols': 2 + }, + { + 'batch_shape': [], + 'rows': 7, + 'cols': 7 + }, + { + 'batch_shape': [2,], + 'rows': 1, + 'cols': 1 + }, + { + 'batch_shape': [2,], + 'rows': 1, + 'cols': 2 + }, + { + 'batch_shape': [2,], + 'rows': 1, + 'cols': 7 + }, + { + 'batch_shape': [2,], + 'rows': 2, + 'cols': 1 + }, + { + 'batch_shape': [2,], + 'rows': 2, + 'cols': 2 + }, + { + 'batch_shape': [2,], + 'rows': 2, + 'cols': 7 + }, + { + 'batch_shape': [2,], + 'rows': 7, + 'cols': 1 + }, + { + 'batch_shape': [2,], + 'rows': 7, + 'cols': 2 + }, + { + 'batch_shape': [2,], + 'rows': 7, + 'cols': 7 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 1, + 'cols': 1 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 1, + 'cols': 2 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 1, + 'cols': 7 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 2, + 'cols': 1 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 2, + 'cols': 2 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 2, + 'cols': 7 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 7, + 'cols': 1 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 7, + 'cols': 2 + }, + { + 'batch_shape': [1, 3, 2], + 'rows': 7, + 'cols': 7 + }, + ) + def testMatrixBandPart(self, batch_shape, rows, cols): + # TODO(b/125505881): Disabled due to LLVM backend crash. + if self.device == 'XLA_CPU' and cols == 7 and rows == 1 and batch_shape == [ + 1, 3, 2 + ]: + pass + for dtype in self.float_types: + with self.session(): + mat = np.ones(batch_shape + [rows, cols]).astype(dtype) + batch_mat = np.tile(mat, batch_shape + [1, 1]) + for lower in -1, 0, 1, rows - 1: + for upper in -1, 0, 1, cols - 1: + band_np = mat + if lower >= 0: + band_np = np.triu(band_np, -lower) + if upper >= 0: + band_np = np.tril(band_np, upper) + if batch_shape: + band_np = np.tile(band_np, batch_shape + [1, 1]) + + placeholder = array_ops.placeholder(dtype) + with self.test_scope(): + band = array_ops.matrix_band_part( + placeholder, constant_op.constant(lower, dtype=dtypes.int32), + constant_op.constant(upper, dtype=dtypes.int32)) + feed_dict = {placeholder: batch_mat} + self.assertAllEqual(band_np, band.eval(feed_dict=feed_dict)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_diag_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_diag_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..16e06e2ebcd0506cce747212e5ab0f95b71e946f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_diag_ops_test.py @@ -0,0 +1,772 @@ +# Copyright 2019 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 XLA matrix diag ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.platform import googletest + +default_v2_alignment = "LEFT_LEFT" +alignment_list = ["RIGHT_LEFT", "LEFT_RIGHT"] + + +def zip_to_first_list_length(a, b): + if len(b) > len(a): + return zip(a, b[:len(a)]) + return zip(a, b + [None] * (len(a) - len(b))) + + +# Routines to convert test cases to have diagonals in a specified alignment. +# Copied from //third_party/tensorflow/python/kernel_tests/array_ops/ +# diag_op_test.py +def repack_diagonals(packed_diagonals, + diag_index, + num_rows, + num_cols, + align=None): + # The original test cases are LEFT_LEFT aligned. + if align == default_v2_alignment or align is None: + return packed_diagonals + + align = align.split("_") + d_lower, d_upper = diag_index + batch_dims = packed_diagonals.ndim - (2 if d_lower < d_upper else 1) + max_diag_len = packed_diagonals.shape[-1] + index = (slice(None),) * batch_dims + repacked_diagonals = np.zeros_like(packed_diagonals) + + # Aligns each diagonal row-by-row. + for diag_index in range(d_lower, d_upper + 1): + diag_len = min(num_rows + min(0, diag_index), num_cols - max(0, diag_index)) + row_index = d_upper - diag_index + padding_len = max_diag_len - diag_len + left_align = (diag_index >= 0 and + align[0] == "LEFT") or (diag_index <= 0 and + align[1] == "LEFT") + # Prepares index tuples. + extra_dim = tuple() if d_lower == d_upper else (row_index,) + packed_last_dim = (slice(None),) if left_align else (slice(0, diag_len, 1),) + repacked_last_dim = (slice(None),) if left_align else (slice( + padding_len, max_diag_len, 1),) + packed_index = index + extra_dim + packed_last_dim + repacked_index = index + extra_dim + repacked_last_dim + + # Repacks the diagonal. + repacked_diagonals[repacked_index] = packed_diagonals[packed_index] + return repacked_diagonals + + +def repack_diagonals_in_tests(tests, align=None): + # The original test cases are LEFT_LEFT aligned. + if align == default_v2_alignment or align is None: + return tests + + new_tests = dict() + # Loops through each case. + for diag_index, (packed_diagonals, padded_diagonals) in tests.items(): + num_rows, num_cols = padded_diagonals.shape[-2:] + repacked_diagonals = repack_diagonals( + packed_diagonals, diag_index, num_rows, num_cols, align=align) + new_tests[diag_index] = (repacked_diagonals, padded_diagonals) + + return new_tests + + +# Test cases shared by MatrixDiagV2, MatrixDiagPartV2, and MatrixSetDiagV2. +# Copied from //third_party/tensorflow/python/kernel_tests/array_ops/ +# diag_op_test.py +def square_cases(align=None): + # pyformat: disable + mat = np.array([[[1, 2, 3, 4, 5], + [6, 7, 8, 9, 1], + [3, 4, 5, 6, 7], + [8, 9, 1, 2, 3], + [4, 5, 6, 7, 8]], + [[9, 1, 2, 3, 4], + [5, 6, 7, 8, 9], + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 1], + [2, 3, 4, 5, 6]]]) + tests = dict() + # tests[d_lower, d_upper] = (compact_diagonals, padded_diagonals) + tests[-1, -1] = (np.array([[6, 4, 1, 7], + [5, 2, 8, 5]]), + np.array([[[0, 0, 0, 0, 0], + [6, 0, 0, 0, 0], + [0, 4, 0, 0, 0], + [0, 0, 1, 0, 0], + [0, 0, 0, 7, 0]], + [[0, 0, 0, 0, 0], + [5, 0, 0, 0, 0], + [0, 2, 0, 0, 0], + [0, 0, 8, 0, 0], + [0, 0, 0, 5, 0]]])) + tests[-4, -3] = (np.array([[[8, 5], + [4, 0]], + [[6, 3], + [2, 0]]]), + np.array([[[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [8, 0, 0, 0, 0], + [4, 5, 0, 0, 0]], + [[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [6, 0, 0, 0, 0], + [2, 3, 0, 0, 0]]])) + tests[-2, 1] = (np.array([[[2, 8, 6, 3, 0], + [1, 7, 5, 2, 8], + [6, 4, 1, 7, 0], + [3, 9, 6, 0, 0]], + [[1, 7, 4, 1, 0], + [9, 6, 3, 9, 6], + [5, 2, 8, 5, 0], + [1, 7, 4, 0, 0]]]), + np.array([[[1, 2, 0, 0, 0], + [6, 7, 8, 0, 0], + [3, 4, 5, 6, 0], + [0, 9, 1, 2, 3], + [0, 0, 6, 7, 8]], + [[9, 1, 0, 0, 0], + [5, 6, 7, 0, 0], + [1, 2, 3, 4, 0], + [0, 7, 8, 9, 1], + [0, 0, 4, 5, 6]]])) + tests[2, 4] = (np.array([[[5, 0, 0], + [4, 1, 0], + [3, 9, 7]], + [[4, 0, 0], + [3, 9, 0], + [2, 8, 5]]]), + np.array([[[0, 0, 3, 4, 5], + [0, 0, 0, 9, 1], + [0, 0, 0, 0, 7], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]], + [[0, 0, 2, 3, 4], + [0, 0, 0, 8, 9], + [0, 0, 0, 0, 5], + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0]]])) + # pyformat: enable + return (mat, repack_diagonals_in_tests(tests, align)) + + +def tall_cases(align=None): + # pyformat: disable + mat = np.array([[[1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [9, 8, 7], + [6, 5, 4]], + [[3, 2, 1], + [1, 2, 3], + [4, 5, 6], + [7, 8, 9], + [9, 8, 7]]]) + tests = dict() + # tests[d_lower, d_upper] = (compact_diagonals, padded_diagonals) + tests[0, 0] = (np.array([[1, 5, 9], + [3, 2, 6]]), + np.array([[[1, 0, 0], + [0, 5, 0], + [0, 0, 9], + [0, 0, 0]], + [[3, 0, 0], + [0, 2, 0], + [0, 0, 6], + [0, 0, 0]]])) + tests[-4, -3] = (np.array([[[9, 5], + [6, 0]], + [[7, 8], + [9, 0]]]), + np.array([[[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [9, 0, 0], + [6, 5, 0]], + [[0, 0, 0], + [0, 0, 0], + [0, 0, 0], + [7, 0, 0], + [9, 8, 0]]])) + tests[-2, -1] = (np.array([[[4, 8, 7], + [7, 8, 4]], + [[1, 5, 9], + [4, 8, 7]]]), + np.array([[[0, 0, 0], + [4, 0, 0], + [7, 8, 0], + [0, 8, 7], + [0, 0, 4]], + [[0, 0, 0], + [1, 0, 0], + [4, 5, 0], + [0, 8, 9], + [0, 0, 7]]])) + tests[-2, 1] = (np.array([[[2, 6, 0], + [1, 5, 9], + [4, 8, 7], + [7, 8, 4]], + [[2, 3, 0], + [3, 2, 6], + [1, 5, 9], + [4, 8, 7]]]), + np.array([[[1, 2, 0], + [4, 5, 6], + [7, 8, 9], + [0, 8, 7], + [0, 0, 4]], + [[3, 2, 0], + [1, 2, 3], + [4, 5, 6], + [0, 8, 9], + [0, 0, 7]]])) + tests[1, 2] = (np.array([[[3, 0], + [2, 6]], + [[1, 0], + [2, 3]]]), + np.array([[[0, 2, 3], + [0, 0, 6], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]], + [[0, 2, 1], + [0, 0, 3], + [0, 0, 0], + [0, 0, 0], + [0, 0, 0]]])) + # pyformat: enable + return (mat, repack_diagonals_in_tests(tests, align)) + + +def fat_cases(align=None): + # pyformat: disable + mat = np.array([[[1, 2, 3, 4], + [5, 6, 7, 8], + [9, 1, 2, 3]], + [[4, 5, 6, 7], + [8, 9, 1, 2], + [3, 4, 5, 6]]]) + tests = dict() + # tests[d_lower, d_upper] = (compact_diagonals, padded_diagonals) + tests[0, 0] = (np.array([[1, 6, 2], + [4, 9, 5]]), + np.array([[[1, 0, 0, 0], + [0, 6, 0, 0], + [0, 0, 2, 0]], + [[4, 0, 0, 0], + [0, 9, 0, 0], + [0, 0, 5, 0]]])) + tests[2, 2] = (np.array([[3, 8], + [6, 2]]), + np.array([[[0, 0, 3, 0], + [0, 0, 0, 8], + [0, 0, 0, 0]], + [[0, 0, 6, 0], + [0, 0, 0, 2], + [0, 0, 0, 0]]])) + tests[-2, 0] = (np.array([[[1, 6, 2], + [5, 1, 0], + [9, 0, 0]], + [[4, 9, 5], + [8, 4, 0], + [3, 0, 0]]]), + np.array([[[1, 0, 0, 0], + [5, 6, 0, 0], + [9, 1, 2, 0]], + [[4, 0, 0, 0], + [8, 9, 0, 0], + [3, 4, 5, 0]]])) + tests[-1, 1] = (np.array([[[2, 7, 3], + [1, 6, 2], + [5, 1, 0]], + [[5, 1, 6], + [4, 9, 5], + [8, 4, 0]]]), + np.array([[[1, 2, 0, 0], + [5, 6, 7, 0], + [0, 1, 2, 3]], + [[4, 5, 0, 0], + [8, 9, 1, 0], + [0, 4, 5, 6]]])) + tests[0, 3] = (np.array([[[4, 0, 0], + [3, 8, 0], + [2, 7, 3], + [1, 6, 2]], + [[7, 0, 0], + [6, 2, 0], + [5, 1, 6], + [4, 9, 5]]]), + np.array([[[1, 2, 3, 4], + [0, 6, 7, 8], + [0, 0, 2, 3]], + [[4, 5, 6, 7], + [0, 9, 1, 2], + [0, 0, 5, 6]]])) + # pyformat: enable + return (mat, repack_diagonals_in_tests(tests, align)) + + +def all_tests(align=None): + return [square_cases(align), tall_cases(align), fat_cases(align)] + + +class MatrixDiagTest(xla_test.XLATestCase): + + def _assertOpOutputMatchesExpected(self, + params, + solution, + high_level=True, + rtol=1e-3, + atol=1e-5): + """Verifies that matrix_diag produces `solution` when fed `params`. + + Args: + params: dictionary containing input parameters to matrix_diag. + solution: numpy array representing the expected output of matrix_diag. + high_level: call high_level matrix_diag + rtol: relative tolerance for equality test. + atol: absolute tolerance for equality test. + """ + diagonal = params["diagonal"] + with self.session() as session: + for dtype in self.numeric_types - {np.int8, np.uint8}: + expected = solution.astype(dtype) + with self.test_scope(): + params["diagonal"] = array_ops.placeholder( + dtype, diagonal.shape, name="diagonal") + if high_level: + # wraps gen_array_ops.matrix_diag_v3 + output = array_ops.matrix_diag(**params) + else: + # TODO(b/201086188): Remove this case once MatrixDiag V1 is removed. + output = gen_array_ops.matrix_diag(**params) + result = session.run(output, + {params["diagonal"]: diagonal.astype(dtype)}) + self.assertEqual(output.dtype, expected.dtype) + self.assertAllCloseAccordingToType( + expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03) + + # Generic tests applicable to both v1 and v2 ops. + # Originally from unary_ops_tests.py. + def _testV1Level(self, high_level): + # pyformat: disable + vecs1 = np.array([[1, 2], + [3, 4]]) + solution1 = np.array([[[1, 0], [0, 2]], + [[3, 0], [0, 4]]]) + vecs2 = np.array([1, 2, 3, 4]) + solution2 = np.array([[1, 0, 0, 0], + [0, 2, 0, 0], + [0, 0, 3, 0], + [0, 0, 0, 4]]) + vecs3 = np.array([[[1, 2, 3], + [4, 5, 6]], + [[7, 8, 9], # pylint: disable=bad-whitespace + [10, 11, 12]]]) + solution3 = np.array([[[[1, 0, 0], + [0, 2, 0], + [0, 0, 3]], + [[4, 0, 0], + [0, 5, 0], + [0, 0, 6]]], + [[[7, 0, 0], + [0, 8, 0], + [0, 0, 9]], + [[10, 0, 0], + [0, 11, 0], + [0, 0, 12]]]]) + # pyformat: enable + self._assertOpOutputMatchesExpected({"diagonal": vecs1}, solution1, + high_level) + self._assertOpOutputMatchesExpected({"diagonal": vecs2}, solution2, + high_level) + self._assertOpOutputMatchesExpected({"diagonal": vecs3}, solution3, + high_level) + + def testV1(self): + self._testV1Level(True) + + def testV1LowLevel(self): + self._testV1Level(False) + + # From here onwards are v2-only tests. + def testSquare(self): + for align in alignment_list: + for _, tests in [square_cases(align)]: + for diag_index, (vecs, solution) in tests.items(): + params = {"diagonal": vecs[0], "k": diag_index, "align": align} + self._assertOpOutputMatchesExpected(params, solution[0]) + + def testSquareBatch(self): + for align in alignment_list: + for _, tests in [square_cases(align)]: + for diag_index, (vecs, solution) in tests.items(): + params = {"diagonal": vecs, "k": diag_index, "align": align} + self._assertOpOutputMatchesExpected(params, solution) + + def testRectangularBatch(self): + # Stores expected num_rows and num_cols (when the other is given). + # expected[(d_lower, d_upper)] = (expected_num_rows, expected_num_cols) + test_list = list() + + # Do not align the test cases here. Re-alignment needs to happen after the + # solution shape is updated. + # Square cases: + expected = { + (-1, -1): (5, 4), + (-4, -3): (5, 2), + (-2, 1): (5, 5), + (2, 4): (3, 5), + } + test_list.append((expected, square_cases())) + + # Tall cases + expected = { + (0, 0): (3, 3), + (-4, -3): (5, 2), + (-2, -1): (4, 3), + (-2, 1): (3, 3), + (1, 2): (2, 3) + } + test_list.append((expected, tall_cases())) + + # Fat cases + expected = { + (2, 2): (2, 4), + (-2, 0): (3, 3), + (-1, 1): (3, 3), + (0, 3): (3, 3) + } + test_list.append((expected, fat_cases())) + + # Giving both num_rows and num_cols + align = alignment_list[0] + for _, tests in [tall_cases(align), fat_cases(align)]: + for diag_index, (vecs, solution) in tests.items(): + self._assertOpOutputMatchesExpected( + { + "diagonal": vecs, + "k": diag_index, + "num_rows": solution.shape[-2], + "num_cols": solution.shape[-1], + "align": align + }, solution) + + # We go through each alignment in a round-robin manner. + align_index = 0 + + # Giving just num_rows or num_cols. + for expected, (_, tests) in test_list: + for diag_index, (new_num_rows, new_num_cols) in expected.items(): + align = alignment_list[align_index] + align_index = (align_index + 1) % len(alignment_list) + vecs, solution = tests[diag_index] + solution_given_num_rows = solution.take( + indices=range(new_num_cols), axis=-1) + # Repacks the diagonal input according to the new solution shape. + vecs_given_num_rows = repack_diagonals( + vecs, + diag_index, + solution_given_num_rows.shape[-2], + new_num_cols, + align=align) + self._assertOpOutputMatchesExpected( + { + "diagonal": vecs_given_num_rows, + "k": diag_index, + "num_rows": solution_given_num_rows.shape[-2], + "align": align + }, solution_given_num_rows) + solution_given_num_cols = solution.take( + indices=range(new_num_rows), axis=-2) + # Repacks the diagonal input according to the new solution shape. + vecs_given_num_cols = repack_diagonals( + vecs, + diag_index, + new_num_rows, + solution_given_num_cols.shape[-1], + align=align) + self._assertOpOutputMatchesExpected( + { + "diagonal": vecs_given_num_cols, + "k": diag_index, + "num_cols": solution_given_num_cols.shape[-1], + "align": align + }, solution_given_num_cols) + + def testPadding(self): + for padding_value, align in zip_to_first_list_length([555, -11], + alignment_list): + for _, tests in all_tests(align): + for diag_index, (vecs, solution) in tests.items(): + mask = (solution == 0) + solution = solution + (mask * padding_value) + self._assertOpOutputMatchesExpected( + { + "diagonal": vecs, + "k": diag_index, + "num_rows": solution.shape[-2], + "num_cols": solution.shape[-1], + "padding_value": padding_value, + "align": align + }, solution) + + +class MatrixSetDiagTest(xla_test.XLATestCase): + + def _assertOpOutputMatchesExpected(self, + params, + solution, + high_level=True, + rtol=1e-3, + atol=1e-5): + """Verifies that matrix_set_diag produces `solution` when fed `params`. + + Args: + params: dictionary containing input parameters to matrix_set_diag. + solution: numpy array representing the expected output of matrix_set_diag. + high_level: call high_level matrix_set_diag + rtol: relative tolerance for equality test. + atol: absolute tolerance for equality test. + """ + input = params["input"] # pylint: disable=redefined-builtin + diagonal = params["diagonal"] + with self.session() as session: + for dtype in self.numeric_types - {np.int8, np.uint8}: + expected = solution.astype(dtype) + with self.test_scope(): + params["input"] = array_ops.placeholder( + dtype, input.shape, name="input") + params["diagonal"] = array_ops.placeholder( + dtype, diagonal.shape, name="diagonal") + if high_level: + # wraps gen_array_ops.matrix_set_diag_v3 + output = array_ops.matrix_set_diag(**params) + else: + # TODO(b/201086188): Remove this case once MatrixDiag V1 is removed. + output = gen_array_ops.matrix_set_diag(**params) + result = session.run( + output, { + params["input"]: input.astype(dtype), + params["diagonal"]: diagonal.astype(dtype) + }) + self.assertEqual(output.dtype, expected.dtype) + self.assertAllCloseAccordingToType( + expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03) + + # Generic tests applicable to both v1 and v2 ops. + # Originally from binary_ops_tests.py. + def _testV1Level(self, high_level): + test_cases = list() + + # pyformat: disable + # pylint: disable=bad-whitespace + # Square cases. + input = np.array([[0, 1, 0], # pylint: disable=redefined-builtin + [1, 0, 1], + [1, 1, 1]]) + diag = np.array([1, 2, 3]) + solution = np.array([[1, 1, 0], + [1, 2, 1], + [1, 1, 3]]) + test_cases.append(({"input": input, "diagonal": diag}, solution)) + + input = np.array([[[1, 0, 3], + [0, 2, 0], + [1, 0, 3]], + [[4, 0, 4], + [0, 5, 0], + [2, 0, 6]]]) + diag = np.array([[-1, 0, -3], + [-4, -5, -6]]) + solution = np.array([[[-1, 0, 3], + [ 0, 0, 0], + [ 1, 0, -3]], + [[-4, 0, 4], + [ 0, -5, 0], + [ 2, 0, -6]]]) + test_cases.append(({"input": input, "diagonal": diag}, solution)) + + # Rectangular cases. + input = np.array([[0, 1, 0], + [1, 0, 1]]) + diag = np.array([3, 4]) + solution = np.array([[3, 1, 0], + [1, 4, 1]]) + test_cases.append(({"input": input, "diagonal": diag}, solution)) + + input = np.array([[0, 1], + [1, 0], + [1, 1]]) + diag = np.array([3, 4]) + solution = np.array([[3, 1], + [1, 4], + [1, 1]]) + test_cases.append(({"input": input, "diagonal": diag}, solution)) + + input = np.array([[[1, 0, 3], + [0, 2, 0]], + [[4, 0, 4], + [0, 5, 0]]]) + diag = np.array([[-1, -2], [-4, -5]]) + solution = np.array([[[-1, 0, 3], + [ 0, -2, 0]], + [[-4, 0, 4], + [ 0, -5, 0]]]) + test_cases.append(({"input": input, "diagonal": diag}, solution)) + # pylint: enable=bad-whitespace + # pyformat: enable + + for test in test_cases: + self._assertOpOutputMatchesExpected(test[0], test[1], high_level) + + def testV1(self): + self._testV1Level(True) + + def testV1LowLevel(self): + self._testV1Level(False) + + # From here onwards are v2-only tests. + def testSingleMatrix(self): + for align in alignment_list: + for _, tests in all_tests(align): + for diag_index, (vecs, banded_mat) in tests.items(): + mask = (banded_mat[0] == 0) + input_mat = np.random.randint(10, size=mask.shape) + solution = input_mat * mask + banded_mat[0] + self._assertOpOutputMatchesExpected( + { + "input": input_mat, + "diagonal": vecs[0], + "k": diag_index, + "align": align + }, solution) + + def testBatch(self): + for align in alignment_list: + for _, tests in all_tests(align): + for diag_index, (vecs, banded_mat) in tests.items(): + mask = (banded_mat == 0) + input_mat = np.random.randint(10, size=mask.shape) + solution = input_mat * mask + banded_mat + self._assertOpOutputMatchesExpected( + { + "input": input_mat, + "diagonal": vecs, + "k": diag_index, + "align": align + }, solution) + + +class MatrixDiagPartTest(xla_test.XLATestCase): + + def _assertOpOutputMatchesExpected(self, + params, + solution, + high_level=True, + rtol=1e-3, + atol=1e-5): + """Verifies that matrix_diag_part produces `solution` when fed `params`. + + Args: + params: dictionary containing input parameters to matrix_diag_part. + solution: numpy array representing the expected output. + high_level: call high_level matrix_set_diag + rtol: relative tolerance for equality test. + atol: absolute tolerance for equality test. + """ + input = params["input"] # pylint: disable=redefined-builtin + with self.session() as session: + for dtype in self.numeric_types - {np.int8, np.uint8}: + expected = solution.astype(dtype) + with self.test_scope(): + params["input"] = array_ops.placeholder( + dtype, input.shape, name="input") + if high_level: + # wraps gen_array_ops.matrix_diag_part_v3 + output = array_ops.matrix_diag_part(**params) + else: + # TODO(b/201086188): Remove this case once MatrixDiag V1 is removed. + output = gen_array_ops.matrix_diag_part(**params) + output = array_ops.matrix_diag_part(**params) + result = session.run(output, { + params["input"]: input.astype(dtype), + }) + self.assertEqual(output.dtype, expected.dtype) + self.assertAllCloseAccordingToType( + expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03) + + # Generic tests applicable to both v1 and v2 ops. + # Originally from unary_ops_tests.py. + def _testV1Level(self, high_level): + matrices = np.arange(3 * 2 * 4).reshape([3, 2, 4]) + solution = np.array([[0, 5], [8, 13], [16, 21]]) + self._assertOpOutputMatchesExpected({"input": matrices}, solution, + high_level) + + def testV1(self): + self._testV1Level(True) + + def testV1LowLevel(self): + self._testV1Level(False) + + # From here onwards are v2-only tests. + def testSingleMatrix(self): + for align in alignment_list: + test_list = [square_cases(align), tall_cases(align), fat_cases(align)] + for mat, tests in test_list: + for diag_index, (solution, _) in tests.items(): + self._assertOpOutputMatchesExpected( + { + "input": mat[0], + "k": diag_index, + "align": align + }, solution[0]) + + def testBatch(self): + for align in alignment_list: + for mat, tests in all_tests(align): + for diag_index, (solution, _) in tests.items(): + self._assertOpOutputMatchesExpected( + { + "input": mat, + "k": diag_index, + "align": align + }, solution) + + def testPadding(self): + for padding_value, align in zip_to_first_list_length([555, -11], + alignment_list): + for mat, tests in all_tests(align): + for diag_index, (solution, _) in tests.items(): + mask = (solution == 0) + solution = solution + (mask * padding_value) + self._assertOpOutputMatchesExpected( + { + "input": mat, + "k": diag_index, + "padding_value": padding_value, + "align": align + }, solution) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_inverse_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_inverse_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c4e8c355cc56b62f9629c5229ca5543437311513 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_inverse_op_test.py @@ -0,0 +1,82 @@ +# 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.math_ops.matrix_inverse.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class InverseOpTest(xla_test.XLATestCase): + + def _verifyInverse(self, x, np_type): + for adjoint in False, True: + y = x.astype(np_type) + with self.session() as sess: + # Verify that x^{-1} * x == Identity matrix. + p = array_ops.placeholder(dtypes.as_dtype(y.dtype), y.shape, name="x") + with self.test_scope(): + inv = linalg_ops.matrix_inverse(p, adjoint=adjoint) + tf_ans = math_ops.matmul(inv, p, adjoint_b=adjoint) + np_ans = np.identity(y.shape[-1]) + if x.ndim > 2: + tiling = list(y.shape) + tiling[-2:] = [1, 1] + np_ans = np.tile(np_ans, tiling) + out = sess.run(tf_ans, feed_dict={p: y}) + self.assertAllClose(np_ans, out, rtol=1e-3, atol=1e-3) + self.assertShapeEqual(y, tf_ans) + + def _verifyInverseReal(self, x): + for np_type in self.float_types & {np.float64, np.float32}: + self._verifyInverse(x, np_type) + + def _makeBatch(self, matrix1, matrix2): + matrix_batch = np.concatenate( + [np.expand_dims(matrix1, 0), + np.expand_dims(matrix2, 0)]) + matrix_batch = np.tile(matrix_batch, [2, 3, 1, 1]) + return matrix_batch + + def testNonsymmetric(self): + # 2x2 matrices + matrix1 = np.array([[1., 2.], [3., 4.]]) + matrix2 = np.array([[1., 3.], [3., 5.]]) + self._verifyInverseReal(matrix1) + self._verifyInverseReal(matrix2) + # A multidimensional batch of 2x2 matrices + self._verifyInverseReal(self._makeBatch(matrix1, matrix2)) + + def testSymmetricPositiveDefinite(self): + # 2x2 matrices + matrix1 = np.array([[2., 1.], [1., 2.]]) + matrix2 = np.array([[3., -1.], [-1., 3.]]) + self._verifyInverseReal(matrix1) + self._verifyInverseReal(matrix2) + # A multidimensional batch of 2x2 matrices + self._verifyInverseReal(self._makeBatch(matrix1, matrix2)) + + def testEmpty(self): + self._verifyInverseReal(np.empty([0, 2, 2])) + self._verifyInverseReal(np.empty([2, 0, 0])) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_solve_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_solve_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6a78ee6e15cc9b74a15e9fe9cb15651f8e2034b4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_solve_op_test.py @@ -0,0 +1,81 @@ +# 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 XLA implementation of tf.linalg.solve.""" + +import os + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.platform import googletest +from tensorflow.python.platform import sysconfig + +class MatrixSolveOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def _verifySolve(self, x, y, adjoint): + for np_type in self.float_types & {np.float32, np.float64}: + tol = 1e-4 if np_type == np.float32 else 1e-12 + a = x.astype(np_type) + b = y.astype(np_type) + np_ans = np.linalg.solve(np.swapaxes(a, -2, -1) if adjoint else a, b) + with self.session() as sess: + with self.test_scope(): + tf_ans = linalg_ops.matrix_solve(a, b, adjoint=adjoint) + out = sess.run(tf_ans) + self.assertEqual(tf_ans.shape, out.shape) + self.assertEqual(np_ans.shape, out.shape) + self.assertAllClose(np_ans, out, atol=tol, rtol=tol) + + @parameterized.named_parameters( + ("Scalar", 1, 1, [], [], False), + ("Vector", 5, 1, [], [], False), + ("MultipleRHS", 5, 4, [], [], False), + ("Adjoint", 5, 4, [], [], True), + ("BatchedScalar", 1, 4, [2], [2], False), + ("BatchedVector", 5, 4, [2], [2], False), + ("BatchedRank2", 5, 4, [7, 4], [7, 4], False), + ("BatchedAdjoint", 5, 4, [7, 4], [7, 4], True), + ) + def testSolve(self, n, nrhs, batch_dims, rhs_batch_dims, adjoint): + matrix = np.random.normal(-5.0, 5.0, batch_dims + [n, n]) + rhs = np.random.normal(-5.0, 5.0, rhs_batch_dims + [n, nrhs]) + self._verifySolve(matrix, rhs, adjoint=adjoint) + + @parameterized.named_parameters( + ("Simple", False), + ("Adjoint", True), + ) + def testConcurrent(self, adjoint): + with self.session() as sess: + lhs1 = random_ops.random_normal([3, 3], seed=42) + lhs2 = random_ops.random_normal([3, 3], seed=42) + rhs1 = random_ops.random_normal([3, 3], seed=42) + rhs2 = random_ops.random_normal([3, 3], seed=42) + with self.test_scope(): + s1 = linalg_ops.matrix_solve(lhs1, rhs1, adjoint=adjoint) + s2 = linalg_ops.matrix_solve(lhs2, rhs2, adjoint=adjoint) + self.assertAllEqual(*sess.run([s1, s2])) + + +if __name__ == "__main__": + sys_details = sysconfig.get_build_info() + if sys_details["is_cuda_build"]: + os.environ["XLA_FLAGS"] = ( + "--xla_gpu_enable_cublaslt=true " + os.environ.get("XLA_FLAGS", "") + ) + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_triangular_solve_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_triangular_solve_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..9a4a4559fb9f89743062ef23a766eb1339ed3c95 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/matrix_triangular_solve_op_test.py @@ -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. +# ============================================================================== +"""Tests for tensorflow.ops.tf.MatrixTriangularSolve.""" + +import itertools + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.platform import test + + +def MakePlaceholder(x, dtype=None): + return array_ops.placeholder( + dtypes.as_dtype(x.dtype) if dtype is None else dtype, shape=x.shape) + + +class MatrixTriangularSolveOpTest(xla_test.XLATestCase): + + # MatrixTriangularSolve defined for float64, float32, complex64, complex128 + # (https://www.tensorflow.org/api_docs/python/tf/matrix_triangular_solve) + @property + def float_types(self): + return set(super(MatrixTriangularSolveOpTest, + self).float_types).intersection( + (np.float64, np.float32, np.complex64, np.complex128)) + + def _VerifyTriangularSolveBase(self, sess, placeholder_a, placeholder_ca, + placeholder_b, a, clean_a, b, verification, + atol): + feed_dict = {placeholder_a: a, placeholder_ca: clean_a, placeholder_b: b} + verification_np = sess.run(verification, feed_dict) + broadcasted_shape = a.shape[:-2] + (b.shape[-2], b.shape[-1]) + broadcasted_b = b + np.zeros(shape=broadcasted_shape, dtype=b.dtype) + self.assertAllClose(broadcasted_b, verification_np, atol=atol) + + def _VerifyTriangularSolve(self, a, b, lower, adjoint, atol, dtype=None): + clean_a = np.tril(a) if lower else np.triu(a) + with self.session() as sess: + placeholder_a = MakePlaceholder(a, dtype) + placeholder_ca = MakePlaceholder(clean_a, dtype) + placeholder_b = MakePlaceholder(b, dtype) + with self.test_scope(): + x = linalg_ops.matrix_triangular_solve( + placeholder_a, placeholder_b, lower=lower, adjoint=adjoint) + verification = test_util.matmul_without_tf32( + placeholder_ca, x, adjoint_a=adjoint) + self._VerifyTriangularSolveBase(sess, placeholder_a, placeholder_ca, + placeholder_b, a, clean_a, b, + verification, atol) + + def _VerifyTriangularSolveCombo(self, a, b, atol=1e-4, dtype=None): + transp = lambda x: np.swapaxes(x, -1, -2) + for lower, adjoint in itertools.product([True, False], repeat=2): + self._VerifyTriangularSolve( + a if lower else transp(a), b, lower, adjoint, atol, dtype=dtype) + + def testBasic(self): + rng = np.random.RandomState(0) + a = np.tril(rng.randn(5, 5)) + b = rng.randn(5, 7) + for dtype in self.float_types: + self._VerifyTriangularSolveCombo(a.astype(dtype), b.astype(dtype)) + + def testBfloat16(self): + rng = np.random.RandomState(0) + a = np.tril(rng.randn(5, 5)) + b = rng.randn(5, 7) + self._VerifyTriangularSolveCombo(a, b, atol=5e-2, dtype=dtypes.bfloat16) + + def testBasicNotActuallyTriangular(self): + rng = np.random.RandomState(0) + a = rng.randn(5, 5) # the `a` matrix is not lower-triangular + b = rng.randn(5, 7) + for dtype in self.float_types: + self._VerifyTriangularSolveCombo(a.astype(dtype), b.astype(dtype)) + + def testBasicComplexDtypes(self): + + if xla_test.test.is_built_with_rocm(): + # The following subtest invokes the call to "BlasTrsm" + # That operation is currently not supported on the ROCm platform + self.skipTest("BlasTrsm op for complex types is not supported in ROCm") + + rng = np.random.RandomState(0) + a = np.tril(rng.randn(5, 5) + rng.randn(5, 5) * 1j) + b = rng.randn(5, 7) + rng.randn(5, 7) * 1j + for dtype in self.complex_types: + self._VerifyTriangularSolveCombo(a.astype(dtype), b.astype(dtype)) + + def testBatch(self): + rng = np.random.RandomState(0) + shapes = [((4, 3, 3), (4, 3, 5)), ((1, 2, 2), (1, 2, 1)), + ((1, 1, 1), (1, 1, 2)), ((2, 3, 4, 4), (2, 3, 4, 1))] + tuples = itertools.product(self.float_types, shapes) + for dtype, (a_shape, b_shape) in tuples: + n = a_shape[-1] + a = np.tril(rng.rand(*a_shape) - 0.5) / (2.0 * n) + np.eye(n) + b = rng.randn(*b_shape) + self._VerifyTriangularSolveCombo( + a.astype(dtype), b.astype(dtype), atol=1e-3) + + def testBatchBroadcast(self): + rng = np.random.RandomState(0) + shapes = [((3, 3), (4, 3, 5)), ((1, 2, 2), (3, 2, 1)), ((1, 1), (1, 1, 2)), + ((1, 3, 4, 4), (2, 1, 4, 1))] + tuples = itertools.product(self.float_types, shapes) + for dtype, (a_shape, b_shape) in tuples: + n = a_shape[-1] + a = np.tril(rng.rand(*a_shape) - 0.5) / (2.0 * n) + np.eye(n) + b = rng.randn(*b_shape) + self._VerifyTriangularSolveCombo( + a.astype(dtype), b.astype(dtype), atol=1e-3) + + def testLarge(self): + n = 1024 + rng = np.random.RandomState(0) + a = np.tril(rng.rand(n, n) - 0.5) / (2.0 * n) + np.eye(n) + b = rng.randn(n, n) + self._VerifyTriangularSolve( + a.astype(np.float32), b.astype(np.float32), True, False, 1e-4) + + @test_util.disable_mlir_bridge("Error handling") + def testNonSquareCoefficientMatrix(self): + rng = np.random.RandomState(0) + for dtype in self.float_types: + a = rng.randn(3, 4).astype(dtype) + b = rng.randn(4, 4).astype(dtype) + with self.test_scope(): + with self.assertRaises((ValueError, errors.InvalidArgumentError)): + linalg_ops.matrix_triangular_solve(a, b) + + @test_util.run_v2_only # Different error types + @test_util.disable_mlir_bridge("Error handling") + def testWrongDimensionsV2(self): + randn = np.random.RandomState(0).randn + for dtype in self.float_types: + lhs = constant_op.constant(randn(3, 3), dtype=dtype) + rhs = constant_op.constant(randn(4, 3), dtype=dtype) + with self.assertRaises(errors.InvalidArgumentError): + linalg_ops.matrix_triangular_solve(lhs, rhs) + with self.assertRaises(errors.InvalidArgumentError): + linalg_ops.matrix_triangular_solve(lhs, rhs) + + @test_util.run_v1_only("Different error types") + @test_util.disable_mlir_bridge("Error handling") + def testWrongDimensionsV1(self): + randn = np.random.RandomState(0).randn + for dtype in self.float_types: + lhs = constant_op.constant(randn(3, 3), dtype=dtype) + rhs = constant_op.constant(randn(4, 3), dtype=dtype) + with self.assertRaises(ValueError): + linalg_ops.matrix_triangular_solve(lhs, rhs) + with self.assertRaises(ValueError): + linalg_ops.matrix_triangular_solve(lhs, rhs) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/mean_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/mean_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..49457030bbed5e28db0bf71a6d9cf119f32a778f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/mean_op_test.py @@ -0,0 +1,39 @@ +# Copyright 2023 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 Mean operators.""" + +from tensorflow.python.eager.def_function import function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +class MeanOpTest(test.TestCase): + def testReduceMeanOverflow(self): + @function(jit_compile=True) + def tpu_computation(): + shape = (4, 32, 512, 512, 96) + dtype = dtypes.float32 + test_ones = array_ops.ones(shape=shape, dtype=dtype) + return math_ops.reduce_mean(test_ones) + with ops.device("TPU:0"): + result = tpu_computation() + self.assertAllClose( + result, 1.0, rtol=1e-4, atol=1e-4) + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/momentum_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/momentum_test.py new file mode 100644 index 0000000000000000000000000000000000000000..43dae0853e1eee6ef1ef7b331711556b52d44605 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/momentum_test.py @@ -0,0 +1,186 @@ +# 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 Momentum.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import momentum as momentum_lib + + +class MomentumOptimizerTest(xla_test.XLATestCase): + + def _update_nesterov_momentum_numpy(self, var, accum, g, lr, momentum): + var += accum * lr * momentum + accum = accum * momentum + g + var -= lr * accum + var -= accum * lr * momentum + return var, accum + + def testBasic(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) + mom_opt = momentum_lib.MomentumOptimizer( + learning_rate=2.0, momentum=0.9) + mom_update = mom_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Check we have slots + self.assertEqual(["momentum"], mom_opt.get_slot_names()) + slot0 = mom_opt.get_slot(var0, "momentum") + self.assertEqual(slot0.get_shape(), var0.get_shape()) + self.assertFalse(slot0 in variables.trainable_variables()) + slot1 = mom_opt.get_slot(var1, "momentum") + self.assertEqual(slot1.get_shape(), var1.get_shape()) + self.assertFalse(slot1 in variables.trainable_variables()) + + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + # Step 1: the momentum accumulators where 0. So we should see a normal + # update: v -= grad * learning_rate + mom_update.run() + # Check that the momentum accumulators have been updated. + self.assertAllCloseAccordingToType( + np.array([0.1, 0.1]), self.evaluate(slot0)) + self.assertAllCloseAccordingToType( + np.array([0.01, 0.01]), self.evaluate(slot1)) + # Check that the parameters have been updated. + self.assertAllCloseAccordingToType( + np.array([1.0 - (0.1 * 2.0), 2.0 - (0.1 * 2.0)]), + self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([3.0 - (0.01 * 2.0), 4.0 - (0.01 * 2.0)]), + self.evaluate(var1)) + # Step 2: the momentum accumulators contain the previous update. + mom_update.run() + # Check that the momentum accumulators have been updated. + self.assertAllCloseAccordingToType( + np.array([(0.9 * 0.1 + 0.1), (0.9 * 0.1 + 0.1)]), + self.evaluate(slot0)) + self.assertAllCloseAccordingToType( + np.array([(0.9 * 0.01 + 0.01), (0.9 * 0.01 + 0.01)]), + self.evaluate(slot1)) + # Check that the parameters have been updated. + self.assertAllCloseAccordingToType( + np.array([ + 1.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), + 2.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0) + ]), self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([ + 2.98 - ((0.9 * 0.01 + 0.01) * 2.0), + 3.98 - ((0.9 * 0.01 + 0.01) * 2.0) + ]), self.evaluate(var1)) + + def testNesterovMomentum(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([0.1, 0.2], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([0.3, 0.4], dtype=dtype) + var0_np = np.array([0.1, 0.2], dtype=dtype) + var1_np = np.array([0.3, 0.4], dtype=dtype) + accum0_np = np.array([0.0, 0.0], dtype=dtype) + accum1_np = np.array([0.0, 0.0], dtype=dtype) + cost = 0.4 * var0 * var0 + 0.9 * var1 + global_step = resource_variable_ops.ResourceVariable( + array_ops.zeros([], dtypes.int32), name="global_step") + mom_op = momentum_lib.MomentumOptimizer( + learning_rate=0.1, momentum=0.9, use_nesterov=True) + opt_op = mom_op.minimize(cost, global_step, [var0, var1]) + self.evaluate(variables.global_variables_initializer()) + for _ in range(1, 5): + opt_op.run() + var0_np, accum0_np = self._update_nesterov_momentum_numpy( + var0_np, accum0_np, var0_np * 0.8, 0.1, 0.9) + var1_np, accum1_np = self._update_nesterov_momentum_numpy( + var1_np, accum1_np, 0.9, 0.1, 0.9) + self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) + self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) + + def testTensorLearningRateAndMomentum(self): + for dtype in self.float_types: + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0], dtype=dtype) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0], dtype=dtype) + grads0 = constant_op.constant([0.1, 0.1], dtype=dtype) + grads1 = constant_op.constant([0.01, 0.01], dtype=dtype) + mom_opt = momentum_lib.MomentumOptimizer( + learning_rate=constant_op.constant(2.0), + momentum=constant_op.constant(0.9)) + mom_update = mom_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + # Check we have slots + self.assertEqual(["momentum"], mom_opt.get_slot_names()) + slot0 = mom_opt.get_slot(var0, "momentum") + self.assertEqual(slot0.get_shape(), var0.get_shape()) + self.assertFalse(slot0 in variables.trainable_variables()) + slot1 = mom_opt.get_slot(var1, "momentum") + self.assertEqual(slot1.get_shape(), var1.get_shape()) + self.assertFalse(slot1 in variables.trainable_variables()) + + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + # Step 1: the momentum accumulators where 0. So we should see a normal + # update: v -= grad * learning_rate + mom_update.run() + # Check that the momentum accumulators have been updated. + self.assertAllCloseAccordingToType( + np.array([0.1, 0.1]), self.evaluate(slot0)) + self.assertAllCloseAccordingToType( + np.array([0.01, 0.01]), self.evaluate(slot1)) + # Check that the parameters have been updated. + self.assertAllCloseAccordingToType( + np.array([1.0 - (0.1 * 2.0), 2.0 - (0.1 * 2.0)]), + self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([3.0 - (0.01 * 2.0), 4.0 - (0.01 * 2.0)]), + self.evaluate(var1)) + # Step 2: the momentum accumulators contain the previous update. + mom_update.run() + # Check that the momentum accumulators have been updated. + self.assertAllCloseAccordingToType( + np.array([(0.9 * 0.1 + 0.1), (0.9 * 0.1 + 0.1)]), + self.evaluate(slot0)) + self.assertAllCloseAccordingToType( + np.array([(0.9 * 0.01 + 0.01), (0.9 * 0.01 + 0.01)]), + self.evaluate(slot1)) + # Check that the parameters have been updated. + self.assertAllCloseAccordingToType( + np.array([ + 1.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0), + 2.0 - (0.1 * 2.0) - ((0.9 * 0.1 + 0.1) * 2.0) + ]), self.evaluate(var0)) + self.assertAllCloseAccordingToType( + np.array([ + 2.98 - ((0.9 * 0.01 + 0.01) * 2.0), + 3.98 - ((0.9 * 0.01 + 0.01) * 2.0) + ]), self.evaluate(var1)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/nary_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/nary_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d2efd35cf80155d571b6ee5b8b341b1aba3467f8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/nary_ops_test.py @@ -0,0 +1,291 @@ +# 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. +# ============================================================================== +"""Test cases for operators with > 3 or arbitrary numbers of arguments.""" + +import unittest + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class NAryOpsTest(xla_test.XLATestCase): + + def _testNAry(self, op, args, expected, equality_fn=None): + with self.session() as session: + with self.test_scope(): + placeholders = [ + array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape) + for arg in args + ] + feeds = {placeholders[i]: args[i] for i in range(0, len(args))} + output = op(placeholders) + result = session.run(output, feeds) + if not equality_fn: + equality_fn = self.assertAllClose + equality_fn(result, expected, rtol=1e-3) + + def _nAryListCheck(self, results, expected, **kwargs): + self.assertEqual(len(results), len(expected)) + for (r, e) in zip(results, expected): + self.assertAllClose(r, e, **kwargs) + + def _testNAryLists(self, op, args, expected): + self._testNAry(op, args, expected, equality_fn=self._nAryListCheck) + + def testFloat(self): + self._testNAry(math_ops.add_n, + [np.array([[1, 2, 3]], dtype=np.float32)], + expected=np.array([[1, 2, 3]], dtype=np.float32)) + + self._testNAry(math_ops.add_n, + [np.array([1, 2], dtype=np.float32), + np.array([10, 20], dtype=np.float32)], + expected=np.array([11, 22], dtype=np.float32)) + self._testNAry(math_ops.add_n, + [np.array([-4], dtype=np.float32), + np.array([10], dtype=np.float32), + np.array([42], dtype=np.float32)], + expected=np.array([48], dtype=np.float32)) + + def testComplex(self): + for dtype in self.complex_types: + self._testNAry( + math_ops.add_n, [np.array([[1 + 2j, 2 - 3j, 3 + 4j]], dtype=dtype)], + expected=np.array([[1 + 2j, 2 - 3j, 3 + 4j]], dtype=dtype)) + + self._testNAry( + math_ops.add_n, [ + np.array([1 + 2j, 2 - 3j], dtype=dtype), + np.array([10j, 20], dtype=dtype) + ], + expected=np.array([1 + 12j, 22 - 3j], dtype=dtype)) + self._testNAry( + math_ops.add_n, [ + np.array([-4, 5j], dtype=dtype), + np.array([2 + 10j, -2], dtype=dtype), + np.array([42j, 3 + 3j], dtype=dtype) + ], + expected=np.array([-2 + 52j, 1 + 8j], dtype=dtype)) + + @unittest.skip("IdentityN is temporarily CompilationOnly as workaround") + def testIdentityN(self): + self._testNAryLists(array_ops.identity_n, + [np.array([[1, 2, 3]], dtype=np.float32)], + expected=[np.array([[1, 2, 3]], dtype=np.float32)]) + self._testNAryLists(array_ops.identity_n, + [np.array([[1, 2], [3, 4]], dtype=np.float32), + np.array([[3, 2, 1], [6, 5, 1]], dtype=np.float32)], + expected=[ + np.array([[1, 2], [3, 4]], dtype=np.float32), + np.array([[3, 2, 1], [6, 5, 1]], dtype=np.float32)]) + self._testNAryLists(array_ops.identity_n, + [np.array([[1], [2], [3], [4]], dtype=np.int32), + np.array([[3, 2, 1], [6, 5, 1]], dtype=np.float32)], + expected=[ + np.array([[1], [2], [3], [4]], dtype=np.int32), + np.array([[3, 2, 1], [6, 5, 1]], dtype=np.float32)]) + + def testConcat(self): + self._testNAry( + lambda x: array_ops.concat(x, 0), [ + np.array( + [[1, 2, 3], [4, 5, 6]], dtype=np.float32), np.array( + [[7, 8, 9], [10, 11, 12]], dtype=np.float32) + ], + expected=np.array( + [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]], dtype=np.float32)) + + self._testNAry( + lambda x: array_ops.concat(x, 1), [ + np.array( + [[1, 2, 3], [4, 5, 6]], dtype=np.float32), np.array( + [[7, 8, 9], [10, 11, 12]], dtype=np.float32) + ], + expected=np.array( + [[1, 2, 3, 7, 8, 9], [4, 5, 6, 10, 11, 12]], dtype=np.float32)) + + def testOneHot(self): + with self.session() as session, self.test_scope(): + indices = array_ops.constant(np.array([[2, 3], [0, 1]], dtype=np.int32)) + op = array_ops.one_hot(indices, + np.int32(4), + on_value=np.float32(7), off_value=np.float32(3)) + output = session.run(op) + expected = np.array([[[3, 3, 7, 3], [3, 3, 3, 7]], + [[7, 3, 3, 3], [3, 7, 3, 3]]], + dtype=np.float32) + self.assertAllEqual(output, expected) + + op = array_ops.one_hot(indices, + np.int32(4), + on_value=np.int32(2), off_value=np.int32(1), + axis=1) + output = session.run(op) + expected = np.array([[[1, 1], [1, 1], [2, 1], [1, 2]], + [[2, 1], [1, 2], [1, 1], [1, 1]]], + dtype=np.int32) + self.assertAllEqual(output, expected) + + def testSplitV(self): + with self.session() as session: + with self.test_scope(): + output = session.run( + array_ops.split(np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 0, 1, 2]], + dtype=np.float32), + [2, 2], 1)) + expected = [np.array([[1, 2], [5, 6], [9, 0]], dtype=np.float32), + np.array([[3, 4], [7, 8], [1, 2]], dtype=np.float32)] + self.assertAllEqual(output, expected) + + def testSplitVNegativeSizes(self): + with self.session() as session: + with self.test_scope(): + with self.assertRaisesRegex( + (ValueError, errors.InvalidArgumentError), + "Split size at index 1 must be >= .*. Got: -2", + ): + _ = session.run( + array_ops.split(np.array([1, 2, 3], dtype=np.float32), [-1, -2], + axis=0)) + + def testStridedSlice(self): + self._testNAry(lambda x: array_ops.strided_slice(*x), + [np.array([[], [], []], dtype=np.float32), + np.array([1, 0], dtype=np.int32), + np.array([3, 0], dtype=np.int32), + np.array([1, 1], dtype=np.int32)], + expected=np.array([[], []], dtype=np.float32)) + + if np.int64 in self.int_types: + self._testNAry( + lambda x: array_ops.strided_slice(*x), [ + np.array([[], [], []], dtype=np.float32), np.array( + [1, 0], dtype=np.int64), np.array([3, 0], dtype=np.int64), + np.array([1, 1], dtype=np.int64) + ], + expected=np.array([[], []], dtype=np.float32)) + + self._testNAry(lambda x: array_ops.strided_slice(*x), + [np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + dtype=np.float32), + np.array([1, 1], dtype=np.int32), + np.array([3, 3], dtype=np.int32), + np.array([1, 1], dtype=np.int32)], + expected=np.array([[5, 6], [8, 9]], dtype=np.float32)) + + self._testNAry(lambda x: array_ops.strided_slice(*x), + [np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + dtype=np.float32), + np.array([0, 2], dtype=np.int32), + np.array([2, 0], dtype=np.int32), + np.array([1, -1], dtype=np.int32)], + expected=np.array([[3, 2], [6, 5]], dtype=np.float32)) + + self._testNAry(lambda x: x[0][0:2, array_ops.newaxis, ::-1], + [np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + dtype=np.float32)], + expected=np.array([[[3, 2, 1]], [[6, 5, 4]]], + dtype=np.float32)) + + self._testNAry(lambda x: x[0][1, :, array_ops.newaxis], + [np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], + dtype=np.float32)], + expected=np.array([[4], [5], [6]], dtype=np.float32)) + + def testStridedSliceGrad(self): + # Tests cases where input shape is empty. + self._testNAry(lambda x: array_ops.strided_slice_grad(*x), + [np.array([], dtype=np.int32), + np.array([], dtype=np.int32), + np.array([], dtype=np.int32), + np.array([], dtype=np.int32), + np.float32(0.5)], + expected=np.array(np.float32(0.5), dtype=np.float32)) + + # Tests case where input shape is non-empty, but gradients are empty. + self._testNAry(lambda x: array_ops.strided_slice_grad(*x), + [np.array([3], dtype=np.int32), + np.array([0], dtype=np.int32), + np.array([0], dtype=np.int32), + np.array([1], dtype=np.int32), + np.array([], dtype=np.float32)], + expected=np.array([0, 0, 0], dtype=np.float32)) + + self._testNAry(lambda x: array_ops.strided_slice_grad(*x), + [np.array([3, 0], dtype=np.int32), + np.array([1, 0], dtype=np.int32), + np.array([3, 0], dtype=np.int32), + np.array([1, 1], dtype=np.int32), + np.array([[], []], dtype=np.float32)], + expected=np.array([[], [], []], dtype=np.float32)) + + self._testNAry(lambda x: array_ops.strided_slice_grad(*x), + [np.array([3, 3], dtype=np.int32), + np.array([1, 1], dtype=np.int32), + np.array([3, 3], dtype=np.int32), + np.array([1, 1], dtype=np.int32), + np.array([[5, 6], [8, 9]], dtype=np.float32)], + expected=np.array([[0, 0, 0], [0, 5, 6], [0, 8, 9]], + dtype=np.float32)) + + def ssg_test(x): + return array_ops.strided_slice_grad(*x, shrink_axis_mask=0x4, + new_axis_mask=0x1) + + self._testNAry(ssg_test, + [np.array([3, 1, 3], dtype=np.int32), + np.array([0, 0, 0, 2], dtype=np.int32), + np.array([0, 3, 1, -4], dtype=np.int32), + np.array([1, 2, 1, -3], dtype=np.int32), + np.array([[[1], [2]]], dtype=np.float32)], + expected=np.array([[[0, 0, 1]], [[0, 0, 0]], [[0, 0, 2]]], + dtype=np.float32)) + + ssg_test2 = lambda x: array_ops.strided_slice_grad(*x, new_axis_mask=0x15) + self._testNAry(ssg_test2, + [np.array([4, 4], dtype=np.int32), + np.array([0, 0, 0, 1, 0], dtype=np.int32), + np.array([0, 3, 0, 4, 0], dtype=np.int32), + np.array([1, 2, 1, 2, 1], dtype=np.int32), + np.array([[[[[1], [2]]], [[[3], [4]]]]], dtype=np.float32)], + expected=np.array([[0, 1, 0, 2], [0, 0, 0, 0], [0, 3, 0, 4], + [0, 0, 0, 0]], dtype=np.float32)) + + self._testNAry(lambda x: array_ops.strided_slice_grad(*x), + [np.array([3, 3], dtype=np.int32), + np.array([0, 2], dtype=np.int32), + np.array([2, 0], dtype=np.int32), + np.array([1, -1], dtype=np.int32), + np.array([[1, 2], [3, 4]], dtype=np.float32)], + expected=np.array([[0, 2, 1], [0, 4, 3], [0, 0, 0]], + dtype=np.float32)) + + self._testNAry(lambda x: array_ops.strided_slice_grad(*x), + [np.array([3, 3], dtype=np.int32), + np.array([2, 2], dtype=np.int32), + np.array([0, 1], dtype=np.int32), + np.array([-1, -2], dtype=np.int32), + np.array([[1], [2]], dtype=np.float32)], + expected=np.array([[0, 0, 0], [0, 0, 2], [0, 0, 1]], + dtype=np.float32)) + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/nullary_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/nullary_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ada959c4e298612884dc75b14f0234dcf7ff75e1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/nullary_ops_test.py @@ -0,0 +1,76 @@ +# 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. +# ============================================================================== +"""Test cases for operators with no arguments.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.platform import googletest + + +class NullaryOpsTest(xla_test.XLATestCase): + + def _testNullary(self, op, expected): + with self.session() as session: + with self.test_scope(): + output = op() + result = session.run(output) + self.assertAllClose(result, expected, rtol=1e-3) + + def testNoOp(self): + with self.session(): + with self.test_scope(): + output = control_flow_ops.no_op() + # This should not crash. + output.run() + + def testConstants(self): + for dtype in self.numeric_types: + constants = [ + dtype(42), + np.array([], dtype=dtype), + np.array([1, 2], dtype=dtype), + np.array([7, 7, 7, 7, 7], dtype=dtype), + np.array([[1, 2, 3], [4, 5, 6]], dtype=dtype), + np.array([[[1, 2], [3, 4], [5, 6]], [[10, 20], [30, 40], [50, 60]]], + dtype=dtype), + np.array([[[]], [[]]], dtype=dtype), + np.array([[[[1]]]], dtype=dtype), + ] + for c in constants: + self._testNullary(lambda c=c: constant_op.constant(c), expected=c) + + def testComplexConstants(self): + for dtype in self.complex_types: + constants = [ + dtype(42 + 3j), + np.array([], dtype=dtype), + np.ones([50], dtype=dtype) * (3 + 4j), + np.array([1j, 2 + 1j], dtype=dtype), + np.array([[1, 2j, 7j], [4, 5, 6]], dtype=dtype), + np.array([[[1, 2], [3, 4 + 6j], [5, 6]], + [[10 + 7j, 20], [30, 40], [50, 60]]], + dtype=dtype), + np.array([[[]], [[]]], dtype=dtype), + np.array([[[[1 + 3j]]]], dtype=dtype), + ] + for c in constants: + self._testNullary(lambda c=c: constant_op.constant(c), expected=c) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/placeholder_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/placeholder_test.py new file mode 100644 index 0000000000000000000000000000000000000000..52f5431cebeaae3aefba19e69c8fa7341276cebc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/placeholder_test.py @@ -0,0 +1,44 @@ +# 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 xla handling of placeholder_with_default.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import googletest + + +class PlaceholderTest(xla_test.XLATestCase): + + def test_placeholder_with_default_default(self): + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(4.0) + ph = array_ops.placeholder_with_default(v, shape=[]) + out = ph * 2 + sess.run(variables.variables_initializer([v])) + self.assertEqual(8.0, self.evaluate(out)) + + def test_placeholder_with_default_fed(self): + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(4.0) + ph = array_ops.placeholder_with_default(v, shape=[]) + out = ph * 2 + sess.run(variables.variables_initializer([v])) + self.assertEqual(2.0, sess.run(out, {ph: 1.0})) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/plugin.bzl b/western_ai/usa/tensorflow/tensorflow/compiler/tests/plugin.bzl new file mode 100644 index 0000000000000000000000000000000000000000..e4f93a4b7a1db61056a0138c136b071cad1e5196 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/plugin.bzl @@ -0,0 +1,29 @@ +# 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. +# ============================================================================== +"""Additional XLA devices to be included in the unit test suite.""" + +# If you wish to edit this file without checking it into the repo, consider: +# git update-index --assume-unchanged tensorflow/compiler/tests/plugin.bzl + +plugins = { + #"example": { + # "device":"XLA_MY_DEVICE", + # "types":"DT_FLOAT,DT_HALF,DT_INT32", + # "tags":[], + # "args":["--disabled_manifest=tensorflow/compiler/plugin/example/disabled_manifest.txt"], + # "data":["//tensorflow/compiler/plugin/example:disabled_manifest.txt"], + # "deps":[], + #}, +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/pooling_ops_3d_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/pooling_ops_3d_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1ed8dc51a7e7cf819124df5d47010deee66a99a7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/pooling_ops_3d_test.py @@ -0,0 +1,457 @@ +# 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. +# ============================================================================== +"""Functional tests for 3d pooling operations.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +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_nn_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import test + + +# Wrapper around AvgPoolGrad that ignores extra arguments needed by +# MaxPoolGrad. +def _AvgPoolGrad(inputs, outputs, output_gradients, ksize, strides, padding): + del outputs # Unused by average-pooling gradients. + return gen_nn_ops.avg_pool3d_grad( + inputs.get_shape().as_list(), + output_gradients, + ksize=ksize, + strides=strides, + padding=padding) + + +class Pooling3DTest(xla_test.XLATestCase): + + def _VerifyValues(self, pool_func, input_sizes, window, strides, padding, + expected): + """Verifies the output values of the pooling function. + + Args: + pool_func: Function to be called: co.MaxPool, co.AvgPool. + input_sizes: Input tensor dimensions. + window: Tuple of kernel dims: planes, rows, cols. + strides: Tuple of strides for dims: planes, rows, cols. + padding: Padding type. + expected: An array containing the expected operation outputs. + """ + total_size = 1 + for s in input_sizes: + total_size *= s + # Initializes the input tensor with array containing incrementing + # numbers from 1. + x = np.arange(1.0, total_size + 1, dtype=np.float32) + x = x.reshape(input_sizes) + with self.session() as sess, self.test_scope(): + inputs = array_ops.placeholder(dtypes.float32) + t = pool_func( + inputs, + ksize=[1] + window + [1], + strides=[1] + strides + [1], + padding=padding) + vals = sess.run(t, {inputs: x}) + # Verifies values. + actual = vals.flatten() + self.assertAllClose(expected, actual) + + def testAvgPool3dValidPadding(self): + expected_output = [20.5, 21.5, 22.5] + self._VerifyValues( + nn_ops.avg_pool3d, + input_sizes=[1, 3, 3, 3, 3], + window=[2, 2, 2], + strides=[2, 2, 2], + padding="VALID", + expected=expected_output) + + def testAvgPool3dSamePadding(self): + expected_output = [20.5, 21.5, 22.5, 26.5, 27.5, 28.5] + self._VerifyValues( + nn_ops.avg_pool3d, + input_sizes=[1, 2, 2, 4, 3], + window=[2, 2, 2], + strides=[2, 2, 2], + padding="SAME", + expected=expected_output) + + def testAvgPool3dSamePaddingDifferentStrides(self): + expected_output = [1.5, 4.5, 7.5, 17.5, 20.5, 23.5, 33.5, 36.5, 39.5] + self._VerifyValues( + nn_ops.avg_pool3d, + input_sizes=[1, 5, 8, 1, 1], + window=[1, 2, 3], + strides=[2, 3, 1], + padding="SAME", + expected=expected_output) + + def testMaxPool3dValidPadding(self): + expected_output = [40.0, 41.0, 42.0] + self._VerifyValues( + nn_ops.max_pool3d, + input_sizes=[1, 3, 3, 3, 3], + window=[2, 2, 2], + strides=[2, 2, 2], + padding="VALID", + expected=expected_output) + + def testMaxPool3dSamePadding(self): + expected_output = [31., 32., 33., 34., 35., 36.] + self._VerifyValues( + nn_ops.max_pool3d, + input_sizes=[1, 2, 2, 3, 3], + window=[2, 2, 2], + strides=[2, 2, 2], + padding="SAME", + expected=expected_output) + + def testMaxPool3dSamePaddingDifferentStrides(self): + expected_output = [2., 5., 8., 18., 21., 24., 34., 37., 40.] + self._VerifyValues( + nn_ops.max_pool3d, + input_sizes=[1, 5, 8, 1, 1], + window=[1, 2, 3], + strides=[2, 3, 1], + padding="SAME", + expected=expected_output) + + # Test pooling on a larger input, with different stride and kernel + # size for the 'z' dimension. + + # Simulate max pooling in numpy to get the expected output. + input_data = np.arange(1, 5 * 27 * 27 * 64 + 1).reshape((5, 27, 27, 64)) + input_data = np.pad(input_data, [[0, 0], [0, 1], [0, 1], [0, 0]], + mode="constant") + expected_output = input_data[:, 1::2, 1::2, :] + expected_output[:, -1, :, :] = input_data[:, -2, 1::2, :] + expected_output[:, :, -1, :] = input_data[:, 1::2, -2, :] + expected_output[:, -1, -1, :] = input_data[:, -2, -2, :] + + self._VerifyValues( + nn_ops.max_pool3d, + input_sizes=[1, 5, 27, 27, 64], + window=[1, 2, 2], + strides=[1, 2, 2], + padding="SAME", + expected=expected_output.flatten()) + + def testKernelSmallerThanStride(self): + self._VerifyValues( + nn_ops.max_pool3d, + input_sizes=[1, 3, 3, 3, 1], + window=[1, 1, 1], + strides=[2, 2, 2], + padding="SAME", + expected=[1, 3, 7, 9, 19, 21, 25, 27]) + + self._VerifyValues( + nn_ops.max_pool3d, + input_sizes=[1, 7, 7, 7, 1], + window=[2, 2, 2], + strides=[3, 3, 3], + padding="VALID", + expected=[58, 61, 79, 82, 205, 208, 226, 229]) + + self._VerifyValues( + nn_ops.avg_pool3d, + input_sizes=[1, 3, 3, 3, 1], + window=[1, 1, 1], + strides=[2, 2, 2], + padding="SAME", + expected=[1, 3, 7, 9, 19, 21, 25, 27]) + + self._VerifyValues( + nn_ops.avg_pool3d, + input_sizes=[1, 7, 7, 7, 1], + window=[2, 2, 2], + strides=[3, 3, 3], + padding="VALID", + expected=[29.5, 32.5, 50.5, 53.5, 176.5, 179.5, 197.5, 200.5]) + + def _VerifyGradient(self, + pool_func, + pool_grad_func, + input_sizes, + ksize, + strides, + padding, + pool_grad_grad_func=None): + """Verifies the output values of the pooling gradient function. + + Args: + pool_func: Forward pooling function + pool_grad_func: Pooling gradient function for pool_grad_func + input_sizes: Input tensor dimensions. + ksize: The kernel size dimensions + strides: The stride dimensions + padding: Padding type. + pool_grad_grad_func: Second-order gradient function, if available. + """ + ksize = [1] + ksize + [1] + strides = [1] + strides + [1] + total_size = np.prod(input_sizes) + x = np.arange(1, total_size + 1, dtype=np.float32).reshape(input_sizes) + with self.session() as sess: + # Use the forward pool function to compute some corresponding outputs + # (needed for the CPU device, and we need the shape in both cases). + with ops.device("CPU"): + inputs = array_ops.placeholder(dtypes.float32, shape=input_sizes) + outputs = pool_func( + inputs, + ksize=ksize, + strides=strides, + padding=padding) + + output_vals = np.array(sess.run(outputs, {inputs: x})) + output_gradient_vals = np.arange( + 1, output_vals.size + 1, dtype=np.float32) + output_gradient_vals = output_gradient_vals.reshape(output_vals.shape) + output_grad_grad_vals = np.arange(1, x.size + 1, dtype=np.float32) + output_grad_grad_vals = output_grad_grad_vals.reshape(x.shape) + + # Use the Tensorflow CPU pooling gradient to compute the expected input + # gradients. + with ops.device("CPU"): + output_gradients = array_ops.placeholder( + dtypes.float32, shape=output_vals.shape) + expected_input_gradients = pool_grad_func( + inputs, + outputs, + output_gradients, + ksize=ksize, + strides=strides, + padding=padding) + expected_input_gradient_vals = sess.run( + expected_input_gradients, + {inputs: x, + output_gradients: output_gradient_vals}) + + output_grad_gradients = array_ops.placeholder( + dtypes.float32, shape=expected_input_gradient_vals.shape) + if pool_grad_grad_func is not None: + expected_grad_gradients = pool_grad_grad_func( + inputs, + outputs, + output_grad_gradients, + ksize=ksize, + strides=strides, + padding=padding, + data_format="NDHWC") + expected_grad_gradients_vals = sess.run(expected_grad_gradients, { + inputs: x, + output_grad_gradients: output_grad_grad_vals + }) + + # Run the gradient op on the XLA device + with self.test_scope(): + outputs = array_ops.placeholder(dtypes.float32, shape=output_vals.shape) + actual_input_gradients = pool_grad_func( + inputs, + outputs, + output_gradients, + ksize=ksize, + strides=strides, + padding=padding) + if pool_grad_grad_func is not None: + actual_grad_gradients = pool_grad_grad_func( + inputs, + outputs, + output_grad_gradients, + ksize=ksize, + strides=strides, + padding=padding, + data_format="NDHWC") + + actual = sess.run(actual_input_gradients, { + inputs: x, + outputs: output_vals, + output_gradients: output_gradient_vals + }) + + # Compare the Tensorflow and XLA results. + self.assertAllClose( + expected_input_gradient_vals.flatten(), + actual.flatten(), + rtol=1e-5, + atol=1e-6) + self.assertShapeEqual(actual, inputs) + + if pool_grad_grad_func is not None: + actual_grad_gradients_vals = sess.run( + actual_grad_gradients, { + inputs: x, + outputs: output_vals, + output_grad_gradients: output_grad_grad_vals + }) + + # Compare the Tensorflow and XLA results. + self.assertAllClose( + expected_grad_gradients_vals, + actual_grad_gradients_vals, + rtol=1e-4, + atol=1e-6) + self.assertShapeEqual(actual_grad_gradients_vals, outputs) + + def testMaxPoolGradValidPadding1_1_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[1, 3, 3, 3, 1], + ksize=[1, 1, 1], + strides=[1, 1, 1], + padding="VALID", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testMaxPoolGradValidPadding2_1_6_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[2, 3, 3, 6, 3], + ksize=[2, 2, 2], + strides=[1, 1, 1], + padding="VALID", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testMaxPoolGradValidPadding2_1_7_3d(self): + # TODO(b/73062247): the bfloat16 implementation of MaxPool3DGradGrad does + # not have enough precision for this test case to pass if + # pool_grad_grad_func is passed. + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[2, 3, 5, 7, 3], + ksize=[2, 2, 2], + strides=[1, 1, 1], + padding="VALID") + + def testMaxPoolGradValidPadding2_2_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[2, 2, 2, 2, 3], + ksize=[2, 2, 2], + strides=[2, 2, 2], + padding="VALID", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testMaxPoolGradSamePadding1_1_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[2, 3, 2, 4, 1], + ksize=[1, 1, 1], + strides=[1, 1, 1], + padding="SAME", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testMaxPoolGradSamePadding2_1_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[2, 3, 2, 4, 1], + ksize=[2, 2, 2], + strides=[1, 1, 1], + padding="SAME", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testMaxPoolGradSamePadding2_2_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[2, 5, 2, 4, 3], + ksize=[2, 2, 2], + strides=[2, 2, 2], + padding="SAME", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testMaxPoolGradSamePadding3_1_3d(self): + self._VerifyGradient( + nn_ops.max_pool3d, + gen_nn_ops.max_pool3d_grad, + input_sizes=[1, 3, 3, 7, 1], + ksize=[3, 3, 3], + strides=[1, 1, 1], + padding="SAME", + pool_grad_grad_func=gen_nn_ops.max_pool3d_grad_grad) + + def testAvgPoolGradValidPadding1_1_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[2, 3, 3, 3, 3], + ksize=[1, 1, 1], + strides=[1, 1, 1], + padding="VALID") + + def testAvgPoolGradValidPadding2_1_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[2, 3, 3, 3, 3], + ksize=[2, 2, 2], + strides=[1, 1, 1], + padding="VALID") + + def testAvgPoolGradValidPadding2_2_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[2, 2, 2, 2, 3], + ksize=[2, 2, 2], + strides=[2, 2, 2], + padding="VALID") + + def testAvgPoolGradSamePadding1_1_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[2, 3, 2, 4, 3], + ksize=[1, 1, 1], + strides=[1, 1, 1], + padding="SAME") + + def testAvgPoolGradSamePadding2_1_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[1, 2, 2, 2, 1], + ksize=[2, 2, 2], + strides=[1, 1, 1], + padding="SAME") + + def testAvgPoolGradSamePadding2_2_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[2, 5, 2, 4, 3], + ksize=[2, 2, 2], + strides=[2, 2, 2], + padding="SAME") + + def testAvgPoolGradSamePadding3_1_3d(self): + self._VerifyGradient( + nn_ops.avg_pool3d, + _AvgPoolGrad, + input_sizes=[1, 3, 6, 7, 1], + ksize=[3, 3, 3], + strides=[1, 1, 1], + padding="SAME") + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/pooling_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/pooling_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5338aa843c6076e5881a06275409fc77e898cb44 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/pooling_ops_test.py @@ -0,0 +1,625 @@ +# 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. +# ============================================================================== +"""Functional tests for pooling operations.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import googletest + + +def NHWCToNCHW(input_tensor): + """Convert the input from NHWC format to NCHW. + + Args: + input_tensor: a 4-D tensor, or a 4-element array representing the same. + + Returns: + the converted tensor or a shape array + """ + if isinstance(input_tensor, tensor.Tensor): + return array_ops.transpose(input_tensor, [0, 3, 1, 2]) + else: + return [input_tensor[0], input_tensor[3], input_tensor[1], input_tensor[2]] + + +def NCHWToNHWC(input_tensor): + """Convert the input from NCHW format to NHWC. + + Args: + input_tensor: a 4-D tensor, or a 4-element array representing the same. + + Returns: + the converted tensor or a shape array + """ + if isinstance(input_tensor, tensor.Tensor): + return array_ops.transpose(input_tensor, [0, 2, 3, 1]) + else: + return [input_tensor[0], input_tensor[2], input_tensor[3], input_tensor[1]] + + +def GetTestConfigs(): + """Get all the valid tests configs to run. + + Returns: + all the valid test configs + """ + test_configs = ["NHWC", "NCHW"] + return test_configs + + +class PoolingTest(xla_test.XLATestCase): + + def _VerifyOneTest(self, pool_func, input_sizes, ksize, strides, padding, + data_format, expected): + """Verifies the output values of the pooling function. + + Args: + pool_func: Function to be called, currently only co.MaxPool. + input_sizes: Input tensor dimensions. + ksize: The kernel size dimensions + strides: The stride dimensions + padding: Padding type. + data_format: The data format we use to run the pooling operation. + expected: An array containing the expected operation outputs. + """ + total_size = np.prod(input_sizes) + # Initializes the input tensor with array containing incrementing + # numbers from 1. + x = np.array([f * 1.0 for f in range(1, total_size + 1)], dtype=np.float32) + x = x.reshape(input_sizes) + with self.session() as sess: + with self.test_scope(): + inputs = array_ops.placeholder(dtypes.float32) + t = inputs + if data_format == "NCHW": + t = NHWCToNCHW(t) + ksize = NHWCToNCHW(ksize) + strides = NHWCToNCHW(strides) + t = pool_func(t, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format) + if data_format == "NCHW": + t = NCHWToNHWC(t) + actual = sess.run(t, {inputs: x}) + self.assertAllClose(expected, actual.flatten(), rtol=1e-5, atol=1e-6) + + def _VerifyValues(self, pool_func, input_sizes, ksize, strides, padding, + expected): + """Verifies the output values of the pooling function. + + Args: + pool_func: Function to be called, co.MaxPool, co.AvgPool, + or the Lua version. + input_sizes: Input tensor dimensions. + ksize: The kernel size dimensions + strides: The stride dimensions + padding: Padding type. + expected: An array containing the expected operation outputs. + """ + for data_format in GetTestConfigs(): + self._VerifyOneTest(pool_func, input_sizes, ksize, strides, padding, + data_format, expected) + + def testMaxPoolValidPadding(self): + expected_output = [13.0, 14.0, 15.0] + self._VerifyValues(nn_ops.max_pool, + input_sizes=[1, 3, 3, 3], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="VALID", + expected=expected_output) + + def testMaxPoolSamePadding(self): + expected_output = [13.0, 14.0, 15.0, 16.0, 17.0, 18.0] + self._VerifyValues(nn_ops.max_pool, + input_sizes=[1, 2, 3, 3], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="SAME", + expected=expected_output) + + def testMaxPoolSamePaddingNonSquareWindow(self): + # input is: + # [1.0, 2.0 + # 3.0 4.0] + # + # Window of [x, x] should do: + # + # [max(1.0, 2.0), max(2.0, padded0), + # max(3.0, 4.0), max(4.0, padded0)] + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 2, 2, 1], + ksize=[1, 1, 2, 1], + strides=[1, 1, 1, 1], + padding="SAME", + expected=[2.0, 2.0, 4.0, 4.0]) + + def testMaxPoolValidPaddingUnevenStride(self): + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 4, 4, 1], + ksize=[1, 2, 2, 1], + strides=[1, 1, 2, 1], + padding="VALID", + expected=[6.0, 8.0, 10.0, 12.0, 14.0, 16.0]) + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 4, 4, 1], + ksize=[1, 2, 2, 1], + strides=[1, 2, 1, 1], + padding="VALID", + expected=[6.0, 7.0, 8.0, 14.0, 15.0, 16.0]) + + def testMaxPoolSamePaddingFilter4(self): + expected_output = [ + 21.0, 22.0, 23.0, 24.0, 29.0, 30.0, 31.0, 32.0, 53.0, 54.0, 55.0, 56.0, + 61.0, 62.0, 63.0, 64.0 + ] + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 4, 4, 4], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="SAME", + expected=expected_output) + + def testMaxPoolSamePaddingFilter8(self): + expected_output = [ + 145.0, 146.0, 147.0, 148.0, 149.0, 150.0, 151.0, 152.0, 161.0, 162.0, + 163.0, 164.0, 165.0, 166.0, 167.0, 168.0, 177.0, 178.0, 179.0, 180.0, + 181.0, 182.0, 183.0, 184.0, 185.0, 186.0, 187.0, 188.0, 189.0, 190.0, + 191.0, 192.0, 273.0, 274.0, 275.0, 276.0, 277.0, 278.0, 279.0, 280.0, + 289.0, 290.0, 291.0, 292.0, 293.0, 294.0, 295.0, 296.0, 305.0, 306.0, + 307.0, 308.0, 309.0, 310.0, 311.0, 312.0, 313.0, 314.0, 315.0, 316.0, + 317.0, 318.0, 319.0, 320.0, 401.0, 402.0, 403.0, 404.0, 405.0, 406.0, + 407.0, 408.0, 417.0, 418.0, 419.0, 420.0, 421.0, 422.0, 423.0, 424.0, + 433.0, 434.0, 435.0, 436.0, 437.0, 438.0, 439.0, 440.0, 441.0, 442.0, + 443.0, 444.0, 445.0, 446.0, 447.0, 448.0, 465.0, 466.0, 467.0, 468.0, + 469.0, 470.0, 471.0, 472.0, 481.0, 482.0, 483.0, 484.0, 485.0, 486.0, + 487.0, 488.0, 497.0, 498.0, 499.0, 500.0, 501.0, 502.0, 503.0, 504.0, + 505.0, 506.0, 507.0, 508.0, 509.0, 510.0, 511.0, 512.0 + ] + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 8, 8, 8], + ksize=[1, 3, 3, 1], + strides=[1, 2, 2, 1], + padding="SAME", + expected=expected_output) + + # Tests for DepthwiseMaxPooling on CPU only. + def testDepthwiseMaxPool1x1DepthWindow1(self): + # input is: + # [1.0, ..., 10.0] along depth, + # + # We maxpool by depth in patches of 2. + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 1, 1, 10], + ksize=[1, 1, 1, 2], + strides=[1, 1, 1, 2], + padding="SAME", + expected=[2.0, 4.0, 6.0, 8.0, 10.0]) + + def testDepthwiseMaxPool2x2DepthWindow3(self): + # input is: + # + # a 2x2x6 cube, and we depthwise max across 3 to produce a 2x2x2 + # output. Each node has contiguous values, so the depthwise max + # should be multiples of 3.0. + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 2, 2, 6], + ksize=[1, 1, 1, 3], + strides=[1, 1, 1, 3], + padding="SAME", + expected=[3.0, 6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0]) + + def testKernelSmallerThanStrideValid(self): + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 7, 7, 1], + ksize=[1, 2, 2, 1], + strides=[1, 3, 3, 1], + padding="VALID", + expected=[9, 12, 30, 33]) + + def testKernelSmallerThanStrideSame(self): + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 3, 3, 1], + ksize=[1, 1, 1, 1], + strides=[1, 2, 2, 1], + padding="SAME", + expected=[1, 3, 7, 9]) + + self._VerifyValues( + nn_ops.max_pool, + input_sizes=[1, 4, 4, 1], + ksize=[1, 1, 1, 1], + strides=[1, 2, 2, 1], + padding="SAME", + expected=[1, 3, 9, 11]) + + # Average pooling + def testAvgPoolValidPadding(self): + expected_output = [7, 8, 9] + self._VerifyValues( + nn_ops.avg_pool, + input_sizes=[1, 3, 3, 3], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="VALID", + expected=expected_output) + + def testAvgPoolSamePadding(self): + expected_output = [7., 8., 9., 11.5, 12.5, 13.5] + self._VerifyValues( + nn_ops.avg_pool, + input_sizes=[1, 2, 3, 3], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="SAME", + expected=expected_output) + + +class PoolGradTest(xla_test.XLATestCase): + + CPU_DEVICE = "/job:localhost/replica:0/task:0/cpu:0" + + def _VerifyOneTest(self, + pool_func, + pool_grad_func, + input_sizes, + ksize, + strides, + padding, + data_format, + pool_grad_grad_func=None): + """Verifies the output values of the pooling gradient function. + + Args: + pool_func: Forward pooling function + pool_grad_func: Pooling gradient function for pool_grad_func + input_sizes: Input tensor dimensions. + ksize: The kernel size dimensions + strides: The stride dimensions + padding: Padding type. + data_format: The data format we use to run the pooling operation. + pool_grad_grad_func: Second-order gradient function, if available. + """ + total_size = np.prod(input_sizes) + # TODO(b/73062247): MaxPoolGradGrad can confuse gradients when x is equally + # maximal at 16 bits. Switch to np.random.randn when resolved. + x = np.arange(1, total_size + 1, dtype=np.float32) + x *= (np.random.randint(2, size=total_size) * 2 - 1) # Flip signs randomly + # Verify some specifically interesting values... + x[np.random.choice(total_size)] = np.inf + x[np.random.choice(total_size)] = -np.inf + # TODO(b/74222344): Fix nan handling for max pool grad. + # x[np.random.choice(total_size)] = np.nan + x = x.reshape(input_sizes) + with self.session() as sess: + # Use the forward pool function to compute some corresponding outputs + # (needed for the CPU device, and we need the shape in both cases). + with ops.device(self.CPU_DEVICE): + inputs = array_ops.placeholder(dtypes.float32, shape=input_sizes) + outputs = pool_func( + inputs, + ksize=ksize, + strides=strides, + padding=padding, + data_format="NHWC") + + output_vals = np.array(sess.run(outputs, {inputs: x})) + output_gradient_vals = np.arange( + 1, output_vals.size + 1, dtype=np.float32) + output_gradient_vals = output_gradient_vals.reshape(output_vals.shape) + output_grad_grad_vals = np.arange(1, x.size + 1, dtype=np.float32) + output_grad_grad_vals = output_grad_grad_vals.reshape(x.shape) + + # Use the Tensorflow CPU pooling gradient to compute the expected input + # gradients. + with ops.device(self.CPU_DEVICE): + output_gradients = array_ops.placeholder( + dtypes.float32, shape=output_vals.shape) + expected_input_gradients = pool_grad_func( + inputs, + outputs, + output_gradients, + ksize=ksize, + strides=strides, + padding=padding, + data_format="NHWC") + expected_input_gradient_vals = sess.run( + expected_input_gradients, + {inputs: x, + output_gradients: output_gradient_vals}) + + output_grad_gradients = array_ops.placeholder( + dtypes.float32, shape=expected_input_gradient_vals.shape) + if pool_grad_grad_func is not None: + expected_grad_gradients = pool_grad_grad_func( + inputs, + outputs, + output_grad_gradients, + ksize=ksize, + strides=strides, + padding=padding, + data_format="NHWC") + expected_grad_gradients_vals = sess.run(expected_grad_gradients, { + inputs: x, + output_grad_gradients: output_grad_grad_vals + }) + + # Run the gradient op on the XLA device + with self.test_scope(): + outputs = array_ops.placeholder(dtypes.float32, shape=output_vals.shape) + xla_inputs = inputs + xla_outputs = outputs + xla_output_gradients = output_gradients + xla_output_grad_gradients = output_grad_gradients + xla_ksize = ksize + xla_strides = strides + if data_format == "NCHW": + xla_inputs = NHWCToNCHW(inputs) + xla_outputs = NHWCToNCHW(outputs) + xla_output_gradients = NHWCToNCHW(output_gradients) + xla_output_grad_gradients = NHWCToNCHW(output_grad_gradients) + xla_ksize = NHWCToNCHW(ksize) + xla_strides = NHWCToNCHW(strides) + actual_input_gradients = pool_grad_func( + xla_inputs, + xla_outputs, + xla_output_gradients, + ksize=xla_ksize, + strides=xla_strides, + padding=padding, + data_format=data_format) + if data_format == "NCHW": + actual_input_gradients = NCHWToNHWC(actual_input_gradients) + if pool_grad_grad_func is not None: + actual_grad_gradients = pool_grad_grad_func( + xla_inputs, + xla_outputs, + xla_output_grad_gradients, + ksize=xla_ksize, + strides=xla_strides, + padding=padding, + data_format=data_format) + if data_format == "NCHW": + actual_grad_gradients = NCHWToNHWC(actual_grad_gradients) + actual_input_gradients_vals = sess.run(actual_input_gradients, { + inputs: x, + outputs: output_vals, + output_gradients: output_gradient_vals + }) + # Compare the Tensorflow and XLA results. + self.assertAllClose( + expected_input_gradient_vals, + actual_input_gradients_vals, + rtol=1e-4, + atol=1e-6) + self.assertShapeEqual(actual_input_gradients_vals, inputs) + + if pool_grad_grad_func is not None: + actual_grad_gradients_vals = sess.run( + actual_grad_gradients, { + inputs: x, + outputs: output_vals, + output_grad_gradients: output_grad_grad_vals + }) + + # Compare the Tensorflow and XLA results. + self.assertAllClose( + expected_grad_gradients_vals, + actual_grad_gradients_vals, + rtol=1e-4, + atol=1e-6) + self.assertShapeEqual(actual_grad_gradients_vals, outputs) + + def _VerifyValues(self, + pool_func, + pool_grad_func, + input_sizes, + ksize, + strides, + padding, + pool_grad_grad_func=None): + """Verifies the output values of the pooling function. + + Args: + pool_func: Pooling function to be called, e.g., tf.nn.max_pool2d + pool_grad_func: Corresponding pooling gradient function. + input_sizes: Input tensor dimensions. + ksize: The kernel size dimensions + strides: The stride dimensions + padding: Padding type. + pool_grad_grad_func: Second-order gradient function, if available. + """ + for data_format in GetTestConfigs(): + self._VerifyOneTest( + pool_func, + pool_grad_func, + input_sizes, + ksize, + strides, + padding, + data_format, + pool_grad_grad_func=pool_grad_grad_func) + + def _TestPooling(self, forward_op, backward_op, pool_grad_grad_func=None): + # VALID padding + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 3, 3, 3], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="VALID", + pool_grad_grad_func=pool_grad_grad_func) + + # SAME padding + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 2, 3, 3], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="SAME", + pool_grad_grad_func=pool_grad_grad_func) + + # SAME padding, non square window + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 2, 2, 1], + ksize=[1, 1, 2, 1], + strides=[1, 1, 1, 1], + padding="SAME", + pool_grad_grad_func=pool_grad_grad_func) + + # VALID padding, uneven stride + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 4, 4, 1], + ksize=[1, 2, 2, 1], + strides=[1, 1, 2, 1], + padding="VALID", + pool_grad_grad_func=pool_grad_grad_func) + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 4, 4, 1], + ksize=[1, 2, 2, 1], + strides=[1, 2, 1, 1], + padding="VALID", + pool_grad_grad_func=pool_grad_grad_func) + + # SAME padding, size 4 input + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 4, 4, 4], + ksize=[1, 2, 2, 1], + strides=[1, 2, 2, 1], + padding="SAME", + pool_grad_grad_func=pool_grad_grad_func) + + # SAME padding, size 8 input + self._VerifyValues( + forward_op, + backward_op, + input_sizes=[1, 8, 8, 8], + ksize=[1, 3, 3, 1], + strides=[1, 2, 2, 1], + padding="SAME", + pool_grad_grad_func=pool_grad_grad_func) + + def testMaxPool(self): + self._TestPooling( + nn_ops.max_pool, + gen_nn_ops.max_pool_grad, + pool_grad_grad_func=gen_nn_ops.max_pool_grad_grad) + + def testAvgPool(self): + # Wrapper around AvgPoolGrad that ignores extra arguments needed by + # MaxPoolGrad. + def AvgPoolGrad(inputs, outputs, output_gradients, ksize, strides, padding, + data_format): + del outputs # Unused by average-pooling gradients. + return gen_nn_ops.avg_pool_grad( + inputs.get_shape().as_list(), + output_gradients, + ksize=ksize, + strides=strides, + padding=padding, + data_format=data_format) + + self._TestPooling(nn_ops.avg_pool, AvgPoolGrad) + + @test_util.disable_mlir_bridge( + "TODO(b/266613412): investigate FPE in AvgPoolGrad for TPU" + ) + def testAvgPoolGradSamePaddingZeroStrideZeroSize(self): + output_gradient_vals = np.array([0.39117979], dtype=np.float32) + output_gradient_vals = output_gradient_vals.reshape([1, 1, 1, 1]) + with self.session() as sess: + with self.test_scope(): + output_gradients = array_ops.placeholder( + dtypes.float32, shape=output_gradient_vals.shape + ) + t = gen_nn_ops.avg_pool_grad( + orig_input_shape=[1, 0, 0, 0], + grad=output_gradients, + ksize=[1, 0, 0, 0], + strides=[1, 0, 0, 0], + padding="SAME", + data_format="NCHW", + ) + with self.assertRaisesRegex( + errors.InvalidArgumentError, + ( + "Sliding window ksize field for dimension 1 must be positive but" + " is 0" + ), + ): + sess.run(t, {output_gradients: output_gradient_vals}) + + # The CPU implementation of AvgPoolGrad doesn't accept kernels smaller than + # the stride size, so we only run the following tests on MaxPoolGrad. + + def testMaxPoolKernelSmallerThanStrideValid(self): + self._VerifyValues( + nn_ops.max_pool, + gen_nn_ops.max_pool_grad, + input_sizes=[1, 7, 7, 1], + ksize=[1, 2, 2, 1], + strides=[1, 3, 3, 1], + padding="VALID") + + def testMaxPoolKernelSmallerThanStrideSame(self): + self._VerifyValues( + nn_ops.max_pool, + gen_nn_ops.max_pool_grad, + input_sizes=[1, 3, 3, 1], + ksize=[1, 1, 1, 1], + strides=[1, 2, 2, 1], + padding="SAME") + + self._VerifyValues( + nn_ops.max_pool, + gen_nn_ops.max_pool_grad, + input_sizes=[1, 4, 4, 1], + ksize=[1, 1, 1, 1], + strides=[1, 2, 2, 1], + padding="SAME") + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/proximal_adagrad_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/proximal_adagrad_test.py new file mode 100644 index 0000000000000000000000000000000000000000..275ae0dae99c1d53ecf46be45f310c5e58bf07f5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/proximal_adagrad_test.py @@ -0,0 +1,170 @@ +# 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 Proximal Adagrad optimizer.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import adagrad +from tensorflow.python.training import proximal_adagrad + + +class ProximalAdagradOptimizerTest(xla_test.XLATestCase): + + def testResourceProximalAdagradwithoutRegularization(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([0.0, 0.0]) + var1 = resource_variable_ops.ResourceVariable([0.0, 0.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + opt = proximal_adagrad.ProximalAdagradOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run 3 steps Proximal Adagrad. + for _ in range(3): + update.run() + + self.assertAllClose( + np.array([-2.60260963, -4.29698515]), self.evaluate(var0)) + self.assertAllClose( + np.array([-0.28432083, -0.56694895]), self.evaluate(var1)) + opt_vars = opt.variables() + self.assertStartsWith(opt_vars[0].name, var0._shared_name) + self.assertStartsWith(opt_vars[1].name, var1._shared_name) + self.assertEqual(2, len(opt_vars)) + + def testProximalAdagradwithoutRegularization2(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + opt = proximal_adagrad.ProximalAdagradOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 3 steps Proximal Adagrad. + for _ in range(3): + update.run() + self.assertAllClose(np.array([-1.60261, -2.296985]), self.evaluate(var0)) + self.assertAllClose(np.array([3.715679, 2.433051]), self.evaluate(var1)) + + def testProximalAdagradWithL1(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + opt = proximal_adagrad.ProximalAdagradOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=0.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps Proximal Adagrad + for _ in range(10): + update.run() + self.assertAllClose(np.array([-6.663634, -9.190331]), self.evaluate(var0)) + self.assertAllClose(np.array([2.959304, 1.029232]), self.evaluate(var1)) + + def testProximalAdagradWithL1_L2(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + opt = proximal_adagrad.ProximalAdagradOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.001, + l2_regularization_strength=2.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps Proximal Adagrad. + for _ in range(10): + update.run() + + self.assertAllClose(np.array([-0.0495, -0.0995]), self.evaluate(var0)) + self.assertAllClose(np.array([-0.0045, -0.0095]), self.evaluate(var1)) + + def applyOptimizer(self, opt, steps=5): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + + # Run ProximalAdagrad for a few steps + for _ in range(steps): + update.run() + + return self.evaluate(var0), self.evaluate(var1) + + def testEquivAdagradwithoutRegularization(self): + with self.session(), self.test_scope(): + val0, val1 = self.applyOptimizer( + proximal_adagrad.ProximalAdagradOptimizer( + 3.0, + initial_accumulator_value=0.1, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0)) + + with self.session(), self.test_scope(): + val2, val3 = self.applyOptimizer( + adagrad.AdagradOptimizer( + 3.0, initial_accumulator_value=0.1)) + + self.assertAllClose(val0, val2) + self.assertAllClose(val1, val3) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/proximal_gradient_descent_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/proximal_gradient_descent_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c633e0cb41243a0397e24a277229e1e49e32262b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/proximal_gradient_descent_test.py @@ -0,0 +1,152 @@ +# 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 Proximal Gradient Descent optimizer.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import gradient_descent +from tensorflow.python.training import proximal_gradient_descent + + +class ProximalGradientDescentOptimizerTest(xla_test.XLATestCase): + + def testResourceProximalGradientDescentwithoutRegularization(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([0.0, 0.0]) + var1 = resource_variable_ops.ResourceVariable([0.0, 0.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + opt = proximal_gradient_descent.ProximalGradientDescentOptimizer( + 3.0, l1_regularization_strength=0.0, l2_regularization_strength=0.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([0.0, 0.0], self.evaluate(var0)) + self.assertAllClose([0.0, 0.0], self.evaluate(var1)) + + # Run 3 steps Proximal Gradient Descent. + for _ in range(3): + update.run() + + self.assertAllClose(np.array([-0.9, -1.8]), self.evaluate(var0)) + self.assertAllClose(np.array([-0.09, -0.18]), self.evaluate(var1)) + + def testProximalGradientDescentwithoutRegularization2(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + opt = proximal_gradient_descent.ProximalGradientDescentOptimizer( + 3.0, l1_regularization_strength=0.0, l2_regularization_strength=0.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 3 steps Proximal Gradient Descent + for _ in range(3): + update.run() + + self.assertAllClose(np.array([0.1, 0.2]), self.evaluate(var0)) + self.assertAllClose(np.array([3.91, 2.82]), self.evaluate(var1)) + + def testProximalGradientDescentWithL1(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + opt = proximal_gradient_descent.ProximalGradientDescentOptimizer( + 3.0, l1_regularization_strength=0.001, l2_regularization_strength=0.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps proximal gradient descent. + for _ in range(10): + update.run() + + self.assertAllClose(np.array([-1.988, -3.988001]), self.evaluate(var0)) + self.assertAllClose(np.array([3.67, 2.37]), self.evaluate(var1)) + + def testProximalGradientDescentWithL1_L2(self): + with self.session(), self.test_scope(): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([4.0, 3.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + opt = proximal_gradient_descent.ProximalGradientDescentOptimizer( + 3.0, l1_regularization_strength=0.001, l2_regularization_strength=2.0) + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([4.0, 3.0], self.evaluate(var1)) + + # Run 10 steps Proximal Gradient Descent + for _ in range(10): + update.run() + + self.assertAllClose(np.array([-0.0495, -0.0995]), self.evaluate(var0)) + self.assertAllClose(np.array([-0.0045, -0.0095]), self.evaluate(var1)) + + def applyOptimizer(self, opt, steps=5): + var0 = resource_variable_ops.ResourceVariable([1.0, 2.0]) + var1 = resource_variable_ops.ResourceVariable([3.0, 4.0]) + grads0 = constant_op.constant([0.1, 0.2]) + grads1 = constant_op.constant([0.01, 0.02]) + + update = opt.apply_gradients(zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + + # Run ProximalAdagrad for a few steps + for _ in range(steps): + update.run() + + return self.evaluate(var0), self.evaluate(var1) + + def testEquivGradientDescentwithoutRegularization(self): + with self.session(), self.test_scope(): + val0, val1 = self.applyOptimizer( + proximal_gradient_descent.ProximalGradientDescentOptimizer( + 3.0, + l1_regularization_strength=0.0, + l2_regularization_strength=0.0)) + + with self.session(), self.test_scope(): + val2, val3 = self.applyOptimizer( + gradient_descent.GradientDescentOptimizer(3.0)) + + self.assertAllClose(val0, val2) + self.assertAllClose(val1, val3) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/qr_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/qr_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ae053c34756ba7f5493d86e12c4c5e58627e4ac0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/qr_op_test.py @@ -0,0 +1,148 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for tensorflow.ops.math_ops.matrix_inverse.""" + +import itertools +import unittest + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + + +@test_util.run_all_without_tensor_float_32( + "XLA QR op calls matmul. Also, matmul used for verification. Also with " + 'TensorFloat-32, mysterious "Unable to launch cuBLAS gemm" error ' + "occasionally occurs") +# TODO(b/165435566): Fix "Unable to launch cuBLAS gemm" error +class QrOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def AdjustedNorm(self, x): + """Computes the norm of matrices in 'x', adjusted for dimension and type.""" + norm = np.linalg.norm(x, axis=(-2, -1)) + return norm / (max(x.shape[-2:]) * np.finfo(x.dtype).eps) + + def CompareOrthogonal(self, x, y, rank): + # We only compare the first 'rank' orthogonal vectors since the + # remainder form an arbitrary orthonormal basis for the + # (row- or column-) null space, whose exact value depends on + # implementation details. Notice that since we check that the + # matrices of singular vectors are unitary elsewhere, we do + # implicitly test that the trailing vectors of x and y span the + # same space. + x = x[..., 0:rank] + y = y[..., 0:rank] + # Q is only unique up to sign (complex phase factor for complex matrices), + # so we normalize the sign first. + sum_of_ratios = np.sum(np.divide(y, x), -2, keepdims=True) + phases = np.divide(sum_of_ratios, np.abs(sum_of_ratios)) + x *= phases + self.assertTrue(np.all(self.AdjustedNorm(x - y) < 30.0)) + + def CheckApproximation(self, a, q, r): + # Tests that a ~= q*r. + precision = self.AdjustedNorm(a - np.matmul(q, r)) + self.assertTrue(np.all(precision < 11.0)) + + def CheckUnitary(self, x): + # Tests that x[...,:,:]^H * x[...,:,:] is close to the identity. + xx = math_ops.matmul(x, x, adjoint_a=True) + identity = array_ops.matrix_band_part(array_ops.ones_like(xx), 0, 0) + tol = 100 * np.finfo(x.dtype).eps + self.assertAllClose(xx, identity, atol=tol) + + def _random_matrix(self, dtype, shape): + np.random.seed(1) + + def rng(): + return np.random.uniform( + low=-1.0, high=1.0, size=np.prod(shape)).reshape(shape).astype(dtype) + + x_np = rng() + if np.issubdtype(dtype, np.complexfloating): + x_np += rng() * dtype(1j) + return x_np + + def _test(self, x_np, full_matrices, full_rank=True): + dtype = x_np.dtype + shape = x_np.shape + with self.session() as sess: + x_tf = array_ops.placeholder(dtype) + with self.device_scope(): + q_tf, r_tf = linalg_ops.qr(x_tf, full_matrices=full_matrices) + q_tf_val, r_tf_val = sess.run([q_tf, r_tf], feed_dict={x_tf: x_np}) + + q_dims = q_tf_val.shape + np_q = np.ndarray(q_dims, dtype) + np_q_reshape = np.reshape(np_q, (-1, q_dims[-2], q_dims[-1])) + new_first_dim = np_q_reshape.shape[0] + + x_reshape = np.reshape(x_np, (-1, x_np.shape[-2], x_np.shape[-1])) + for i in range(new_first_dim): + if full_matrices: + np_q_reshape[i, :, :], _ = np.linalg.qr( + x_reshape[i, :, :], mode="complete") + else: + np_q_reshape[i, :, :], _ = np.linalg.qr( + x_reshape[i, :, :], mode="reduced") + np_q = np.reshape(np_q_reshape, q_dims) + if full_rank: + # Q is unique up to sign/phase if the matrix is full-rank. + self.CompareOrthogonal(np_q, q_tf_val, min(shape[-2:])) + self.CheckApproximation(x_np, q_tf_val, r_tf_val) + self.CheckUnitary(q_tf_val) + + SIZES = [1, 2, 5, 10, 32, 100, 300, 603] + DTYPES = [np.float32, np.complex64] + PARAMS = itertools.product(SIZES, SIZES, DTYPES) + + @parameterized.parameters(*PARAMS) + def testQR(self, rows, cols, dtype): + for full_matrices in [True, False]: + # Only tests the (3, 2) case for small numbers of rows/columns. + for batch_dims in [(), (3,)] + [(3, 2)] * (max(rows, cols) < 10): + x_np = self._random_matrix(dtype, batch_dims + (rows, cols)) + self._test(x_np, full_matrices) + + def testLarge2000x2000(self): + x_np = self._random_matrix(np.float32, (2000, 2000)) + self._test(x_np, full_matrices=True) + + @unittest.skip("Test times out on CI") + def testLarge17500x128(self): + x_np = self._random_matrix(np.float32, (17500, 128)) + self._test(x_np, full_matrices=True) + + @parameterized.parameters((23, 25), (513, 23)) + def testZeroColumn(self, rows, cols): + x_np = self._random_matrix(np.complex64, (rows, cols)) + x_np[:, 7] = 0. + self._test(x_np, full_matrices=True) + + @parameterized.parameters((4, 4), (514, 20)) + def testRepeatedColumn(self, rows, cols): + x_np = self._random_matrix(np.complex64, (rows, cols)) + x_np[:, 1] = x_np[:, 2] + self._test(x_np, full_matrices=True, full_rank=False) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/quantized_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/quantized_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..25f0bf17f6a4676523cf1657d98c0925cd303f8b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/quantized_ops_test.py @@ -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. +# ============================================================================== +"""Tests for quantized operations.""" + +import math + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +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 bitwise_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class QuantizedOpsTest(xla_test.XLATestCase): + + # Verify that quantized types can be clustered by XLA. + def testQuantizedTypeRoundtrip(self): + with self.session() as session: + for dtype in self.quantized_tf_types: + in_values = np.array([1, 2, 3, 4, 5, 6]) + expected = [[1, 2], [3, 4], [5, 6]] + with self.test_scope(): + p = array_ops.placeholder(dtype=dtypes.int32) + x = math_ops.cast(p, dtype) + x = array_ops.reshape(x, [3, 2]) + + value = session.run(x, {p: in_values}) + self.assertAllEqual(value, expected) + + +class DequantizedOpsTest(xla_test.XLATestCase): + + def pack_uint8_r2_to_uint32(self, test_input): + num_rows, num_columns = test_input.get_shape().as_list() + num_output_columns = int(math.ceil(num_columns / 4.0)) + padding_input = array_ops.pad( + math_ops.cast(test_input, dtype=dtypes.uint8), + constant_op.constant([[ + 0, + 0, + ], [0, num_output_columns * 4 - num_columns]])) + output = array_ops.zeros([num_rows, num_output_columns], + dtype=dtypes.uint32) + num_elements_per_pack = 4 + shift_bits = 8 + + iota_r1 = math_ops.range(num_output_columns * num_elements_per_pack) + + for p in range(num_elements_per_pack): + selected_index = math_ops.equal( + math_ops.mod(iota_r1, num_elements_per_pack), p) + gather_index = array_ops.boolean_mask(iota_r1, selected_index) + gathered_input = array_ops.gather(padding_input, gather_index, axis=1) + total_shift_bits = shift_bits * (num_elements_per_pack - p - 1) + left_shift_input = bitwise_ops.left_shift( + math_ops.cast(gathered_input, dtype=dtypes.uint32), total_shift_bits) + output = bitwise_ops.bitwise_or(output, left_shift_input) + return output + + def testDequantizeQuint8(self): + num_rows = 100 + num_columns = 3547 + random_input = np.random.normal(128.0, 10.0, [num_rows, num_columns]) + with self.session() as session: + with ops.device("CPU"): + test_input = ops.convert_to_tensor(random_input, dtype=dtypes.float32) + transposed_input = array_ops.transpose(test_input, [1, 0]) + quantized_input = array_ops.quantize(transposed_input, 0.0, 255.0, + dtypes.quint8) + packed_input = self.pack_uint8_r2_to_uint32(quantized_input.output) + with self.test_scope(): + transposed_quantized_output = xla.dequantize(packed_input, 0.0, 255.0, + "MIN_COMBINED", True) + quantized_output = array_ops.slice(transposed_quantized_output, [0, 0], + [num_rows, num_columns]) + + value = session.run(quantized_output) + self.assertAllClose(value, random_input, 1.0) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/random_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/random_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2e6485da2a301140ff4296527989a8672fb382ea --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/random_ops_test.py @@ -0,0 +1,290 @@ +# 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 random-number generation ops in the XLA JIT compiler.""" + +import math + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops.distributions import special_math +from tensorflow.python.platform import googletest + + +class RandomOpsTest(xla_test.XLATestCase, parameterized.TestCase): + """Test cases for random-number generating operators.""" + + def _random_types(self): + return set(self.numeric_types) - set( + self.complex_types) - {np.uint64, np.int64, np.uint8, np.int8} + + def _testRngIsNotConstant(self, rng, dtype): + # Tests that 'rng' does not always return the same value. + with self.session(): + with self.test_scope(): + x = rng(dtype) + + # The random-number generator, if working correctly, should produce the + # same output multiple times with low probability. + y = self.evaluate(x) + z = self.evaluate(x) + w = self.evaluate(x) + + # We use exact equality here. If the random-number generator is producing + # deterministic output, all three outputs will be bitwise identical. + self.assertTrue((not np.array_equal(y, z)) or + (not np.array_equal(z, w)) or (not np.array_equal(y, w))) + + def testRandomUniformIsNotConstant(self): + + def rng(dtype): + dtype = dtypes.as_dtype(dtype) + return random_ops.random_uniform(shape=[2], dtype=dtype, maxval=dtype.max) + + for dtype in self._random_types(): + self._testRngIsNotConstant(rng, dtype) + + def testRandomNormalIsNotConstant(self): + + def rng(dtype): + return random_ops.random_normal(shape=[2], dtype=dtype) + + for dtype in self._random_types() & self.float_types: + self._testRngIsNotConstant(rng, dtype) + + @parameterized.parameters({ + 'mean': 1.4, + 'stddev': 1.2 + }, { + 'mean': 2.3, + 'stddev': 2.0 + }) + def testRandomNormal(self, mean, stddev): + num_elts = 1000000 + for dtype in self._random_types() & self.float_types: + with self.session(): + with self.test_scope(): + normal = random_ops.random_normal([num_elts], + dtype=dtype, + mean=mean, + stddev=stddev) + self._checkTruncatedNormalIsInRange( + normal, + a=normal.dtype.min, + b=normal.dtype.max, + mu=mean, + sigma=stddev, + count=num_elts, + stat_test=True) + + def testRandomUniformIsInRange(self): + for dtype in self._random_types(): + # TODO (b/112272078): enable bfloat16 for CPU and GPU when the bug is + # fixed. + if (self.device in ['XLA_GPU', 'XLA_CPU' + ]) and (dtype in [dtypes.bfloat16, dtypes.half]): + continue + with self.session(): + with self.test_scope(): + x = random_ops.random_uniform( + shape=[1000], dtype=dtype, minval=-2, maxval=33) + y = self.evaluate(x) + msg = str(y) + str(dtype) + self.assertEqual((y >= -2).sum(), 1000, msg) + self.assertEqual((y < 33).sum(), 1000, msg) + + def testTruncatedNormalIsNotConstant(self): + + def rng(dtype): + return random_ops.truncated_normal(shape=[2], dtype=dtype) + + # TODO(b/34339814): make this test work with 16 bit float types. + for dtype in self._random_types() & {np.float32, np.float64}: + self._testRngIsNotConstant(rng, dtype) + + def _checkTruncatedNormalIsInRange(self, x, a, b, mu, sigma, count, + stat_test): + + def normal_cdf(x): + return .5 * math.erfc(-x / math.sqrt(2)) + + def normal_pdf(x): + return math.exp(-(x**2) / 2.) / math.sqrt(2 * math.pi) + + def probit(x): + return self.evaluate(special_math.ndtri(x)) + + y = self.evaluate(x) + + alpha = (a - mu) / sigma + beta = (b - mu) / sigma + z = normal_cdf(beta) - normal_cdf(alpha) + + self.assertEqual((y >= a).sum(), count) + self.assertEqual((y <= b).sum(), count) + + # Skip statistical test for low probability regions. + if not stat_test: + return + + # For more information on these calculations, see: + # Burkardt, John. "The Truncated Normal Distribution". + # Department of Scientific Computing website. Florida State University. + expected_mean = mu + (normal_pdf(alpha) - normal_pdf(beta)) / z * sigma + actual_mean = np.mean(y, dtype=np.float64) + if x.dtype == dtypes.bfloat16: + atol = rtol = 1e-1 + else: + atol = rtol = 2e-2 + self.assertAllClose(actual_mean, expected_mean, atol=atol, rtol=rtol) + + expected_median = mu + probit( + (normal_cdf(alpha) + normal_cdf(beta)) / 2.) * sigma + actual_median = np.median(y) + self.assertAllClose(actual_median, expected_median, atol=atol, rtol=rtol) + + 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, dtype=np.float64) + self.assertAllClose( + actual_variance, expected_variance, atol=atol, rtol=rtol) + + def testTruncatedNormalIsInRange(self): + count = 10000000 + # TODO(b/34339814): make this test work with 16 bit float types. + for dtype in self._random_types() & {np.float32, np.float64}: + with self.session(): + with self.test_scope(): + x = random_ops.truncated_normal(shape=[count], dtype=dtype) + self._checkTruncatedNormalIsInRange( + x, a=-2, b=2, mu=0, sigma=1, count=count, stat_test=True) + + def _implParameterizedTruncatedNormalIsInRange(self, a, b, mu, sigma, count, + stat_test): + # TODO(b/34339814): make this test work with 16 bit float types. + for dtype in self._random_types() & {np.float32, np.float64}: + with self.session(): + with self.test_scope(): + x = random_ops.parameterized_truncated_normal( + shape=[count], + dtype=dtype, + means=mu, + stddevs=sigma, + minvals=a, + maxvals=b) + self._checkTruncatedNormalIsInRange( + x, a=a, b=b, mu=mu, sigma=sigma, count=count, stat_test=stat_test) + + def testParameterizedTruncatedNormalBroadcasting(self): + for dtype in self._random_types() & {np.float32, np.float64}: + with self.session(): + with self.test_scope(): + a = -1. + b = 1. + mu = 0. + sigma = 1. + count = 10000000 + x = random_ops.parameterized_truncated_normal( + shape=[1, count], + dtype=dtype, + means=mu, + stddevs=sigma, + minvals=[a], + maxvals=[b]) + self._checkTruncatedNormalIsInRange( + x, a=a, b=b, mu=mu, sigma=sigma, count=count, stat_test=True) + + def testParameterizedTruncatedNormalBatched(self): + # TODO(b/112289993): Make this test work with dtype np.float64. + for dtype in self._random_types() & {np.float32}: + with self.session(): + with self.test_scope(): + count = 10000000 + a = -100. + b = 100. + mu0 = 0. + mu1 = 1. + sigma = .1 + x = random_ops.parameterized_truncated_normal( + shape=[2, count], + dtype=dtype, + means=[mu0, mu1], + stddevs=sigma, + minvals=[a], + maxvals=[b]) + self._checkTruncatedNormalIsInRange( + x[0], a=a, b=b, mu=mu0, sigma=sigma, count=count, stat_test=True) + self._checkTruncatedNormalIsInRange( + x[1], a=a, b=b, mu=mu1, sigma=sigma, count=count, stat_test=True) + + def testParameterizedTruncatedNormalIsInRangeCenter(self): + count = 10000000 + self._implParameterizedTruncatedNormalIsInRange( + a=-10, b=20, mu=5, sigma=5, count=count, stat_test=True) + + def testParameterizedTruncatedNormalIsInRangeLeft(self): + count = 10000000 + # the region is on the left side of the parent normal distribution + self._implParameterizedTruncatedNormalIsInRange( + a=-10, b=-4, mu=0, sigma=1, count=count, stat_test=False) + self._implParameterizedTruncatedNormalIsInRange( + a=-np.inf, b=-4, mu=0, sigma=1, count=count, stat_test=False) + + def testParameterizedTruncatedNormalIsInRangeRight(self): + count = 10000000 + # the region is on the right side of the parent normal distribution + self._implParameterizedTruncatedNormalIsInRange( + a=4, b=10, mu=0, sigma=1, count=count, stat_test=False) + self._implParameterizedTruncatedNormalIsInRange( + a=4, b=np.inf, mu=0, sigma=1, count=count, stat_test=False) + + def testShuffle1d(self): + with self.session(): + with self.test_scope(): + x = math_ops.range(1 << 16) + shuffle = random_ops.random_shuffle(x) + result = self.evaluate(shuffle) + expected = range(1 << 16) + # Compare sets to avoid randomness behavior changes but make sure still + # have all the values. + self.assertAllEqual(set(result), set(expected)) + + def testShuffle2d(self): + with self.session(): + with self.test_scope(): + x = array_ops.diag(math_ops.range(20)) + shuffle = random_ops.random_shuffle(x) + result = self.evaluate(shuffle) + expected = np.diag(range(20)).flatten() + # Compare sets to avoid randomness behavior changes but make sure still + # have all the values. + self.assertAllEqual(len(result.flatten()), len(expected)) + self.assertAllEqual(set(result.flatten()), set(expected)) + + def testRandomShuffleInputRank0(self): + with self.session(): + with self.test_scope(): + shuffle = random_ops.random_shuffle(value=1e20) + self.evaluate(shuffle) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/randomized_tests.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tests/randomized_tests.cc new file mode 100644 index 0000000000000000000000000000000000000000..cede4db3f55646c19fb3613f6700199b64f85d47 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/randomized_tests.cc @@ -0,0 +1,4947 @@ +/* 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. +==============================================================================*/ + +// Randomized tests for XLA implementations of Tensorflow operations. +// +// For each operator, the tests in this file choose a set of random inputs and +// attributes. The test then compares the outputs of the operator when executed +// via Tensorflow using the CPU device and when executed via XLA. +// +// By default, each test chooses a random seed nondeterministically (using +// std::random_device). However, a particular choice of random seed can be +// forced using the flag --tf_xla_random_seed; each test logs the +// flag value necessary to reproduce its outputs. +// +// Example usage: +// Run tests, comparing the Tensorflow CPU operators with their XLA-compiled +// counterparts: +// randomized_tests \ +// --tf_xla_test_use_jit=true --tf_xla_test_device=CPU:0 \ +// --tf_xla_test_repetitions=20 + +// TODO(phawkins): add tests for: +// * DepthwiseConv2DNative +// * Gather +// * InvertPermutation +// * MaxPoolGrad (requires implementation of forward operator) +// * Select +// * Unpack +// +// TODO(phawkins): improve tests for: +// * StridedSliceGrad (need to use shape function to compute sensible inputs) + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/fixed_array.h" +#include "absl/container/flat_hash_set.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/jit/defs.h" +#include "tensorflow/compiler/jit/flags.h" +#include "xla/tsl/lib/core/status_test_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/status.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/framework/device.h" +#include "tensorflow/core/framework/device_factory.h" +#include "tensorflow/core/framework/kernel_shape_util.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/node_def_builder.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/numeric_types.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.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/graph.h" +#include "tensorflow/core/platform/bfloat16.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/public/session.h" +#include "tensorflow/core/public/session_options.h" +#include "tensorflow/core/util/command_line_flags.h" +#include "tensorflow/core/util/device_name_utils.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +// Command line flags: see main() below. +int64_t tf_xla_random_seed = 0; +int32_t tf_xla_test_repetitions = 20; +int64_t tf_xla_max_tensor_size = 10000LL; +std::string* tf_xla_test_device_ptr; // initial value set in main() +std::string* tf_xla_reference_device_ptr; // initial value set in main() +bool tf_xla_test_use_jit = true; +bool tf_xla_test_use_mlir = false; + +std::string LocalDeviceToFullDeviceName(const std::string& device) { + return absl::StrCat("/job:localhost/replica:0/task:0/device:", device); +} + +constexpr std::array kAllXlaTypes = { + {DT_INT32, DT_INT64, DT_FLOAT, DT_BOOL, DT_COMPLEX64}}; +constexpr std::array kAllNumberTypes = { + {DT_INT32, DT_INT64, DT_FLOAT, DT_COMPLEX64}}; + +// An OpTestBuilder is a graph builder class that takes as input an operator to +// test, its inputs and attributes, and builds a graph that executes the +// operator. +class OpTestBuilder { + public: + explicit OpTestBuilder(const std::string& op_name); + + // Adds an input 'tensor' as a Placeholder node. + OpTestBuilder& Input(const Tensor& tensor); + + // Adds a random input tensor with 'type' as a Placeholder node. + // If 'dims' is not provided, RandomDims() is used. + OpTestBuilder& RandomInput(DataType type); + OpTestBuilder& RandomInput(DataType type, std::vector dims); + + // As RandomInput but the values are unique. + OpTestBuilder& RandomUniqueInput(DataType type, std::vector dims); + + // Add variadic input tensors as Placehodler nodes. + OpTestBuilder& VariadicInput(const std::vector& tensor); + + // Sets an attribute. + template + OpTestBuilder& Attr(absl::string_view attr_name, T&& value); + + // Overload needed to allow {...} expressions for value. + template + OpTestBuilder& Attr(absl::string_view attr_name, + std::initializer_list value); + + // Adds nodes that executes the operator under test on 'device' to 'graphdef'. + // If 'use_jit' is true, marks the operator under test to be compiled by XLA. + // The graph will consist of one Placeholder node per input, the operator + // itself, and one Identity node per output. If 'test_node_def' is not null, + // sets it to the NodeDef of the operator under test. Fills 'inputs' and + // 'outputs' with the names of the input placeholder nodes and the output + // identity nodes, respectively. + absl::Status BuildGraph(const std::string& name_prefix, + const std::string& device, bool use_jit, + GraphDef* graphdef, NodeDef** test_node_def, + std::vector* inputs, + std::vector* outputs) const; + + struct InputDescription { + Tensor tensor; + + DataType type = DT_INVALID; + bool has_dims = false; + bool needs_unique_values = false; + std::vector dims; + }; + + const std::vector& inputs() const { return inputs_; } + + private: + NodeDef node_def_; + std::vector inputs_; +}; + +OpTestBuilder::OpTestBuilder(const std::string& op_name) { + node_def_.set_op(op_name); +} + +OpTestBuilder& OpTestBuilder::Input(const Tensor& tensor) { + VLOG(1) << "Adding input: " << tensor.DebugString(); + InputDescription input; + input.tensor = tensor; + inputs_.push_back(input); + return *this; +} + +OpTestBuilder& OpTestBuilder::RandomInput(DataType type) { + VLOG(1) << "Adding random input: " << type; + InputDescription input; + input.type = type; + inputs_.push_back(input); + return *this; +} + +OpTestBuilder& OpTestBuilder::RandomInput(DataType type, + std::vector dims) { + VLOG(1) << "Adding input: " << type << " " << TensorShape(dims).DebugString(); + InputDescription input; + input.type = type; + input.has_dims = true; + input.dims = std::move(dims); + inputs_.push_back(input); + return *this; +} + +OpTestBuilder& OpTestBuilder::RandomUniqueInput(DataType type, + std::vector dims) { + VLOG(1) << "Adding input: " << type << " " << TensorShape(dims).DebugString(); + InputDescription input; + input.type = type; + input.has_dims = true; + input.needs_unique_values = true; + input.dims = std::move(dims); + inputs_.push_back(input); + return *this; +} + +OpTestBuilder& OpTestBuilder::VariadicInput( + const std::vector& tensors) { + VLOG(1) << "Adding variadic input of length " << tensors.size() << ":"; + for (auto& t : tensors) { + Input(t); + } + return *this; +} + +template +OpTestBuilder& OpTestBuilder::Attr(absl::string_view attr_name, T&& value) { + AddNodeAttr(attr_name, std::forward(value), &node_def_); + return *this; +} + +template +OpTestBuilder& OpTestBuilder::Attr(absl::string_view attr_name, + std::initializer_list value) { + Attr>(attr_name, std::move(value)); + return *this; +} + +absl::Status OpTestBuilder::BuildGraph( + const std::string& name_prefix, const std::string& device, bool use_jit, + GraphDef* graphdef, NodeDef** test_node_def, + std::vector* inputs, std::vector* outputs) const { + OpRegistryInterface* op_registry = OpRegistry::Global(); + + const OpDef* op_def; + TF_RETURN_IF_ERROR(op_registry->LookUpOpDef(node_def_.op(), &op_def)); + + NodeDef* test_def = graphdef->add_node(); + *test_def = node_def_; + test_def->set_name(absl::StrCat(name_prefix, "_op_under_test")); + test_def->set_device(device); + AddDefaultsToNodeDef(*op_def, test_def); + if (use_jit) { + AddNodeAttr(kXlaCompileAttr, true, test_def); + } + VLOG(1) << "Op under test: " << test_def->DebugString(); + + DataTypeVector input_types, output_types; + TF_RETURN_IF_ERROR( + InOutTypesForNode(*test_def, *op_def, &input_types, &output_types)); + + // Build feed and fetch nodes. + for (int i = 0; i < input_types.size(); ++i) { + NodeDef* def = graphdef->add_node(); + std::string name = absl::StrCat(name_prefix, "_input_", i); + TF_RETURN_IF_ERROR(NodeDefBuilder(name, "Placeholder") + .Device(device) + .Attr("dtype", input_types[i]) + .Finalize(def)); + inputs->push_back(name); + test_def->add_input(name); + } + + for (int i = 0; i < output_types.size(); ++i) { + NodeDef* def = graphdef->add_node(); + std::string name = absl::StrCat(name_prefix, "_output_", i); + TF_RETURN_IF_ERROR(NodeDefBuilder(name, "Identity") + .Device(device) + .Attr("T", output_types[i]) + .Input(test_def->name(), i, output_types[i]) + .Finalize(def)); + outputs->push_back(name); + } + + if (test_node_def) { + *test_node_def = test_def; + } + + return absl::OkStatus(); +} + +// Test fixture. The fixture manages the random number generator and its seed, +// and has a number of convenience methods for building random Tensors, shapes, +// etc. +class OpTest : public ::testing::Test { + public: + OpTest(); + + enum TestResult { + // The test saw an unrecoverable error. Don't try any more runs. + kFatalError, + // The parameters of the test were invalid (e.g., the "golden" + // implementation failed, or the parameters are oversize). Reruns are ok. + kInvalid, + // The test ran successfully, and we have a verdict. Does *not* mean the + // test passed. + kOk, + }; + + // Runs 'fn' up to --tf_xla_test_repetitions times, or until a test failure + // occurs; whichever happens first. Reruns if the TestResult is kInvalid. + void Repeatedly(const std::function& fn); + + // Select a random element from 'candidates'. + template + T Choose(absl::Span candidates); + + static constexpr int kDefaultMaxRank = 5; + static constexpr int64_t kDefaultMaxDimensionSize = 256LL; + + // Returns true if 'dims' have a size less than tf_xla_max_tensor_size. + bool TensorSizeIsOk(absl::Span dims); + + // Returns a random dimension size, in the range [min, max). + int64_t RandomDim(int64_t min = 0, int64_t max = kDefaultMaxDimensionSize); + + // Returns a random shape. The tensor has rank in the range [min_rank, + // max_rank). Each dimension has size [min_size, max_size). + std::vector RandomDims(int min_rank = 0, + int max_rank = kDefaultMaxRank, + int64_t min_size = 0, + int64_t max_size = kDefaultMaxDimensionSize); + + // Given a shape 'dims', build dimensions that are broadcastable to 'dims'. + std::vector BroadcastableToDims(std::vector dims); + + // Given a shape 'dims', build a pair of dimensions such that one broadcasts + // to the other. + std::pair, std::vector> BroadcastableDims( + std::vector dims); + + // Builds a random pair of broadcastable dims. + // TODO(phawkins): currently the maximum rank is 3, because broadcasting > 3 + // dimensions is unimplemented by the Tensorflow Eigen code (b/29268487) + std::pair, std::vector> BroadcastableDims(); + + // Returns a tensor filled with random but "reasonable" values from the middle + // of the type's range. If the shape is omitted, a random shape is used. + // TODO(phawkins): generalize this code to a caller-supplied distribution. + Tensor RandomTensor(DataType dtype, bool needs_unique_values, + absl::Span shape); + Tensor RandomTensor(DataType dtype); + + // Like RandomTensor, but uses values >= 0. + Tensor RandomNonNegativeTensor(DataType dtype, + absl::Span shape); + Tensor RandomNonNegativeTensor(DataType dtype); + + // Like RandomTensor, but all values are in the range [lo, hi]. + template + Tensor RandomBoundedTensor(DataType dtype, T lo, T hi, + bool needs_unique_values, + absl::Span shape); + template + Tensor RandomBoundedTensor(DataType dtype, T lo, T hi, + bool needs_unique_values); + + // Like RandomTensor, but the value at index i is in the range [lo[i], hi[i]]. + Tensor RandomBoundedTensor(DataType dtype, Tensor lo, Tensor hi); + + // Like RandomTensor, but return a pair {left, right} with + // left[i] <= right[i]. + std::pair RandomLteTensors(DataType dtype, + absl::Span shape); + std::pair RandomLteTensors(DataType dtype); + + // Returns a random subset of the integers in the range [0, rank), suitable + // for use as reduction indices. + Tensor RandomReductionIndices(int rank); + + // Returns a random bit. + bool RandomBool(); + + // Randomly choose a seed for a random number generator. + int64_t RandomSeed(); + + struct WindowedSpatialDims { + Padding padding; + std::vector kernel_dims; + std::vector stride_dims; + std::vector input_dims; + std::vector output_dims; + }; + // Choose spatial dimensions for a windowed op such as pooling or convolution. + WindowedSpatialDims ChooseWindowedSpatialDims(int num_spatial_dims); + + struct BatchMatMulArguments { + std::vector lhs_dims; + std::vector rhs_dims; + DataType dtype; + bool adj_lhs; + bool adj_rhs; + }; + // Choose arguments for the tf.BatchMatMul{V2} ops. + BatchMatMulArguments ChooseBatchMatMulArguments(bool broadcastable_batch); + + struct ConcatArguments { + std::vector values; + Tensor axis; + int n; + DataType type; + DataType type_idx; + }; + // Choose arguments for the tf.Concat{V2} ops. + ConcatArguments ChooseConcatArguments(bool int64_idx_allowed); + + struct EinsumArguments { + std::vector lhs_dims; + std::vector rhs_dims; + DataType type; + std::string equation; + }; + // Choose arguments for the tf.{Xla}Einsum ops. + EinsumArguments ChooseEinsumArguments(); + + struct GatherArguments { + int64_t batch_dims; + DataType axis_type; + DataType indices_type; + DataType params_type; + std::vector params_shape; + Tensor indices; + Tensor axis; + }; + // Choose arguments for the tf.Gather{V2} ops. + GatherArguments ChooseGatherArguments(bool axis_0); + + struct PadArguments { + DataType input_type; + DataType paddings_type; + std::vector input_shape; + Tensor paddings; + Tensor constant_values; + }; + // Choose arguments for the tf.Pad{V2} ops. + PadArguments ChoosePadArguments(); + + struct ScatterArguments { + DataType type; + DataType indices_type; + Tensor indices; + Tensor updates; + std::vector shape; + }; + // Choose arguments for ScatterNd and TensorScatterUpdate. + ScatterArguments ChooseScatterArguments(); + + struct SliceArguments { + DataType type; + DataType indices_type; + std::vector shape; + Tensor indices; + std::vector size; + }; + // Choose arguments for the tf.{XlaDynamicUpdate}Slice ops. + SliceArguments ChooseSliceArguments(bool neg_one_size); + + struct XlaDotArguments { + std::vector lhs_dims; + std::vector rhs_dims; + std::string dnums_encoded; + std::string precision_config_encoded; + DataType dtype; + }; + // Choose arguments for tf.XlaDot operation. + XlaDotArguments ChooseXlaDotArguments(); + + // Builds dimensions for a windowed op such as pooling or convolution, + // including a batch and feature dimension. + std::vector ImageDims(TensorFormat format, int batch, int feature, + const std::vector& spatial_dims); + + // Converts an int64 vector to an int32 vector. + std::vector AsInt32s(const std::vector& int64s); + + std::mt19937& generator() { return *generator_; } + + // Run the test case described by 'builder' with and without XLA and check + // that the outputs are close. Tensors x and y are close if they have the same + // type, same shape, and have close values. For floating-point tensors, the + // element-wise difference between x and y must no more than + // atol + rtol * abs(x); or both elements may be NaN or infinity. For + // non-floating-point tensors the element values must match exactly. + TestResult ExpectTfAndXlaOutputsAreClose(const OpTestBuilder& builder, + double atol = 1e-2, + double rtol = 1e-2); + + protected: + // Per-test state: + std::unique_ptr generator_; + + std::unique_ptr session_; + + // Number of test cases built in 'session_'. Used to uniquify node names. + int num_tests_ = 0; +}; + +OpTest::OpTest() { + // Creates a random-number generator for the test case. Use the value of + // --tf_xla_random_seed as the seed, if provided. + int64_t s = tf_xla_random_seed; + unsigned int seed; + if (s <= 0) { + std::random_device random_device; + seed = random_device(); + } else { + seed = static_cast(s); + } + LOG(ERROR) << "Random seed for test case: " << seed + << ". To reproduce the " + "results of this test, pass flag --tf_xla_random_seed=" + << seed; + generator_ = std::make_unique(seed); +} + +namespace { +template +Tensor TensorFromValues(DataType dtype, absl::Span shape, + absl::Span vals) { + Tensor tensor(dtype, TensorShape(shape)); + test::FillValues(&tensor, vals); + return tensor; +} + +int64_t ShapeNumVals(absl::Span shape) { + int64_t num_vals = 1; + for (int i = 0; i < shape.size(); ++i) { + num_vals *= shape[i]; + } + return num_vals; +} +} // namespace + +// TensorGenerator is an abstract class that has one implementing class for each +// (DataType,T) pair. The implementing class implements RandomVals, which is +// the only Tensor generation code that is specific to the DataType. +template +class TensorGenerator { + public: + explicit TensorGenerator(OpTest& test) : test_(test) {} + virtual ~TensorGenerator() = default; + virtual DataType dtype() = 0; + virtual void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) = 0; + + Tensor RandomTensor(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::Span shape) { + absl::FixedArray vals(ShapeNumVals(shape)); + RandomVals(lo, hi, needs_unique_values, vals); + return TensorFromValues(dtype(), shape, absl::Span(vals)); + } + + std::pair RandomLteTensors(absl::Span shape) { + int64_t num_vals = ShapeNumVals(shape); + absl::FixedArray less(num_vals); + RandomVals({}, {}, false, less); + absl::FixedArray greater(num_vals); + RandomVals({}, {}, false, greater); + for (int i = 0; i < num_vals; ++i) { + if (less[i] > greater[i]) { + std::swap(less[i], greater[i]); + } + } + std::pair pair( + TensorFromValues(dtype(), shape, absl::Span(less)), + TensorFromValues(dtype(), shape, absl::Span(greater))); + return pair; + } + + protected: + OpTest& test_; +}; + +class TensorGeneratorFloat : public TensorGenerator { + public: + explicit TensorGeneratorFloat(OpTest& test) : TensorGenerator(test) {} + DataType dtype() override { return DT_FLOAT; } + void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) override { + absl::flat_hash_set already_generated; + std::uniform_real_distribution distribution(lo.value_or(-1.0f), + hi.value_or(1.0f)); + for (int64_t i = 0; i < vals.size(); ++i) { + float generated; + do { + generated = distribution(test_.generator()); + } while (needs_unique_values && + !already_generated.insert(generated).second); + vals[i] = (generated); + } + } +}; + +class TensorGeneratorDouble : public TensorGenerator { + public: + explicit TensorGeneratorDouble(OpTest& test) : TensorGenerator(test) {} + DataType dtype() override { return DT_DOUBLE; } + void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) override { + absl::flat_hash_set already_generated; + std::uniform_real_distribution distribution(lo.value_or(-1.0), + hi.value_or(1.0)); + for (int64_t i = 0; i < vals.size(); ++i) { + double generated; + do { + generated = distribution(test_.generator()); + } while (needs_unique_values && + !already_generated.insert(generated).second); + vals[i] = generated; + } + } +}; + +class TensorGeneratorComplex64 : public TensorGenerator { + public: + explicit TensorGeneratorComplex64(OpTest& test) : TensorGenerator(test) {} + DataType dtype() override { return DT_COMPLEX64; } + void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) override { + absl::flat_hash_set> already_generated; + if (lo || hi) { + LOG(FATAL) << "Lower or upper bounds are not supported for complex64."; + } + std::uniform_real_distribution distribution(-1.0f, 1.0f); + for (int64_t i = 0; i < vals.size(); ++i) { + complex64 generated; + do { + generated = complex64(distribution(test_.generator()), + distribution(test_.generator())); + } while (needs_unique_values && + !already_generated + .insert(std::make_pair(generated.real(), generated.imag())) + .second); + vals[i] = generated; + } + } +}; + +class TensorGeneratorInt32 : public TensorGenerator { + public: + explicit TensorGeneratorInt32(OpTest& test) : TensorGenerator(test) {} + DataType dtype() override { return DT_INT32; } + void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) override { + absl::flat_hash_set already_generated; + std::uniform_int_distribution distribution(lo.value_or(-(1 << 20)), + hi.value_or(1 << 20)); + for (int64_t i = 0; i < vals.size(); ++i) { + int32_t generated; + do { + generated = distribution(test_.generator()); + } while (needs_unique_values && + !already_generated.insert(generated).second); + vals[i] = generated; + } + } +}; + +class TensorGeneratorInt64 : public TensorGenerator { + public: + explicit TensorGeneratorInt64(OpTest& test) : TensorGenerator(test) {} + DataType dtype() override { return DT_INT64; } + void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) override { + absl::flat_hash_set already_generated; + std::uniform_int_distribution distribution( + lo.value_or(-(1LL << 40)), hi.value_or(1LL << 40)); + for (int64_t i = 0; i < vals.size(); ++i) { + int64_t generated; + do { + generated = distribution(test_.generator()); + } while (needs_unique_values && + !already_generated.insert(generated).second); + vals[i] = generated; + } + } +}; + +class TensorGeneratorBool : public TensorGenerator { + public: + explicit TensorGeneratorBool(OpTest& test) : TensorGenerator(test) {} + DataType dtype() override { return DT_BOOL; } + void RandomVals(std::optional lo, std::optional hi, + bool needs_unique_values, + absl::FixedArray& vals) override { + absl::flat_hash_set already_generated; + if (lo || hi) { + LOG(FATAL) << "Lower or upper bounds are not supported for bool."; + } + std::bernoulli_distribution distribution; + for (int64_t i = 0; i < vals.size(); ++i) { + bool generated; + do { + generated = distribution(test_.generator()); + } while (needs_unique_values && + !already_generated.insert(generated).second); + vals[i] = generated; + } + } +}; + +void OpTest::Repeatedly(const std::function& fn) { + int const max_repetitions = tf_xla_test_repetitions; + int valid_test_runs = 0; + // We run up to 100 * max_repetitions times; the idea is that if we roll the + // dice enough times we will find some valid parameters. We want to put an + // upper limit on the number iterations just in case the probability of + // finding feasible parameters is very low. + for (int i = 0; !HasFailure() && i < max_repetitions * 100 && + valid_test_runs < max_repetitions; + ++i) { + TestResult result = fn(); + switch (result) { + case kOk: + ++valid_test_runs; + break; + + case kFatalError: + ASSERT_TRUE(false) << "Test had fatal failure"; + return; + + case kInvalid: + break; + } + } + if (!HasFailure()) { + EXPECT_GE(valid_test_runs, max_repetitions) + << "Not enough test instances passed; this means that either the " + "golden implementation is buggy or the operator harness is not " + "producing well-formed test cases with a high probability."; + } +} + +template +T OpTest::Choose(absl::Span candidates) { + std::uniform_int_distribution d(0, candidates.size() - 1); + return candidates[d(generator())]; +} + +int64_t OpTest::RandomDim(int64_t min, int64_t max) { + std::uniform_int_distribution size_distribution(min, max - 1); + return size_distribution(generator()); +} + +bool OpTest::TensorSizeIsOk(absl::Span dims) { + int64_t size = 1LL; + for (int64_t dim : dims) { + size *= dim; + } + return size < tf_xla_max_tensor_size; +} + +std::vector OpTest::RandomDims(int min_rank, int max_rank, + int64_t min_size, int64_t max_size) { + CHECK_LE(0, min_rank); + CHECK_LE(min_rank, max_rank); + std::uniform_int_distribution rank_distribution(min_rank, max_rank); + int rank = rank_distribution(generator()); + std::vector dims(rank); + if (rank == 0) { + return dims; + } + int64_t per_dim_limit = std::pow(tf_xla_max_tensor_size, 1.0 / rank); + int64_t per_dim_max = std::min(max_size, per_dim_limit); + std::generate(dims.begin(), dims.end(), [this, min_size, per_dim_max]() { + return RandomDim(min_size, per_dim_max); + }); + CHECK(TensorSizeIsOk(dims)); // Crash OK + return dims; +} + +bool OpTest::RandomBool() { + std::bernoulli_distribution d(0.5); + return d(generator()); +} + +int64_t OpTest::RandomSeed() { + std::uniform_int_distribution seed_dist( + std::numeric_limits::min(), std::numeric_limits::max()); + int64_t seed = seed_dist(generator()); + if (seed == 0) return 1; + return seed; +} + +Tensor OpTest::RandomTensor(DataType dtype, bool needs_unique_values, + absl::Span shape) { + switch (dtype) { + case DT_FLOAT: + return TensorGeneratorFloat(*this).RandomTensor( + {}, {}, needs_unique_values, shape); + case DT_DOUBLE: + return TensorGeneratorDouble(*this).RandomTensor( + {}, {}, needs_unique_values, shape); + case DT_COMPLEX64: + return TensorGeneratorComplex64(*this).RandomTensor( + {}, {}, needs_unique_values, shape); + case DT_INT32: + return TensorGeneratorInt32(*this).RandomTensor( + {}, {}, needs_unique_values, shape); + case DT_INT64: + return TensorGeneratorInt64(*this).RandomTensor( + {}, {}, needs_unique_values, shape); + case DT_BOOL: + return TensorGeneratorBool(*this).RandomTensor( + {}, {}, needs_unique_values, shape); + default: + LOG(FATAL) << "Unimplemented type " << dtype << " in RandomTensor"; + } +} + +Tensor OpTest::RandomTensor(DataType dtype) { + return RandomTensor(dtype, /*needs_unique_values=*/false, RandomDims()); +} + +Tensor OpTest::RandomNonNegativeTensor(DataType dtype, + absl::Span shape) { + switch (dtype) { + case DT_FLOAT: + return TensorGeneratorFloat(*this).RandomTensor({0.0f}, {}, false, shape); + case DT_DOUBLE: + return TensorGeneratorDouble(*this).RandomTensor({0.0}, {}, false, shape); + case DT_INT32: + return TensorGeneratorInt32(*this).RandomTensor({0}, {}, false, shape); + case DT_INT64: + return TensorGeneratorInt64(*this).RandomTensor({0}, {}, false, shape); + default: + LOG(FATAL) << "Unimplemented type " << dtype + << " in RandomNonNegativeTensor"; + } +} + +Tensor OpTest::RandomNonNegativeTensor(DataType dtype) { + return RandomNonNegativeTensor(dtype, RandomDims()); +} + +template +Tensor OpTest::RandomBoundedTensor(DataType dtype, T lo, T hi, + bool needs_unique_values, + absl::Span shape) { + switch (dtype) { + case DT_FLOAT: + return TensorGeneratorFloat(*this).RandomTensor( + {lo}, {hi}, needs_unique_values, shape); + case DT_DOUBLE: + return TensorGeneratorDouble(*this).RandomTensor( + {lo}, {hi}, needs_unique_values, shape); + case DT_INT32: + return TensorGeneratorInt32(*this).RandomTensor( + {lo}, {hi}, needs_unique_values, shape); + case DT_INT64: + return TensorGeneratorInt64(*this).RandomTensor( + {lo}, {hi}, needs_unique_values, shape); + default: + LOG(FATAL) << "RandomBoundedTensor does not support type " << dtype + << "."; + } +} + +template +Tensor OpTest::RandomBoundedTensor(DataType dtype, T lo, T hi, + bool needs_unique_values) { + return RandomBoundedTensor(dtype, lo, hi, needs_unique_values, + RandomDims()); +} + +Tensor OpTest::RandomBoundedTensor(DataType dtype, Tensor lo, Tensor hi) { + TensorShape shape = lo.shape(); + if (hi.shape() != shape) { + LOG(FATAL) << "hi and lo do not have the same shape in RandomBoundedTensor"; + } + if (hi.dtype() != dtype) { + LOG(FATAL) << "hi does not have the expected dtype in RandomBoundedTensor"; + } + if (lo.dtype() != dtype) { + LOG(FATAL) << "lo does not have the expected dtype in RandomBoundedTensor"; + } + Tensor tensor(dtype, shape); + switch (dtype) { + case DT_FLOAT: { + auto lo_flat = lo.flat(); + auto hi_flat = hi.flat(); + test::FillFn(&tensor, [this, &lo_flat, &hi_flat](int i) -> float { + std::uniform_real_distribution distribution(lo_flat(i), + hi_flat(i)); + return distribution(generator()); + }); + break; + } + case DT_DOUBLE: { + auto lo_flat = lo.flat(); + auto hi_flat = hi.flat(); + test::FillFn( + &tensor, [this, &lo_flat, &hi_flat](int i) -> double { + std::uniform_real_distribution distribution(lo_flat(i), + hi_flat(i)); + return distribution(generator()); + }); + break; + } + case DT_INT32: { + auto lo_flat = lo.flat(); + auto hi_flat = hi.flat(); + test::FillFn( + &tensor, [this, &lo_flat, &hi_flat](int i) -> int32_t { + std::uniform_int_distribution distribution(lo_flat(i), + hi_flat(i)); + return distribution(generator()); + }); + break; + } + case DT_INT64: { + auto lo_flat = lo.flat(); + auto hi_flat = hi.flat(); + test::FillFn( + &tensor, [this, &lo_flat, &hi_flat](int i) -> int64_t { + std::uniform_int_distribution distribution(lo_flat(i), + hi_flat(i)); + return distribution(generator()); + }); + break; + } + default: + LOG(FATAL) << "RandomBoundedTensor does not support type " << dtype + << "."; + } + return tensor; +} + +std::pair OpTest::RandomLteTensors( + DataType dtype, absl::Span shape) { + switch (dtype) { + case DT_FLOAT: + return TensorGeneratorFloat(*this).RandomLteTensors(shape); + case DT_DOUBLE: + return TensorGeneratorDouble(*this).RandomLteTensors(shape); + case DT_COMPLEX64: + LOG(FATAL) << "RandomLteTensors unavailable for DT_COMPLEX64"; + break; + case DT_INT32: + return TensorGeneratorInt32(*this).RandomLteTensors(shape); + case DT_INT64: + return TensorGeneratorInt64(*this).RandomLteTensors(shape); + case DT_BOOL: + LOG(FATAL) << "RandomLteTensors unavailable for DT_BOOL"; + break; + default: + LOG(FATAL) << "Unimplemented type " << dtype << " in RandomLteTensors"; + } + Tensor tensor(dtype, TensorShape(shape)); + return std::pair(tensor, tensor); +} + +std::pair OpTest::RandomLteTensors(DataType dtype) { + return RandomLteTensors(dtype, RandomDims()); +} + +std::vector OpTest::BroadcastableToDims(std::vector dims) { + if (dims.empty()) return dims; + + // Remove some dimensions from the front of 'dims'. + size_t skip = + std::uniform_int_distribution(0, dims.size() - 1)(generator()); + + std::vector bdims(dims.begin() + skip, dims.end()); + + // Randomly replace some of the remaining dimensions of 'dims' with 1. + std::bernoulli_distribution random_bool; + + for (int64_t& dim : bdims) { + if (random_bool(generator())) { + dim = 1LL; + } + } + return bdims; +} + +std::pair, std::vector> OpTest::BroadcastableDims( + std::vector dims) { + auto bdims = BroadcastableToDims(dims); + // Possibly swap the roles of 'dims' and 'bdims'. + std::bernoulli_distribution random_bool; + if (random_bool(generator())) { + dims.swap(bdims); + } + return {dims, bdims}; +} + +std::pair, std::vector> +OpTest::BroadcastableDims() { + return BroadcastableDims(RandomDims(0, 3)); +} + +Tensor OpTest::RandomReductionIndices(int rank) { + std::bernoulli_distribution random_bool; + std::vector indices; + for (int i = 0; i < rank; ++i) { + if (random_bool(generator())) { + indices.push_back(i); + } + } + return test::AsTensor(indices); +} + +// Helper that converts 'values' to an int32 or int64 Tensor. +static Tensor AsIntTensor(DataType dtype, const std::vector& values) { + switch (dtype) { + case DT_INT32: { + std::vector values32(values.begin(), values.end()); + return test::AsTensor(values32); + } + case DT_INT64: + return test::AsTensor(values); + default: + LOG(FATAL); + } +} + +OpTest::BatchMatMulArguments OpTest::ChooseBatchMatMulArguments( + bool broadcastable_batch) { + BatchMatMulArguments a; + a.dtype = Choose({DT_FLOAT, DT_COMPLEX64}); + + int64_t min_size = 0; + int64_t max_size = 7; + auto batch_dims_to = RandomDims(0, 3, min_size, max_size); + int rank = batch_dims_to.size() + 2; + std::pair, std::vector> batch_dims_nobcast( + batch_dims_to, batch_dims_to); + auto batch_dims = broadcastable_batch ? BroadcastableDims(batch_dims_to) + : batch_dims_nobcast; + std::vector lhs_dims(batch_dims.first), rhs_dims(batch_dims.second); + int64_t inner_dim = RandomDim(); + lhs_dims.push_back(RandomDim(min_size, max_size)); + lhs_dims.push_back(inner_dim); + rhs_dims.push_back(inner_dim); + rhs_dims.push_back(RandomDim(min_size, max_size)); + + std::bernoulli_distribution random_bool; + a.adj_lhs = random_bool(generator()); + a.adj_rhs = random_bool(generator()); + if (a.adj_lhs) { + std::swap(lhs_dims[rank - 1], lhs_dims[rank - 2]); + } + if (a.adj_rhs) { + std::swap(rhs_dims[rank - 1], rhs_dims[rank - 2]); + } + + a.lhs_dims = lhs_dims; + a.rhs_dims = rhs_dims; + return a; +} + +OpTest::ConcatArguments OpTest::ChooseConcatArguments(bool int64_idx_allowed) { + ConcatArguments a; + + std::bernoulli_distribution random_bool; + bool use_int64_idx = random_bool(generator()); + + a.type = Choose(kAllXlaTypes); + a.type_idx = use_int64_idx ? DT_INT64 : DT_INT32; + a.n = std::uniform_int_distribution(2, 4)(generator()); + + std::vector dims = RandomDims(1, 4, 0, 64); + + int axis = + std::uniform_int_distribution(0, dims.size() - 1)(generator()); + a.axis = use_int64_idx ? test::AsScalar(axis) + : test::AsScalar(axis); + + for (int i = 0; i < a.n; ++i) { + std::vector shape = dims; + shape[axis] = RandomDim(0, 64); + a.values.push_back(RandomTensor(a.type, false, shape)); + } + + return a; +} + +OpTest::EinsumArguments OpTest::ChooseEinsumArguments() { + EinsumArguments a; + + enum EinsumType { matmul, batchmatmul, dot, outer }; + int op_kind = Choose({matmul, batchmatmul, dot, outer}); + switch (op_kind) { + case matmul: + case batchmatmul: { + std::vector dims; + if (op_kind == matmul) { + a.equation = "ij,jk->ik"; + dims = RandomDims(2, 2); + } else { + a.equation = "...ij,...jk->...ik"; + dims = RandomDims(2); + } + int64_t ndims = dims.size(); + int64_t inner_dim = RandomDim(); + a.lhs_dims = dims; + a.rhs_dims = dims; + a.lhs_dims[ndims - 1] = inner_dim; + a.rhs_dims[ndims - 2] = inner_dim; + break; + } + case dot: { + a.equation = "i,i->"; + std::vector dims = RandomDims(1, 1); + a.lhs_dims = dims; + a.rhs_dims = dims; + break; + } + case outer: { + a.equation = "i,j->ij"; + a.lhs_dims = RandomDims(1, 1); + a.rhs_dims = RandomDims(1, 1); + break; + } + } + + a.type = Choose(kAllXlaTypes); + return a; +} + +OpTest::GatherArguments OpTest::ChooseGatherArguments(bool axis_0) { + GatherArguments a; + + a.axis_type = DT_INT32; + a.indices_type = DT_INT32; + a.params_type = Choose(kAllXlaTypes); + + // Choose parameters such that + // 0 <= batch_dims <= axis < params.rank <= kDefaultMaxRank + a.batch_dims = 0; + int64_t axis; + if (axis_0) { + axis = 0; + } else { + std::uniform_int_distribution axis_distribution( + a.batch_dims, kDefaultMaxRank - 1); + axis = axis_distribution(generator()); + } + a.axis = test::AsScalar((int32_t)axis); + a.params_shape = RandomDims(axis + 1, kDefaultMaxRank, 1, 16); + std::vector indices_shape = RandomDims(0, 3, 0, 16); + a.indices = RandomBoundedTensor( + DT_INT32, 0, a.params_shape[axis] - 1, false, indices_shape); + + return a; +} + +OpTest::PadArguments OpTest::ChoosePadArguments() { + PadArguments a; + + a.input_type = Choose(kAllXlaTypes); + a.input_shape = RandomDims(); + int input_rank = a.input_shape.size(); + + a.paddings_type = Choose({DT_INT32, DT_INT64}); + std::vector paddings_vec; + for (int i = 0; i < input_rank; ++i) { + std::uniform_int_distribution pad_distribution(0, a.input_shape[i]); + int pad_size = pad_distribution(generator()); + std::uniform_int_distribution lower_distribution(0, pad_size); + int low_pad_size = lower_distribution(generator()); + paddings_vec.push_back(low_pad_size); + paddings_vec.push_back(pad_size - low_pad_size); + a.input_shape[i] -= pad_size; + } + CHECK( + a.paddings.CopyFrom(AsIntTensor(a.paddings_type, paddings_vec), + TensorShape({static_cast(input_rank), 2}))); + + a.constant_values = RandomTensor(a.input_type, false, {}); + + return a; +} + +OpTest::ScatterArguments OpTest::ChooseScatterArguments() { + ScatterArguments a; + + a.type = Choose(kAllXlaTypes); + a.indices_type = DT_INT32; + a.shape = RandomDims(1, kDefaultMaxRank, 1); + int rank = a.shape.size(); + std::uniform_int_distribution index_len_dist(1, rank); + int index_len = index_len_dist(generator()); + std::vector indices_first = RandomDims(1, kDefaultMaxRank - 1, 1); + std::vector indices_shape(indices_first); + indices_shape.push_back(index_len); + std::vector updates_shape(indices_first); + for (int i = 0; i < rank - index_len; ++i) { + updates_shape.push_back(a.shape[index_len + i]); + } + Tensor indices_lo(a.indices_type, TensorShape(indices_shape)); + test::FillFn(&indices_lo, [](int i) -> int32_t { return 0; }); + Tensor indices_hi(a.indices_type, TensorShape(indices_shape)); + test::FillFn(&indices_hi, [index_len, &a](int i) -> int32_t { + int idx_dim = i % index_len; + return a.shape[idx_dim] - 1; + }); + a.indices = RandomBoundedTensor(a.indices_type, indices_lo, indices_hi); + a.updates = RandomTensor(a.type, false, updates_shape); + + return a; +} + +OpTest::SliceArguments OpTest::ChooseSliceArguments(bool neg_one_size) { + SliceArguments a; + + a.type = Choose(kAllXlaTypes); + a.indices_type = DT_INT32; + a.shape = RandomDims(); + int rank = a.shape.size(); + + std::vector indices(rank); + a.size.resize(rank); + for (int i = 0; i < rank; ++i) { + indices[i] = + std::uniform_int_distribution(0, a.shape[i])(generator()); + int64_t low = neg_one_size ? -1 : 0; + a.size[i] = std::uniform_int_distribution( + low, a.shape[i] - indices[i])(generator()); + } + a.indices = test::AsTensor(indices); + + return a; +} + +OpTest::WindowedSpatialDims OpTest::ChooseWindowedSpatialDims( + int num_spatial_dims) { + WindowedSpatialDims d; + d.padding = Choose({SAME, VALID}); + std::uniform_int_distribution random_int(1, 5); + d.kernel_dims.resize(num_spatial_dims); + d.input_dims.resize(num_spatial_dims); + d.output_dims.resize(num_spatial_dims); + d.stride_dims.resize(num_spatial_dims); + for (int i = 0; i < num_spatial_dims; ++i) { + absl::Status s; + // Repeatedly try different filter/stride sizes until we find a valid + // combination. + do { + // CPU implementations require stride <= kernel size. + d.kernel_dims[i] = random_int(generator()), + d.input_dims[i] = RandomDim(d.kernel_dims[i]); + d.stride_dims[i] = + std::uniform_int_distribution(1, d.kernel_dims[i])(generator()); + int64_t pad_dummy; + s = GetWindowedOutputSize(d.input_dims[i], d.kernel_dims[i], + /*dilation_rate=*/1, d.stride_dims[i], + d.padding, &d.output_dims[i], &pad_dummy); + } while (!s.ok()); + } + return d; +} + +OpTest::XlaDotArguments OpTest::ChooseXlaDotArguments() { + std::vector batch_dims = RandomDims(0, 2); + std::vector contracting_dims = RandomDims(0, 2); + std::vector lhs_outer_dims = RandomDims(0, 2); + std::vector rhs_outer_dims = RandomDims(0, 2); + + XlaDotArguments a; + a.lhs_dims.insert(a.lhs_dims.end(), batch_dims.begin(), batch_dims.end()); + a.lhs_dims.insert(a.lhs_dims.end(), contracting_dims.begin(), + contracting_dims.end()); + a.lhs_dims.insert(a.lhs_dims.end(), lhs_outer_dims.begin(), + lhs_outer_dims.end()); + a.rhs_dims.insert(a.rhs_dims.end(), batch_dims.begin(), batch_dims.end()); + a.rhs_dims.insert(a.rhs_dims.end(), contracting_dims.begin(), + contracting_dims.end()); + a.rhs_dims.insert(a.rhs_dims.end(), rhs_outer_dims.begin(), + rhs_outer_dims.end()); + + xla::DotDimensionNumbers dnums; + for (auto i = 0; i < batch_dims.size(); ++i) { + dnums.add_lhs_batch_dimensions(i); + dnums.add_rhs_batch_dimensions(i); + } + for (auto i = 0; i < contracting_dims.size(); ++i) { + dnums.add_lhs_contracting_dimensions(batch_dims.size() + i); + dnums.add_rhs_contracting_dimensions(batch_dims.size() + i); + } + dnums.SerializeToString(&a.dnums_encoded); + + a.precision_config_encoded = ""; + + a.dtype = Choose(kAllXlaTypes); + return a; +} + +std::vector OpTest::ImageDims( + TensorFormat format, int batch, int feature, + const std::vector& spatial_dims) { + std::vector dims; + switch (format) { + case FORMAT_NHWC: + dims.push_back(batch); + for (int dim : spatial_dims) { + dims.push_back(dim); + } + dims.push_back(feature); + break; + case FORMAT_NCHW: + dims.push_back(batch); + dims.push_back(feature); + for (int dim : spatial_dims) { + dims.push_back(dim); + } + break; + default: + LOG(FATAL) << "Tensor format " << ToString(format) << " not supported."; + } + return dims; +} + +std::vector OpTest::AsInt32s(const std::vector& int64s) { + return std::vector(int64s.begin(), int64s.end()); +} + +// Functions for comparing tensors. + +template +double Abs(T x) { + return std::fabs(x); +} + +template <> +double Abs(complex64 x) { + return std::abs(x); +} + +template +bool IsClose(const T& x, const T& y, double atol, double rtol) { + if (std::isnan(x) && std::isnan(y)) return true; + if (x == y) return true; // Allow inf == inf. + return Abs(x - y) < atol + rtol * Abs(x); +} + +template <> +bool IsClose(const complex64& x, const complex64& y, double atol, + double rtol) { + if (std::isnan(x.real()) && std::isnan(y.real())) { + if (std::isnan(x.imag()) && std::isnan(y.imag())) { + return true; + } + if (x.imag() == y.imag()) return true; // Allow inf == inf. + return Abs(x.imag() - y.imag()) < atol + rtol * Abs(x.imag()); + } else if (std::isnan(x.imag()) && std::isnan(y.imag())) { + if (x.real() == y.real()) return true; // Allow inf == inf. + return Abs(x.real() - y.real()) < atol + rtol * Abs(x.real()); + } + if (x == y) return true; // Allow inf == inf. + return Abs(x - y) < atol + rtol * Abs(x); +} + +template +std::string Str(T x) { + return absl::StrCat(x); +} +template <> +std::string Str(complex64 x) { + return absl::StrCat("(", x.real(), ", ", x.imag(), ")"); +} + +template +absl::Status TensorsAreCloseImpl(const Tensor& x, const Tensor& y, double atol, + double rtol) { + auto Tx = x.flat(); + auto Ty = y.flat(); + for (int i = 0; i < Tx.size(); ++i) { + if (!IsClose(Tx(i), Ty(i), atol, rtol)) { + return errors::InvalidArgument( + absl::StrCat(i, "-th tensor element isn't close: ", Str(Tx(i)), + " vs. ", Str(Ty(i)), ". x = ", x.DebugString(), + "y = ", y.DebugString(), "atol = ", atol, + " rtol = ", rtol, " tol = ", atol + rtol * Abs(Tx(i)))); + } + } + return absl::OkStatus(); +} + +template +absl::Status TensorsAreEqualImpl(const Tensor& x, const Tensor& y) { + auto Tx = x.flat(); + auto Ty = y.flat(); + for (int i = 0; i < Tx.size(); ++i) { + if (Tx(i) != Ty(i)) { + return errors::InvalidArgument(absl::StrCat( + i, "-th tensor element isn't equal: ", Str(Tx(i)), " vs. ", + Str(Ty(i)), ". x = ", x.DebugString(), "y = ", y.DebugString())); + } + } + return absl::OkStatus(); +} + +absl::Status TensorsAreEqualImplBfloat16(const Tensor& x, const Tensor& y) { + auto Tx = x.flat(); + auto Ty = y.flat(); + for (int i = 0; i < Tx.size(); ++i) { + if (Tx(i) != Ty(i)) { + return absl::InvalidArgumentError(absl::StrCat( + i, "-th tensor element isn't equal: ", static_cast(Tx(i)), + " vs. ", static_cast(Ty(i)), ". x = ", x.DebugString(), + "y = ", y.DebugString())); + } + } + return absl::OkStatus(); +} + +// Tests if "x" and "y" are tensors of the same type, same shape, and with +// close values. For floating-point tensors, the element-wise difference between +// x and y must no more than atol + rtol * abs(x). For non-floating-point +// tensors the values must match exactly. +absl::Status TensorsAreClose(const Tensor& a, const Tensor& b, double atol, + double rtol) { + if (a.dtype() != b.dtype()) { + return absl::InvalidArgumentError(absl::StrCat( + "Tensors have different types: ", DataTypeString(a.dtype()), " and ", + DataTypeString(b.dtype()))); + } + if (!a.IsSameSize(b)) { + return absl::InvalidArgumentError( + absl::StrCat("Tensors have different shapes: ", a.shape().DebugString(), + " and ", b.shape().DebugString())); + } + + switch (a.dtype()) { + case DT_FLOAT: + return TensorsAreCloseImpl(a, b, atol, rtol); + case DT_DOUBLE: + return TensorsAreCloseImpl(a, b, atol, rtol); + case DT_COMPLEX64: + return TensorsAreCloseImpl(a, b, atol, rtol); + case DT_INT32: + return TensorsAreEqualImpl(a, b); + case DT_INT64: + return TensorsAreEqualImpl(a, b); + case DT_BOOL: + return TensorsAreEqualImpl(a, b); + case DT_BFLOAT16: + return TensorsAreEqualImplBfloat16(a, b); + default: + LOG(FATAL) << "Unexpected type : " << DataTypeString(a.dtype()); + } +} + +OpTest::TestResult OpTest::ExpectTfAndXlaOutputsAreClose( + const OpTestBuilder& builder, double atol, double rtol) { + const std::vector& inputs = builder.inputs(); + std::vector input_tensors; + input_tensors.reserve(inputs.size()); + for (const OpTestBuilder::InputDescription& input : inputs) { + if (input.type == DT_INVALID) { + input_tensors.push_back(input.tensor); + } else { + std::vector dims; + if (input.has_dims) { + dims = input.dims; + } else { + dims = RandomDims(); + } + if (!TensorSizeIsOk(dims)) { + VLOG(1) << "Input: " << input.type << " " + << TensorShape(input.dims).DebugString(); + VLOG(1) << "Ignoring oversize dims."; + return kInvalid; + } + input_tensors.push_back( + RandomTensor(input.type, input.needs_unique_values, dims)); + } + VLOG(1) << "Input: " << input_tensors.back().DebugString(); + } + + std::string reference_device = + LocalDeviceToFullDeviceName(*tf_xla_reference_device_ptr); + std::string test_device = + LocalDeviceToFullDeviceName(*tf_xla_test_device_ptr); + + DeviceNameUtils::ParsedName parsed_name; + if (!DeviceNameUtils::ParseLocalName(*tf_xla_test_device_ptr, &parsed_name)) { + LOG(ERROR) << "Could not parse device name: " << *tf_xla_test_device_ptr; + return kFatalError; + } + DeviceType test_device_type(parsed_name.type); + ++num_tests_; + + GraphDef graph; + std::vector expected_inputs, test_inputs; + std::vector expected_fetches, test_fetches; + absl::Status status = builder.BuildGraph( + absl::StrCat("test", num_tests_, "_expected"), reference_device, + /*use_jit=*/false, &graph, /*test_node_def=*/nullptr, &expected_inputs, + &expected_fetches); + if (!status.ok()) { + LOG(ERROR) << "Expected graph construction failed: " << status; + return kFatalError; + } + + NodeDef* node_def; + status = builder.BuildGraph(absl::StrCat("test", num_tests_, "_test"), + test_device, tf_xla_test_use_jit, &graph, + &node_def, &test_inputs, &test_fetches); + if (!status.ok()) { + LOG(ERROR) << "Test graph construction failed: " << status; + return kFatalError; + } + + // Check that there's a kernel corresponding to 'node_def' on the device under + // test. + status = FindKernelDef(test_device_type, *node_def, nullptr, nullptr); + if (!status.ok()) { + VLOG(1) << "Skipping test because there is no corresponding registered " + << "kernel on the test device: " << status; + return kInvalid; + } + + // Create a session with the corresponding graph. + SessionOptions session_options; + session_.reset(NewSession(session_options)); + status = session_->Create(graph); + if (!status.ok()) { + LOG(ERROR) << "Session::Create() failed: " << status; + return kFatalError; + } + + std::vector> expected_feeds( + expected_inputs.size()); + std::vector> test_feeds(test_inputs.size()); + CHECK_EQ(input_tensors.size(), expected_inputs.size()); + CHECK_EQ(input_tensors.size(), test_inputs.size()); + + for (int i = 0; i < input_tensors.size(); ++i) { + expected_feeds[i] = {expected_inputs[i], input_tensors[i]}; + test_feeds[i] = {test_inputs[i], input_tensors[i]}; + } + + std::vector expected_outputs, test_outputs; + VLOG(1) << "Running expected graph"; + absl::Status s = + session_->Run(expected_feeds, expected_fetches, {}, &expected_outputs); + if (!s.ok()) { + VLOG(1) << "Expected graph failed with status: " << s << ". Ignoring test"; + return kInvalid; + } + for (const Tensor& expected : expected_outputs) { + VLOG(1) << "Expected: " << expected.DebugString(); + } + + VLOG(1) << "Running test graph"; + status = session_->Run(test_feeds, test_fetches, {}, &test_outputs); + if (!status.ok()) { + LOG(ERROR) << "Test graph failed: " << status; + return kFatalError; + } + + CHECK_EQ(expected_outputs.size(), test_outputs.size()); + for (int j = 0; s.ok() && j < test_outputs.size(); ++j) { + s = TensorsAreClose(expected_outputs[j], test_outputs[j], atol, rtol); + } + TF_EXPECT_OK(s); + + return kOk; +} + +TEST_F(OpTest, _EagerConst) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("_EagerConst").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Abs) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Abs").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Acos) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Acos") + .Input(RandomBoundedTensor(DT_FLOAT, -1, 1, false)) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Acosh) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Acosh").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Add) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Add") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, AddN) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + int n = std::uniform_int_distribution(1, 5)(generator()); + + auto shape = RandomDims(); + + OpTestBuilder builder("AddN"); + builder.Attr("T", type); + builder.Attr("N", n); + for (int i = 0; i < n; ++i) { + builder.RandomInput(type, shape); + } + return ExpectTfAndXlaOutputsAreClose(builder); + }); +} + +TEST_F(OpTest, AddV2) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("AddV2") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, All) { + Repeatedly([this]() { + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("All") + .RandomInput(DT_BOOL, data_dims) + .Input(indices) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, Angle) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Angle") + .RandomInput(DT_COMPLEX64) + .Attr("T", DT_COMPLEX64)); + }); +} + +TEST_F(OpTest, Any) { + Repeatedly([this]() { + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Any") + .RandomInput(DT_BOOL, data_dims) + .Input(indices) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, ApproximateEqual) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ApproximateEqual") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, ArgMax) { + Repeatedly([this]() { + auto type = Choose({DT_BOOL, DT_FLOAT}); + std::vector dims = RandomDims(1, 5, 1); + int num_dims = dims.size(); + int reduce_dim = std::uniform_int_distribution( + -num_dims, num_dims)(generator()); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ArgMax") + .RandomInput(type, dims) + .Input(test::AsScalar(reduce_dim)) + .Attr("T", type) + .Attr("Tidx", DT_INT32) + .Attr("output_type", DT_INT32)); + }); +} + +TEST_F(OpTest, ArgMin) { + Repeatedly([this]() { + auto type = Choose({DT_BOOL, DT_FLOAT}); + std::vector dims = RandomDims(1, 5, 1); + int num_dims = dims.size(); + int reduce_dim = std::uniform_int_distribution( + -num_dims, num_dims)(generator()); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ArgMin") + .RandomInput(type, dims) + .Input(test::AsScalar(reduce_dim)) + .Attr("T", type) + .Attr("Tidx", DT_INT32) + .Attr("output_type", DT_INT32)); + }); +} + +TEST_F(OpTest, Asin) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Asin") + .Input(RandomBoundedTensor(DT_FLOAT, -1, 1, false)) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Asinh) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Asinh").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Atanh) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Atanh").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Atan) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Atan").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Atan2) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Atan2") + .RandomInput(DT_FLOAT, dims.first) + .RandomInput(DT_FLOAT, dims.second) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, AvgPool) { + Repeatedly([this]() { + std::uniform_int_distribution random_int(1, 5); + std::vector dims = RandomDims(4, 4, 1); + int kernel_rows = + std::uniform_int_distribution(1, dims[1])(generator()); + int kernel_cols = + std::uniform_int_distribution(1, dims[2])(generator()); + int stride_rows = random_int(generator()), + stride_cols = random_int(generator()); + std::string padding = Choose({"SAME", "VALID"}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("AvgPool") + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT) + .Attr("ksize", {1, kernel_rows, kernel_cols, 1}) + .Attr("strides", {1, stride_rows, stride_cols, 1}) + .Attr("padding", padding) + .Attr("data_format", "NHWC")); + }); + // TODO(phawkins): the CPU device only implements spatial pooling. Add tests + // for batch pooling when supported. +} + +TEST_F(OpTest, AvgPool3D) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + std::uniform_int_distribution random_int(1, 5); + std::vector dims = RandomDims(5, 5, 1); + + std::vector input_dims, kernel_dims, stride_dims; + for (int i = 0; i < 3; ++i) { + kernel_dims.push_back( + std::uniform_int_distribution(1, dims[i])(generator())); + input_dims.push_back(dims[i]); + stride_dims.push_back(random_int(generator())); + } + int64_t batch = dims[3]; + int64_t feature = dims[4]; + + std::string padding = Choose({"SAME", "VALID"}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("AvgPool3D") + .RandomInput(DT_FLOAT, + ImageDims(FORMAT_NHWC, batch, feature, input_dims)) + .Attr("T", DT_FLOAT) + .Attr("ksize", ImageDims(FORMAT_NHWC, 1, 1, kernel_dims)) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, stride_dims)) + .Attr("padding", padding) + .Attr("data_format", "NDHWC")); + }); + // TODO(phawkins): test NCHW format (not supported by CPU) +} + +TEST_F(OpTest, AvgPoolGrad) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + int batch = RandomDim(1), features = RandomDim(1); + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::vector input_dims = + AsInt32s(ImageDims(FORMAT_NHWC, batch, features, d.input_dims)); + std::vector output_dims = + ImageDims(FORMAT_NHWC, batch, features, d.output_dims); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("AvgPoolGrad") + .Input(test::AsTensor(input_dims)) + .RandomInput(DT_FLOAT, output_dims) + .Attr("T", DT_FLOAT) + .Attr("ksize", ImageDims(FORMAT_NHWC, 1, 1, d.kernel_dims)) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NHWC")); + }); +} + +TEST_F(OpTest, AvgPool3DGrad) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + int batch = RandomDim(1), features = RandomDim(1); + WindowedSpatialDims d = ChooseWindowedSpatialDims(3); + std::vector input_dims = + AsInt32s(ImageDims(FORMAT_NHWC, batch, features, d.input_dims)); + std::vector output_dims = + ImageDims(FORMAT_NHWC, batch, features, d.output_dims); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("AvgPool3DGrad") + .Input(test::AsTensor(input_dims)) + .RandomInput(DT_FLOAT, output_dims) + .Attr("T", DT_FLOAT) + .Attr("ksize", ImageDims(FORMAT_NHWC, 1, 1, d.kernel_dims)) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NDHWC")); + }); +} + +TEST_F(OpTest, BatchMatMul) { + // See note about failing Kokoro tests: b/214080339#comment22 + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + const BatchMatMulArguments a = ChooseBatchMatMulArguments(false); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BatchMatMul") + .RandomInput(a.dtype, a.lhs_dims) + .RandomInput(a.dtype, a.rhs_dims) + .Attr("T", a.dtype) + .Attr("adj_x", a.adj_lhs) + .Attr("adj_y", a.adj_rhs)); + }); +} + +TEST_F(OpTest, BatchMatMulV2) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + // :randomized_tests_seeded is flaky with --tf_xla_random_seed=200839030 + // See b/229622638. + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + const BatchMatMulArguments a = ChooseBatchMatMulArguments(true); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BatchMatMulV2") + .RandomInput(a.dtype, a.lhs_dims) + .RandomInput(a.dtype, a.rhs_dims) + .Attr("T", a.dtype) + .Attr("adj_x", a.adj_lhs) + .Attr("adj_y", a.adj_rhs)); + }); +} + +TEST_F(OpTest, BatchToSpace) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + const int num_block_dims = 2; + std::vector block_dims = + RandomDims(num_block_dims, num_block_dims, 0, 5); + int64_t block_size = RandomDim(2, 5); + + std::vector input_dims(1 + num_block_dims + 1); + input_dims[0] = RandomDim(); + for (int i = 0; i < num_block_dims; ++i) { + input_dims[0] *= block_size; + input_dims[1 + i] = block_dims[i]; + } + input_dims[1 + num_block_dims] = RandomDim(); + + std::vector crop_vals; + std::uniform_int_distribution distribution(0, 4); + for (int i = 0; i < num_block_dims; ++i) { + // Chooses crop values; does not always choose legal values. + crop_vals.push_back(distribution(generator())); + crop_vals.push_back(distribution(generator())); + } + Tensor crops; + CHECK(crops.CopyFrom(AsIntTensor(DT_INT32, crop_vals), + TensorShape({num_block_dims, 2}))); + + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BatchToSpace") + .RandomInput(type, input_dims) + .Input(crops) + .Attr("T", type) + .Attr("block_size", block_size)); + }); +} + +TEST_F(OpTest, BatchToSpaceND) { + Repeatedly([this]() { + std::vector block_dims = RandomDims(1, 3, 0, 5); + int num_block_dims = block_dims.size(); + std::vector remaining_dims = RandomDims(0, 3); + std::vector block_multipliers = + RandomDims(block_dims.size(), block_dims.size(), 0, 4); + + std::vector input_dims(1 + num_block_dims + remaining_dims.size()); + input_dims[0] = RandomDim(); + for (int i = 0; i < num_block_dims; ++i) { + input_dims[0] *= block_dims[i]; + } + std::copy(block_multipliers.begin(), block_multipliers.end(), + input_dims.begin() + 1); + std::copy(remaining_dims.begin(), remaining_dims.end(), + input_dims.begin() + 1 + num_block_dims); + + std::vector crop_vals; + std::uniform_int_distribution distribution(0, 3); + for (int i = 0; i < num_block_dims; ++i) { + // Chooses crop values; does not always choose legal values. + crop_vals.push_back(distribution(generator())); + crop_vals.push_back(distribution(generator())); + } + Tensor crops; + CHECK(crops.CopyFrom(AsIntTensor(DT_INT32, crop_vals), + TensorShape({num_block_dims, 2}))); + + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("BatchToSpaceND") + .RandomInput(type, input_dims) + .Input(test::AsTensor( + std::vector(block_dims.begin(), block_dims.end()))) + .Input(crops) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, BiasAdd) { + Repeatedly([this]() { + auto x_dims = RandomDims(2, kDefaultMaxRank); + auto y_dims = {x_dims[x_dims.size() - 1]}; + // TODO(phawkins): test both data formats. + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BiasAdd") + .RandomInput(type, x_dims) + .RandomInput(type, y_dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, BiasAddGrad) { + Repeatedly([this]() { + // TODO(phawkins): test both data formats. + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("BiasAddGrad").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, BiasAddV1) { + Repeatedly([this]() { + auto x_dims = RandomDims(2, kDefaultMaxRank); + auto y_dims = {x_dims[x_dims.size() - 1]}; + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BiasAddV1") + .RandomInput(type, x_dims) + .RandomInput(type, y_dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Bitcast) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto src_type = Choose(kAllNumberTypes); + auto dst_type = Choose(kAllNumberTypes); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Bitcast") + .RandomInput(src_type) + .Attr("T", src_type) + .Attr("type", dst_type)); + }); +} + +TEST_F(OpTest, BitwiseAnd) { + Repeatedly([this]() { + DataType type = DT_INT32; + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BitwiseAnd") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, BitwiseOr) { + Repeatedly([this]() { + DataType type = DT_INT32; + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BitwiseOr") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, BitwiseXor) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("BitwiseXor") + .RandomInput(DT_INT32, dims.first) + .RandomInput(DT_INT32, dims.second) + .Attr("T", DT_INT32)); + }); +} + +TEST_F(OpTest, BroadcastArgs) { + Repeatedly([this]() { + // TODO(phawkins): only int32 seems to be implemented in Tensorflow. + // auto type = Choose({DT_INT32, DT_INT64}); + DataType type = DT_INT32; + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("BroadcastArgs") + .Input(AsIntTensor(type, dims.first)) + .Input(AsIntTensor(type, dims.second)) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, BroadcastGradientArgs) { + Repeatedly([this]() { + // TODO(phawkins): only int32 seems to be implemented in Tensorflow. + // auto type = Choose({DT_INT32, DT_INT64}); + DataType type = DT_INT32; + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("BroadcastGradientArgs") + .Input(AsIntTensor(type, dims.first)) + .Input(AsIntTensor(type, dims.second)) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, BroadcastTo) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto type_idx = Choose({DT_INT32, DT_INT64}); + auto dims_to = RandomDims(); + auto dims_from = BroadcastableToDims(dims_to); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("BroadcastTo") + .RandomInput(type, dims_from) + .Input(AsIntTensor(type_idx, dims_to)) + .Attr("T", type) + .Attr("Tidx", type_idx)); + }); +} + +TEST_F(OpTest, Cast) { + Repeatedly([this]() { + DataType src_type, dst_type; + src_type = Choose({DT_INT32, DT_FLOAT, DT_BOOL, DT_COMPLEX64}); + dst_type = Choose({DT_INT32, DT_FLOAT, DT_BOOL, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Cast") + .RandomInput(src_type) + .Attr("SrcT", src_type) + .Attr("DstT", dst_type)); + }); +} + +TEST_F(OpTest, CastBF16) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + DataType src_type, dst_type; + src_type = Choose({DT_FLOAT}); + dst_type = Choose({DT_BFLOAT16}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Cast") + .RandomInput(src_type) + .Attr("SrcT", src_type) + .Attr("DstT", dst_type) + .Attr("Truncate", true)); + }); +} + +TEST_F(OpTest, Ceil) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Ceil").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, ClipByValue) { + // TODO(b/211012085): Change input_dims to BroadcastableDimsN(3). The + // compiled ClipByValue fails in this case. + // --tf_xla_random_seed=200839030 + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_INT64, DT_FLOAT}); + // ClipByValue requires that broadcasting min and max tensors do not cause + // the returned shape to be larger than the input shape. + auto input_dims = RandomDims(); + // clip_value_min must be <= clip_value_max for correct results. Different + // implementations handle the max < min case differently, so ensure that + // min <= max. + auto min_max_dims = BroadcastableToDims(input_dims); + auto min_max = RandomLteTensors(type, min_max_dims); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ClipByValue") + .RandomInput(type, input_dims) + .Input(min_max.first) + .Input(min_max.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Complex) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Complex") + .RandomInput(DT_FLOAT, dims.first) + .RandomInput(DT_FLOAT, dims.second) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Concat) { + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + ConcatArguments a = ChooseConcatArguments(false); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Concat") + .Input(a.axis) + .VariadicInput(a.values) + .Attr("N", a.n) + .Attr("T", a.type)); + }); +} + +TEST_F(OpTest, ConcatV2) { + Repeatedly([this]() { + ConcatArguments a = ChooseConcatArguments(true); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ConcatV2") + .VariadicInput(a.values) + .Input(a.axis) + .Attr("N", a.n) + .Attr("T", a.type) + .Attr("Tidx", a.type_idx)); + }); +} + +TEST_F(OpTest, ConcatOffset) { + Repeatedly([this]() { + int n = std::uniform_int_distribution(2, 5)(generator()); + + std::vector dims = RandomDims(1); + int concat_dim = + std::uniform_int_distribution(0, dims.size() - 1)(generator()); + + OpTestBuilder builder("ConcatOffset"); + builder.Input(test::AsScalar(concat_dim)); + builder.Attr("N", n); + for (int i = 0; i < n; ++i) { + std::vector shape(dims.begin(), dims.end()); + shape[concat_dim] = RandomDim(); + builder.Input(test::AsTensor(shape)); + } + return ExpectTfAndXlaOutputsAreClose(builder); + }); +} + +TEST_F(OpTest, Conj) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Conj") + .RandomInput(DT_COMPLEX64) + .Attr("T", DT_COMPLEX64)); + }); +} + +TEST_F(OpTest, Const) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Const") + .Attr("value", RandomTensor(type)) + .Attr("dtype", type)); + }); +} + +TEST_F(OpTest, FFT) { + Repeatedly([this]() { + std::vector dims = RandomDims(1, kDefaultMaxRank); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("FFT").RandomInput(DT_COMPLEX64, dims)); + }); +} + +TEST_F(OpTest, FFT2D) { + Repeatedly([this]() { + std::vector dims = RandomDims(2, kDefaultMaxRank); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("FFT2D").RandomInput(DT_COMPLEX64, dims)); + }); +} + +TEST_F(OpTest, FFT3D) { + Repeatedly([this]() { + std::vector dims = RandomDims(3, kDefaultMaxRank); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("FFT3D").RandomInput(DT_COMPLEX64, dims)); + }); +} + +TEST_F(OpTest, IFFT) { + Repeatedly([this]() { + std::vector dims = RandomDims(1, kDefaultMaxRank); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("IFFT").RandomInput(DT_COMPLEX64, dims)); + }); +} + +TEST_F(OpTest, IFFT2D) { + Repeatedly([this]() { + std::vector dims = RandomDims(2, kDefaultMaxRank); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("IFFT2D").RandomInput(DT_COMPLEX64, dims)); + }); +} + +TEST_F(OpTest, IFFT3D) { + Repeatedly([this]() { + std::vector dims = RandomDims(3, kDefaultMaxRank); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("IFFT3D").RandomInput(DT_COMPLEX64, dims)); + }); +} + +TEST_F(OpTest, RFFT) { + Repeatedly([this]() { + std::vector dims = RandomDims(1, kDefaultMaxRank, 3); + Tensor fft_shape = + test::AsTensor(AsInt32s({dims[dims.size() - 1]})); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("RFFT").RandomInput(DT_FLOAT, dims).Input(fft_shape)); + }); +} + +TEST_F(OpTest, RFFT2D) { + Repeatedly([this]() { + std::vector dims = RandomDims(2, kDefaultMaxRank, 3); + Tensor fft_shape = test::AsTensor( + AsInt32s({dims[dims.size() - 2], dims[dims.size() - 1]})); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("RFFT2D").RandomInput(DT_FLOAT, dims).Input(fft_shape)); + }); +} + +TEST_F(OpTest, RFFT3D) { + Repeatedly([this]() { + std::vector dims = RandomDims(3, kDefaultMaxRank, 3); + Tensor fft_shape = test::AsTensor(AsInt32s( + {dims[dims.size() - 3], dims[dims.size() - 2], dims[dims.size() - 1]})); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("RFFT3D").RandomInput(DT_FLOAT, dims).Input(fft_shape)); + }); +} + +TEST_F(OpTest, IRFFT) { + Repeatedly([this]() { + std::vector dims = RandomDims(1, kDefaultMaxRank, 3); + int64_t orig_size = dims[dims.size() - 1]; + dims[dims.size() - 1] = dims[dims.size() - 1] / 2 + 1; + Tensor fft_shape = test::AsTensor(AsInt32s({orig_size})); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("IRFFT") + .RandomInput(DT_COMPLEX64, dims) + .Input(fft_shape)); + }); +} + +TEST_F(OpTest, IRFFT2D) { + Repeatedly([this]() { + std::vector dims = RandomDims(2, kDefaultMaxRank, 3); + std::vector orig_size = {dims[dims.size() - 2], + dims[dims.size() - 1]}; + dims[dims.size() - 1] = dims[dims.size() - 1] / 2 + 1; + Tensor fft_shape = test::AsTensor(AsInt32s({orig_size})); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("IRFFT2D") + .RandomInput(DT_COMPLEX64, dims) + .Input(fft_shape)); + }); +} + +TEST_F(OpTest, IRFFT3D) { + Repeatedly([this]() { + std::vector dims = RandomDims(3, kDefaultMaxRank, 3); + std::vector orig_size = { + dims[dims.size() - 3], dims[dims.size() - 2], dims[dims.size() - 1]}; + dims[dims.size() - 1] = dims[dims.size() - 1] / 2 + 1; + Tensor fft_shape = test::AsTensor(AsInt32s({orig_size})); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("IRFFT3D") + .RandomInput(DT_COMPLEX64, dims) + .Input(fft_shape)); + }); +} + +TEST_F(OpTest, Conv2D) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int features_out = random_int(generator()); + + int64_t batch = RandomDim(); + + std::vector data_dims = + ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); + + std::vector kernel_dims = {d.kernel_dims[0], d.kernel_dims[1], + features_in, features_out}; + DataType type = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Conv2D") + .RandomInput(type, data_dims) + .RandomInput(type, kernel_dims) + .Attr("T", type) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NHWC")); + }); +} + +TEST_F(OpTest, Conv2DBackpropFilter) { + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int features_out = random_int(generator()); + int32_t batch = RandomDim(); + std::vector activations = + ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); + std::vector backprop = + ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); + Tensor kernel_shape = test::AsTensor(AsInt32s( + {d.kernel_dims[0], d.kernel_dims[1], features_in, features_out})); + DataType type = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Conv2DBackpropFilter") + .RandomInput(type, activations) + .Input(kernel_shape) + .RandomInput(type, backprop) + .Attr("T", type) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NHWC")); + }); +} + +TEST_F(OpTest, Conv2DBackpropInput) { + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int features_out = random_int(generator()); + int32_t batch = RandomDim(); + Tensor in_shape = test::AsTensor( + AsInt32s(ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims))); + std::vector backprop = + ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); + std::vector kernel = {d.kernel_dims[0], d.kernel_dims[1], + features_in, features_out}; + DataType type = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Conv2DBackpropInput") + .Input(in_shape) + .RandomInput(type, kernel) + .RandomInput(type, backprop) + .Attr("T", type) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NHWC")); + }); +} + +TEST_F(OpTest, Conv3D) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(3); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int features_out = random_int(generator()); + std::vector data = {RandomDim(), d.input_dims[0], d.input_dims[1], + d.input_dims[2], features_in}; + + std::vector kernel = {d.kernel_dims[0], d.kernel_dims[1], + d.kernel_dims[2], features_in, features_out}; + DataType type = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Conv3D") + .RandomInput(type, data) + .RandomInput(type, kernel) + .Attr("T", type) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); + }); +} + +TEST_F(OpTest, Conv3DBackpropFilter) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(3); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int features_out = random_int(generator()); + int32_t batch = RandomDim(1); + std::vector activations = + ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); + std::vector backprop = + ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); + Tensor kernel_shape = test::AsTensor( + AsInt32s({d.kernel_dims[0], d.kernel_dims[1], d.kernel_dims[2], + features_in, features_out})); + DataType type = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Conv3DBackpropFilterV2") + .RandomInput(type, activations) + .Input(kernel_shape) + .RandomInput(type, backprop) + .Attr("T", type) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); + }); +} + +TEST_F(OpTest, Conv3DBackpropInput) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(3); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int features_out = random_int(generator()); + int32_t batch = RandomDim(1); + Tensor in_shape = test::AsTensor( + AsInt32s(ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims))); + std::vector backprop = + ImageDims(FORMAT_NHWC, batch, features_out, d.output_dims); + std::vector kernel = {d.kernel_dims[0], d.kernel_dims[1], + d.kernel_dims[2], features_in, features_out}; + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Conv3DBackpropInputV2") + .Input(in_shape) + .RandomInput(type, kernel) + .RandomInput(type, backprop) + .Attr("T", type) + .Attr("strides", ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims)) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); + }); +} + +TEST_F(OpTest, ComplexAbs) { + Repeatedly([this]() { + auto type = DT_COMPLEX64; + auto type_out = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ComplexAbs") + .RandomInput(type) + .Attr("T", type) + .Attr("Tout", type_out)); + }); +} + +TEST_F(OpTest, Cos) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Cos").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Cosh) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Cosh").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, DepthToSpace) { + Repeatedly([this]() { + int64_t block = RandomDim(2, 5); + std::vector input_dims = RandomDims(4, 4); + input_dims[1] = (input_dims[1] + (block - 1)) / block; + input_dims[2] = (input_dims[2] + (block - 1)) / block; + input_dims[3] *= block * block; + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("DepthToSpace") + .RandomInput(type, input_dims) + .Attr("T", type) + .Attr("block_size", block)); + }); +} + +TEST_F(OpTest, DepthwiseConv2DNative) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int depth_multiplier = random_int(generator()); + std::vector input_dims = {RandomDim(), d.input_dims[0], + d.input_dims[1], features_in}; + + std::vector kernel_dims = {d.kernel_dims[0], d.kernel_dims[1], + features_in, depth_multiplier}; + std::vector strides = ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims); + strides[2] = strides[1]; // Current impl only supports equal strides + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("DepthwiseConv2dNative") + .RandomInput(DT_FLOAT, input_dims) + .RandomInput(DT_FLOAT, kernel_dims) + .Attr("T", DT_FLOAT) + .Attr("strides", strides) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID")); + }); +} + +TEST_F(OpTest, DepthwiseConv2DNativeBackpropFilter) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int depth_multiplier = random_int(generator()); + int32_t batch = RandomDim(); + std::vector activations = + ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims); + std::vector backprop = ImageDims( + FORMAT_NHWC, batch, features_in * depth_multiplier, d.output_dims); + Tensor kernel_shape = test::AsTensor(AsInt32s( + {d.kernel_dims[0], d.kernel_dims[1], features_in, depth_multiplier})); + std::vector strides = ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims); + strides[2] = strides[1]; // Current impl only supports equal strides + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("DepthwiseConv2dNativeBackpropFilter") + .RandomInput(DT_FLOAT, activations) + .Input(kernel_shape) + .RandomInput(DT_FLOAT, backprop) + .Attr("T", DT_FLOAT) + .Attr("strides", strides) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NHWC")); + }); +} + +TEST_F(OpTest, DepthwiseConv2DBackpropInput) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + WindowedSpatialDims d = ChooseWindowedSpatialDims(2); + std::uniform_int_distribution random_int(1, 5); + int features_in = random_int(generator()); + int depth_multiplier = random_int(generator()); + int32_t batch = RandomDim(); + Tensor in_shape = test::AsTensor( + AsInt32s(ImageDims(FORMAT_NHWC, batch, features_in, d.input_dims))); + std::vector backprop = ImageDims( + FORMAT_NHWC, batch, features_in * depth_multiplier, d.output_dims); + std::vector kernel = {d.kernel_dims[0], d.kernel_dims[1], + features_in, depth_multiplier}; + std::vector strides = ImageDims(FORMAT_NHWC, 1, 1, d.stride_dims); + strides[2] = strides[1]; // Current impl only supports equal strides + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("DepthwiseConv2dNativeBackpropInput") + .Input(in_shape) + .RandomInput(DT_FLOAT, kernel) + .RandomInput(DT_FLOAT, backprop) + .Attr("T", DT_FLOAT) + .Attr("strides", strides) + .Attr("padding", d.padding == SAME ? "SAME" : "VALID") + .Attr("data_format", "NHWC")); + }); +} + +TEST_F(OpTest, Diag) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector dims; + // Diag causes a quadratic blowup in output size. + int64_t size; + do { + dims = RandomDims(1); + size = TensorShape(dims).num_elements(); + } while (size * size > tf_xla_max_tensor_size); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Diag").RandomInput(type, dims).Attr("T", type)); + }); +} + +TEST_F(OpTest, DiagPart) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto dims = RandomDims(1, 3); + // Duplicate the random dims. + std::vector doubled_dims(dims.size() * 2); + std::copy(dims.begin(), dims.end(), doubled_dims.begin()); + std::copy(dims.begin(), dims.end(), doubled_dims.begin() + dims.size()); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("DiagPart") + .RandomInput(type, doubled_dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Digamma) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Digamma").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Div) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Div") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, DivNoNan) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("DivNoNan") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, DynamicStitch) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + int n = std::uniform_int_distribution(2, 5)(generator()); + OpTestBuilder builder("DynamicStitch"); + builder.Attr("T", type); + builder.Attr("N", n); + std::vector> index_dims; + int size = 0; + // TODO(phawkins): the XLA implementation of DynamicStitch does not + // accept an empty set of indices. + do { + size = 0; + index_dims.clear(); + for (int i = 0; i < n; ++i) { + std::vector dims = RandomDims(0, 3, 0, 5); + size += TensorShape(dims).num_elements(); + index_dims.push_back(dims); + } + } while (size == 0); + + // Shuffle the range of indices that cover the output. + // TODO(phawkins): The documentation for DynamicStitch doesn't require + // that the indices cover all positions of the output. The XLA + // implementation does so require. However, the native TF implementation + // leaves undefined values if we don't cover everything, so we can't + // really test that case anyway. + std::vector indices(size); + std::iota(indices.begin(), indices.end(), 0); + std::shuffle(indices.begin(), indices.end(), generator()); + + int pos = 0; + for (int i = 0; i < n; ++i) { + TensorShape shape(index_dims[i]); + Tensor t = test::AsTensor( + absl::Span(indices).subspan(pos, shape.num_elements()), + shape); + builder.Input(t); + pos += t.NumElements(); + } + + std::vector constant_dims = RandomDims(0, 3, 0, 5); + for (int i = 0; i < n; ++i) { + std::vector dims(index_dims[i].begin(), index_dims[i].end()); + std::copy(constant_dims.begin(), constant_dims.end(), + std::back_inserter(dims)); + builder.RandomInput(type, dims); + } + return ExpectTfAndXlaOutputsAreClose(builder); + }); +} + +TEST_F(OpTest, Einsum) { + Repeatedly([this]() { + const EinsumArguments a = ChooseEinsumArguments(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Einsum") + .RandomInput(a.type, a.lhs_dims) + .RandomInput(a.type, a.rhs_dims) + .Attr("equation", a.equation) + .Attr("T", a.type) + .Attr("N", 2), + 2e-1, 2e-1); + }); +} + +TEST_F(OpTest, Empty) { + Repeatedly([this]() { + auto type = Choose({kAllXlaTypes}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Empty") + .Input(AsIntTensor(DT_INT32, RandomDims())) + .Attr("init", true) + .Attr("dtype", type)); + }); +} + +TEST_F(OpTest, Elu) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Elu").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, EluGrad) { + Repeatedly([this]() { + auto dims = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("EluGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, ScatterNd) { + Repeatedly([this]() { + auto a = ChooseScatterArguments(); + auto shape = test::AsTensor( + std::vector(a.shape.begin(), a.shape.end())); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ScatterNd") + .Input(a.indices) + .Input(a.updates) + .Input(shape) + .Attr("T", a.type) + .Attr("Tindices", a.indices_type)); + }); +} + +TEST_F(OpTest, Selu) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Selu").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, SeluGrad) { + Repeatedly([this]() { + auto dims = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SeluGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Equal) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Equal") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Erf) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Erf").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Erfc) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Erfc").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Exp) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Exp").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Expm1) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Expm1").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, ExpandDims) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector in_dims = RandomDims(); + Tensor dim(DT_INT32, TensorShape()); + std::uniform_int_distribution d(-1 - in_dims.size(), + in_dims.size()); + dim.scalar()() = d(generator()); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ExpandDims") + .RandomInput(type, in_dims) + .Input(dim) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Fill) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector dims = RandomDims(); + std::vector shape(dims.begin(), dims.end()); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Fill") + .Input(test::AsTensor(shape)) + .RandomInput(type, {}) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Floor) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Floor").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, FloorDiv) { + Repeatedly([this]() { + DataType type = DT_INT32; + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("FloorDiv") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, FloorMod) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("FloorMod") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Gather) { + Repeatedly([this]() { + GatherArguments a = ChooseGatherArguments(true); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Gather") + .RandomInput(a.params_type, a.params_shape) + .Input(a.indices) + .Attr("Tparams", a.params_type) + .Attr("Tindices", a.indices_type)); + }); +} + +TEST_F(OpTest, GatherV2) { + Repeatedly([this]() { + GatherArguments a = ChooseGatherArguments(false); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("GatherV2") + .RandomInput(a.params_type, a.params_shape) + .Input(a.indices) + .Input(a.axis) + .Attr("batch_dims", a.batch_dims) + .Attr("Taxis", a.axis_type) + .Attr("Tindices", a.indices_type) + .Attr("Tparams", a.params_type)); + }); +} + +TEST_F(OpTest, GatherNd) { + // :randomized_tests_mlir fails with --tf_xla_random_seed=459353625 + // --test_arg=--tf_xla_test_repetitions=100 + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + // See b/214080339#comment27 as this test causes Kokoro to crash. + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto params_type = Choose(kAllXlaTypes); + // GatherNd seems undefined on the case where params has rank 0. + std::vector params_shape = RandomDims(1); + auto indices_type = DT_INT32; + std::vector output_outer_shape = RandomDims(0, 4, 0, 32); + int64_t index_len = RandomDim(0, params_shape.size() + 1); + std::vector output_shape(output_outer_shape); + output_shape.push_back(index_len); + Tensor lo(indices_type, TensorShape(output_shape)); + test::FillFn(&lo, [](int i) -> int32_t { return 0; }); + Tensor hi(indices_type, TensorShape(output_shape)); + test::FillFn(&hi, [index_len, ¶ms_shape](int i) -> int32_t { + int idx_dim = i % index_len; + return params_shape[idx_dim] - 1; + }); + Tensor indices = RandomBoundedTensor(indices_type, lo, hi); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("GatherNd") + .RandomInput(params_type, params_shape) + .Input(indices) + .Attr("Tindices", indices_type) + .Attr("Tparams", params_type)); + }); +} + +TEST_F(OpTest, Greater) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Greater") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, GreaterEqual) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("GreaterEqual") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Identity) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Identity").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Imag) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Imag") + .RandomInput(DT_COMPLEX64) + .Attr("T", DT_COMPLEX64)); + }); +} + +TEST_F(OpTest, InplaceUpdate) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector common_dims = + RandomDims(0, kDefaultMaxRank - 1, 0, kDefaultMaxDimensionSize); + // TODO(b/211012712): Once needs_unique_values case is linear instead of + // quadratic time, use default Dim max instead of 8. + std::vector v_dims{RandomDim(1, 8)}; + v_dims.insert(v_dims.end(), common_dims.begin(), common_dims.end()); + std::vector x_dims{RandomDim(v_dims[0])}; + x_dims.insert(x_dims.end(), common_dims.begin(), common_dims.end()); + std::vector i_shape{v_dims[0]}; + Tensor i = + RandomBoundedTensor(DT_INT32, 0, x_dims[0] - 1, true, i_shape); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("InplaceUpdate") + .RandomInput(type, x_dims) + .Input(i) + .RandomInput(type, v_dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Inv) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Inv").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Invert) { + Repeatedly([this]() { + DataType type = DT_INT32; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Invert").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, InvertPermutation) { + Repeatedly([this]() { + // TODO(b/211012712): Once needs_unique_values case is linear instead of + // quadratic time, use default Dim max instead of 8. + int64_t len = RandomDim(0, 8); + Tensor x = RandomBoundedTensor(DT_INT32, 0, len - 1, true, {len}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("InvertPermutation").Input(x).Attr("T", DT_INT32)); + }); +} + +TEST_F(OpTest, IsFinite) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("IsFinite").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, IsInf) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("IsInf").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, IsNan) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("IsNan").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, L2Loss) { + Repeatedly([this]() { + DataType type = DT_FLOAT; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("L2Loss").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, LeakyRelu) { + Repeatedly([this]() { + std::uniform_real_distribution alpha(-2.0f, 2.0f); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LeakyRelu") + .RandomInput(DT_FLOAT) + .Attr("T", DT_FLOAT) + .Attr("alpha", alpha(generator()))); + }); +} + +TEST_F(OpTest, LeakyReluGrad) { + Repeatedly([this]() { + auto dims = RandomDims(1); + std::uniform_real_distribution alpha(-2.0f, 2.0f); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LeakyReluGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT) + .Attr("alpha", alpha(generator()))); + }); +} + +TEST_F(OpTest, LeftShift) { + Repeatedly([this]() { + bool is64 = RandomBool(); + auto dims = RandomDims(); + auto type = is64 ? DT_INT64 : DT_INT32; + int max_shift = is64 ? 63 : 31; + auto y = RandomBoundedTensor(type, 0, max_shift, false, dims); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("LeftShift") + .RandomInput(type, dims) + .Input(y) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Less) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Less") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, LessEqual) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("LessEqual") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Lgamma) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Lgamma").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, LinSpace) { + Repeatedly([this]() { + auto ToScalar = [](DataType type, int x) { + if (type == DT_INT32) return test::AsScalar(x); + return test::AsScalar(x); + }; + std::uniform_int_distribution distribution(-50, 50); + auto type = Choose({DT_INT32, DT_INT64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LinSpace") + .RandomInput(DT_FLOAT, {}) + .RandomInput(DT_FLOAT, {}) + .Input(ToScalar(type, distribution(generator()))) + .Attr("T", DT_FLOAT) + .Attr("Tidx", type)); + }); +} + +TEST_F(OpTest, Log) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Log").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Log1p) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Log1p").RandomInput(type).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, LogicalAnd) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LogicalAnd") + .RandomInput(DT_BOOL, dims.first) + .RandomInput(DT_BOOL, dims.second)); + }); +} + +TEST_F(OpTest, LogicalNot) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LogicalNot").RandomInput(DT_BOOL)); + }); +} + +TEST_F(OpTest, LogicalOr) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LogicalOr") + .RandomInput(DT_BOOL, dims.first) + .RandomInput(DT_BOOL, dims.second)); + }); +} + +TEST_F(OpTest, LogSoftmax) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LogSoftmax") + .RandomInput(DT_FLOAT, RandomDims(2, 2)) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, LRN) { + Repeatedly([this]() { + // TODO(b/31362467): Crashes with 0 dims on GPU. Re-enable when fixed. + std::vector data_dims = RandomDims(4, 4, 1, 8); + // CuDNN requires depth_radius > 0. + std::uniform_int_distribution radius(1, data_dims[3]); + std::uniform_real_distribution coeff(0.01, 2.0); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LRN") + .RandomInput(DT_FLOAT, data_dims) + .Attr("T", DT_FLOAT) + .Attr("depth_radius", radius(generator())) + .Attr("bias", coeff(generator())) + .Attr("alpha", coeff(generator())) + .Attr("beta", coeff(generator()))); + }); +} + +TEST_F(OpTest, LRNGrad) { + Repeatedly([this]() { + // TODO(b/31362467): Crashes with 0 dims on GPU. Re-enable when fixed. + std::vector dims = RandomDims(4, 4, 1, 8); + // CuDNN requires depth_radius > 0. + std::uniform_int_distribution radius(1, dims[3]); + std::uniform_real_distribution coeff(0.0, 2.0); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("LRNGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT) + .Attr("depth_radius", radius(generator())) + .Attr("bias", coeff(generator())) + .Attr("alpha", coeff(generator())) + .Attr("beta", coeff(generator()))); + }); +} + +TEST_F(OpTest, MatMul) { + Repeatedly([this]() { + int64_t x = RandomDim(); + int64_t y = RandomDim(); + int64_t z = RandomDim(); + + std::vector a_dims = {x, y}; + std::vector b_dims = {y, z}; + + std::bernoulli_distribution random_bool; + bool transpose_a = random_bool(generator()); + bool transpose_b = random_bool(generator()); + if (transpose_a) { + std::swap(a_dims[0], a_dims[1]); + } + if (transpose_b) { + std::swap(b_dims[0], b_dims[1]); + } + + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatMul") + .RandomInput(type, a_dims) + .RandomInput(type, b_dims) + .Attr("T", type) + .Attr("transpose_a", transpose_a) + .Attr("transpose_b", transpose_b)); + }); +} + +TEST_F(OpTest, MatrixBandPart) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto index_type = Choose({DT_INT32, DT_INT64}); + auto num_lower = + RandomBoundedTensor(index_type, -2 * kDefaultMaxDimensionSize, + 2 * kDefaultMaxDimensionSize, false, {}); + auto num_upper = + RandomBoundedTensor(index_type, -2 * kDefaultMaxDimensionSize, + 2 * kDefaultMaxDimensionSize, false, {}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixBandPart") + .RandomInput(type) + .Input(num_lower) + .Input(num_upper) + .Attr("T", type) + .Attr("Tindex", index_type)); + }); +} + +TEST_F(OpTest, MatrixDiag) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixDiag") + .RandomInput(type, RandomDims(1)) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, MatrixDiagPart) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixDiagPart") + .RandomInput(type, RandomDims(2)) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, MatrixDiagPartV3) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto type = Choose(kAllXlaTypes); + auto align = Choose( + {"LEFT_RIGHT", "RIGHT_LEFT", "LEFT_LEFT", "RIGHT_RIGHT"}); + auto k0 = std::uniform_int_distribution( + -2 * kDefaultMaxDimensionSize, + 2 * kDefaultMaxDimensionSize)(generator()); + auto k1 = std::uniform_int_distribution( + k0, 2 * kDefaultMaxDimensionSize)(generator()); + auto k = test::AsTensor({k0, k1}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixDiagPartV3") + .RandomInput(type) + .Input(k) + .RandomInput(type, {}) + .Attr("align", align) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, MatrixSetDiag) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto shape = RandomDims(2); + int rank = shape.size(); + std::vector diagonal_shape(shape); + diagonal_shape.pop_back(); + diagonal_shape.pop_back(); + diagonal_shape.push_back(std::min(shape[rank - 2], shape[rank - 1])); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixSetDiag") + .RandomInput(type, shape) + .RandomInput(type, diagonal_shape) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, MatrixSetDiagV2) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto shape = RandomDims(2, kDefaultMaxRank, 1 /* non-zero dims */); + int rank = shape.size(); + int64_t max_num_diags = shape[rank - 2] + shape[rank - 1] - 1; + int64_t num_diags = + std::uniform_int_distribution(2, max_num_diags)(generator()); + int32_t k0 = std::uniform_int_distribution( + -shape[rank - 2] + 1, shape[rank - 1] - num_diags)(generator()); + int32_t k1 = k0 + num_diags - 1; + Tensor k = test::AsTensor({k0, k1}); + int64_t max_diag_len = std::min(shape[rank - 2] + std::min(k1, 0), + shape[rank - 1] + std::min(-k0, 0)); + std::vector diagonal_shape(shape); + diagonal_shape.pop_back(); + diagonal_shape.pop_back(); + diagonal_shape.push_back(num_diags); + diagonal_shape.push_back(max_diag_len); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("MatrixSetDiagV2") + .RandomInput(type, shape) + .RandomInput(type, diagonal_shape) + .Input(k) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Max) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Max") + .RandomInput(type, data_dims) + .Input(indices) + .Attr("T", type) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, Maximum) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Maximum") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, MaxPool) { + Repeatedly([this]() { + std::uniform_int_distribution random_int(1, 5); + std::vector dims = RandomDims(4, 4, 1); + int kernel_rows = + std::uniform_int_distribution(1, dims[1])(generator()); + int kernel_cols = + std::uniform_int_distribution(1, dims[2])(generator()); + int stride_rows = random_int(generator()), + stride_cols = random_int(generator()); + + std::string padding = Choose({"SAME", "VALID"}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("MaxPool") + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT) + .Attr("ksize", {1, kernel_rows, kernel_cols, 1}) + .Attr("strides", {1, stride_rows, stride_cols, 1}) + .Attr("padding", padding) + .Attr("data_format", "NHWC")); + }); + // TODO(phawkins): test NCHW format (not supported by CPU) +} + +TEST_F(OpTest, MaxPool3D) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + std::uniform_int_distribution random_int(1, 5); + std::vector dims = RandomDims(5, 5, 1); + + std::vector input_dims, kernel_dims, stride_dims; + kernel_dims.push_back(1); + stride_dims.push_back(1); + for (int i = 0; i < 3; ++i) { + kernel_dims.push_back( + std::uniform_int_distribution(1, dims[i])(generator())); + input_dims.push_back(dims[i]); + stride_dims.push_back(random_int(generator())); + } + kernel_dims.push_back(1); + stride_dims.push_back(1); + int64_t batch = dims[3]; + int64_t feature = dims[4]; + + std::string padding = Choose({"SAME", "VALID"}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("MaxPool3D") + .RandomInput(DT_FLOAT, + ImageDims(FORMAT_NHWC, batch, feature, input_dims)) + .Attr("T", DT_FLOAT) + .Attr("ksize", kernel_dims) + .Attr("strides", stride_dims) + .Attr("padding", padding) + .Attr("data_format", "NDHWC")); + }); + // TODO(phawkins): test NCHW format (not supported by CPU) +} + +TEST_F(OpTest, Mean) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + // TODO(phawkins): CPU and XLA differ output for reducing across a + // size-0 dimension (nan vs 0). For now, require size >= 1. + std::vector data_dims = RandomDims(0, kDefaultMaxRank, 1); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mean") + .RandomInput(type, data_dims) + .Input(indices) + .Attr("T", type) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, Min) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Min") + .RandomInput(type, data_dims) + .Input(indices) + .Attr("T", type) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, Minimum) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Minimum") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Mod) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mod") + .RandomInput(DT_INT32, dims.first) + .RandomInput(DT_INT32, dims.second) + .Attr("T", DT_INT32)); + }); +} + +TEST_F(OpTest, Mul) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mul") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, MulNoNan) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Mul") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Neg) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Neg").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, NextAfter) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT}); + auto dims = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("NextAfter") + .RandomInput(type, dims) + .RandomInput(type, dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, NotEqual) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("NotEqual") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, OneHot) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + + std::vector dims = RandomDims(); + int num_dims = dims.size(); + + int32_t depth = RandomDim(); + + Tensor indices(DT_INT32, TensorShape(dims)); + std::uniform_int_distribution distribution(-depth * 2, depth * 2); + test::FillFn(&indices, [this, &distribution](int i) -> int32_t { + return distribution(generator()); + }); + + int axis = std::uniform_int_distribution( + -num_dims - 5, num_dims + 5)(generator()); + + OpTestBuilder builder("OneHot"); + builder.Attr("T", type); + builder.Attr("TI", DT_INT32); + builder.Attr("axis", axis); + builder.Input(indices); + builder.Input(test::AsScalar(depth)); + builder.RandomInput(type, {}); + builder.RandomInput(type, {}); + return ExpectTfAndXlaOutputsAreClose(builder); + }); +} + +TEST_F(OpTest, OnesLike) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("OnesLike").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Pack) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + int n = std::uniform_int_distribution(1, 5)(generator()); + + std::vector dims = RandomDims(); + int num_dims = dims.size(); + int axis = std::uniform_int_distribution(-num_dims - 1, + num_dims)(generator()); + + OpTestBuilder builder("Pack"); + builder.Attr("T", type); + builder.Attr("N", n); + builder.Attr("axis", axis); + for (int i = 0; i < n; ++i) { + builder.RandomInput(type, dims); + } + return ExpectTfAndXlaOutputsAreClose(builder); + }); +} + +TEST_F(OpTest, Pad) { + // See note about failing Kokoro tests: b/214080339#comment22 + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + auto a = ChoosePadArguments(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Pad") + .RandomInput(a.input_type, a.input_shape) + .Input(a.paddings) + .Attr("T", a.input_type) + .Attr("Tpaddings", a.paddings_type)); + }); +} + +TEST_F(OpTest, PadV2) { + Repeatedly([this]() { + auto a = ChoosePadArguments(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("PadV2") + .RandomInput(a.input_type, a.input_shape) + .Input(a.paddings) + .Input(a.constant_values) + .Attr("T", a.input_type) + .Attr("Tpaddings", a.paddings_type)); + }); +} + +TEST_F(OpTest, Pow) { + // TODO(phawkins): Feeding large DT_INT32 values to Pow() leads to + // nontermination. + Repeatedly([this]() { + auto dims = BroadcastableDims(); + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Pow") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Prod) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Prod") + .RandomInput(type, data_dims) + .Input(indices) + .Attr("T", type) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, Qr) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Qr") + .RandomInput(type, RandomDims(2, kDefaultMaxRank, 1)) + .Attr("T", type) + .Attr("full_matrices", true)); + }); +} + +TEST_F(OpTest, QuantizeAndDequantizeV2) { + Repeatedly([this]() { + std::uniform_int_distribution num_bits_dist(1, 64); + int64_t num_bits = num_bits_dist(generator()); + std::string round_mode = Choose({"HALF_TO_EVEN", "HALF_UP"}); + auto dims = RandomDims(0, kDefaultMaxRank, 1); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("QuantizeAndDequantizeV2") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) // unused because range_given = false + .RandomInput(DT_FLOAT, dims) // unused because range_given = false + .Attr("signed_input", RandomBool()) + .Attr("num_bits", num_bits) + .Attr("range_given", false) + .Attr("round_mode", round_mode) + .Attr("narrow_range", RandomBool()) + .Attr("axis", -1) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, RandomShuffle) { + // See b/209062491 as this test passes with --tf_xla_test_device=CPU:0 + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("RandomShuffle") + .RandomInput(type, RandomDims(1)) + .Attr("seed", RandomSeed()) + .Attr("seed2", RandomSeed()) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, RandomStandardNormal) { + Repeatedly([this]() { + auto shape_type = Choose({DT_INT32, DT_INT64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("RandomStandardNormal") + .Input(AsIntTensor(shape_type, RandomDims())) + .Attr("seed", RandomSeed()) + .Attr("seed2", RandomSeed()) + .Attr("T", shape_type) + .Attr("dtype", DT_FLOAT)); + }); +} + +TEST_F(OpTest, RandomUniform) { + Repeatedly([this]() { + auto shape_type = Choose({DT_INT32, DT_INT64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("RandomStandardNormal") + .Input(AsIntTensor(shape_type, RandomDims())) + .Attr("seed", RandomSeed()) + .Attr("seed2", RandomSeed()) + .Attr("T", shape_type) + .Attr("dtype", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Range) { + Repeatedly([this]() { + auto ToScalar = [](DataType type, int x) { + if (type == DT_INT32) return test::AsScalar(x); + if (type == DT_INT64) return test::AsScalar(x); + if (type == DT_FLOAT) return test::AsScalar(x); + if (type == DT_DOUBLE) return test::AsScalar(x); + LOG(FATAL) << "Unknown type " << DataTypeString(type); + }; + std::uniform_int_distribution distribution(-50, 50); + DataType tidx = Choose({DT_INT32, DT_INT64, DT_FLOAT, DT_DOUBLE}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Range") + .Input(ToScalar(tidx, distribution(generator()))) + .Input(ToScalar(tidx, distribution(generator()))) + .Input(ToScalar(tidx, distribution(generator()))) + .Attr("Tidx", tidx)); + }); +} + +TEST_F(OpTest, Rank) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Rank").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Real) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Real") + .RandomInput(DT_COMPLEX64) + .Attr("T", DT_COMPLEX64)); + }); +} + +TEST_F(OpTest, RealDiv) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("RealDiv") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Reciprocal) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Reciprocal").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, ReciprocalGrad) { + Repeatedly([this]() { + std::vector dims = RandomDims(); + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ReciprocalGrad") + .RandomInput(type, dims) + .RandomInput(type, dims) + .Attr("T", type)); + }); +} +TEST_F(OpTest, Relu) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Relu").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Relu6) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Relu6").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Relu6Grad) { + Repeatedly([this]() { + auto dims = RandomDims(1); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Relu6Grad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, ReluGrad) { + Repeatedly([this]() { + auto dims = RandomDims(1); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ReluGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Reshape) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector dims = RandomDims(); + std::bernoulli_distribution random_bool; + std::vector dims_before, dims_after; + for (std::vector* out : {&dims_before, &dims_after}) { + std::shuffle(dims.begin(), dims.end(), generator()); + for (int64_t dim : dims) { + // Either add the dimension as a new dimension or merge it with the + // previous dimension. + if (out->empty() || random_bool(generator())) { + out->push_back(dim); + } else { + out->back() *= dim; + } + } + } + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Reshape") + .RandomInput(type, dims_before) + .Input(test::AsTensor( + std::vector(dims_after.begin(), dims_after.end()))) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, ResizeNearestNeighbor) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_INT32, DT_INT64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ResizeNearestNeighbor") + .RandomInput(type, RandomDims(4, 4, 1)) + .Input(AsIntTensor(DT_INT32, RandomDims(2, kDefaultMaxRank, 1))) + .Attr("align_corners", RandomBool()) + .Attr("half_pixel_centers", RandomBool()) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, ResizeBilinear) { + Repeatedly([this]() { + std::vector in_dims = RandomDims(4, 4); + std::vector out_dims = RandomDims(2, 2); + + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ResizeBilinear") + .RandomInput(DT_FLOAT, in_dims) + .Input(test::AsTensor( + std::vector(out_dims.begin(), out_dims.end()))) + .Attr("T", DT_FLOAT) + .Attr("align_corners", true)); + }); +} + +TEST_F(OpTest, ResizeBilinearGrad) { + Repeatedly([this]() { + std::vector in_dims = RandomDims(4, 4); + std::vector out_dims = RandomDims(2, 2); + + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ResizeBilinearGrad") + .RandomInput(DT_FLOAT, in_dims) + .RandomInput(DT_FLOAT, + {in_dims[0], out_dims[0], out_dims[1], in_dims[3]}) + .Attr("T", DT_FLOAT) + .Attr("align_corners", true)); + }); +} + +TEST_F(OpTest, Reverse) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + std::vector dims = RandomDims(1); + auto type = Choose(kAllXlaTypes); + int64_t rank = dims.size(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Reverse") + .RandomInput(type, dims) + .RandomInput(DT_BOOL, {rank}) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, ReverseSequence) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + std::vector dims = RandomDims(/*min_rank=*/2); + auto type = Choose(kAllXlaTypes); + int64_t rank = dims.size(); + + // Choose random batch and sequence dimensions. + std::vector shuffled_dim_ids(rank); + absl::c_iota(shuffled_dim_ids, 0); + absl::c_shuffle(shuffled_dim_ids, generator()); + shuffled_dim_ids.resize(2); + int batch_dim = shuffled_dim_ids[0]; + int seq_dim = shuffled_dim_ids[1]; + + int batch_size = dims[batch_dim]; + int max_seq_len = dims[seq_dim]; + std::vector seq_lens(batch_size); + std::uniform_int_distribution d(0, max_seq_len); + absl::c_generate(seq_lens, [&]() { return d(generator()); }); + + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ReverseSequence") + .RandomInput(type, dims) + .Input(test::AsTensor(seq_lens)) + .Attr("seq_dim", seq_dim) + .Attr("batch_dim", batch_dim) + .Attr("T", type) + .Attr("Tlen", DT_INT32)); + }); +} + +TEST_F(OpTest, ReverseV2) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("ReverseV2") + .RandomInput(type, data_dims) + .Input(indices) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, RightShift) { + Repeatedly([this]() { + bool is64 = RandomBool(); + auto dims = RandomDims(); + auto type = is64 ? DT_INT64 : DT_INT32; + int max_shift = is64 ? 63 : 31; + auto y = RandomBoundedTensor(type, 0, max_shift, false, dims); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("RightShift") + .RandomInput(type, dims) + .Input(y) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Rint) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Rint").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Roll) { + Repeatedly([this]() { + auto input_type = Choose(kAllXlaTypes); + auto axis_type = Choose({DT_INT32, DT_INT64}); + // TODO(b/201095155,b/197140886): shift_type = DT_INT64 doesn't work. + auto shift_type = DT_INT32; + auto input_shape = RandomDims(1); + int rank = input_shape.size(); + auto axis_shape = RandomDims(1, 1, 1, rank + 1); + auto axis = RandomBoundedTensor(axis_type, 0, rank - 1, true, axis_shape); + auto shift = RandomTensor(shift_type, false, axis_shape); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Roll") + .RandomInput(input_type, input_shape) + .Input(shift) + .Input(axis) + .Attr("T", input_type) + .Attr("Taxis", axis_type) + .Attr("Tshift", shift_type)); + }); +} + +TEST_F(OpTest, Round) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Round").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Rsqrt) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Rsqrt").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, RsqrtGrad) { + Repeatedly([this]() { + auto dims = RandomDims(); + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("RsqrtGrad") + .RandomInput(type, dims) + .RandomInput(type, dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Select) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto shape = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Select") + .RandomInput(DT_BOOL, shape) + .RandomInput(type, shape) + .RandomInput(type, shape) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, SelectV2) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto shape = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SelectV2") + .RandomInput(DT_BOOL, shape) + .RandomInput(type, shape) + .RandomInput(type, shape) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Shape) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Shape").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, ShapeN) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + int n = std::uniform_int_distribution(1, 5)(generator()); + OpTestBuilder builder("ShapeN"); + builder.Attr("T", type); + builder.Attr("N", n); + for (int i = 0; i < n; ++i) { + builder.RandomInput(type); + } + return ExpectTfAndXlaOutputsAreClose(builder); + }); +} + +TEST_F(OpTest, Sigmoid) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Sigmoid").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, SigmoidGrad) { + Repeatedly([this]() { + auto dims = RandomDims(); + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SigmoidGrad") + .RandomInput(type, dims) + .RandomInput(type, dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Sign) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Sign").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Sin) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Sin").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Sinh) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Sinh").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Size) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Size").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Slice) { + Repeatedly([this]() { + SliceArguments a = ChooseSliceArguments(true); + std::vector size; + size.insert(size.end(), a.size.begin(), a.size.end()); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Slice") + .RandomInput(a.type, a.shape) + .Input(a.indices) + .Input(test::AsTensor(size)) + .Attr("T", a.type) + .Attr("Index", a.indices_type)); + }); +} + +TEST_F(OpTest, Softmax) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Softmax") + .RandomInput(DT_FLOAT, RandomDims(2, 2)) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, SoftmaxCrossEntropyWithLogits) { + Repeatedly([this]() { + std::vector dims = RandomDims(2, 2, 1); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("SoftmaxCrossEntropyWithLogits") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Softplus) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Softplus").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, SoftplusGrad) { + Repeatedly([this]() { + std::vector dims = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SoftplusGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Softsign) { + Repeatedly([this]() { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Softsign").RandomInput(DT_FLOAT).Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, SoftsignGrad) { + Repeatedly([this]() { + std::vector dims = RandomDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SoftsignGrad") + .RandomInput(DT_FLOAT, dims) + .RandomInput(DT_FLOAT, dims) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, SpaceToBatch) { + Repeatedly([this]() { + std::vector block_dims = RandomDims(4, 4, 0, 5); + const int num_block_dims = 2; + int64_t block_size = RandomDim(2, 5); + + std::vector input_dims(1 + num_block_dims + 1); + input_dims[0] = RandomDim(); + for (int i = 0; i < num_block_dims; ++i) { + input_dims[1 + i] = block_dims[i] * block_size; + } + input_dims[1 + num_block_dims] = RandomDim(); + + std::vector padding_vals; + std::uniform_int_distribution distribution(0, 7); + for (int i = 0; i < num_block_dims; ++i) { + int64_t pad_before; + int64_t pad_after; + do { + pad_before = distribution(generator()); + pad_after = distribution(generator()); + } while (pad_before + pad_after > input_dims[1 + i]); + input_dims[1 + i] -= pad_before + pad_after; + padding_vals.push_back(pad_before); + padding_vals.push_back(pad_after); + } + Tensor paddings; + CHECK(paddings.CopyFrom(AsIntTensor(DT_INT32, padding_vals), + TensorShape({num_block_dims, 2}))); + + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SpaceToBatch") + .RandomInput(type, input_dims) + .Input(paddings) + .Attr("T", type) + .Attr("block_size", block_size)); + }); +} + +TEST_F(OpTest, SpaceToBatchND) { + Repeatedly([this]() { + std::vector block_dims = RandomDims(1, 3, 0, 5); + int num_block_dims = block_dims.size(); + std::vector remaining_dims = RandomDims(0, 3); + std::vector block_multipliers = + RandomDims(block_dims.size(), block_dims.size(), 0, 4); + + std::vector input_dims(1 + num_block_dims + remaining_dims.size()); + input_dims[0] = RandomDim(); + for (int i = 0; i < num_block_dims; ++i) { + input_dims[1 + i] = block_dims[i] * block_multipliers[i]; + } + std::copy(remaining_dims.begin(), remaining_dims.end(), + input_dims.begin() + 1 + num_block_dims); + + std::vector padding_vals; + std::uniform_int_distribution distribution(0, 7); + for (int i = 0; i < num_block_dims; ++i) { + int64_t pad_before; + int64_t pad_after; + do { + pad_before = distribution(generator()); + pad_after = distribution(generator()); + } while (pad_before + pad_after > input_dims[1 + i]); + input_dims[1 + i] -= pad_before + pad_after; + padding_vals.push_back(pad_before); + padding_vals.push_back(pad_after); + } + Tensor paddings; + CHECK(paddings.CopyFrom(AsIntTensor(DT_INT32, padding_vals), + TensorShape({num_block_dims, 2}))); + + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("SpaceToBatchND") + .RandomInput(type, input_dims) + .Input(test::AsTensor( + std::vector(block_dims.begin(), block_dims.end()))) + .Input(paddings) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, SpaceToDepth) { + Repeatedly([this]() { + int64_t block = RandomDim(2, 5); + std::vector input_dims = RandomDims(4, 4); + // Round spatial dimensions up to a multiple of the block size + input_dims[1] = (input_dims[1] + (block - 1)) / block * block; + input_dims[2] = (input_dims[2] + (block - 1)) / block * block; + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SpaceToDepth") + .RandomInput(DT_FLOAT, input_dims) + .Attr("T", DT_FLOAT) + .Attr("block_size", block)); + }); +} + +TEST_F(OpTest, SparseMatMul) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + int64_t x = RandomDim(); + int64_t y = RandomDim(); + int64_t z = RandomDim(); + + std::vector a_dims = {x, y}; + std::vector b_dims = {y, z}; + + std::bernoulli_distribution random_bool; + bool transpose_a = random_bool(generator()); + bool transpose_b = random_bool(generator()); + if (transpose_a) { + std::swap(a_dims[0], a_dims[1]); + } + if (transpose_b) { + std::swap(b_dims[0], b_dims[1]); + } + + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SparseMatMul") + .RandomInput(DT_FLOAT, a_dims) + .RandomInput(DT_FLOAT, b_dims) + .Attr("Ta", DT_FLOAT) + .Attr("Tb", DT_FLOAT) + .Attr("transpose_a", transpose_a) + .Attr("transpose_b", transpose_b)); + }); +} + +TEST_F(OpTest, SparseSoftmaxCrossEntropyWithLogits) { + Repeatedly([this]() { + std::vector dims = RandomDims(2, 2, 1); + int64_t batch_size = dims[0]; + int64_t num_classes = dims[1]; + + std::vector indices(batch_size); + for (int64_t i = 0; i < batch_size; ++i) { + indices[i] = std::uniform_int_distribution( + 0, num_classes - 1)(generator()); + } + + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("SparseSoftmaxCrossEntropyWithLogits") + .RandomInput(DT_FLOAT, dims) + .Input(test::AsTensor(indices)) + .Attr("T", DT_FLOAT) + .Attr("Tlabels", DT_INT32)); + }); +} + +TEST_F(OpTest, Split) { + // See b/214080339#comment27 as this test causes Kokoro to crash. + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector dims = RandomDims(1); + std::uniform_int_distribution ud; + int32_t dim = std::uniform_int_distribution( + -static_cast(dims.size()), + static_cast(dims.size()) - 1)(generator()); + int n = std::uniform_int_distribution(1, 5)(generator()); + // Ensure 'dim' is evenly divisible by 'n'. + dims[dim] /= n; + dims[dim] *= n; + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Split") + .Input(test::AsScalar(dim)) + .RandomInput(type, dims) + .Attr("T", type) + .Attr("num_split", n)); + }); +} + +TEST_F(OpTest, SplitV) { + // Likely this only fails when dim is negative. Try type = DT_FLOAT first. + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto type = Choose(kAllXlaTypes); + std::vector dims = RandomDims(1, kDefaultMaxRank, 1); + int32_t dim = std::uniform_int_distribution( + -static_cast(dims.size()), + static_cast(dims.size()) - 1)(generator()); + int n = std::uniform_int_distribution( + 1, std::min(5, static_cast(dims[dim])))(generator()); + std::vector size_splits(n); + for (int i = 0; i < n - 1; ++i) { + size_splits.push_back(dims[dim] / n); + } + size_splits.push_back(dims[dim] - (n - 1) * (dims[dim] / n)); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("SplitV") + .RandomInput(type, dims) + .Input(test::AsTensor(size_splits)) + .Input(test::AsScalar(dim)) + .Attr("T", type) + .Attr("num_split", n) + .Attr("Tlen", DT_INT32)); + }); +} + +TEST_F(OpTest, Sqrt) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Sqrt").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, StopGradient) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("StopGradient").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, SqrtGrad) { + Repeatedly([this]() { + auto dims = RandomDims(); + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SqrtGrad") + .RandomInput(type, dims) + .RandomInput(type, dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, SquaredDifference) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("SquaredDifference") + .RandomInput(DT_FLOAT, dims.first) + .RandomInput(DT_FLOAT, dims.second) + .Attr("T", DT_FLOAT)); + }); +} + +TEST_F(OpTest, Square) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Square").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Squeeze) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector t_dims = RandomDims(0, kDefaultMaxRank, 0, 5); + std::bernoulli_distribution random_bool; + std::vector squeeze_dims; + for (int i = 0; i < t_dims.size(); ++i) { + if (t_dims[i] == 1 && random_bool(generator())) { + squeeze_dims.push_back(i); + } + } + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Squeeze") + .RandomInput(type, t_dims) + .Attr("squeeze_dims", squeeze_dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Sub) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Sub") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Sum) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + std::vector data_dims = RandomDims(); + Tensor indices = RandomReductionIndices(data_dims.size()); + bool keep_dims = Choose({false, true}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Sum") + .RandomInput(type, data_dims) + .Input(indices) + .Attr("T", type) + .Attr("keep_dims", keep_dims)); + }); +} + +TEST_F(OpTest, StridedSlice) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector data_dims = RandomDims(); + std::vector begin(data_dims.size()), end(data_dims.size()); + std::vector strides(data_dims.size()); + for (int i = 0; i < data_dims.size(); ++i) { + begin[i] = std::uniform_int_distribution( + -2 * data_dims[i], 2 * data_dims[i])(generator()); + end[i] = std::uniform_int_distribution( + -2 * data_dims[i], 2 * data_dims[i])(generator()); + // TODO(b/31360685): support strides other than 1 or -1 + strides[i] = std::bernoulli_distribution()(generator()) ? 1 : -1; + } + int64_t max_bitmask = (1LL << data_dims.size()) - 1; + std::uniform_int_distribution bitmask_distribution(0, max_bitmask); + int64_t begin_mask = bitmask_distribution(generator()); + int64_t end_mask = bitmask_distribution(generator()); + + // Create a ellipsis bitmask with at most one 1 bit set. + int64_t ellipsis_mask = 0; + if (!data_dims.empty() && std::bernoulli_distribution()(generator())) { + int ellipsis_pos = std::uniform_int_distribution( + 0, data_dims.size() - 1)(generator()); + ellipsis_mask = 1LL << ellipsis_pos; + } + + int64_t new_axis_mask = bitmask_distribution(generator()); + int64_t shrink_axis_mask = bitmask_distribution(generator()); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("StridedSlice") + .RandomInput(type, data_dims) + .Input(test::AsTensor(begin)) + .Input(test::AsTensor(end)) + .Input(test::AsTensor(strides)) + .Attr("T", type) + .Attr("Index", DT_INT32) + .Attr("begin_mask", begin_mask) + .Attr("end_mask", end_mask) + .Attr("ellipsis_mask", ellipsis_mask) + .Attr("new_axis_mask", new_axis_mask) + .Attr("shrink_axis_mask", shrink_axis_mask)); + }); +} + +TEST_F(OpTest, StridedSliceGrad) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + + // Dimensions of the forward input. + std::vector dims = RandomDims(); + + std::vector begin(dims.size()), end(dims.size()); + std::vector strides(dims.size()); + for (int i = 0; i < dims.size(); ++i) { + begin[i] = std::uniform_int_distribution( + -2 * dims[i], 2 * dims[i])(generator()); + end[i] = std::uniform_int_distribution(-2 * dims[i], + 2 * dims[i])(generator()); + strides[i] = std::uniform_int_distribution( + -2 * dims[i], 2 * dims[i])(generator()); + } + int64_t max_bitmask = (1LL << dims.size()) - 1; + std::uniform_int_distribution bitmask_distribution(0, max_bitmask); + int64_t begin_mask = bitmask_distribution(generator()); + int64_t end_mask = bitmask_distribution(generator()); + + // Create a ellipsis bitmask with at most one 1 bit set. + int64_t ellipsis_mask = 0; + if (!dims.empty() && std::bernoulli_distribution()(generator())) { + int ellipsis_pos = + std::uniform_int_distribution(0, dims.size() - 1)(generator()); + ellipsis_mask = 1LL << ellipsis_pos; + } + + int64_t new_axis_mask = bitmask_distribution(generator()); + int64_t shrink_axis_mask = bitmask_distribution(generator()); + + // TODO(phawkins): use shape inference for the forward op to compute the + // gradient shape for the backward op. At present, there is a low + // probability of the golden op succeeding. + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("StridedSliceGrad") + .Input(test::AsTensor(dims)) + .Input(test::AsTensor(begin)) + .Input(test::AsTensor(end)) + .Input(test::AsTensor(strides)) + .RandomInput(type, RandomDims(1)) + .Attr("T", type) + .Attr("Index", DT_INT64) + .Attr("begin_mask", begin_mask) + .Attr("end_mask", end_mask) + .Attr("ellipsis_mask", ellipsis_mask) + .Attr("new_axis_mask", new_axis_mask) + .Attr("shrink_axis_mask", shrink_axis_mask)); + }); +} + +TEST_F(OpTest, Tan) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Tan").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Tanh) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Tanh").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, TanhGrad) { + Repeatedly([this]() { + auto dims = RandomDims(); + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TanhGrad") + .RandomInput(type, dims) + .RandomInput(type, dims) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, TensorScatterUpdate) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto a = ChooseScatterArguments(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TensorScatterUpdate") + .RandomInput(a.type, a.shape) + .Input(a.indices) + .Input(a.updates) + .Attr("T", a.type) + .Attr("Tindices", a.indices_type)); + }); +} + +TEST_F(OpTest, Tile) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector t_dims = RandomDims(1); + std::vector multiples(t_dims.size()); + for (int i = 0; i < t_dims.size(); ++i) { + multiples[i] = std::uniform_int_distribution(1, 3)(generator()); + } + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Tile") + .RandomInput(type, t_dims) + .Input(test::AsTensor(multiples)) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, TopKV2) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { // NOLINT: due to GTEST_SKIP + auto type = Choose({DT_INT32, DT_FLOAT, DT_INT64}); + auto shape = RandomDims(1); + int32_t k = + std::uniform_int_distribution(1, shape[0])(generator()); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TopKV2") + .RandomInput(type, shape) + .Input(test::AsScalar(k)) + .Attr("sorted", RandomBool()) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Transpose) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + std::vector data_dims = RandomDims(); + std::vector perm(data_dims.size()); + std::iota(perm.begin(), perm.end(), 0); + std::shuffle(perm.begin(), perm.end(), generator()); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("Transpose") + .RandomInput(type, data_dims) + .Input(test::AsTensor(perm)) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, TruncateDiv) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + Repeatedly([this]() { + DataType type = DT_INT32; + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TruncateDiv") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, TruncateMod) { + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("TruncateMod") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Unpack) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + auto shape = RandomDims(1); + int axis = + std::uniform_int_distribution(0, shape.size() - 1)(generator()); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Unpack") + .RandomInput(type, shape) + .Attr("axis", axis) + .Attr("T", type) + .Attr("num", shape[axis])); + }); +} + +TEST_F(OpTest, Xdivy) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Xdivy") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, XlaDot) { + Repeatedly([this]() { + const XlaDotArguments& a = ChooseXlaDotArguments(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("XlaDot") + .RandomInput(a.dtype, a.lhs_dims) + .RandomInput(a.dtype, a.rhs_dims) + .Attr("dimension_numbers", a.dnums_encoded) + .Attr("precision_config", a.precision_config_encoded) + .Attr("T", a.dtype)); + }); +} + +TEST_F(OpTest, XlaDotV2) { + Repeatedly([this]() { + const XlaDotArguments& a = ChooseXlaDotArguments(); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("XlaDotV2") + .RandomInput(a.dtype, a.lhs_dims) + .RandomInput(a.dtype, a.rhs_dims) + .Attr("dimension_numbers", a.dnums_encoded) + .Attr("precision_config", a.precision_config_encoded) + .Attr("LhsT", a.dtype) + .Attr("RhsT", a.dtype) + .Attr("preferred_element_type", a.dtype)); + }); +} + +TEST_F(OpTest, XlaDynamicUpdateSlice) { + Repeatedly([this]() { + SliceArguments a = ChooseSliceArguments(false); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("XlaDynamicUpdateSlice") + .RandomInput(a.type, a.shape) + .RandomInput(a.type, a.size) + .Input(a.indices) + .Attr("T", a.type) + .Attr("Tindices", a.indices_type)); + }); +} + +TEST_F(OpTest, XlaEinsum) { + Repeatedly([this]() { + const EinsumArguments a = ChooseEinsumArguments(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("XlaEinsum") + .RandomInput(a.type, a.lhs_dims) + .RandomInput(a.type, a.rhs_dims) + .Attr("equation", a.equation) + .Attr("T", a.type)); + }); +} + +TEST_F(OpTest, XlaSort) { + Repeatedly([this]() { + auto type = Choose(kAllXlaTypes); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("XlaSort") + .RandomInput(type, RandomDims()) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Xlog1py) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Xlog1py") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, Xlogy) { + Repeatedly([this]() { + auto type = Choose({DT_FLOAT, DT_COMPLEX64}); + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Xlogy") + .RandomInput(type, dims.first) + .RandomInput(type, dims.second) + .Attr("T", type)); + }); +} + +TEST_F(OpTest, ZerosLike) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + Repeatedly([this]() { + auto type = Choose({DT_INT32, DT_FLOAT, DT_COMPLEX64}); + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("ZerosLike").RandomInput(type).Attr("T", type)); + }); +} + +TEST_F(OpTest, Zeta) { + Repeatedly([this]() { + auto dims = BroadcastableDims(); + return ExpectTfAndXlaOutputsAreClose(OpTestBuilder("Xlogy") + .RandomInput(DT_FLOAT, dims.first) + .RandomInput(DT_FLOAT, dims.second) + .Attr("T", DT_FLOAT)); + }); +} + +// Example failing run: +// --tf_xla_reference_device=GPU:0 +// --tf_xla_test_use_jit=true --tf_xla_test_device=GPU:0 +// --tf_xla_test_use_mlir=true +// --tf_xla_test_repetitions=2 +// --gunit_filter='OpTest.FusedBatchNormTraining' +// --tf_xla_random_seed=2838146746 +TEST_F(OpTest, FusedBatchNormTraining) { + if (tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/201095155"; + if (!tensorflow::tf_xla_test_use_mlir) GTEST_SKIP() << "b/197140886"; + bool is_nhwc = RandomBool(); + std::vector x_dims = RandomDims(/*min_rank=*/4, /*max_rank=*/4, + /*min_size=*/5, /*max_size=*/20); + std::vector scale_dims = {x_dims[is_nhwc ? 3 : 1]}; + std::vector offset_dims = {x_dims[is_nhwc ? 3 : 1]}; + std::vector mean_dims = {0}; + std::vector variance_dims = {0}; + DataType type = DT_FLOAT; + Repeatedly([&] { + return ExpectTfAndXlaOutputsAreClose( + OpTestBuilder("FusedBatchNorm") + .RandomInput(type, x_dims) + .RandomInput(type, scale_dims) + .RandomInput(type, offset_dims) + .RandomInput(type, mean_dims) + .RandomInput(type, variance_dims) + .Attr("T", type) + .Attr("data_format", is_nhwc ? "NHWC" : "NCHW") + .Attr("epsilon", static_cast(1.001e-05)) + .Attr("is_training", true)); + }); +} +} // anonymous namespace +} // namespace tensorflow + +int main(int argc, char** argv) { + tensorflow::tf_xla_test_device_ptr = new std::string("GPU:0"); + tensorflow::tf_xla_reference_device_ptr = new std::string("CPU:0"); + std::vector flag_list = { + tensorflow::Flag( + "tf_xla_random_seed", &tensorflow::tf_xla_random_seed, + "Random seed to use for XLA tests. <= 0 means choose a seed " + "nondeterministically."), + // TODO(phawkins): it might make more sense to run each test up to a + // configurable time bound. + tensorflow::Flag("tf_xla_test_repetitions", + &tensorflow::tf_xla_test_repetitions, + "Number of repetitions for each test."), + tensorflow::Flag("tf_xla_max_tensor_size", + &tensorflow::tf_xla_max_tensor_size, + "Maximum number of elements for random input tensors."), + tensorflow::Flag("tf_xla_test_device", tensorflow::tf_xla_test_device_ptr, + "Tensorflow device type to use for test"), + tensorflow::Flag("tf_xla_reference_device", + tensorflow::tf_xla_reference_device_ptr, + "Tensorflow device type to use for reference"), + tensorflow::Flag("tf_xla_test_use_jit", &tensorflow::tf_xla_test_use_jit, + "Use JIT compilation for the operator under test"), + tensorflow::Flag( + "tf_xla_test_use_mlir", &tensorflow::tf_xla_test_use_mlir, + "Use MLIR legalization kernels for the operator under test"), + }; + std::string usage = tensorflow::Flags::Usage(argv[0], flag_list); + const bool parse_result = tensorflow::Flags::Parse(&argc, argv, flag_list); + if (!parse_result) { + LOG(ERROR) << "\n" << usage; + return 2; + } + testing::InitGoogleTest(&argc, argv); + if (argc > 1) { + LOG(ERROR) << "Unknown argument " << argv[1] << "\n" << usage; + return 2; + } + // XLA devices register kernels at construction time; create all known devices + // to make sure the kernels are registered. + std::vector> devices; + CHECK_OK(tensorflow::DeviceFactory::AddDevices(tensorflow::SessionOptions(), + "", &devices)); + tensorflow::StaticDeviceMgr device_mgr(std::move(devices)); + + tensorflow::Device* ignored; + TF_QCHECK_OK( + device_mgr.LookupDevice(*tensorflow::tf_xla_test_device_ptr, &ignored)) + << "Unknown test device (" << *tensorflow::tf_xla_test_device_ptr + << "). Did you build in the right configuration (e.g., is CUDA enabled)?"; + + if (tensorflow::tf_xla_test_use_mlir) + tensorflow::GetMlirCommonFlags()->tf_mlir_enable_mlir_bridge = + tensorflow::ConfigProto::Experimental::MLIR_BRIDGE_ROLLOUT_ENABLED; + return RUN_ALL_TESTS(); +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/reduce_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reduce_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..24d9eecc6702a823d9cca54c7670b7e8bff1d462 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reduce_ops_test.py @@ -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. +# ============================================================================== +"""Tests for reduction operators.""" + +import functools +import itertools + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +@parameterized.named_parameters(('32_bit_index', dtypes.int32), + ('64_bit_index', dtypes.int64)) +class ReduceOpsTest(xla_test.XLATestCase, parameterized.TestCase): + def _testReduction(self, + tf_reduce_fn, + np_reduce_fn, + dtype, + test_inputs, + index_dtype, + rtol=1e-4, + atol=1e-4): + """Tests that the output of 'tf_reduce_fn' matches numpy's output.""" + + for test_input in test_inputs: + with self.session() as sess: + with self.test_scope(): + a = array_ops.placeholder(dtype) + index = array_ops.placeholder(index_dtype) + out = tf_reduce_fn(a, index) + result = sess.run(out, {a: test_input, index: [0]}) + self.assertAllClose( + result, np_reduce_fn(test_input, axis=0), rtol=rtol, atol=atol) + + result = sess.run(out, {a: test_input, index: [1]}) + self.assertAllClose( + result, np_reduce_fn(test_input, axis=1), rtol=rtol, atol=atol) + + result = sess.run(out, {a: test_input, index: [-1]}) + self.assertAllClose( + result, np_reduce_fn(test_input, axis=1), rtol=rtol, atol=atol) + + # MLIR bridge doesn't return the same error so it can't be matched + # directly. + if not test_util.is_mlir_bridge_enabled(): + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, 'Invalid reduction dim'): + sess.run(out, {a: test_input, index: [-33]}) + + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, 'Invalid reduction dim'): + sess.run(out, {a: test_input, index: [2]}) + + REAL_DATA = [ + np.zeros(shape=(2, 0)), + np.zeros(shape=(0, 30)), + np.arange(1, 7).reshape(2, 3), + np.arange(-10, -4).reshape(2, 3), + np.arange(-4, 2).reshape(2, 3), + ] + COMPLEX_DATA = [ + np.zeros(shape=(2, 0)).astype(np.complex64), + np.zeros(shape=(0, 30)).astype(np.complex64), + np.arange(1, 13, dtype=np.float32).view(np.complex64).reshape(2, 3), + np.arange(-14, -2, dtype=np.float32).view(np.complex64).reshape(2, 3), + np.arange(-4, 8, dtype=np.float32).view(np.complex64).reshape(2, 3), + ] + NONEMPTY_REAL_DATA = [x for x in REAL_DATA if np.size(x) > 0] + NONEMPTY_COMPLEX_DATA = [x for x in COMPLEX_DATA if np.size(x) > 0] + BOOL_DATA = [ + np.array([], dtype=np.bool_).reshape(2, 0), + np.array([], dtype=np.bool_).reshape(0, 3), + np.array([[False, True, False], [True, True, False]]), + ] + ONES = [np.ones([34000, 2])] + + def testReduceSumF32(self, index_dtype): + self._testReduction(math_ops.reduce_sum, np.sum, np.float32, self.REAL_DATA, + index_dtype) + + def testReduceSumC64(self, index_dtype): + self._testReduction(math_ops.reduce_sum, np.sum, np.complex64, + self.COMPLEX_DATA, index_dtype) + + def testReduceProdF32(self, index_dtype): + self._testReduction(math_ops.reduce_prod, np.prod, np.float32, + self.REAL_DATA, index_dtype) + + def testReduceProdC64(self, index_dtype): + self._testReduction(math_ops.reduce_prod, np.prod, np.complex64, + self.COMPLEX_DATA, index_dtype) + + def testReduceMin(self, index_dtype): + + def reference_min(dtype, inp, axis): + """Wrapper around np.amin that returns +infinity for an empty input.""" + if inp.shape[axis] == 0: + if np.issubdtype(dtype, np.floating): + return np.full(inp.shape[0:axis] + inp.shape[axis + 1:], float('inf')) + return np.full(inp.shape[0:axis] + inp.shape[axis + 1:], + np.iinfo(dtype).max) + return np.amin(inp, axis) + + for dtype in set(self.all_types).intersection( + [np.float32, np.int32, np.int64]): + self._testReduction(math_ops.reduce_min, + functools.partial(reference_min, dtype), dtype, + self.REAL_DATA, index_dtype) + + def testReduceMax(self, index_dtype): + + def reference_max(dtype, inp, axis): + """Wrapper around np.amax that returns -infinity for an empty input.""" + if inp.shape[axis] == 0: + if np.issubdtype(dtype, np.floating): + return np.full(inp.shape[0:axis] + inp.shape[axis + 1:], + float('-inf')) + return np.full(inp.shape[0:axis] + inp.shape[axis + 1:], + np.iinfo(dtype).min) + return np.amax(inp, axis) + + for dtype in set(self.all_types).intersection( + [np.float32, np.int32, np.int64]): + self._testReduction(math_ops.reduce_max, + functools.partial(reference_max, dtype), dtype, + self.REAL_DATA, index_dtype) + + def testReduceMeanF32(self, index_dtype): + # TODO(phawkins): mean on XLA currently returns 0 instead of NaN when + # reducing across zero inputs. + self._testReduction(math_ops.reduce_mean, np.mean, np.float32, + self.NONEMPTY_REAL_DATA, index_dtype) + + def testReduceMeanF16(self, index_dtype): + if np.float16 in self.all_types: + self._testReduction(math_ops.reduce_mean, np.mean, np.float16, self.ONES, + index_dtype) + + def testReduceMeanC64(self, index_dtype): + self._testReduction(math_ops.reduce_mean, np.mean, np.complex64, + self.NONEMPTY_COMPLEX_DATA, index_dtype) + + def testReduceAll(self, index_dtype): + self._testReduction(math_ops.reduce_all, np.all, np.bool_, self.BOOL_DATA, + index_dtype) + + def testReduceAny(self, index_dtype): + self._testReduction(math_ops.reduce_any, np.any, np.bool_, self.BOOL_DATA, + index_dtype) + + @test_util.disable_mlir_bridge('Error messages differ') + def testReduceSumWithDuplicateAxes(self, index_dtype): + with self.session() as sess: + with self.test_scope(): + a = array_ops.placeholder(np.float32) + index = array_ops.placeholder(np.int32) + out = math_ops.reduce_sum(a, index) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + 'Axes contains duplicate dimension'): + sess.run(out, {a: [10, 20, 30], index: [0, 0]}) + + +class ReduceOpPrecisionTest(xla_test.XLATestCase): + + def _testReduceSum(self, + expected_result, + dtype, + test_inputs, + rtol=1e-3, + atol=1e-4): + """Tests reduce sum on a list of input arrays. + + For each array in test_inputs, check that performing reduce sum on the array + produces a value that is close to the expected result. + + Args: + expected_result: the expected result. + dtype: the data type of the reduce sum operation. + test_inputs: a list of input arrays for the reduce sum operation. + rtol: the relative error. + atol: the absolute error. + """ + + for test_input in test_inputs: + with self.session() as sess: + with self.test_scope(): + a = array_ops.placeholder(dtype) + index = array_ops.placeholder(dtypes.int32) + out = math_ops.reduce_sum(a, index) + result = sess.run(out, { + a: np.array(test_input, dtype=dtype), + index: [0] + }) + # Compare the results using float32 type. + self.assertAllClose( + np.float32(result), + np.float32(expected_result), + rtol=rtol, + atol=atol) + + def testReduceSumF16(self): + """Tests the reduce sum of float16 doesn't lose too much precision.""" + + if np.float16 not in self.all_types: + return + + f16_max = np.finfo(np.float16).max + self._testReduceSum( + f16_max, np.float16, + itertools.permutations([f16_max, f16_max, f16_max * (-1.0)], 3)) + + def testReduceSumBF16(self): + """Tests the reduce sum of bfloat16 doesn't lose too much precision.""" + + if dtypes.bfloat16.as_numpy_dtype not in self.all_types: + return + + bf16_max = np.float32(dtypes.bfloat16.max) + f32_max = dtypes.float32.max + value = min(bf16_max, f32_max - bf16_max) / 2 + self._testReduceSum( + dtypes.bfloat16.as_numpy_dtype(value), dtypes.bfloat16.as_numpy_dtype, + itertools.permutations([bf16_max, value, bf16_max * (-1.0)], 3)) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/reduce_window_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reduce_window_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d02a2bc0e7bff23420bd5610385aeec1a87e64eb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reduce_window_test.py @@ -0,0 +1,98 @@ +# 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 xla.reduce_window.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import googletest + + +class ReduceWindowTest(xla_test.XLATestCase): + """Test cases for xla.reduce_window.""" + + def _reduce_window(self, operand, init, reducer, **kwargs): + with self.session(): + placeholder = array_ops.placeholder(operand.dtype) + with self.test_scope(): + output = xla.reduce_window(placeholder, init, reducer, **kwargs) + return output.eval(feed_dict={placeholder: operand}) + + def testReduceWindow(self): + + # TODO(b/77644762): float16 and float64 ReduceWindow are unimplemented. + for dtype in set(self.numeric_types).intersection( + set([dtypes.bfloat16.as_numpy_dtype, np.float32])): + + @function.Defun(dtype, dtype) + def sum_reducer(x, y): + return x + y + + @function.Defun(dtype, dtype) + def mul_reducer(x, y): + return x * y + + self.assertAllClose( + np.array([3, 5, 7, 9, 11, 13], dtype=dtype), + self._reduce_window( + np.array([1, 2, 3, 4, 5, 6, 7], dtype=dtype), + 0.0, + sum_reducer, + window_dimensions=[2])) + + self.assertAllClose( + np.array([3, 7, 11], dtype=dtype), + self._reduce_window( + np.array([1, 2, 3, 4, 5, 6, 7], dtype=dtype), + 0.0, + sum_reducer, + window_dimensions=[2], + window_strides=[2])) + + self.assertAllClose( + np.array([1, 4, 7], dtype=dtype), + self._reduce_window( + np.array([1, 2, 3, 4, 5, 6, 7], dtype=dtype), + 0.0, + sum_reducer, + window_dimensions=[1], + window_strides=[3])) + + self.assertAllClose( + np.array([[24, 36, 24], [96, 0, 0]], dtype=dtype), + self._reduce_window( + np.array([[1, 2, 3, 4], [4, 3, 2, 1], [2, 4, 0, 1]], dtype=dtype), + 1.0, + mul_reducer, + window_dimensions=[2, 2], + window_strides=[1, 1])) + + self.assertAllClose( + np.array([[0, 0, 0], [5, 10, 5], [2, 4, 1], [0, 0, 0]], dtype=dtype), + self._reduce_window( + np.array([[1, 2, 3, 4], [4, 3, 2, 1], [2, 4, 0, 1]], dtype=dtype), + 0.0, + sum_reducer, + window_dimensions=[2, 2], + window_strides=[2, 2], + padding=[[2, 3], [1, 2]])) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/repeat_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/repeat_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..33deaa4cf097268088e8d53e287fae81268dcbb8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/repeat_op_test.py @@ -0,0 +1,47 @@ +# Copyright 2021 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.array_ops.repeat.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class RepeatTest(xla_test.XLATestCase): + + def test(self): + + # Verifies that bounded dynamic result generated from the Where op can be + # Reshaped correctly. + @def_function.function(jit_compile=True) + def repeat(values, repeats, axis): + return array_ops.repeat(values, repeats, axis) + + with self.session() as sess: + with self.test_scope(): + values = array_ops.constant([[1, 2], [3, 4]], dtype=dtypes.int32) + repeats = array_ops.constant([1, 2], dtype=dtypes.int32) + y1 = repeat(values, repeats, 0) + y2 = repeat(values, repeats, 1) + actual1, actual2 = sess.run([y1, y2]) + + self.assertAllEqual(actual1, [[1, 2], [3, 4], [3, 4]]) + self.assertAllEqual(actual2, [[1, 2, 2], [3, 4, 4]]) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/reshape_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reshape_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..70c71b9e9026963227ed9c903f2ae022df1b791b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reshape_op_test.py @@ -0,0 +1,58 @@ +# 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 reshape.""" + +from absl.testing import parameterized + +from tensorflow.compiler.tests import xla_test +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 googletest + + +class ReshapeTest(xla_test.XLATestCase, parameterized.TestCase): + + @parameterized.named_parameters(('32_bit_index', dtypes.int32), + ('64_bit_index', dtypes.int64)) + def testBasic(self, index_dtype): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[2, 3]) + with self.test_scope(): + shape = constant_op.constant([3, 2], dtype=index_dtype) + o = array_ops.reshape(i, shape) + params = { + i: [[1, 2, 3], [4, 5, 6]], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[1, 2], [3, 4], [5, 6]], result) + + def testInt64(self): + with self.session(): + with self.test_scope(): + x = array_ops.zeros([50000, 50000], dtype=dtypes.bool) + # Provide dimension larger than int32 + y = array_ops.reshape(x, [50000**2]) + self.assertEqual([50000**2], y.get_shape().as_list()) + # Even if first dimension is within int32, ensure we correctly go to + # int64 + y = array_ops.reshape(x, [1, 50000**2]) + self.assertEqual([1, 50000**2], y.get_shape().as_list()) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b2d4f0d47c5d3af00e18c88aba86da06b4b72213 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_ops_test.py @@ -0,0 +1,69 @@ +# 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. +# ============================================================================== +"""Functional tests for XLA Reverse Ops.""" + +import itertools + +import numpy as np + +from tensorflow.compiler.tests import xla_test +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 googletest + + +class ReverseOpsTest(xla_test.XLATestCase): + + def testReverseOneDim(self): + shape = (7, 5, 9, 11) + 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(-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): + np.random.seed(120) + pval = np.random.randint(0, 100, size=shape).astype(float) + with self.session(): + with self.test_scope(): + p = array_ops.placeholder(dtypes.int32, shape=shape) + axis = constant_op.constant( + np.array(revdims, dtype=np.int32), + shape=(len(revdims),), + dtype=dtypes.int32) + rval = array_ops.reverse(p, axis).eval({p: pval}) + + slices = tuple( + 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__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_sequence_op_args_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_sequence_op_args_test.py new file mode 100644 index 0000000000000000000000000000000000000000..dae0f13c6ac45c4a5375bc43d8a8367774b8bd86 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_sequence_op_args_test.py @@ -0,0 +1,52 @@ +# Copyright 2023 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.reverse_sequence_op.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.compat import v2_compat +from tensorflow.python.eager import def_function +from tensorflow.python.framework import errors +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class ReverseSequenceArgsTest(xla_test.XLATestCase): + """Tests argument verification of array_ops.reverse_sequence.""" + + def testInvalidArguments(self): + # seq_axis negative + with self.assertRaisesRegex( + (errors.InvalidArgumentError, ValueError), "seq_dim must be >=0" + ): + + @def_function.function(jit_compile=True) + def f(x): + return array_ops.reverse_sequence(x, [2, 2], seq_axis=-1) + + f([[1, 2], [3, 4]]) + + # batch_axis negative + with self.assertRaisesRegex(ValueError, "batch_dim must be >=0"): + + @def_function.function(jit_compile=True) + def g(x): + return array_ops.reverse_sequence(x, [2, 2], seq_axis=1, batch_axis=-1) + + g([[1, 2], [3, 4]]) + + +if __name__ == "__main__": + v2_compat.enable_v2_behavior() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_sequence_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_sequence_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..c7efe0f0427c2155b76e281b9e7c3981bae00214 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/reverse_sequence_op_test.py @@ -0,0 +1,89 @@ +# 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.reverse_sequence_op.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class ReverseSequenceTest(xla_test.XLATestCase): + + def _testReverseSequence(self, + x, + batch_axis, + seq_axis, + seq_lengths, + truth, + expected_err_re=None): + with self.session(): + p = array_ops.placeholder(dtypes.as_dtype(x.dtype)) + lengths = array_ops.placeholder(dtypes.as_dtype(seq_lengths.dtype)) + with self.test_scope(): + ans = array_ops.reverse_sequence( + p, batch_axis=batch_axis, seq_axis=seq_axis, seq_lengths=lengths) + if expected_err_re is None: + tf_ans = ans.eval(feed_dict={p: x, lengths: seq_lengths}) + self.assertAllClose(tf_ans, truth, atol=1e-10) + else: + with self.assertRaisesOpError(expected_err_re): + ans.eval(feed_dict={p: x, lengths: seq_lengths}) + + def testSimple(self): + x = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=np.int32) + expected = np.array([[1, 2, 3], [6, 5, 4], [8, 7, 9]], dtype=np.int32) + self._testReverseSequence( + x, + batch_axis=0, + seq_axis=1, + seq_lengths=np.array([1, 3, 2], np.int32), + truth=expected) + + def _testBasic(self, dtype, len_dtype): + x = np.asarray( + [[[1, 2, 3, 4], [5, 6, 7, 8]], [[9, 10, 11, 12], [13, 14, 15, 16]], + [[17, 18, 19, 20], [21, 22, 23, 24]]], + dtype=dtype) + x = x.reshape(3, 2, 4, 1, 1) + x = x.transpose([2, 1, 0, 3, 4]) # permute axes 0 <=> 2 + + # reverse dim 2 up to (0:3, none, 0:4) along dim=0 + seq_lengths = np.asarray([3, 0, 4], dtype=len_dtype) + + truth_orig = np.asarray( + [ + [[3, 2, 1, 4], [7, 6, 5, 8]], # reverse 0:3 + [[9, 10, 11, 12], [13, 14, 15, 16]], # reverse none + [[20, 19, 18, 17], [24, 23, 22, 21]] + ], # reverse 0:4 (all) + dtype=dtype) + truth_orig = truth_orig.reshape(3, 2, 4, 1, 1) + truth = truth_orig.transpose([2, 1, 0, 3, 4]) # permute axes 0 <=> 2 + + seq_axis = 0 # permute seq_axis and batch_axis (originally 2 and 0, resp.) + batch_axis = 2 + self._testReverseSequence(x, batch_axis, seq_axis, seq_lengths, truth) + + def testSeqLength(self): + for dtype in self.all_types: + for seq_dtype in self.all_types & {np.int32, np.int64}: + self._testBasic(dtype, seq_dtype) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/rmsprop_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/rmsprop_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fb65626fbbfb86ff3f78dd83c69aaf16eaa018b6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/rmsprop_test.py @@ -0,0 +1,128 @@ +# 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 RMSProp optimizer.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test +from tensorflow.python.training import rmsprop + + +class RmspropTest(xla_test.XLATestCase): + + def _rmsprop_update_numpy(self, + var, + g, + mg, + rms, + mom, + lr, + decay=0.9, + momentum=0.0, + epsilon=1e-10, + centered=False): + 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 + else: + mg_t = mg + 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 testBasic(self): + for dtype in self.float_types | self.complex_types: + for centered in [False, True]: + with self.session(), self.test_scope(): + # Initialize variables for numpy implementation. + var0_np = np.array([1.0, 2.0], dtype=dtype) + grads0_np = np.array([0.1, 0.1], dtype=dtype) + var1_np = np.array([3.0, 4.0], dtype=dtype) + grads1_np = np.array([0.01, 0.01], dtype=dtype) + mg0_np = np.array([0.0, 0.0], dtype=dtype) + mg1_np = np.array([0.0, 0.0], dtype=dtype) + rms0_np = np.array([1.0, 1.0], dtype=dtype) + rms1_np = np.array([1.0, 1.0], dtype=dtype) + mom0_np = np.array([0.0, 0.0], dtype=dtype) + mom1_np = np.array([0.0, 0.0], dtype=dtype) + + var0 = resource_variable_ops.ResourceVariable(var0_np) + var1 = resource_variable_ops.ResourceVariable(var1_np) + grads0 = constant_op.constant(grads0_np) + grads1 = constant_op.constant(grads1_np) + learning_rate = 3.0 + rms_opt = rmsprop.RMSPropOptimizer(learning_rate, centered=centered) + rms_update = rms_opt.apply_gradients( + zip([grads0, grads1], [var0, var1])) + self.evaluate(variables.global_variables_initializer()) + + mg0 = rms_opt.get_slot(var0, "mg") + self.assertEqual(mg0 is not None, centered) + mg1 = rms_opt.get_slot(var1, "mg") + self.assertEqual(mg1 is not None, centered) + rms0 = rms_opt.get_slot(var0, "rms") + self.assertIsNotNone(rms0) + rms1 = rms_opt.get_slot(var1, "rms") + self.assertIsNotNone(rms1) + mom0 = rms_opt.get_slot(var0, "momentum") + self.assertIsNotNone(mom0) + mom1 = rms_opt.get_slot(var1, "momentum") + self.assertIsNotNone(mom1) + + # Fetch params to validate initial values + self.assertAllClose([1.0, 2.0], self.evaluate(var0)) + self.assertAllClose([3.0, 4.0], self.evaluate(var1)) + + # Run 3 steps of RMSProp + for _ in range(3): + self.evaluate(rms_update) + + var0_np, mg0_np, rms0_np, mom0_np = self._rmsprop_update_numpy( + var0_np, + grads0_np, + mg0_np, + rms0_np, + mom0_np, + learning_rate, + centered=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, + centered=centered) + + # Validate updated params + if centered: + self.assertAllCloseAccordingToType(mg0_np, self.evaluate(mg0)) + self.assertAllCloseAccordingToType(mg1_np, self.evaluate(mg1)) + self.assertAllCloseAccordingToType(rms0_np, self.evaluate(rms0)) + self.assertAllCloseAccordingToType(rms1_np, self.evaluate(rms1)) + self.assertAllCloseAccordingToType(mom0_np, self.evaluate(mom0)) + self.assertAllCloseAccordingToType(mom1_np, self.evaluate(mom1)) + self.assertAllCloseAccordingToType(var0_np, self.evaluate(var0)) + self.assertAllCloseAccordingToType(var1_np, self.evaluate(var1)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/runtime_shape_check_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/runtime_shape_check_test.py new file mode 100644 index 0000000000000000000000000000000000000000..aff517eb28bb4643564b61af05ce653c54b57e44 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/runtime_shape_check_test.py @@ -0,0 +1,70 @@ +# Copyright 2022 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 shape checks at runtime in XLA:GPU.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_function +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.platform import test + + +class RuntimeShapeCheckTest(xla_test.XLATestCase): + + def testUniqueDifferentSizes(self): + """Test that we correctly check for shape mismatches at runtime.""" + if 'tpu' in self.device.lower(): + self.skipTest('We do not check shapes on TPU') + + with ops.device(f'device:{self.device}:0'): + + @def_function.function(jit_compile=True) + def f(x, y): + return array_ops.unique(x).y + array_ops.unique(y).y + + f(constant_op.constant([3.1, 3.2]), constant_op.constant([3.3, 3.2])) + + with self.assertRaisesRegex(errors.InternalError, 'different size'): + f( + constant_op.constant([3.1, 3.2]), + constant_op.constant([3.1, 3.2, 3.3])) + + def testWhereOpDifferentSizes(self): + """Test shape mismatches with multiple dimensions.""" + if 'tpu' in self.device.lower(): + self.skipTest('We do not check shapes on TPU') + + with ops.device(f'device:{self.device}:0'): + + @def_function.function(jit_compile=True) + def f(x, y): + return array_ops.where(x) + array_ops.where(y) + + f( + constant_op.constant([[3.1, 3.2, 0], [3.1, 3.2, 0]]), + constant_op.constant([[3.3, 3.2, 0, 0, 0], [3.3, 3.2, 0, 0, 0]])) + + with self.assertRaisesRegex(errors.InternalError, 'different size'): + f( + constant_op.constant([[3.1, 3.2, 0], [3.1, 3.2, 0]]), + constant_op.constant([[3.3, 3.2, 0, 0, 0], [3.3, 3.2, 3.3, 0, 0]])) + + +if __name__ == '__main__': + ops.enable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/scan_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/scan_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4f01df50aee2ffcb7bddca1b60a45aa866988034 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/scan_ops_test.py @@ -0,0 +1,319 @@ +# 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. +# ============================================================================== +"""Functional tests for scan ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +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 math_ops +from tensorflow.python.platform import test + + +def numpy_reverse(x, axis): + length = len(x.shape) + if axis < 0: + axis = length + axis + + ix = tuple( + slice(None, None, -1) if i == axis else slice(None) for i in range(length) + ) + return x[ix] + + +def handle_options(func, init_fn, x, axis, exclusive, reverse): + """Adds tf options to numpy scan ops.""" + length = len(x.shape) + if axis < 0: + axis = length + axis + + if reverse: + x = numpy_reverse(x, axis) + + if exclusive: + ix_head = tuple(slice(0, 1) if i == axis else slice(None) + for i in range(length)) + ix_init = tuple( + slice(0, -1) if i == axis else slice(None) for i in range(length) + ) + init = init_fn(x[ix_head]) + x = np.concatenate([init, func(x[ix_init], axis=axis)], axis=axis) + else: + x = func(x, axis=axis) + + if reverse: + x = numpy_reverse(x, axis) + return x + + +class CumsumTest(xla_test.XLATestCase): + + valid_dtypes = [np.float32, np.int32, np.int64] + + def axis_dtypes(self): + return set(self.int_types).intersection([np.int32, np.int64]) + + def _compare(self, x, axis, exclusive, reverse): + np_out = handle_options(np.cumsum, np.zeros_like, x, axis, exclusive, + reverse) + with self.session(), self.test_scope(): + p = array_ops.placeholder(x.dtype) + tf_out = math_ops.cumsum(p, axis, exclusive, reverse).eval( + feed_dict={p: x}) + + self.assertAllClose(np_out, tf_out) + + def _compareAll(self, x, axis): + for exclusive in [True, False]: + for reverse in [True, False]: + self._compare(x, axis, exclusive, reverse) + + def testEmpty(self): + for dtype in self.valid_dtypes: + x = np.zeros([0]).astype(dtype) + for axis in (-1, 0): + self._compareAll(x, axis) + + def testAxisType(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 6).reshape([5]).astype(dtype) + for axis_dtype in self.axis_dtypes(): + with self.session(), self.test_scope(): + p = array_ops.placeholder(x.dtype) + axis = constant_op.constant(0, axis_dtype) + math_ops.cumsum(p, axis).eval(feed_dict={p: x}) + + def test1D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 6).reshape([5]).astype(dtype) + for axis in (-1, 0): + self._compareAll(x, axis) + + def test2D(self): + for dtype in self.valid_dtypes: + x = np.arange(0, 10).reshape([2, 5]).astype(dtype) + for axis in (-2, -1, 0, 1): + self._compareAll(x, axis) + + def test3D(self): + for dtype in self.valid_dtypes: + x = np.arange(0, 20).reshape([2, 2, 5]).astype(dtype) + for axis in (-3, -2, -1, 0, 1, 2): + self._compareAll(x, axis) + + def test6D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 145).reshape([2, 2, 3, 3, 2, 2]).astype(dtype) + for axis in range(-6, 6, 3): + self._compareAll(x, axis) + + def testMixedPrecision(self): + with self.session(), self.test_scope(): + y = math_ops.cumsum( + constant_op.constant([1., 2., 3., 4.], dtypes.bfloat16), + -1, + exclusive=True).eval() + self.assertAllEqual(y, [0., 1., 3., 6.]) + + @test_util.disable_mlir_bridge("Error handling") + def testInvalidAxis(self): + x = np.arange(0, 10).reshape([2, 5]).astype(np.float32) + with self.session(), self.test_scope(): + input_tensor = ops.convert_to_tensor(x) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "Expected scan axis in the range [-2, 2)" in str(e)): + math_ops.cumsum(input_tensor, -3).eval() + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "Expected scan axis in the range [-2, 2)" in str(e)): + math_ops.cumsum(input_tensor, 2).eval() + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "axis must be a scalar" in str(e)): + math_ops.cumsum(input_tensor, [0]).eval() + + +class CumulativeLogSumExpTest(xla_test.XLATestCase): + + valid_dtypes = [np.float32, np.float64] + + def axis_dtypes(self): + return set(self.int_types).intersection([np.int32, np.int64]) + + def _compare(self, x, axis, exclusive, reverse): + + def neginf_like(x): + return -np.inf * np.ones_like(x) + + np_out = handle_options(np.logaddexp.accumulate, neginf_like, x, axis, + exclusive, reverse) + with self.session(), self.test_scope(): + p = array_ops.placeholder(x.dtype) + tf_out = math_ops.cumulative_logsumexp(p, axis, exclusive, + reverse).eval(feed_dict={p: x}) + + self.assertAllClose(np_out, tf_out, rtol=4e-5) + + def _compareAll(self, x, axis): + for exclusive in [True, False]: + for reverse in [True, False]: + self._compare(x, axis, exclusive, reverse) + + def testEmpty(self): + for dtype in self.valid_dtypes: + x = np.zeros([0]).astype(dtype) + for axis in (-1, 0): + self._compareAll(x, axis) + + def testAxisType(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 6).reshape([5]).astype(dtype) + for axis_dtype in self.axis_dtypes(): + with self.session(), self.test_scope(): + p = array_ops.placeholder(x.dtype) + axis = constant_op.constant(0, axis_dtype) + math_ops.cumulative_logsumexp(p, axis).eval(feed_dict={p: x}) + + def test1D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 6).reshape([5]).astype(dtype) + for axis in (-1, 0): + self._compareAll(x, axis) + + def test2D(self): + for dtype in self.valid_dtypes: + x = np.arange(0, 10).reshape([2, 5]).astype(dtype) + for axis in (-2, -1, 0, 1): + self._compareAll(x, axis) + + def test3D(self): + for dtype in self.valid_dtypes: + x = np.arange(0, 20).reshape([2, 2, 5]).astype(dtype) + for axis in (-3, -2, -1, 0, 1, 2): + self._compareAll(x, axis) + + def test6D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 145).reshape([2, 2, 3, 3, 2, 2]).astype(dtype) + for axis in range(-6, 6, 3): + self._compareAll(x, axis) + + @test_util.disable_mlir_bridge("Error handling") + def testInvalidAxis(self): + x = np.arange(0, 10).reshape([2, 5]).astype(np.float32) + with self.session(), self.test_scope(): + input_tensor = ops.convert_to_tensor(x) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "Expected scan axis in the range [-2, 2)" in str(e)): + math_ops.cumulative_logsumexp(input_tensor, -3).eval() + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "Expected scan axis in the range [-2, 2)" in str(e)): + math_ops.cumulative_logsumexp(input_tensor, 2).eval() + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "axis must be a scalar" in str(e)): + math_ops.cumulative_logsumexp(input_tensor, [0]).eval() + + +class CumprodTest(xla_test.XLATestCase): + + valid_dtypes = [np.float32, np.int32] + + def axis_dtypes(self): + return set(self.int_types).intersection([np.int32, np.int64]) + + def _compare(self, x, axis, exclusive, reverse): + np_out = handle_options(np.cumprod, np.ones_like, x, axis, exclusive, + reverse) + with self.session(), self.test_scope(): + p = array_ops.placeholder(x.dtype) + prod = math_ops.cumprod(p, axis, exclusive, reverse) + tf_out = prod.eval(feed_dict={p: x}) + + self.assertAllClose(np_out, tf_out) + + def _compareAll(self, x, axis): + for exclusive in [True, False]: + for reverse in [True, False]: + self._compare(x, axis, exclusive, reverse) + + def testEmpty(self): + for dtype in self.valid_dtypes: + x = np.zeros([0]).astype(dtype) + for axis in (-1, 0): + self._compareAll(x, axis) + + def testAxisType(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 6).reshape([5]).astype(dtype) + for axis_dtype in self.axis_dtypes(): + with self.session(), self.test_scope(): + p = array_ops.placeholder(x.dtype) + axis = constant_op.constant(0, axis_dtype) + math_ops.cumprod(x, axis).eval(feed_dict={p: x}) + + def test1D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 6).reshape([5]).astype(dtype) + for axis in (-1, 0): + self._compareAll(x, axis) + + def test2D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 11).reshape([2, 5]).astype(dtype) + for axis in (-2, -1, 0, 1): + self._compareAll(x, axis) + + def test3D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 21).reshape([2, 2, 5]).astype(dtype) + for axis in (-3, -2, -1, 0, 1, 2): + self._compareAll(x, axis) + + def test6D(self): + for dtype in self.valid_dtypes: + x = np.arange(1, 145).reshape([2, 2, 3, 3, 2, 2]).astype(dtype) + for axis in range(-6, 6, 3): + self._compareAll(x, axis) + + @test_util.disable_mlir_bridge("Error handling") + def testInvalidAxis(self): + x = np.arange(0, 10).reshape([2, 5]).astype(np.float32) + with self.session(), self.test_scope(): + input_tensor = ops.convert_to_tensor(x) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "Expected scan axis in the range [-2, 2)" in str(e)): + math_ops.cumprod(input_tensor, -3).eval() + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "Expected scan axis in the range [-2, 2)" in str(e)): + math_ops.cumprod(input_tensor, 2).eval() + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + lambda e: "axis must be a scalar" in str(e)): + math_ops.cumprod(input_tensor, [0]).eval() + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/scatter_nd_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/scatter_nd_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d3dfe32668dd09f13c2fafbfa1489c44f7e7626a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/scatter_nd_op_test.py @@ -0,0 +1,245 @@ +# Copyright 2018 The TensorFlow Authors. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# ============================================================================== +"""Tests for tensorflow.ops.tf.scatter_nd.""" + +import functools + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import errors +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +def _AsType(v, vtype): + return v.astype(vtype) if isinstance(v, np.ndarray) else vtype(v) + + +def _FlatInnerDims(tensor, ndims=2): + shape = list(tensor.shape) + return tensor.reshape( + [functools.reduce(lambda x, y: x * y, shape[:-ndims + 1], 1)] + + shape[-ndims + 1:]) + + +def _FlatOuterDims(tensor, ndims=2): + shape = list(tensor.shape) + return tensor.reshape( + shape[:ndims - 1] + + [functools.reduce(lambda x, y: x * y, shape[ndims - 1:], 1)]) + + +def _NumpyScatterNd(ref, indices, updates, op): + ixdim = indices.shape[-1] + num_updates = indices.size // ixdim + total_nd = len(ref.shape) + slice_size = 1 + for i in range(ixdim, total_nd): + slice_size *= ref.shape[i] + flat_indices = _FlatInnerDims(indices) + flat_updates = updates.reshape((num_updates, slice_size)) + output_flat = _FlatOuterDims(ref, ixdim + 1) + for ix_updates, ix_output in enumerate(flat_indices): + ix_output = tuple(ix_output) + output_flat[ix_output] = op(output_flat[ix_output], + flat_updates[ix_updates]) + return output_flat.reshape(ref.shape) + + +def _NumpyUpdate(indices, updates, shape): + ref = np.zeros(shape, dtype=updates.dtype) + return _NumpyScatterNd(ref, indices, updates, lambda p, u: u) + + +class ScatterNdTest(xla_test.XLATestCase): + + def _VariableRankTest(self, + np_scatter, + tf_scatter, + vtype, + itype, + repeat_indices=False): + np.random.seed(8) + ref_shapes = [(3, 6), (3, 6), (3, 6, 9), (3, 6, 9), (3, 6, 9), (3, 6, 9)] + indices_shapes = [(2,), (2, 2), (2,), (2, 2), (2, 3), (2, 3, 3)] + for ref_shape, indices_shape in zip(ref_shapes, indices_shapes): + num_updates = indices_shape[0] + ixdim = indices_shape[-1] + + indexable_area_shape = () + for i in range(ixdim): + indexable_area_shape += (ref_shape[i],) + all_indices = [ + list(coord) + for coord, _ in np.ndenumerate(np.empty(indexable_area_shape, vtype)) + ] + np.random.shuffle(all_indices) + indices = np.array(all_indices[:num_updates]) + + if num_updates > 1 and repeat_indices: + indices = indices[:num_updates // 2] + for _ in range(num_updates - num_updates // 2): + indices = np.append( + indices, [indices[np.random.randint(num_updates // 2)]], axis=0) + np.random.shuffle(indices) + indices = _AsType(indices[:num_updates], itype) + + updates_shape = (num_updates,) + for i in range(ixdim, len(ref_shape)): + updates_shape += (ref_shape[i],) + updates = _AsType(np.random.randn(*(updates_shape)), vtype) + + # Scatter via numpy + np_out = np_scatter(indices, updates, ref_shape) + # Scatter via tensorflow + tf_out = tf_scatter(indices, updates, ref_shape) + + self.assertAllClose(np_out, tf_out) + + def _VariableRankTests(self, np_scatter, tf_scatter): + for vtype in self.numeric_types: + for itype in set([np.int32, np.int64]).intersection(set(self.int_types)): + self._VariableRankTest(np_scatter, tf_scatter, vtype, itype) + + def _runScatterNd(self, indices, updates, shape): + with self.session(): + updates_placeholder = array_ops.placeholder(updates.dtype) + indices_placeholder = array_ops.placeholder(indices.dtype) + with self.test_scope(): + output = array_ops.scatter_nd(indices_placeholder, updates_placeholder, + shape) + feed_dict = {updates_placeholder: updates, indices_placeholder: indices} + return output.eval(feed_dict=feed_dict) + + def testSimple(self): + indices = np.array([[4], [3], [1], [7]], dtype=np.int32) + updates = np.array([9, 10, 11, 12], dtype=np.float32) + expected = np.array([0, 11, 0, 10, 9, 0, 0, 12], dtype=np.int32) + self.assertAllEqual(expected, self._runScatterNd(indices, updates, [8])) + + def testRepeatedIndices(self): + indices = np.array([[0], [1], [0], [1]], dtype=np.int32) + updates = np.array([9, 10, 11, 12], dtype=np.float32) + expected = np.array([20, 22], dtype=np.int32) + self.assertAllEqual(expected, self._runScatterNd(indices, updates, [2])) + + def testSimple2(self): + indices = np.array([[1, 0], [1, 1]], dtype=np.int32) + updates = np.array([11., 12.], dtype=np.float32) + expected = np.array([[0., 0.], [11., 12.], [0., 0.]], dtype=np.float32) + self.assertAllEqual(expected, self._runScatterNd(indices, updates, [3, 2])) + + def testSimple3(self): + indices = np.array([[1]], dtype=np.int32) + updates = np.array([[11., 12.]], dtype=np.float32) + expected = np.array([[0., 0.], [11., 12.], [0., 0.]]) + self.assertAllEqual(expected, self._runScatterNd(indices, updates, [3, 2])) + + def testVariableRankUpdate(self): + self._VariableRankTests(_NumpyUpdate, self._runScatterNd) + + def testExtraIndicesDimensions(self): + indices = np.zeros([1, 1, 2], np.int32) + updates = np.zeros([1, 1], np.int32) + expected = np.zeros([2, 2], dtype=np.int32) + self.assertAllEqual(expected, self._runScatterNd(indices, updates, [2, 2])) + + @test_util.disable_mlir_bridge("Error messages differ") + def testRank3InvalidShape1(self): + indices = np.zeros([3, 2, 2], np.int32) + updates = np.zeros([2, 2, 2], np.int32) + with self.assertRaisesWithPredicateMatch(errors.InvalidArgumentError, + "Must have updates.shape"): + self._runScatterNd(indices, updates, [2, 2, 2]) + + @test_util.disable_mlir_bridge("Error messages differ") + def testRank3InvalidShape2(self): + indices = np.zeros([2, 2, 1], np.int32) + updates = np.zeros([2, 2], np.int32) + with self.assertRaisesWithPredicateMatch(errors.InvalidArgumentError, + "Must have updates.shape"): + self._runScatterNd(indices, updates, [2, 2, 2]) + + def testScatterOutOfRange(self): + updates = np.array([-3, -4, -5]).astype(np.float32) + + # Indices all in range, no problem. + indices = np.array([[2], [0], [5]], dtype=np.int32) + self._runScatterNd(indices, updates, [6]) + + # Indices out of range should not fail. It produces implementation-defined + # output. + indices = np.array([[-1], [0], [5]], dtype=np.int32) + self._runScatterNd(indices, updates, [6]) + indices = np.array([[2], [0], [6]], dtype=np.int32) + self._runScatterNd(indices, updates, [6]) + + +class ScatterNdTensorTest(xla_test.XLATestCase): + + def _runScatter(self, op): + indices_np = np.array([[4], [3], [1], [7]], dtype=np.int32) + updates_np = np.array([9, 10, 11, 12], dtype=np.float32) + with self.session() as sess, self.test_scope(): + indices = array_ops.placeholder(indices_np.dtype, shape=indices_np.shape) + updates = array_ops.placeholder(updates_np.dtype, shape=updates_np.shape) + t = array_ops.ones([8], dtype=np.float32) + + out = op(t, indices, updates) + return sess.run(out, feed_dict={indices: indices_np, updates: updates_np}) + + def testAdd(self): + self.assertAllEqual( + self._runScatter(array_ops.tensor_scatter_add), + np.array([1, 12, 1, 11, 10, 1, 1, 13], dtype=np.float32)) + + def testSub(self): + self.assertAllEqual( + self._runScatter(array_ops.tensor_scatter_sub), + np.array([1, -10, 1, -9, -8, 1, 1, -11], dtype=np.float32)) + + def testUpdate(self): + self.assertAllEqual( + self._runScatter(array_ops.tensor_scatter_update), + np.array([1, 11, 1, 10, 9, 1, 1, 12], dtype=np.float32)) + + +class ScatterNdTensorScalarUpdateTest(xla_test.XLATestCase): + + def _runScatter(self, op): + indices_np = np.array([[4], [3], [1], [7]], dtype=np.int32) + updates_np = np.array(9, dtype=np.float32) + with self.session() as sess, self.test_scope(): + indices = array_ops.placeholder(indices_np.dtype, shape=indices_np.shape) + updates = array_ops.placeholder(updates_np.dtype, shape=updates_np.shape) + t = array_ops.ones([8], dtype=np.float32) + + out = op(t, indices, updates) + return sess.run(out, feed_dict={indices: indices_np, updates: updates_np}) + + def testUpdate(self): + self.assertAllEqual( + self._runScatter(array_ops.tensor_scatter_update), + np.array([1, 9, 1, 9, 9, 1, 1, 9], dtype=np.float32)) + + def testAdd(self): + self.assertAllEqual( + self._runScatter(array_ops.tensor_scatter_add), + np.array([1, 10, 1, 10, 10, 1, 1, 10], dtype=np.float32)) + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/searchsorted_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/searchsorted_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..24a985e81ff32af436f1f3cc326ee9f985763295 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/searchsorted_op_test.py @@ -0,0 +1,92 @@ +# Copyright 2020 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. +# ============================================================================== +"""Test for XLA implementation of tf.searchsorted.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class SearchSorteddOpTest(xla_test.XLATestCase): + + def test1D(self): + # Test against NumPy implementation (which is 1D only). + np.random.seed(1) + for side in ['left', 'right']: + for dtype in [np.float32, np.int32]: + values = np.random.uniform( + low=-1000, high=1000, size=(10,)).astype(dtype) + unsorted = np.random.uniform( + low=-1000, high=1000, size=(20,)).astype(dtype) + + sorted_sequence = np.sort(unsorted) + np_ans = np.searchsorted(sorted_sequence, values, side=side) + + with self.session() as session: + with self.test_scope(): + tf_ans = array_ops.searchsorted(sorted_sequence, values, side=side) + tf_out = session.run(tf_ans) + self.assertAllEqual(np_ans, tf_out) + + def testNanValue(self): + for dtype in self.float_types: + sorted_sequence = np.array([[1, 3, 5, 7, 9]], dtype) + values = np.array([[np.nan]], dtype) + + self._test2DExample( + dtype, + 'left', + sorted_sequence, + values, + np.array([[0]], dtype=np.int32), + ) + + self._test2DExample( + dtype, + 'right', + sorted_sequence, + values, + np.array([[5]], dtype=np.int32), + ) + + def _test2DExample(self, dtype, side, sorted_sequence, values, correct_ans): + + with self.session() as session: + with self.test_scope(): + tf_ans = array_ops.searchsorted(sorted_sequence, values, side=side) + tf_out = session.run(tf_ans) + self.assertAllEqual(correct_ans, tf_out) + + def testLowerBound2DExample(self): + # 2D TensorFlow documentation example. + for dtype in self.float_types | self.int_types: + sorted_sequence = np.array([[0, 3, 9, 9, 10], [1, 2, 3, 4, 5]], dtype) + values = np.array([[2, 4, 9], [0, 2, 6]], dtype) + correct_ans = np.array([[1, 2, 2], [0, 1, 5]], dtype) + self._test2DExample(dtype, 'left', sorted_sequence, values, correct_ans) + + def testUpperBound2DExample(self): + # 2D TensorFlow documentation example. + for dtype in self.float_types | self.int_types: + sorted_sequence = np.array([[0, 3, 9, 9, 10], [1, 2, 3, 4, 5]], dtype) + values = np.array([[2, 4, 9], [0, 2, 6]], dtype) + correct_ans = np.array([[1, 2, 4], [0, 2, 5]], dtype) + self._test2DExample(dtype, 'right', sorted_sequence, values, correct_ans) + + +if __name__ == '__main__': + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/segment_reduction_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/segment_reduction_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..bffbba979211a6d00584f8d98d4e06245c2c4c5d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/segment_reduction_ops_test.py @@ -0,0 +1,338 @@ +# 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. +# ============================================================================== +"""Test cases for segment reduction ops.""" + +import functools + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.client import device_lib +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class SegmentReductionOpsTest(xla_test.XLATestCase): + """Test cases for segment reduction ops.""" + + def _findDevice(self, device_name): + devices = device_lib.list_local_devices() + for d in devices: + if d.device_type == device_name: + return True + return False + + def _segmentReduction(self, op, data, indices, num_segments): + with self.session() as sess, self.test_scope(): + d = array_ops.placeholder(data.dtype, shape=data.shape) + if isinstance(indices, int): + i = array_ops.placeholder(np.int32, shape=[]) + else: + i = array_ops.placeholder(indices.dtype, shape=indices.shape) + return sess.run(op(d, i, num_segments), {d: data, i: indices}) + + def _unsortedSegmentSum(self, data, indices, num_segments): + return self._segmentReduction(math_ops.unsorted_segment_sum, data, indices, + num_segments) + + def _segmentSumV2(self, data, indices, num_segments): + return self._segmentReduction(math_ops.segment_sum_v2, data, indices, + num_segments) + + def _segmentProdV2(self, data, indices, num_segments): + return self._segmentReduction(math_ops.segment_prod_v2, data, indices, + num_segments) + + def _segmentMinV2(self, data, indices, num_segments): + return self._segmentReduction(math_ops.segment_min_v2, data, indices, + num_segments) + + def _segmentMaxV2(self, data, indices, num_segments): + return self._segmentReduction(math_ops.segment_max_v2, data, indices, + num_segments) + + def _unsortedSegmentProd(self, data, indices, num_segments): + return self._segmentReduction(math_ops.unsorted_segment_prod, data, indices, + num_segments) + + def _unsortedSegmentMin(self, data, indices, num_segments): + return self._segmentReduction(math_ops.unsorted_segment_min, data, indices, + num_segments) + + def _unsortedSegmentMax(self, data, indices, num_segments): + return self._segmentReduction(math_ops.unsorted_segment_max, data, indices, + num_segments) + + def testSegmentSum(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array([1, 0, 2, 12], dtype=dtype), + self._segmentSumV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 4)) + + def testSegmentProd(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array([0, 1, 2, 60], dtype=dtype), + self._segmentProdV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 4)) + + def testSegmentProdNumSegmentsLess(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array([0, 1, 2], dtype=dtype), + self._segmentProdV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 3)) + + def testSegmentProdNumSegmentsMore(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array([0, 1, 2, 60, 1], dtype=dtype), + self._segmentProdV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 5)) + + def testSegmentMin(self): + for dtype in self.int_types | self.float_types: + maxval = dtypes.as_dtype(dtype).max + if dtype == np.float64 and self._findDevice("TPU"): + maxval = np.inf + self.assertAllClose( + np.array([0, maxval, 2, 3], dtype=dtype), + self._segmentMinV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 4)) + + def testSegmentMinNumSegmentsLess(self): + for dtype in self.int_types | self.float_types: + maxval = dtypes.as_dtype(dtype).max + if dtype == np.float64 and self._findDevice("TPU"): + maxval = np.inf + self.assertAllClose( + np.array([0, maxval, 2], dtype=dtype), + self._segmentMinV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 3)) + + def testSegmentMinNumSegmentsMore(self): + for dtype in self.int_types | self.float_types: + maxval = dtypes.as_dtype(dtype).max + if dtype == np.float64 and self._findDevice("TPU"): + maxval = np.inf + self.assertAllClose( + np.array([0, maxval, 2, 3, maxval], dtype=dtype), + self._segmentMinV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 5)) + + def testSegmentMax(self): + for dtype in self.int_types | self.float_types: + minval = dtypes.as_dtype(dtype).min + if dtype == np.float64 and self._findDevice("TPU"): + minval = -np.inf + self.assertAllClose( + np.array([1, minval, 2, 5], dtype=dtype), + self._segmentMaxV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 4)) + + def testSegmentMaxNumSegmentsLess(self): + for dtype in self.int_types | self.float_types: + minval = dtypes.as_dtype(dtype).min + if dtype == np.float64 and self._findDevice("TPU"): + minval = -np.inf + self.assertAllClose( + np.array([1, minval, 2], dtype=dtype), + self._segmentMaxV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 3)) + + def testSegmentMaxNumSegmentsMore(self): + for dtype in self.int_types | self.float_types: + minval = dtypes.as_dtype(dtype).min + if dtype == np.float64 and self._findDevice("TPU"): + minval = -np.inf + self.assertAllClose( + np.array([1, minval, 2, 5, minval], dtype=dtype), + self._segmentMaxV2( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([0, 0, 2, 3, 3, 3], dtype=np.int32), 5)) + + def testUnsortedSegmentSum0DIndices1DData(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array( + [[0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0], [0, 1, 2, 3, 4, 5], + [0, 0, 0, 0, 0, 0]], + dtype=dtype), + self._unsortedSegmentSum( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), 2, 4)) + + def testUnsortedSegmentSum1DIndices1DData(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array([1, 3, 2, 9], dtype=dtype), + self._unsortedSegmentSum( + np.array([0, 1, 2, 3, 4, 5], dtype=dtype), + np.array([3, 0, 2, 1, 3, 3], dtype=np.int32), 4)) + + def testUnsortedSegmentSum1DIndices1DDataNegativeIndices(self): + for dtype in self.numeric_types: + self.assertAllClose( + np.array([6, 3, 0, 6], dtype=dtype), + self._unsortedSegmentSum( + np.array([0, 1, 2, 3, 4, 5, 6], dtype=dtype), + np.array([3, -1, 0, 1, 0, -1, 3], dtype=np.int32), 4)) + + def testUnsortedSegmentSum1DIndices2DDataDisjoint(self): + for dtype in self.numeric_types: + data = np.array( + [[0, 1, 2, 3], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43], + [50, 51, 52, 53]], + dtype=dtype) + indices = np.array([8, 1, 0, 3, 7], dtype=np.int32) + num_segments = 10 + y = self._unsortedSegmentSum(data, indices, num_segments) + self.assertAllClose( + np.array( + [[30, 31, 32, 33], [20, 21, 22, 23], [0, 0, 0, 0], + [40, 41, 42, 43], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], + [50, 51, 52, 53], [0, 1, 2, 3], [0, 0, 0, 0]], + dtype=dtype), y) + + def testUnsortedSegmentSum1DIndices2DDataNonDisjoint(self): + for dtype in self.numeric_types: + data = np.array( + [[0, 1, 2, 3], [20, 21, 22, 23], [30, 31, 32, 33], [40, 41, 42, 43], + [50, 51, 52, 53]], + dtype=dtype) + indices = np.array([0, 1, 2, 0, 1], dtype=np.int32) + num_segments = 4 + y = self._unsortedSegmentSum(data, indices, num_segments) + self.assertAllClose( + np.array( + [[40, 42, 44, 46], [70, 72, 74, 76], [30, 31, 32, 33], + [0, 0, 0, 0]], + dtype=dtype), y) + + def testUnsortedSegmentSum2DIndices3DData(self): + for dtype in self.numeric_types: + data = np.array( + [[[0, 1, 2], [10, 11, 12]], [[100, 101, 102], [110, 111, 112]], [[ + 80, 81, 82 + ], [123, 124, 125]], [[103, 104, 105], [106, 107, 108]]], + dtype=dtype) + indices = np.array([[3, 5], [3, 1], [5, 0], [6, 2]], dtype=np.int32) + num_segments = 8 + y = self._unsortedSegmentSum(data, indices, num_segments) + self.assertAllClose( + np.array( + [[123, 124, 125], [110, 111, 112], [106, 107, 108], [ + 100, 102, 104 + ], [0, 0, 0.], [90, 92, 94], [103, 104, 105], [0, 0, 0]], + dtype=dtype), y) + + def testUnsortedSegmentSum1DIndices3DData(self): + for dtype in self.numeric_types: + data = np.array( + [[[0, 1, 2], [10, 11, 12]], [[100, 101, 102], [110, 111, 112]], [[ + 120, 121, 122 + ], [123, 124, 125]], [[103, 104, 105], [106, 107, 108]]], + dtype=dtype) + indices = np.array([3, 0, 2, 5], dtype=np.int32) + num_segments = 6 + y = self._unsortedSegmentSum(data, indices, num_segments) + self.assertAllClose( + np.array( + [[[100, 101, 102.], [110, 111, 112]], [[0, 0, 0], [0, 0, 0]], + [[120, 121, 122], [123, 124, 125]], [[0, 1, 2.], [10, 11, 12]], + [[0, 0, 0], [0, 0, 0]], [[103, 104, 105], [106, 107, 108]]], + dtype=dtype), y) + + def testUnsortedSegmentSumShapeError(self): + for dtype in self.numeric_types: + data = np.ones((4, 8, 7), dtype=dtype) + indices = np.ones((3, 2), dtype=np.int32) + num_segments = 4 + self.assertRaises( + ValueError, + functools.partial(self._segmentReduction, + math_ops.unsorted_segment_sum, data, indices, + num_segments)) + + def testUnsortedSegmentOps1DIndices1DDataNegativeIndices(self): + """Tests for min, max, and prod ops. + + These share most of their implementation with sum, so we only test basic + functionality. + """ + for dtype in self.numeric_types: + self.assertAllClose( + np.array([8, 3, 1, 0], dtype=dtype), + self._unsortedSegmentProd( + np.array([0, 1, 2, 3, 4, 5, 6], dtype=dtype), + np.array([3, -1, 0, 1, 0, -1, 3], dtype=np.int32), 4)) + + for dtype in self.int_types | self.float_types: + minval = dtypes.as_dtype(dtype).min + maxval = dtypes.as_dtype(dtype).max + + self.assertAllClose( + np.array([2, 3, maxval, 0], dtype=dtype), + self._unsortedSegmentMin( + np.array([0, 1, 2, 3, 4, 5, 6], dtype=dtype), + np.array([3, -1, 0, 1, 0, -1, 3], dtype=np.int32), 4)) + self.assertAllClose( + np.array([4, 3, minval, 6], dtype=dtype), + self._unsortedSegmentMax( + np.array([0, 1, 2, 3, 4, 5, 6], dtype=dtype), + np.array([3, -1, 0, 1, 0, -1, 3], dtype=np.int32), 4)) + + def testNaNHandling(self): + for dtype in self.float_types: + hi = dtypes.as_dtype(dtype).max + lo = dtypes.as_dtype(dtype).min + if self.device == "TPU" and dtype == np.float64: + hi = np.inf + lo = -np.inf + self.assertAllClose( + np.array([1.0], dtype=dtype), + self._unsortedSegmentMin( + np.array([1.0, np.nan, 3.0], dtype=dtype), + np.array([0, 0, 0], dtype=np.int32), 1)) + self.assertAllClose( + np.array([3.0], dtype=dtype), + self._unsortedSegmentMax( + np.array([np.nan, 1.0, 3.0], dtype=dtype), + np.array([0, 0, 0], dtype=np.int32), 1)) + self.assertAllClose( + np.array([hi], dtype=dtype), + self._unsortedSegmentMin( + np.array([np.nan, np.nan], dtype=dtype), + np.array([0, 0], dtype=np.int32), 1)) + self.assertAllClose( + np.array([lo], dtype=dtype), + self._unsortedSegmentMax( + np.array([np.nan, np.nan], dtype=dtype), + np.array([0, 0], dtype=np.int32), 1)) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/self_adjoint_eig_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/self_adjoint_eig_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..4b6f6bcc59cd061b5b0b7bae08bba253633234d5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/self_adjoint_eig_op_test.py @@ -0,0 +1,59 @@ +# Copyright 2019 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.self_adjoint_eig.""" + +import itertools + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.platform import test + + +class SelfAdjointEigOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def _test(self, dtype, shape): + np.random.seed(1) + x_np = np.random.uniform( + low=-1.0, high=1.0, size=np.prod(shape)).reshape(shape).astype(dtype) + x_np = x_np + np.swapaxes(x_np, -1, -2) + n = shape[-1] + + e_np, _ = np.linalg.eigh(x_np) + with self.session() as sess: + x_tf = array_ops.placeholder(dtype) + with self.test_scope(): + e, v = linalg_ops.self_adjoint_eig(x_tf) + e_val, v_val = sess.run([e, v], feed_dict={x_tf: x_np}) + + v_diff = np.matmul(v_val, np.swapaxes(v_val, -1, -2)) - np.eye(n) + self.assertAlmostEqual(np.mean(v_diff**2), 0.0, delta=1e-6) + self.assertAlmostEqual(np.mean((e_val - e_np)**2), 0.0, delta=1e-6) + + SIZES = [1, 2, 5, 10, 32] + DTYPES = [np.float32] + PARAMS = itertools.product(SIZES, DTYPES) + + @parameterized.parameters(*PARAMS) + def testSelfAdjointEig(self, n, dtype): + for batch_dims in [(), (3,)] + [(3, 2)] * (n < 10): + self._test(dtype, batch_dims + (n, n)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/sharding_util_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/sharding_util_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..b8010594f26006c70e843ed6ab6f80590b615b63 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/sharding_util_ops_test.py @@ -0,0 +1,713 @@ +# Copyright 2021 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 sharding util ops (XlaSplitND, XlaConcatND).""" + +from typing import Any, List, Optional + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.client.session import Session +from tensorflow.python.framework import constant_op +from tensorflow.python.framework.ops import control_dependencies +from tensorflow.python.framework.tensor import Tensor +from tensorflow.python.ops import gen_tpu_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.platform import test + + +def create_tensor_split_graph( + sess: Session, + input_value: Any, + input_dtype: Any, + num_outputs: int, + num_splits: List[int], + paddings: Optional[List[int]] = None) -> List[Tensor]: + del sess + + const_input_op = constant_op.constant(input_value, dtype=input_dtype) + return gen_tpu_ops.xla_split_nd( + const_input_op, num_outputs, num_splits, paddings=paddings) + + +def create_resource_split_graph( + sess: Session, + input_value: Any, + input_dtype: Any, + num_outputs: int, + num_splits: List[int], + paddings: Optional[List[int]] = None) -> List[Tensor]: + variable = resource_variable_ops.ResourceVariable( + initial_value=input_value, dtype=input_dtype) + sess.run(variables.variables_initializer([variable])) + return gen_tpu_ops.read_variable_xla_split_nd( + variable.handle, input_dtype, num_outputs, num_splits, paddings=paddings) + + +class XlaSplitNDOpTest(xla_test.XLATestCase, parameterized.TestCase): + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testSplitDimensionZero(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[[0]]], + input_dtype=dtype, + num_outputs=1, + num_splits=[1, 1, 0]) + with self.assertRaisesOpError('index 2 must be positive, but got 0'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testSplitDimensionNegative(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[[0]]], + input_dtype=dtype, + num_outputs=1, + num_splits=[1, -1, 1]) + with self.assertRaisesOpError('index 1 must be positive, but got -1'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testNumOutputsMismatch(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[0, 1], + input_dtype=dtype, + num_outputs=1, + num_splits=[2]) + with self.assertRaisesOpError('\'N\' must match number of slices 2'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testPaddingsLengthMismatch(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[0, 1], [2, 3]], + input_dtype=dtype, + num_outputs=4, + num_splits=[2, 2], + paddings=[0]) + with self.assertRaisesOpError('length 2, but got 1'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testPaddingsNegative(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[0, 1], [2, 3]], + input_dtype=dtype, + num_outputs=4, + num_splits=[2, 2], + paddings=[0, -1]) + with self.assertRaisesOpError('non-negative, but got -1 at index 1'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testInputRankSplitMismatch(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[0, 1], [2, 3]], + input_dtype=dtype, + num_outputs=8, + num_splits=[2, 2, 2]) + with self.assertRaisesOpError( + '\'num_splits\' length 3, but got rank 2'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testDimNotEvenlySplit(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[0, 1], [2, 3], [4, 5], [6, 7]], + input_dtype=dtype, + num_outputs=6, + num_splits=[3, 2]) + with self.assertRaisesOpError('divisible by \'num_splits\' 3'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testDimWithPaddingNotEvenlySplit(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[0, 1], [2, 3], [4, 5], [6, 7]], + input_dtype=dtype, + num_outputs=4, + num_splits=[2, 2], + paddings=[0, 1]) + with self.assertRaisesOpError('divisible by \'num_splits\' 2'): + sess.run(split) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testNoSplits(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[[0, 1], [2, 3]], [[4, 5], [6, 7]]], + input_dtype=dtype, + num_outputs=1, + num_splits=[1, 1, 1]) + results = sess.run(split) + self.assertLen(results, 1) + self.assertAllClose(results[0], [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testNoSplitsWithPadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[[0]], [[1]]], + input_dtype=dtype, + num_outputs=1, + num_splits=[1, 1, 1], + paddings=[0, 1, 1]) + results = sess.run(split) + self.assertLen(results, 1) + self.assertAllClose(results[0], [[[0, 0], [0, 0]], [[1, 0], [0, 0]]]) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testSplitNoPadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[ + [0, 1, 2, 3], + [4, 5, 6, 7], + [8, 9, 10, 11], + [12, 13, 14, 15], + ], + input_dtype=dtype, + num_outputs=4, + num_splits=[2, 2]) + results = sess.run(split) + self.assertLen(results, 4) + self.assertAllClose(results[0], [[0, 1], [4, 5]]) + self.assertAllClose(results[1], [[2, 3], [6, 7]]) + self.assertAllClose(results[2], [[8, 9], [12, 13]]) + self.assertAllClose(results[3], [[10, 11], [14, 15]]) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testSplitPartialPadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8], + ], + input_dtype=dtype, + num_outputs=4, + num_splits=[2, 2], + paddings=[1, 1]) + results = sess.run(split) + self.assertLen(results, 4) + self.assertAllClose(results[0], [[0, 1], [3, 4]]) + self.assertAllClose(results[1], [[2, 0], [5, 0]]) + self.assertAllClose(results[2], [[6, 7], [0, 0]]) + self.assertAllClose(results[3], [[8, 0], [0, 0]]) + + @parameterized.named_parameters(('Tensor', create_tensor_split_graph), + ('Resource', create_resource_split_graph)) + def testSplitCompletePadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=[[0], [1]], + input_dtype=dtype, + num_outputs=4, + num_splits=[2, 2], + paddings=[2, 3]) + results = sess.run(split) + self.assertLen(results, 4) + self.assertAllClose(results[0], [[0, 0], [1, 0]]) + self.assertAllClose(results[1], [[0, 0], [0, 0]]) + self.assertAllClose(results[2], [[0, 0], [0, 0]]) + self.assertAllClose(results[3], [[0, 0], [0, 0]]) + + @parameterized.named_parameters( + ('1Tensor', create_tensor_split_graph, 1), + ('2Tensor', create_tensor_split_graph, 2), + ('3Tensor', create_tensor_split_graph, 3), + ('4Tensor', create_tensor_split_graph, 4), + ('5Tensor', create_tensor_split_graph, 5), + ('6Tensor', create_tensor_split_graph, 6), + ('7Tensor', create_tensor_split_graph, 7), + ('8Tensor', create_tensor_split_graph, 8), + ('1Resource', create_resource_split_graph, 1), + ('2Resource', create_resource_split_graph, 2), + ('3Resource', create_resource_split_graph, 3), + ('4Resource', create_resource_split_graph, 4), + ('5Resource', create_resource_split_graph, 5), + ('6Resource', create_resource_split_graph, 6), + ('7Resource', create_resource_split_graph, 7), + ('8Resource', create_resource_split_graph, 8), + ) + def testRanked(self, graph_fn, rank): + num_splits = [2] * rank + num_outputs = 2 << (rank - 1) + input_value = np.reshape(np.arange(np.prod(num_splits)), num_splits) + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + split = graph_fn( + sess, + input_value=input_value, + input_dtype=dtype, + num_outputs=num_outputs, + num_splits=num_splits) + results = sess.run(split) + self.assertLen(results, num_outputs) + for i, result in enumerate(results): + expected_output = np.reshape(i, [1] * rank).astype(dtype) + self.assertAllClose(result, expected_output) + + +def create_tensor_concat_graph( + sess: Session, + input_values: List[Any], + input_dtype: Any, + num_concats: List[int], + paddings: Optional[List[int]] = None, + output_shape: Optional[List[int]] = None) -> Tensor: + del sess + del output_shape + + const_input_ops = [ + constant_op.constant(i, dtype=input_dtype) for i in input_values + ] + return gen_tpu_ops.xla_concat_nd(const_input_ops, num_concats, paddings) + + +def create_resource_concat_graph( + sess: Session, + input_values: List[Any], + input_dtype: Any, + num_concats: List[int], + paddings: Optional[List[int]] = None, + output_shape: Optional[List[int]] = None) -> Tensor: + variable_shape = [] if output_shape is None else output_shape + variable = resource_variable_ops.ResourceVariable( + initial_value=np.zeros(variable_shape, dtype=input_dtype), + dtype=input_dtype) + sess.run(variables.variables_initializer([variable])) + const_input_ops = [ + constant_op.constant(i, dtype=input_dtype) for i in input_values + ] + concat = gen_tpu_ops.assign_variable_xla_concat_nd(variable.handle, + const_input_ops, + num_concats, paddings) + with control_dependencies([concat]): + return variable.read_value() + + +class XlaConcatNDOpTest(xla_test.XLATestCase, parameterized.TestCase): + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testConcatDimensionZero(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[[[0]]]], + input_dtype=dtype, + num_concats=[1, 1, 0]) + with self.assertRaisesOpError('index 2 must be positive, but got 0'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testConcatDimensionNegative(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[[[0]]]], + input_dtype=dtype, + num_concats=[1, -1, 1]) + with self.assertRaisesOpError('index 1 must be positive, but got -1'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testNumInputsMismatch(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, input_values=[[0, 1]], input_dtype=dtype, num_concats=[2]) + with self.assertRaisesOpError('\'N\' must match number of slices 2'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testPaddingsLengthMismatch(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[[0, 1], [2, 3]]], + input_dtype=dtype, + num_concats=[1, 1], + paddings=[0]) + with self.assertRaisesOpError('length 2, but got 1'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testPaddingsNegative(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[[0, 1], [2, 3]]], + input_dtype=dtype, + num_concats=[1, 1], + paddings=[0, -1]) + with self.assertRaisesOpError('non-negative, but got -1 at index 1'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testInputRankConcatMismatch(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, input_values=[[0]], input_dtype=dtype, num_concats=[1, 1]) + with self.assertRaisesOpError( + '\'num_concats\' length 2, but got rank 1'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testDifferentShapedInputs(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[0], [1, 2]], + input_dtype=dtype, + num_concats=[2]) + with self.assertRaisesOpError( + r'same expected shape \[1\], but got \[2\] at index 1'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testPaddingExceedsOutputDimSize(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[0]], + input_dtype=dtype, + num_concats=[1], + paddings=[2]) + with self.assertRaisesOpError( + 'exceed expected output shape dimension 1 at index 0, but got 2'): + sess.run(concat) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testNoConcats(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]], + input_dtype=dtype, + num_concats=[1, 1, 1], + output_shape=[2, 2, 2]) + result = sess.run(concat) + self.assertAllClose(result, [[[0, 1], [2, 3]], [[4, 5], [6, 7]]]) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testNoConcatsWithPadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[[[[0, 1], [2, 3]], [[4, 5], [6, 7]]]], + input_dtype=dtype, + num_concats=[1, 1, 1], + output_shape=[1, 1, 1], + paddings=[1, 1, 1]) + result = sess.run(concat) + self.assertAllClose(result, [[[0]]]) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testConcatNoPadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[ + [[0, 1], [2, 3]], + [[4, 5], [6, 7]], + [[8, 9], [10, 11]], + [[12, 13], [14, 15]], + ], + input_dtype=dtype, + num_concats=[2, 2], + output_shape=[4, 4]) + result = sess.run(concat) + self.assertAllClose( + result, + [[0, 1, 4, 5], [2, 3, 6, 7], [8, 9, 12, 13], [10, 11, 14, 15]]) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testConcatPartialPadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[ + [[0, 1], [2, 3]], + [[4, 5], [6, 7]], + [[8, 9], [10, 11]], + [[12, 13], [14, 15]], + ], + input_dtype=dtype, + num_concats=[2, 2], + output_shape=[3, 3], + paddings=[1, 1]) + result = sess.run(concat) + self.assertAllClose(result, [[0, 1, 4], [2, 3, 6], [8, 9, 12]]) + + @parameterized.named_parameters(('Tensor', create_tensor_concat_graph), + ('Resource', create_resource_concat_graph)) + def testConcatCompletePadding(self, graph_fn): + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=[ + [[0, 1], [2, 3]], + [[4, 5], [6, 7]], + [[8, 9], [10, 11]], + [[12, 13], [14, 15]], + ], + input_dtype=dtype, + num_concats=[2, 2], + output_shape=[2, 2], + paddings=[2, 2]) + result = sess.run(concat) + self.assertAllClose(result, [[0, 1], [2, 3]]) + + @parameterized.named_parameters( + ('1Tensor', create_tensor_concat_graph, 1), + ('2Tensor', create_tensor_concat_graph, 2), + ('3Tensor', create_tensor_concat_graph, 3), + ('4Tensor', create_tensor_concat_graph, 4), + ('5Tensor', create_tensor_concat_graph, 5), + ('6Tensor', create_tensor_concat_graph, 6), + ('7Tensor', create_tensor_concat_graph, 7), + ('8Tensor', create_tensor_concat_graph, 8), + ('1Resource', create_resource_concat_graph, 1), + ('2Resource', create_resource_concat_graph, 2), + ('3Resource', create_resource_concat_graph, 3), + ('4Resource', create_resource_concat_graph, 4), + ('5Resource', create_resource_concat_graph, 5), + ('6Resource', create_resource_concat_graph, 6), + ('7Resource', create_resource_concat_graph, 7), + ('8Resource', create_resource_concat_graph, 8), + ) + def testRanked(self, graph_fn, rank): + num_concats = [2] * rank + num_inputs = 2 << (rank - 1) + input_values = [np.reshape(i, [1] * rank) for i in range(num_inputs)] + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + concat = graph_fn( + sess, + input_values=input_values, + input_dtype=dtype, + num_concats=num_concats, + output_shape=num_concats) + result = sess.run(concat) + expected_output = np.arange(0, + num_inputs).reshape(num_concats).astype(dtype) + self.assertAllClose(result, expected_output) + + +def create_tensor_roundtrip_graph( + sess: Session, + value: Any, + dtype: Any, + num_partitions: List[int], + paddings: Optional[List[int]] = None) -> Tensor: + del sess + + const_input_op = constant_op.constant(value, dtype=dtype) + split = gen_tpu_ops.xla_split_nd( + const_input_op, + np.prod(num_partitions), + num_partitions, + paddings=paddings) + concat = gen_tpu_ops.xla_concat_nd(split, num_partitions, paddings) + return math_ops.equal(const_input_op, concat) + + +def create_resource_roundtrip_graph( + sess: Session, + value: Any, + dtype: Any, + num_partitions: List[int], + paddings: Optional[List[int]] = None) -> Tensor: + variable = resource_variable_ops.ResourceVariable( + initial_value=value, dtype=dtype) + sess.run(variables.variables_initializer([variable])) + split = gen_tpu_ops.read_variable_xla_split_nd( + variable.handle, + dtype, + np.prod(num_partitions), + num_partitions, + paddings=paddings) + concat = gen_tpu_ops.assign_variable_xla_concat_nd(variable.handle, split, + num_partitions, paddings) + with control_dependencies([concat]): + return math_ops.equal(variable.read_value(), + constant_op.constant(value, dtype=dtype)) + + +class XlaSplitConcatNDTest(xla_test.XLATestCase, parameterized.TestCase): + + @parameterized.named_parameters( + ('1Tensor', create_tensor_roundtrip_graph, 1), + ('2Tensor', create_tensor_roundtrip_graph, 2), + ('3Tensor', create_tensor_roundtrip_graph, 3), + ('4Tensor', create_tensor_roundtrip_graph, 4), + ('5Tensor', create_tensor_roundtrip_graph, 5), + ('6Tensor', create_tensor_roundtrip_graph, 6), + ('7Tensor', create_tensor_roundtrip_graph, 7), + ('8Tensor', create_tensor_roundtrip_graph, 8), + ('1Resource', create_resource_roundtrip_graph, 1), + ('2Resource', create_resource_roundtrip_graph, 2), + ('3Resource', create_resource_roundtrip_graph, 3), + ('4Resource', create_resource_roundtrip_graph, 4), + ('5Resource', create_resource_roundtrip_graph, 5), + ('6Resource', create_resource_roundtrip_graph, 6), + ('7Resource', create_resource_roundtrip_graph, 7), + ('8Resource', create_resource_roundtrip_graph, 8), + ) + def testNoPadding(self, graph_fn, rank): + num_partitions = [2] * rank + shape = [4] * rank + value = np.arange(0, np.prod(shape)).reshape(shape) + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + validate = graph_fn(sess, value, dtype, num_partitions) + result = sess.run(validate) + self.assertAllEqual(result, np.broadcast_to(True, shape)) + + @parameterized.named_parameters( + ('1Tensor', create_tensor_roundtrip_graph, 1), + ('2Tensor', create_tensor_roundtrip_graph, 2), + ('3Tensor', create_tensor_roundtrip_graph, 3), + ('4Tensor', create_tensor_roundtrip_graph, 4), + ('5Tensor', create_tensor_roundtrip_graph, 5), + ('6Tensor', create_tensor_roundtrip_graph, 6), + ('7Tensor', create_tensor_roundtrip_graph, 7), + ('8Tensor', create_tensor_roundtrip_graph, 8), + ('1Resource', create_resource_roundtrip_graph, 1), + ('2Resource', create_resource_roundtrip_graph, 2), + ('3Resource', create_resource_roundtrip_graph, 3), + ('4Resource', create_resource_roundtrip_graph, 4), + ('5Resource', create_resource_roundtrip_graph, 5), + ('6Resource', create_resource_roundtrip_graph, 6), + ('7Resource', create_resource_roundtrip_graph, 7), + ('8Resource', create_resource_roundtrip_graph, 8), + ) + def testPartialPadding(self, graph_fn, rank): + num_partitions = [2] * rank + shape = [4] * rank + value = np.arange(0, np.prod(shape)).reshape(shape) + paddings = [2] * rank + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + validate = graph_fn(sess, value, dtype, num_partitions, paddings) + result = sess.run(validate) + self.assertAllEqual(result, np.broadcast_to(True, shape)) + + @parameterized.named_parameters( + ('1Tensor', create_tensor_roundtrip_graph, 1), + ('2Tensor', create_tensor_roundtrip_graph, 2), + ('3Tensor', create_tensor_roundtrip_graph, 3), + ('4Tensor', create_tensor_roundtrip_graph, 4), + ('5Tensor', create_tensor_roundtrip_graph, 5), + ('6Tensor', create_tensor_roundtrip_graph, 6), + ('7Tensor', create_tensor_roundtrip_graph, 7), + ('8Tensor', create_tensor_roundtrip_graph, 8), + ('1Resource', create_resource_roundtrip_graph, 1), + ('2Resource', create_resource_roundtrip_graph, 2), + ('3Resource', create_resource_roundtrip_graph, 3), + ('4Resource', create_resource_roundtrip_graph, 4), + ('5Resource', create_resource_roundtrip_graph, 5), + ('6Resource', create_resource_roundtrip_graph, 6), + ('7Resource', create_resource_roundtrip_graph, 7), + ('8Resource', create_resource_roundtrip_graph, 8), + ) + def testCompletePadding(self, graph_fn, rank): + num_partitions = [2] * rank + shape = [4] * rank + value = np.arange(0, np.prod(shape)).reshape(shape) + paddings = [4] * rank + for dtype in self.numeric_types: + with self.session() as sess, self.device_scope(): + validate = graph_fn(sess, value, dtype, num_partitions, paddings) + result = sess.run(validate) + self.assertAllEqual(result, np.broadcast_to(True, shape)) + + +if __name__ == '__main__': + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/slice_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/slice_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..92c602de96da98862b8d88814e236b1da2404210 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/slice_ops_test.py @@ -0,0 +1,302 @@ +# 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 slicing.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class SliceTest(xla_test.XLATestCase): + + def test1D(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[10]) + with self.test_scope(): + o = array_ops.slice(i, [2], [4]) + params = { + i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([2, 3, 4, 5], result) + + def testZeroSlice(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[2]) + with self.test_scope(): + o = array_ops.slice(i, [0], [0]) + params = { + i: [0, 1], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([], result) + + def test3D(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[3, 3, 10]) + with self.test_scope(): + o = array_ops.slice(i, [1, 2, 2], [1, 1, 4]) + params = { + i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [5, 3, 1, 7, 9, 2, 4, 6, 8, 0]], + [[5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [8, 7, 6, 5, 4, 3, 2, 1, 8, 7]], + [[7, 5, 7, 5, 7, 5, 7, 5, 7, 5], + [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], + [9, 8, 7, 9, 8, 7, 9, 8, 7, 9]]] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[[6, 5, 4, 3]]], result) + + def test3DWithDynamicBegin(self): + """Tests a slice where the start offset is not known at compile time.""" + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[3, 3, 10]) + begin = array_ops.placeholder(dtypes.int32, shape=[3]) + with self.test_scope(): + o = array_ops.slice(i, begin, [1, 1, 4]) + params = { + i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [5, 3, 1, 7, 9, 2, 4, 6, 8, 0]], + [[5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [8, 7, 6, 5, 4, 3, 2, 1, 8, 7]], + [[7, 5, 7, 5, 7, 5, 7, 5, 7, 5], + [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], + [9, 8, 7, 9, 8, 7, 9, 8, 7, 9]]], + begin: [1, 2, 2] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[[6, 5, 4, 3]]], result) + + def test3DWithDynamicBeginAndNegativeSize(self): + """Tests a slice where `begin` is fed dynamically and `size` contains -1.""" + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[3, 3, 10]) + begin = array_ops.placeholder(dtypes.int32, shape=[3]) + with self.test_scope(): + o = array_ops.slice(i, begin, [1, -1, 4]) + params = { + i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [5, 3, 1, 7, 9, 2, 4, 6, 8, 0]], + [[5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [8, 7, 6, 5, 4, 3, 2, 1, 8, 7]], + [[7, 5, 7, 5, 7, 5, 7, 5, 7, 5], + [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], + [9, 8, 7, 9, 8, 7, 9, 8, 7, 9]]], + begin: [1, 1, 2] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[[1, 1, 1, 1], [6, 5, 4, 3]]], result) + + +class StridedSliceTest(xla_test.XLATestCase): + + def test1D(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[10]) + with self.test_scope(): + o = array_ops.strided_slice(i, [2], [6], [2]) + params = { + i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([2, 4], result) + + def test1DDynamic(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[10]) + begin = array_ops.placeholder(dtypes.int32, shape=[1]) + with self.test_scope(): + end = math_ops.add(begin, [1]) + o = array_ops.strided_slice(i, begin, end, [1]) + params = { + i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + begin: [0] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([0], result) + + def testDynamicSliceOutOfBounds(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[10]) + begin = array_ops.placeholder(dtypes.int32, shape=[1]) + end = array_ops.placeholder(dtypes.int32, shape=[1]) + with self.test_scope(): + o = array_ops.strided_slice(i, begin, end, [1]) + params = {i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], begin: [5], end: [15]} + result = o.eval(feed_dict=params) + + self.assertAllEqual([5, 6, 7, 8, 9], result) + + def test1DNegativeStride(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[10]) + with self.test_scope(): + o = array_ops.strided_slice(i, [6], [2], [-2]) + params = { + i: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([6, 4], result) + + def test2DDegenerate(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[2, 3]) + with self.test_scope(): + o = array_ops.strided_slice(i, [-1, 0], [0, 3]) + params = { + i: [[0, 1, 2], + [3, 4, 5]] + } + result = o.eval(feed_dict=params) + + self.assertEqual(tensor_shape.TensorShape((0, 3)), result.shape) + + def test2DDegenerateNegativeStride(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[2, 3]) + with self.test_scope(): + o = array_ops.strided_slice(i, [0, 0], [-1, 3], [-1, 1]) + params = { + i: [[0, 1, 2], + [3, 4, 5]] + } + result = o.eval(feed_dict=params) + + self.assertEqual(tensor_shape.TensorShape((0, 3)), result.shape) + + def test2DFullSlice(self): + for dtype in self.numeric_types: + with self.session(): + with self.test_scope(): + i = array_ops.placeholder(dtype, shape=[2, 4]) + begin = array_ops.placeholder(dtypes.int32, shape=[2]) + end = math_ops.add(begin, [1, 1]) + o = array_ops.strided_slice(i, begin, end, [1, 1]) + params = { + i: [[0, 1, 2, 3], [4, 5, 6, 7]], + begin: [1, 1] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[5]], result) + + def test3D(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[3, 3, 10]) + with self.test_scope(): + o = array_ops.strided_slice(i, [0, 2, 2], [2, 3, 6], [1, 1, 2]) + params = { + i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [5, 3, 1, 7, 9, 2, 4, 6, 8, 0]], + [[5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], + [8, 7, 6, 5, 4, 3, 2, 1, 8, 7]], + [[7, 5, 7, 5, 7, 5, 7, 5, 7, 5], + [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], + [9, 8, 7, 9, 8, 7, 9, 8, 7, 9]]] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[[1, 9]], [[6, 4]]], result) + + def test3DNegativeStride(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[3, 4, 10]) + with self.test_scope(): + o = array_ops.strided_slice(i, [2, 2, 6], [0, 0, 2], [-1, -1, -2]) + params = { + i: [[[0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + [9, 8, 7, 6, 5, 4, 3, 2, 1, 0], + [5, 3, 1, 7, 9, 2, 4, 6, 8, 0], + [4, 5, 2, 4, 3, 7, 6, 8, 9, 4]], + [[5, 5, 5, 5, 5, 5, 5, 5, 5, 5], + [4, 3, 4, 5, 7, 6, 5, 3, 4, 5], + [8, 7, 6, 5, 4, 3, 2, 1, 8, 7], + [7, 1, 7, 1, 8, 1, 8, 1, 3, 1]], + [[7, 5, 7, 5, 7, 5, 7, 5, 7, 5], + [1, 2, 1, 2, 1, 2, 1, 2, 1, 2], + [9, 8, 7, 9, 8, 7, 9, 8, 7, 9], + [9, 9, 5, 5, 6, 6, 3, 3, 6, 6]]] + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([[[9, 8], + [1, 1]], + [[2, 4], + [5, 7]]], result) + + # Test shrink_axis_mask. This `strided_slice` call is equivalent to `i[1,:]`. + def testShrinkAxisMask(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[2, 3]) + with self.test_scope(): + o = array_ops.strided_slice(i, [1, 0], [10, 3], shrink_axis_mask=1) + params = { + i: [[0, 1, 2], [3, 4, 5]], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([3, 4, 5], result) + + # Test shrink_axis_mask with the range for the second dimension implicit. + # This `strided_slice` call is equivalent to `i[1]`. + def testShrinkAxisMaskImplicitRange(self): + for dtype in self.numeric_types: + with self.session(): + i = array_ops.placeholder(dtype, shape=[2, 3]) + with self.test_scope(): + o = array_ops.strided_slice(i, [1], [10], shrink_axis_mask=1) + params = { + i: [[0, 1, 2], [3, 4, 5]], + } + result = o.eval(feed_dict=params) + + self.assertAllEqual([3, 4, 5], result) + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/sort_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/sort_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..beb9e3869d8cac0ad05a4f91c53e8b7f5a2a36ec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/sort_ops_test.py @@ -0,0 +1,482 @@ +# 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 sorting operators.""" + +import unittest + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import tensor +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 nn_ops +from tensorflow.python.ops import sort_ops +from tensorflow.python.platform import test + +ALL_KEY_TYPES = [ + dtypes.bfloat16.as_numpy_dtype, np.float16, np.float32, np.float64, + np.int32, np.uint32, np.int16, np.uint16, np.int8, np.uint8 +] + + +class XlaSortOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def _assertOpOutputMatchesExpected(self, op, args, expected): + """Tests that op(*args) == expected.""" + with self.session() as session: + with self.test_scope(): + placeholders = [ + array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape) + for arg in args + ] + feeds = {placeholders[i]: args[i] for i in range(0, len(args))} + output = op(*placeholders) + if isinstance(output, tensor.Tensor): + output = [output] + + results = session.run(output, feeds) + for result, v in zip(results, expected): + self.assertAllClose(v, result, rtol=1e-3) + + def _shuffled_arange(self, shape, dtype): + x = np.arange(np.prod(shape), dtype=dtype) + np.random.shuffle(x) + return x.reshape(shape) + + def _supported_key_types(self): + supported_key_types = set(ALL_KEY_TYPES) + res = supported_key_types.intersection(self.numeric_types) + assert res + return res + + def testSort(self): + for dtype in self._supported_key_types(): + x = self._shuffled_arange((101,), dtype) + self._assertOpOutputMatchesExpected( + xla.sort, [x], expected=[np.arange(101, dtype=dtype)]) + + def testKeyValueSort(self): + for key_type in self._supported_key_types(): + for value_type in self._supported_key_types(): + if key_type == np.uint8 or value_type == np.uint8: + # I do not understand why the test fails on uint8. We plan to + # deprecate xla.key_value_sort in favor of xla.variadic_sort anyway. + continue + x = self._shuffled_arange((101,), key_type) + y = (-x).astype(value_type) + self._assertOpOutputMatchesExpected( + xla.key_value_sort, [x, y], + expected=[ + np.arange(101, dtype=key_type), + -np.arange(101, dtype=value_type) + ]) + + # Flip is the only reliable way to get a descending sort across any dimension. + # 1. -np.sort(-x) doesn't work with unsigned integers. + # 2. np.sort(x, axis=a)[::-1] is not generic over axis wher reversing array + # 3. x.argsort() either requires "-1" (first option) or flip, so the same. + def _descendingSort(self, x, dimension): + b = np.sort(x, axis=dimension) + return np.flip(b, axis=dimension) + + @parameterized.parameters(0, 1, 2) + def testMisleadingComparator(self, dimension): + shape = (4, 3, 4) + for key_type in self._supported_key_types(): + x = self._shuffled_arange(shape, key_type) + expected = self._descendingSort(x, dimension) + + # pylint: disable=cell-var-from-loop + @function.Defun(key_type, key_type) + def compare_gt(x1, x2): + return x2 < x1 # "greater than" with misleading "<" sign + + def wrap_sort(x): + return xla.variadic_sort([x], + dimension=dimension, + is_stable=False, + comparator=compare_gt) + + self._assertOpOutputMatchesExpected(wrap_sort, [x], expected=[expected]) + + @parameterized.parameters(0, 1, 2) + def testVariadicSortDimension(self, dimension): + shape = (2, 3, 4) + for key_type in self._supported_key_types(): + x = self._shuffled_arange(shape, key_type) + expected = np.sort(x, axis=dimension) + + @function.Defun(key_type, key_type) + def compare_lt(x1, x2): + return x1 < x2 + + def wrap_sort(x): + return xla.variadic_sort([x], + dimension=dimension, + is_stable=False, + comparator=compare_lt) + + self._assertOpOutputMatchesExpected(wrap_sort, [x], expected=[expected]) + + @parameterized.parameters(0, 1, 2) + def testVariadicSortReverse(self, dimension): + shape = (100, 3, 4) + for key_type in self._supported_key_types(): + x = self._shuffled_arange(shape, key_type) + expected = self._descendingSort(x, dimension) + + @function.Defun(key_type, key_type) + def compare_gt(x1, x2): + return x1 > x2 + + def wrap_sort(x): + return xla.variadic_sort([x], + dimension=dimension, + is_stable=False, + comparator=compare_gt) + + self._assertOpOutputMatchesExpected(wrap_sort, [x], expected=[expected]) + + @parameterized.product(dimension=[0, 1, 2], key_type=ALL_KEY_TYPES) + def testVariadicSortSeveral(self, dimension, key_type): + if np.__version__ < "1.15": + raise unittest.SkipTest("np.take_along_axis was added in 1.15") + if key_type not in self._supported_key_types(): + return + shape = (2, 3, 4) + for value_type_1 in self._supported_key_types(): + for value_type_2 in self._supported_key_types(): + inputs = [ + self._shuffled_arange(shape, key_type), + self._shuffled_arange(shape, value_type_1), + self._shuffled_arange(shape, value_type_2) + ] + + # The first array is sorted, and the others are shuffled the same way + sorted_indices = np.argsort(inputs[0], axis=dimension) + expected = [ + np.take_along_axis(inp, sorted_indices, axis=dimension) + for inp in inputs + ] + self.assertAllEqual(np.sort(inputs[0], axis=dimension), expected[0]) + + @function.Defun(key_type, key_type, value_type_1, value_type_1, + value_type_2, value_type_2) + def compare_lt(x1, x2, y1, y2, z1, z2): + del y1, y2, z1, z2 + return x1 < x2 + + def wrap_sort(*args): + return xla.variadic_sort( + args, # Pass the arguments as a tuple + comparator=compare_lt, + dimension=dimension, + is_stable=False) + + self._assertOpOutputMatchesExpected( + wrap_sort, inputs, expected=expected) + + @parameterized.parameters(ALL_KEY_TYPES) + @test_util.disable_mlir_bridge("Not supported yet") + def testVariadicSortLexicographic(self, key_type_2): + # Three inputs: the first two are used for lexicographic sort, and the + # third is just swapped accordingly. + # The first array will contain only 0 and 1, to test lexicographic order + if np.__version__ < "1.15": + raise unittest.SkipTest("np.take_along_axis was added in 1.15") + shape = (20,) + if key_type_2 not in self._supported_key_types(): + return + for key_type_1 in [np.int16, np.uint16, np.int32, np.uint32]: + for value_type in self._supported_key_types(): + inputs = [ + # Ensure that some keys in the first input are equal + np.random.uniform(0, 2, shape).astype(key_type_1), + self._shuffled_arange(shape, key_type_2), + self._shuffled_arange(shape, value_type) + ] + # The first two arrays are sorted lexicographically, and the third + # is shuffled the same way + sorted_indices = np.argsort(100 * inputs[0] + inputs[1]) + expected = [ + np.take_along_axis(inp, sorted_indices, axis=0) for inp in inputs + ] + + @function.Defun(key_type_1, key_type_1, key_type_2, key_type_2, + value_type, value_type) + def compare_lexicographic(x1, x2, y1, y2, z1, z2): + del z1, z2 + return math_ops.logical_or( + x1 < x2, math_ops.logical_and(math_ops.equal(x1, x2), y1 < y2)) + + def wrap_sort(*args): + return xla.variadic_sort( + args, # Pass the arguments as a tuple + comparator=compare_lexicographic, + dimension=0, + is_stable=False) + + self._assertOpOutputMatchesExpected( + wrap_sort, inputs, expected=expected) + + @parameterized.product(dimension=[0, 1, 2], key_type=ALL_KEY_TYPES) + def testVariadicSortSeveralStable(self, dimension, key_type): + shape = (2, 3, 4) + if key_type not in self._supported_key_types(): + return + for value_type_1 in self._supported_key_types(): + for value_type_2 in self._supported_key_types(): + # The first input is all 0s, there should be no changes for + # stable sort. + inputs = [ + np.zeros(shape, key_type), + self._shuffled_arange(shape, value_type_1), + self._shuffled_arange(shape, value_type_2) + ] + + @function.Defun(key_type, key_type, value_type_1, value_type_1, + value_type_2, value_type_2) + def compare_lt(x1, x2, y1, y2, z1, z2): + del y1, y2, z1, z2 + return x1 < x2 + + def wrap_sort(*args): + return xla.variadic_sort( + args, # Pass the arguments as a tuple + comparator=compare_lt, + dimension=dimension, + is_stable=True) + + self._assertOpOutputMatchesExpected(wrap_sort, inputs, expected=inputs) + + @parameterized.product(dimension=[0, 1, 2], dtype=ALL_KEY_TYPES) + def testArgsort(self, dimension, dtype): + shape = (2, 3, 4) + if dtype not in self._supported_key_types(): + return + + def argsort(v, axis=dimension): + return sort_ops.argsort(v, axis, stable=True) + + x = self._shuffled_arange(shape, dtype) + self._assertOpOutputMatchesExpected( + argsort, [x], expected=[np.argsort(x, axis=dimension, kind="stable")] + ) + + @parameterized.product( + dtype=[ + dtypes.bfloat16.as_numpy_dtype, + np.float16, + np.float32, + np.float64, + np.int32, + np.uint32, + np.int64, + np.uint64, + np.uint8, + np.int8, + ], + rank=[1, 2, 3], + ) + def testTopK(self, dtype, rank): + if dtype in self.numeric_types: + # Use small input size for bfloat16. Otherwise, we'll get duplicate values + # after conversion to bfloat16, so the possible resulting index array is + # no longer unique. + if dtype in (dtypes.bfloat16.as_numpy_dtype, np.float16): + array_size = 20 + k_options = [0, 1, 2, 10, 20] + elif dtype in (dtypes.uint8.as_numpy_dtype, dtypes.int8.as_numpy_dtype): + array_size = 111 + k_options = [0, 1, 2, 10, 20] + else: + array_size = 200 * 1000 + k_options = [0, 1, 2, 10, 20, 100, 1000, 200 * 1000] + + # Tile array to tensor of specified rank, then shuffle along the last dim + x = np.arange(array_size) + x = np.tile(x, (2,) * (rank - 1) + (1,)) + np.apply_along_axis(np.random.shuffle, -1, x) + + sorted_indices = x.argsort(axis=-1)[..., ::-1] + sorted_values = np.sort(x, axis=-1)[..., ::-1] + for k in k_options: + indices = sorted_indices[..., :k] + expected = sorted_values[..., :k] + + def topk(v, k=k): + return nn_ops.top_k(v, k=k, sorted=True) + + self._assertOpOutputMatchesExpected( + topk, + [x.astype(dtype)], + expected=[expected.astype(dtype), indices], + ) + + def testTopKZeros(self): + """Tests that positive and negative zeros sort correctly.""" + supported_types = set( + [dtypes.bfloat16.as_numpy_dtype, np.float16, np.float32, np.float64]) + for dtype in supported_types.intersection(self.numeric_types): + with self.session() as sess: + p = array_ops.placeholder(dtype) + with self.test_scope(): + topk = nn_ops.top_k(p, k=4) + results = sess.run( + topk, + {p: np.array([0., -0., 0., 3., -0., -4., 0., -0.], dtype=dtype)}) + self.assertAllEqual(np.array([3., 0., 0., 0.], dtype=dtype), results[0]) + self.assertEqual(list([3, 0, 2, 6]), list(results[1])) + + def testTopKInfinities(self): + """Tests that positive and negative infinity sort correctly.""" + supported_types = set( + [dtypes.bfloat16.as_numpy_dtype, np.float16, np.float32, np.float64]) + for dtype in supported_types.intersection(self.numeric_types): + with self.session() as sess: + p = array_ops.placeholder(dtype) + with self.test_scope(): + topk = nn_ops.top_k(p, k=6) + results = sess.run(topk, { + p: + np.array([1, 2, float("inf"), -float("inf"), -1, -2], + dtype=dtype) + }) + self.assertAllEqual( + np.array([float("inf"), 2.0, 1.0, -1.0, -2.0, -float("inf")], + dtype=dtype), results[0]) + self.assertEqual(list([2, 1, 0, 4, 5, 3]), list(results[1])) + + @parameterized.named_parameters( + ("Int32", np.int32), + ("Int64", np.uint64), + ) + def testInTopK(self, dtype): + if dtype in self.numeric_types: + array_size = 200 * 1000 + k_options = [0, 1, 2, 10, 20, 100, 1000, 200 * 1000] + batch = 16 + for x in [np.arange(batch * array_size)]: + np.random.shuffle(x) + x = np.reshape(x, [batch, array_size]) + y = np.random.randint(0, array_size, size=batch) + for k in k_options: + indices = x.argsort(axis=1)[::, -1:-k - 1:-1] + expected = [y[i] in indices[i] for i in range(batch)] + + def in_topk(predictions, targets, k=k): + return nn_ops.in_top_k(predictions, targets, k) + + self._assertOpOutputMatchesExpected( + in_topk, + [x.astype(np.float32), y.astype(dtype)], + expected=[expected]) + + +class SortOpsBenchmark(test.Benchmark): + """Microbenchmarks for the sort ops.""" + + def _benchmarkSort(self, name, dtype, is_stable, use_xla_jit): + + def get_shuffled_arr(sorted_arr, shape): + shuffled = sorted_arr.copy() + np.random.shuffle(shuffled) + return shuffled.reshape(shape) + + @function.Defun(dtype, dtype) + def compare_lt(x1, x2): + return x1 < x2 + + def builder_fn(): + shape = (100001,) + sorted_arr = np.arange(np.prod(shape), dtype=dtype) + shuffled = get_shuffled_arr(sorted_arr, shape) + given_result = xla.variadic_sort( + [shuffled], dimension=0, is_stable=is_stable, comparator=compare_lt + ) + stable_str = "stable" if is_stable else "unstable" + return "%s_%s.shape%s" % (stable_str, name, shape), [given_result] + + xla_test.Benchmark(self, builder_fn, use_xla_jit=use_xla_jit, device="cpu") + + def benchmarkStableSortF16(self): + self._benchmarkSort( + "sort_f16", dtype=np.float16, is_stable=True, use_xla_jit=False + ) + + def benchmarkStableSortF32(self): + self._benchmarkSort( + "sort_f32", dtype=np.float32, is_stable=True, use_xla_jit=False + ) + + def benchmarkStableSortF64(self): + self._benchmarkSort( + "sort_f64", dtype=np.float64, is_stable=True, use_xla_jit=False + ) + + def benchmarkStableSortF16XLA(self): + self._benchmarkSort( + "sort_f16", dtype=np.float16, is_stable=True, use_xla_jit=True + ) + + def benchmarkStableSortF32XLA(self): + self._benchmarkSort( + "sort_f32", dtype=np.float32, is_stable=True, use_xla_jit=True + ) + + def benchmarkStableSortF64XLA(self): + self._benchmarkSort( + "sort_f64", dtype=np.float64, is_stable=True, use_xla_jit=True + ) + + def benchmarkUnstableSortF16(self): + self._benchmarkSort( + "sort_f16", dtype=np.float16, is_stable=False, use_xla_jit=False + ) + + def benchmarkUnstableSortF32(self): + self._benchmarkSort( + "sort_f32", dtype=np.float32, is_stable=False, use_xla_jit=False + ) + + def benchmarkUnstableSortF64(self): + self._benchmarkSort( + "sort_f64", dtype=np.float64, is_stable=False, use_xla_jit=False + ) + + def benchmarkUnstableSortF16XLA(self): + self._benchmarkSort( + "sort_f16", dtype=np.float16, is_stable=False, use_xla_jit=True + ) + + def benchmarkUnstableSortF32XLA(self): + self._benchmarkSort( + "sort_f32", dtype=np.float32, is_stable=False, use_xla_jit=True + ) + + def benchmarkUnstableSortF64XLA(self): + self._benchmarkSort( + "sort_f64", dtype=np.float64, is_stable=False, use_xla_jit=True + ) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/spacetobatch_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/spacetobatch_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fc9de3c5aad532a0330609e663de0408082d2ff6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/spacetobatch_op_test.py @@ -0,0 +1,311 @@ +# 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. +# ============================================================================== +"""Functional tests for SpaceToBatch and BatchToSpace ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.platform import test + + +def space_to_batch_direct(input_array, block_shape, paddings): + """Direct Python implementation of space-to-batch conversion. + + This is used for tests only. + + Args: + input_array: N-D array + block_shape: 1-D array of shape [num_block_dims]. + paddings: 2-D array of shape [num_block_dims, 2]. + + Returns: + Converted tensor. + """ + input_array = np.array(input_array) + block_shape = np.array(block_shape) + num_block_dims = len(block_shape) + paddings = np.array(paddings).reshape((len(block_shape), 2)) + + padded = np.pad(input_array, + pad_width=([[0, 0]] + list(paddings) + [[0, 0]] * + (input_array.ndim - 1 - num_block_dims)), + mode="constant") + reshaped_padded_shape = [input_array.shape[0]] + output_shape = [input_array.shape[0] * np.prod(block_shape)] + for block_dim, block_shape_value in enumerate(block_shape): + reduced_size = padded.shape[block_dim + 1] // block_shape_value + reshaped_padded_shape.append(reduced_size) + output_shape.append(reduced_size) + reshaped_padded_shape.append(block_shape_value) + reshaped_padded_shape.extend(input_array.shape[num_block_dims + 1:]) + output_shape.extend(input_array.shape[num_block_dims + 1:]) + + reshaped_padded = padded.reshape(reshaped_padded_shape) + permuted_reshaped_padded = np.transpose(reshaped_padded, ( + list(np.arange(num_block_dims) * 2 + 2) + [0] + + list(np.arange(num_block_dims) * 2 + 1) + list( + np.arange(input_array.ndim - num_block_dims - 1) + 1 + num_block_dims + * 2))) + return permuted_reshaped_padded.reshape(output_shape) + + +class SpaceToBatchTest(xla_test.XLATestCase): + """Tests input-output pairs for the SpaceToBatch and BatchToSpace ops.""" + + def _testPad(self, inputs, paddings, block_size, outputs): + with self.session() as sess, self.test_scope(): + for dtype in self.float_types: + # outputs = space_to_batch(inputs) + placeholder = array_ops.placeholder(dtype) + x_tf = gen_array_ops.space_to_batch( + placeholder, paddings, block_size=block_size) + self.assertAllEqual(sess.run(x_tf, {placeholder: inputs}), outputs) + # inputs = batch_to_space(outputs) + x_tf = gen_array_ops.batch_to_space( + placeholder, paddings, block_size=block_size) + self.assertAllEqual(sess.run(x_tf, {placeholder: outputs}), inputs) + + def _testOne(self, inputs, block_size, outputs): + paddings = np.zeros((2, 2), dtype=np.int32) + self._testPad(inputs, paddings, block_size, outputs) + + # [1, 2, 2, 1] <-> [4, 1, 1, 1] + def testSmallInput2x2(self): + x_np = [[[[1], [2]], [[3], [4]]]] + block_size = 2 + x_out = [[[[1]]], [[[2]]], [[[3]]], [[[4]]]] + self._testOne(x_np, block_size, x_out) + + # [1, 2, 2, 1] <-> [1, 3, 3, 1] (padding) <-> [9, 1, 1, 1] + def testSmallInput2x2Pad1x0(self): + x_np = [[[[1], [2]], [[3], [4]]]] + paddings = np.array([[1, 0], [1, 0]], dtype=np.int32) + block_size = 3 + x_out = [[[[0]]], [[[0]]], [[[0]]], [[[0]]], [[[1]]], [[[2]]], [[[0]]], + [[[3]]], [[[4]]]] + self._testPad(x_np, paddings, block_size, x_out) + + # Test with depth larger than 1. + # [1, 2, 2, 3] <-> [4, 1, 1, 3] + def testDepthInput2x2(self): + x_np = [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]] + block_size = 2 + x_out = [[[[1, 2, 3]]], [[[4, 5, 6]]], [[[7, 8, 9]]], [[[10, 11, 12]]]] + self._testOne(x_np, block_size, x_out) + + # Test for larger input dimensions. + # [1, 4, 4, 1] <-> [4, 2, 2, 1] + def testLargerInput2x2(self): + x_np = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], + [[9], [10], [11], [12]], [[13], [14], [15], [16]]]] + block_size = 2 + x_out = [[[[1], [3]], [[9], [11]]], [[[2], [4]], [[10], [12]]], + [[[5], [7]], [[13], [15]]], [[[6], [8]], [[14], [16]]]] + self._testOne(x_np, block_size, x_out) + + # Test with batch larger than 1. + # [2, 2, 4, 1] <-> [8, 1, 2, 1] + def testBatchInput2x2(self): + x_np = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]]], + [[[9], [10], [11], [12]], [[13], [14], [15], [16]]]] + block_size = 2 + x_out = [[[[1], [3]]], [[[9], [11]]], [[[2], [4]]], [[[10], [12]]], + [[[5], [7]]], [[[13], [15]]], [[[6], [8]]], [[[14], [16]]]] + self._testOne(x_np, block_size, x_out) + + # Tests for larger input spatial dimensions AND batch larger than 1, to ensure + # that elements are correctly laid out spatially and properly interleaved + # along the batch dimension. + # [2, 4, 4, 1] <-> [8, 2, 2, 1] + def testLargerInputBatch2x2(self): + x_np = [[[[1], [2], [3], [4]], [[5], [6], [7], [8]], + [[9], [10], [11], [12]], [[13], [14], [15], [16]]], + [[[17], [18], [19], [20]], [[21], [22], [23], [24]], + [[25], [26], [27], [28]], [[29], [30], [31], [32]]]] + x_out = [[[[1], [3]], [[9], [11]]], [[[17], [19]], [[25], [27]]], + [[[2], [4]], [[10], [12]]], [[[18], [20]], [[26], [28]]], + [[[5], [7]], [[13], [15]]], [[[21], [23]], [[29], [31]]], + [[[6], [8]], [[14], [16]]], [[[22], [24]], [[30], [32]]]] + block_size = 2 + self._testOne(x_np, block_size, x_out) + + +class SpaceToBatchNDErrorHandlingTest(xla_test.XLATestCase): + + def testInvalidBlockShape(self): + with self.assertRaisesRegex(ValueError, "block_shape must be positive"): + with self.session() as sess, self.test_scope(): + tf_in = constant_op.constant( + -3.5e+35, shape=[10, 20, 20], dtype=dtypes.float32) + block_shape = constant_op.constant(-10, shape=[2], dtype=dtypes.int64) + paddings = constant_op.constant(0, shape=[2, 2], dtype=dtypes.int32) + sess.run(array_ops.space_to_batch_nd(tf_in, block_shape, paddings)) + + def testOutputSizeOutOfBounds(self): + with self.assertRaisesRegex(ValueError, + "Negative.* dimension size caused by overflow"): + with self.session() as sess, self.test_scope(): + tf_in = constant_op.constant( + -3.5e+35, shape=[10, 19, 22], dtype=dtypes.float32) + block_shape = constant_op.constant( + 1879048192, shape=[2], dtype=dtypes.int64) + paddings = constant_op.constant(0, shape=[2, 2], dtype=dtypes.int32) + sess.run(array_ops.space_to_batch_nd(tf_in, block_shape, paddings)) + + +class SpaceToBatchNDTest(xla_test.XLATestCase): + """Tests input-output pairs for the SpaceToBatchND and BatchToSpaceND ops.""" + + def _testPad(self, inputs, block_shape, paddings, outputs): + block_shape = np.array(block_shape) + paddings = np.array(paddings).reshape((len(block_shape), 2)) + with self.session() as sess, self.test_scope(): + for dtype in self.float_types: + # TODO(b/68813416): Skip bfloat16's as the input type for direct is + # float32 and results in a mismatch, while making testDirect provide the + # correctly typed input results in 'no fill-function for data-type' + # error. + if dtype == dtypes.bfloat16.as_numpy_dtype: + continue + if dtype == np.float16: + actual_inputs = np.array(inputs).astype(dtype) + actual_paddings = np.array(paddings).astype(dtype) + expected_outputs = np.array(outputs).astype(dtype) + else: + actual_inputs = inputs + actual_paddings = paddings + expected_outputs = outputs + placeholder = array_ops.placeholder(dtype) + # outputs = space_to_batch(inputs) + x_tf = array_ops.space_to_batch_nd(placeholder, block_shape, + actual_paddings) + self.assertAllEqual( + sess.run(x_tf, {placeholder: actual_inputs}), expected_outputs) + # inputs = batch_to_space(outputs) + placeholder = array_ops.placeholder(dtype) + x_tf = array_ops.batch_to_space_nd(placeholder, block_shape, + actual_paddings) + self.assertAllEqual( + sess.run(x_tf, {placeholder: expected_outputs}), actual_inputs) + + def _testDirect(self, input_shape, block_shape, paddings): + inputs = np.arange(np.prod(input_shape), dtype=np.float32) + inputs = inputs.reshape(input_shape) + self._testPad(inputs, block_shape, paddings, + space_to_batch_direct(inputs, block_shape, paddings)) + + def testZeroBlockDimsZeroRemainingDims(self): + self._testPad( + inputs=[1, 2], + block_shape=[], + paddings=[], + outputs=[1, 2],) + + def testZeroBlockDimsOneRemainingDim(self): + self._testPad( + inputs=[[1, 2], [3, 4]], + block_shape=[], + paddings=[], + outputs=[[1, 2], [3, 4]]) + + # Same thing, but with a no-op block dim. + self._testPad( + inputs=[[1, 2], [3, 4]], + block_shape=[1], + paddings=[[0, 0]], + outputs=[[1, 2], [3, 4]]) + + def testZeroBlockDimsTwoRemainingDims(self): + self._testPad( + inputs=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], + block_shape=[], + paddings=[], + outputs=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + + # Same thing, but with a no-op block dim. + self._testPad( + inputs=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], + block_shape=[1], + paddings=[[0, 0]], + outputs=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + + # Same thing, but with two no-op block dims. + self._testPad( + inputs=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]], + block_shape=[1, 1], + paddings=[[0, 0], [0, 0]], + outputs=[[[1, 2], [3, 4]], [[5, 6], [7, 8]]]) + + def testOneBlockDimZeroRemainingDims(self): + self._testPad( + inputs=[[1, 2, 3], [4, 5, 6]], + block_shape=[2], + paddings=[1, 0], + outputs=[[0, 2], [0, 5], [1, 3], [4, 6]]) + + def testOneBlockDimOneRemainingDim(self): + self._testPad( + inputs=[[[1, 11], [2, 21], [3, 31]], [[4, 41], [5, 51], [6, 61]]], + block_shape=[2], + paddings=[1, 0], + outputs=[[[0, 0], [2, 21]], [[0, 0], [5, 51]], [[1, 11], [3, 31]], + [[4, 41], [6, 61]]]) + + def testDirect0(self): + # Test with zero-size remaining dimension. + self._testDirect( + input_shape=[3, 1, 2, 0], block_shape=[3], paddings=[[0, 2]]) + + def testDirect1(self): + # Test with zero-size blocked dimension. + self._testDirect( + input_shape=[3, 0, 2, 5], block_shape=[3], paddings=[[0, 0]]) + + def testDirect2(self): + # Test with padding up from zero size. + self._testDirect( + input_shape=[3, 0, 2, 5], block_shape=[3], paddings=[[1, 2]]) + + def testDirect3(self): + self._testDirect( + input_shape=[3, 3, 4, 5, 2], + block_shape=[3, 4, 2], + paddings=[[1, 2], [0, 0], [3, 0]]) + + def testDirect4(self): + self._testDirect( + input_shape=[3, 3, 4, 5, 2], + block_shape=[3, 4, 2, 2], + paddings=[[1, 2], [0, 0], [3, 0], [0, 0]]) + + def testDirect5(self): + self._testDirect( + input_shape=[3, 2, 2, 3, 4, 5, 2, 5], + block_shape=[1, 1, 3, 4, 2, 2], + paddings=[[0, 0], [0, 0], [1, 2], [0, 0], [3, 0], [0, 0]]) + + def testDirect6(self): + self._testDirect( + input_shape=[3, 2, 2, 3, 4, 5, 2, 5], + block_shape=[1, 1, 3, 4, 2, 2, 1], + paddings=[[0, 0], [0, 0], [1, 2], [0, 0], [3, 0], [0, 0], [0, 0]]) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/sparse_to_dense_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/sparse_to_dense_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..84481ae2460f1260a0e4c1795b5215004a419408 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/sparse_to_dense_op_test.py @@ -0,0 +1,124 @@ +# 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.kernels.sparse_op.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import sparse_ops +from tensorflow.python.platform import test + + +def _SparseToDense(sparse_indices, + output_size, + sparse_values, + default_value, + validate_indices=True): + feed_sparse_indices = array_ops.placeholder(dtypes.int32) + feed_dict = {feed_sparse_indices: sparse_indices} + return sparse_ops.sparse_to_dense( + feed_sparse_indices, + output_size, + sparse_values, + default_value=default_value, + validate_indices=validate_indices).eval(feed_dict=feed_dict) + + +class SparseToDenseTest(xla_test.XLATestCase): + + def testInt(self): + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([1, 3], [5], 1, 0) + np_ans = np.array([0, 1, 0, 1, 0]).astype(np.int32) + self.assertAllClose(np_ans, tf_ans) + + def testFloat(self): + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([1, 3], [5], 1.0, 0.0) + np_ans = np.array([0, 1, 0, 1, 0]).astype(np.float32) + self.assertAllClose(np_ans, tf_ans) + + def testSetValue(self): + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([1, 3], [5], [1, 2], -1) + np_ans = np.array([-1, 1, -1, 2, -1]).astype(np.int32) + self.assertAllClose(np_ans, tf_ans) + + def testSetSingleValue(self): + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([1, 3], [5], 1, -1) + np_ans = np.array([-1, 1, -1, 1, -1]).astype(np.int32) + self.assertAllClose(np_ans, tf_ans) + + def test2d(self): + # pylint: disable=bad-whitespace + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([[1, 3], [2, 0]], [3, 4], 1, -1) + np_ans = np.array([[-1, -1, -1, -1], + [-1, -1, -1, 1], + [ 1, -1, -1, -1]]).astype(np.int32) + self.assertAllClose(np_ans, tf_ans) + + def testZeroDefault(self): + with self.session(): + x = sparse_ops.sparse_to_dense(2, [4], 7).eval() + self.assertAllEqual(x, [0, 0, 7, 0]) + + def test3d(self): + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([[1, 3, 0], [2, 0, 1]], [3, 4, 2], 1, -1) + np_ans = np.ones((3, 4, 2), dtype=np.int32) * -1 + np_ans[1, 3, 0] = 1 + np_ans[2, 0, 1] = 1 + self.assertAllClose(np_ans, tf_ans) + + def testDegenerateIndexMatrix(self): + with self.session(), self.test_scope(): + tf_ans = _SparseToDense([[2], [3], [4], [5], [6], [7], [8], [9]], [10], + [1, 2, 3, 4, 5, 6, 7, 8], -1) + self.assertAllClose([-1, -1, 1, 2, 3, 4, 5, 6, 7, 8], tf_ans) + + def testBadShape(self): + with self.session(), self.test_scope(): + with self.assertRaisesWithPredicateMatch(ValueError, "must be rank 1"): + _SparseToDense([1, 3], [[5], [3]], 1, -1) + + @test_util.disable_mlir_bridge("Error handling") + def testBadValue(self): + with self.session(), self.test_scope(): + with self.assertRaisesOpError( + r"sparse_values has incorrect shape \[2,1\], " + r"should be \[\] or \[2\]"): + _SparseToDense([1, 3], [5], [[5], [3]], -1) + + @test_util.disable_mlir_bridge("Error handling") + def testBadNumValues(self): + with self.session(), self.test_scope(): + with self.assertRaisesOpError( + r"sparse_values has incorrect shape \[3\], should be \[\] or \[2\]"): + _SparseToDense([1, 3], [5], [1, 2, 3], -1) + + @test_util.disable_mlir_bridge("Error handling") + def testBadDefault(self): + with self.session(), self.test_scope(): + with self.assertRaisesOpError("default_value should be a scalar"): + _SparseToDense([1, 3], [5], [1, 2], [0]) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/special_math_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/special_math_test.py new file mode 100644 index 0000000000000000000000000000000000000000..510fbc15055d5bf78efb3837dce9c2edbec9e3ca --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/special_math_test.py @@ -0,0 +1,624 @@ +# Copyright 2020 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 special math operations.""" + +import os + +from absl import flags +from absl.testing import parameterized + +import numpy as np +import scipy.special as sps + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_function +from tensorflow.python.framework import constant_op +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_random_ops +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test + +flags.DEFINE_bool('vary_seed', False, + ('Whether to vary the PRNG seed unpredictably. ' + 'With --runs_per_test=N, produces N iid runs.')) + +NUM_SAMPLES = int(1e3) + + +@def_function.function(jit_compile=True) +def _igamma(a, x): + return math_ops.igamma(a, x) + + +@def_function.function(jit_compile=True) +def _igammac(a, x): + return math_ops.igammac(a, x) + + +@def_function.function(jit_compile=True) +def _polygamma(n, x): + return math_ops.polygamma(n, x) + + +@def_function.function(jit_compile=True) +def _zeta(a, q): + return math_ops.zeta(a, q) + + +# This is df/da / df/dx, where f = igamma. +def implicit_reparameterization_grad(a, x): + log_prob = math_ops.xlogy(a - 1., x) - math_ops.lgamma(a) - x + prob = math_ops.exp(log_prob) + return -gen_math_ops.igamma_grad_a(a, x) / prob + + +@def_function.function(jit_compile=True) +def _log1p(x): + return math_ops.log1p(x) + + +class Log1pTest(xla_test.XLATestCase, parameterized.TestCase): + + def setUp(self): + if flags.FLAGS.vary_seed: + entropy = os.urandom(64) + answer = int.from_bytes(entropy, 'big') + np.random.seed(answer % (2**32 - 1)) + super(Log1pTest, self).setUp() + + def adjust_tolerance(self, dtype, rtol, atol): + if self.device in ['TPU']: + if dtype == np.float32: + return 4e-4, 0.0 + return 1e-10, 0.0 + if self.device in ['XLA_GPU', 'GPU']: + if dtype == np.float32: + return max(rtol, 2.5e-07), atol + return rtol, atol + + def _test_range(self, low, high, dtype, rtol, atol, is_negative=False): + # Test values near zero. + rtol, atol = self.adjust_tolerance(dtype, rtol, atol) + x = np.exp(np.random.uniform( + low=low, high=high, size=[NUM_SAMPLES])).astype(dtype) + if is_negative: + x = -x + expected_values = np.log1p(x) + with self.session() as sess: + with self.test_scope(): + actual = _log1p(x) + actual = sess.run(actual) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-7, 0.), + (np.float64, 1e-15, 0.)) + def testSmallX(self, dtype, rtol, atol): + self._test_range(-40., -20., dtype, rtol, atol, is_negative=False) + self._test_range(-40., -20., dtype, rtol, atol, is_negative=True) + + @parameterized.parameters((np.float32, 2e-7, 0.), + (np.float64, 1e-15, 0.)) + def testGreaterThanNegativeTwentyExponent(self, dtype, rtol, atol): + self._test_range(-20., -10., dtype, rtol, atol, is_negative=False) + self._test_range(-20., -10., dtype, rtol, atol, is_negative=True) + + @parameterized.parameters((np.float32, 2e-7, 0.), + (np.float64, 1e-15, 0.)) + def testGreaterThanNegativeTenExponent(self, dtype, rtol, atol): + self._test_range(-10., -5., dtype, rtol, atol, is_negative=False) + self._test_range(-10., -5., dtype, rtol, atol, is_negative=True) + + @parameterized.parameters((np.float32, 2e-7, 0.), + (np.float64, 1e-15, 0.)) + def testGreaterThanNegativeFiveExponent(self, dtype, rtol, atol): + self._test_range(-5., -1., dtype, rtol, atol, is_negative=False) + self._test_range(-5., -1., dtype, rtol, atol, is_negative=True) + + @parameterized.parameters((np.float32, 4e-7, 0.), + (np.float64, 3e-14, 0.)) + def testXGreaterThanOneTenth(self, dtype, rtol, atol): + self._test_range(-1., 0., dtype, rtol, atol, is_negative=False) + self._test_range(-1., 0., dtype, rtol, atol, is_negative=True) + + @parameterized.parameters((np.float32, 2e-7, 0.), + (np.float64, 2e-15, 0.)) + def testXGreaterThanOne(self, dtype, rtol, atol): + self._test_range(0., 3., dtype, rtol, atol, is_negative=False) + + +class ZetaTest(xla_test.XLATestCase, parameterized.TestCase): + + def setUp(self): + if flags.FLAGS.vary_seed: + entropy = os.urandom(64) + answer = int.from_bytes(entropy, 'big') + np.random.seed(answer % (2**32 - 1)) + super(ZetaTest, self).setUp() + + def adjust_tolerance_for_tpu(self, dtype, rtol, atol): + if self.device not in ['TPU']: + return rtol, atol + + if dtype == np.float32: + return 2e-2, 1e-7 + return 2e-4, 1e-20 + + def testBadValues(self): + q = np.random.uniform(low=0.3, high=20., size=[10]) + with self.session() as sess: + with self.test_scope(): + y = _zeta(np.float64(1.), q) + actual = sess.run(y) + # When x == 1, this is the Harmonic series. + self.assertTrue(np.all(np.isinf(actual))) + + with self.session() as sess: + with self.test_scope(): + y = _zeta(np.float64(0.1), q) + actual = sess.run(y) + # When x < 1, this is undefined. + self.assertTrue(np.all(np.isnan(actual))) + + with self.session() as sess: + with self.test_scope(): + y = _zeta([1.1, 1.2, 2.1, 2.2, 3.1], [-2.0, -1.1, -1.0, -0.5, -0.1]) + actual = sess.run(y) + # For q <= 0, x must be an integer. + self.assertTrue(np.all(np.isnan(actual))) + + with self.session() as sess: + with self.test_scope(): + y = _zeta([2.0, 4.0, 6.0], [0.0, -1.0, -2.0]) + actual = sess.run(y) + # For integer q <= 0, zeta has poles with a defined limit of +inf where x is + # an even integer. + self.assertTrue(np.all(np.isinf(actual))) + + with self.session() as sess: + with self.test_scope(): + y = _zeta([3.0, 5.0, 7.0], [0.0, -1.0, -2.0]) + actual = sess.run(y) + # For non-positive integer q, zeta has poles with an undefined limit where x + # is an odd integer. + self.assertTrue(np.all(np.isnan(actual))) + + with self.session() as sess: + with self.test_scope(): + y = _zeta([1.1, 2.2, 3.3], [-1.1, -1.0, 0.0]) + actual = sess.run(y) + # For non-positive q, zeta is not defined if x is not an integer. + self.assertTrue(np.all(np.isnan(actual))) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testLargeXSmallQ(self, dtype, rtol, atol): + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + if self.device not in ['XLA_GPU', 'XLA_CPU'] and dtype == np.float64: + # TODO(b/165739664): Figure out why on TPU F64 Zeta sometimes returns + # infs. + self.skipTest( + 'Skipping test because some F64 operations are numerically ' + 'unstable on TPU.') + + x = np.random.uniform(low=100., high=200., size=[NUM_SAMPLES]).astype(dtype) + q = np.random.uniform(low=0.3, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.zeta(x, q) + with self.session() as sess: + with self.test_scope(): + y = _zeta(x, q) + actual = sess.run(y) + + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testSmallValues(self, dtype, rtol, atol): + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform(low=1.1, high=10., size=[NUM_SAMPLES]).astype(dtype) + q = np.random.uniform( + low=np.finfo(dtype).tiny, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.zeta(x, q) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_zeta(x, q)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testMediumValues(self, dtype, rtol, atol): + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + x = np.random.uniform(low=1.1, high=100., size=[NUM_SAMPLES]).astype(dtype) + q = np.random.uniform(low=1., high=1e1, size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.zeta(x, q) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_zeta(x, q)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 2e-2, 1e-5), (np.float64, 1e-4, 1e-30)) + def testLargeValues(self, dtype, rtol, atol): + x = np.random.uniform( + low=100., high=int(1e3), size=[NUM_SAMPLES]).astype(dtype) + q = np.random.uniform( + low=1., high=int(1e1), size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.zeta(x, q) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_zeta(x, q)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + +class PolygammaTest(xla_test.XLATestCase, parameterized.TestCase): + + def setUp(self): + if flags.FLAGS.vary_seed: + entropy = os.urandom(64) + answer = int.from_bytes(entropy, 'big') + np.random.seed(answer % (2**32 - 1)) + super(PolygammaTest, self).setUp() + + def adjust_tolerance_for_tpu(self, dtype, rtol, atol): + if self.device not in ['TPU']: + return rtol, atol + + if dtype == np.float32: + return 2e-2, 1e-7 + return 2e-4, 1e-20 + + def testBadValues(self): + x = np.random.uniform(low=0.3, high=20., size=[10]) + with self.session() as sess: + with self.test_scope(): + y = _polygamma(np.float64(-1.), x) + actual = sess.run(y) + # Not defined for negative numbers. + self.assertTrue(np.all(np.isnan(actual))) + + with self.session() as sess: + with self.test_scope(): + y = _polygamma(np.float64(0.1), x) + actual = sess.run(y) + # Not defined for non-integers. + self.assertTrue(np.all(np.isnan(actual))) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testRecoverDigamma(self, dtype, rtol, atol): + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + if self.device not in ['XLA_GPU', 'XLA_CPU'] and dtype == np.float64: + self.skipTest( + 'Skipping test because some F64 operations are ' + 'numerically unstable on TPU.' + ) + + x = np.random.uniform(low=0.1, high=50., size=[NUM_SAMPLES]).astype(dtype) + expected_values = sps.digamma(x) + with self.session() as sess: + with self.test_scope(): + y = _polygamma(dtype(0.), x) + actual = sess.run(y) + + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testSmallN(self, dtype, rtol, atol): + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + n = np.random.randint(low=1, high=5, size=[NUM_SAMPLES]).astype(dtype) + x = np.random.uniform( + low=np.finfo(dtype).tiny, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.polygamma(n, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_polygamma(n, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testMediumLargeN(self, dtype, rtol, atol): + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + n = np.random.randint(low=5, high=10, size=[NUM_SAMPLES]).astype(dtype) + x = np.random.uniform(low=1., high=1e1, size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.polygamma(n, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_polygamma(n, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + +class IgammaTest(xla_test.XLATestCase, parameterized.TestCase): + + def setUp(self): + if flags.FLAGS.vary_seed: + entropy = os.urandom(64) + answer = int.from_bytes(entropy, 'big') + np.random.seed(answer % (2**32 - 1)) + super(IgammaTest, self).setUp() + + # Skip Float64 test on TPU due to missing ops. + def maybe_skip_test(self, dtype): + if self.device not in ['XLA_GPU', 'XLA_CPU'] and dtype == np.float64: + self.skipTest( + 'Skipping test because some F64 operations not supported on TPU.') + + def adjust_tolerance_for_tpu(self, dtype, rtol, atol): + if self.device not in ['TPU']: + return rtol, atol + + if dtype == np.float32: + return 2e-2, 1e-7 + return 2e-4, 1e-20 + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testLargeXSmallA(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform(low=100., high=200., size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform(low=0.3, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammainc(a, x) + with self.session() as sess: + with self.test_scope(): + y = _igamma(a, x) + actual = sess.run(y) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testSmallValues(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform( + low=np.finfo(dtype).tiny, high=1., size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform( + low=np.finfo(dtype).tiny, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammainc(a, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_igamma(a, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testMediumValues(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform(low=1., high=100., size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform(low=1., high=100., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammainc(a, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_igamma(a, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 2e-2, 1e-5), (np.float64, 1e-4, 1e-30)) + def testLargeValues(self, dtype, rtol, atol): + if self.device == 'TPU': + # TODO(b/154908275): Remove this once fixed for large a, x. + self.skipTest('Skipping test since numerically unstable on TPU.') + # Test values near zero. + x = np.random.uniform( + low=100., high=int(1e4), size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform( + low=100., high=int(1e4), size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammainc(a, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_igamma(a, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + # We don't check small values because the numerical gradients become quite + # large. + @parameterized.parameters((np.float32, 0.09), (np.float64, 1e-7)) + def testGradMediumValues(self, dtype, tolerance): + self.maybe_skip_test(dtype) + with self.session(): + with self.test_scope(): + x = constant_op.constant( + np.random.uniform(low=1., high=100., + size=[NUM_SAMPLES]).astype(dtype)) + a = constant_op.constant( + np.random.uniform(low=1., high=100., + size=[NUM_SAMPLES]).astype(dtype)) + + f = lambda b: _igamma(b, x) + max_error = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient(f, x=[a], delta=1e-3)) + self.assertLessEqual(max_error, tolerance) + + @parameterized.parameters((np.float32, 0.5), (np.float64, 1e-7)) + def testGradLargeValues(self, dtype, tolerance): + self.maybe_skip_test(dtype) + with self.session(): + with self.test_scope(): + x = constant_op.constant( + np.random.uniform(low=100., high=int(1e4), + size=[NUM_SAMPLES]).astype(dtype)) + a = constant_op.constant( + np.random.uniform(low=100., high=int(1e4), + size=[NUM_SAMPLES]).astype(dtype)) + + f = lambda b: _igamma(b, x) + max_error = gradient_checker_v2.max_error( + *gradient_checker_v2.compute_gradient(f, x=[a], delta=1e-2)) + self.assertLessEqual(max_error, tolerance) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testRandomGammaGradSmallValues(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + + with self.session() as sess: + with self.test_scope(): + x = constant_op.constant( + np.random.uniform( + low=np.finfo(dtype).tiny, high=1., + size=[NUM_SAMPLES]).astype(dtype)) + a = constant_op.constant( + np.random.uniform( + low=np.finfo(dtype).tiny, high=1., + size=[NUM_SAMPLES]).astype(dtype)) + gamma_sample_grad = gen_random_ops.random_gamma_grad(a, x) + actual_grad = implicit_reparameterization_grad(a, x) + gamma_sample_grad, actual_grad = sess.run( + [gamma_sample_grad, actual_grad]) + # We do this because the ratio computed in + # implicit_reparameterization_grad can very easily result in a NaN due + # to the computed numerator and denominator zeroing out. + gamma_sample_grad = gamma_sample_grad[ + ~np.logical_or(np.isnan(actual_grad), np.isinf(actual_grad))] + actual_grad = actual_grad[ + ~np.logical_or(np.isnan(actual_grad), np.isinf(actual_grad))] + self.assertAllClose(actual_grad, gamma_sample_grad, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testRandomGammaGradMediumValues(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + + with self.session() as sess: + with self.test_scope(): + x = constant_op.constant( + np.random.uniform(low=1., high=10., + size=[NUM_SAMPLES]).astype(dtype)) + a = constant_op.constant( + np.random.uniform(low=1., high=10., + size=[NUM_SAMPLES]).astype(dtype)) + gamma_sample_grad = gen_random_ops.random_gamma_grad(a, x) + actual_grad = implicit_reparameterization_grad(a, x) + gamma_sample_grad, actual_grad = sess.run( + [gamma_sample_grad, actual_grad]) + # We do this because the ratio computed in + # implicit_reparameterization_grad can very easily result in a NaN due + # to the computed numerator and denominator zeroing out. + gamma_sample_grad = gamma_sample_grad[ + ~np.logical_or(np.isnan(actual_grad), np.isinf(actual_grad))] + actual_grad = actual_grad[ + ~np.logical_or(np.isnan(actual_grad), np.isinf(actual_grad))] + self.assertAllClose(actual_grad, gamma_sample_grad, atol=atol, rtol=rtol) + + +class IgammacTest(xla_test.XLATestCase, parameterized.TestCase): + + def setUp(self): + if flags.FLAGS.vary_seed: + entropy = os.urandom(64) + answer = int.from_bytes(entropy, 'big') + np.random.seed(answer % (2**32 - 1)) + super(IgammacTest, self).setUp() + + # Skip Float64 test on TPU due to missing ops. + def maybe_skip_test(self, dtype): + if self.device not in ['XLA_GPU', 'XLA_CPU'] and dtype == np.float64: + # TODO(b/154908275): Remove this once fixed for large a, x. + self.skipTest( + 'Skipping test because some F64 operations not supported on TPU.') + + def adjust_tolerance_for_tpu(self, dtype, rtol, atol): + if self.device not in ['TPU']: + return rtol, atol + + if dtype == np.float32: + return 2e-2, 1e-7 + return 2e-4, 1e-20 + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testLargeXSmallA(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform(low=100., high=200., size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform(low=0.3, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammaincc(a, x) + with self.session() as sess: + with self.test_scope(): + y = _igammac(a, x) + actual = sess.run(y) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testSmallValues(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform( + low=np.finfo(dtype).tiny, high=1., size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform( + low=np.finfo(dtype).tiny, high=1., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammaincc(a, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_igammac(a, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 1e-2, 1e-11), + (np.float64, 1e-4, 1e-30)) + def testMediumValues(self, dtype, rtol, atol): + self.maybe_skip_test(dtype) + rtol, atol = self.adjust_tolerance_for_tpu(dtype, rtol, atol) + # Test values near zero. + x = np.random.uniform(low=1., high=100., size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform(low=1., high=100., size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammaincc(a, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_igammac(a, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + @parameterized.parameters((np.float32, 2e-2, 1e-5), (np.float64, 1e-4, 1e-30)) + def testLargeValues(self, dtype, rtol, atol): + if self.device == 'TPU': + self.skipTest('Skipping test since numerically unstable on TPU.') + # Test values near zero. + x = np.random.uniform( + low=100., high=int(1e4), size=[NUM_SAMPLES]).astype(dtype) + a = np.random.uniform( + low=100., high=int(1e4), size=[NUM_SAMPLES]).astype(dtype) + + expected_values = sps.gammaincc(a, x) + with self.session() as sess: + with self.test_scope(): + actual = sess.run(_igammac(a, x)) + self.assertAllClose(expected_values, actual, atol=atol, rtol=rtol) + + +if __name__ == '__main__': + os.environ['XLA_FLAGS'] = '--xla_cpu_enable_fast_math=false' + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/stack_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stack_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..8c3dccd2725f73c4dd7d513aa5a8b7ed33fa73fa --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stack_ops_test.py @@ -0,0 +1,121 @@ +# 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 tensorflow.ops.stack_ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.compiler.xla import xla +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_data_flow_ops +from tensorflow.python.platform import test + + +class StackOpTest(xla_test.XLATestCase): + + def testStackPushPop(self): + with self.session(), self.test_scope(): + + v = array_ops.placeholder(dtypes.float32) + + def fn(): + h = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + c = gen_data_flow_ops.stack_push_v2(h, v) + with ops.control_dependencies([c]): + c1 = gen_data_flow_ops.stack_pop_v2(h, dtypes.float32) + return c1 + + self.assertAllClose([[4.0, 5.0]], + xla.compile(fn)[0].eval({v: [[4.0, 5.0]]})) + + def testStackPushPopSwap(self): + with self.session(), self.test_scope(): + a = np.arange(2000) + x = array_ops.placeholder(dtypes.float32) + + def fn(): + h = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + c = gen_data_flow_ops.stack_push_v2(h, x, swap_memory=True) + with ops.control_dependencies([c]): + return gen_data_flow_ops.stack_pop_v2(h, dtypes.float32) + + self.assertAllClose(a, xla.compile(fn)[0].eval({x: a})) + + def testMultiStack(self): + with self.session(), self.test_scope(): + v = array_ops.placeholder(dtypes.float32) + + def fn(): + h1 = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + c1 = gen_data_flow_ops.stack_push_v2(h1, v) + with ops.control_dependencies([c1]): + c1 = gen_data_flow_ops.stack_pop_v2(h1, dtypes.float32) + h2 = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="bar") + c2 = gen_data_flow_ops.stack_push_v2(h2, 5.0) + with ops.control_dependencies([c2]): + c2 = gen_data_flow_ops.stack_pop_v2(h2, dtypes.float32) + return c1 + c2 + + self.assertAllClose(9.0, xla.compile(fn)[0].eval({v: 4.0})) + + def testSameNameStacks(self): + """Different stacks with the same name do not interfere.""" + with self.session() as sess, self.test_scope(): + v1 = array_ops.placeholder(dtypes.float32) + v2 = array_ops.placeholder(dtypes.float32) + + def fn(): + h1 = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + h2 = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + + c1 = gen_data_flow_ops.stack_push_v2(h1, v1) + with ops.control_dependencies([c1]): + c2 = gen_data_flow_ops.stack_push_v2(h2, v2) + with ops.control_dependencies([c2]): + pop1 = gen_data_flow_ops.stack_pop_v2(h1, dtypes.float32) + pop2 = gen_data_flow_ops.stack_pop_v2(h2, dtypes.float32) + return [pop1, pop2] + + [pop1_compiled, pop2_compiled] = xla.compile(fn) + out1, out2 = sess.run([pop1_compiled, pop2_compiled], {v1: 4.0, v2: 5.0}) + self.assertAllClose(out1, 4.0) + self.assertAllClose(out2, 5.0) + + def testCloseStack(self): + with self.session() as sess, self.test_scope(): + + def fn(): + h = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + gen_data_flow_ops.stack_close_v2(h) + + sess.run(xla.compile(fn)) + + def testPushCloseStack(self): + with self.session() as sess, self.test_scope(): + v = array_ops.placeholder(dtypes.float32) + + def fn(): + h = gen_data_flow_ops.stack_v2(5, dtypes.float32, stack_name="foo") + c = gen_data_flow_ops.stack_push_v2(h, v) + with ops.control_dependencies([c]): + gen_data_flow_ops.stack_close_v2(h) + + sess.run(xla.compile(fn), {v: [[4.0, 5.0]]}) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/stateful_random_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stateful_random_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7ddce51d58fc172b20fe21cef0ae995cd904d9dd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stateful_random_ops_test.py @@ -0,0 +1,389 @@ +# Copyright 2019 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 stateful random-number generation ops.""" + +import itertools +import os + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.client import device_lib +from tensorflow.python.eager import def_function +from tensorflow.python.framework import config +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.kernel_tests.random import util as \ +random_test_util +from tensorflow.python.ops import gen_stateful_random_ops +from tensorflow.python.ops import random_ops_util +from tensorflow.python.ops import stateful_random_ops as \ +random +from tensorflow.python.ops import variables +from tensorflow.python.platform import flags +from tensorflow.python.platform import test + + +FLAGS = flags.FLAGS + + +def xla_device(): + devices = device_lib.list_local_devices() + def find_type(device_type): + for d in devices: + if d.device_type == device_type: + return d + return None + d = find_type("TPU") or find_type("XLA_GPU") or find_type("XLA_CPU") + if d is None: + raise ValueError( + "Can't find any XLA device. Available devices:\n%s" % devices) + return d + + +def xla_device_name(): + return str(xla_device().name) + + +ALGS = [ + random_ops_util.Algorithm.PHILOX.value, + random_ops_util.Algorithm.THREEFRY.value, + random_ops_util.Algorithm.AUTO_SELECT.value, +] +INTS = [dtypes.int32, dtypes.uint32, dtypes.int64, dtypes.uint64] +FLOATS = [dtypes.bfloat16, dtypes.float32, dtypes.float64] + + +class StatefulRandomOpsTest(xla_test.XLATestCase, parameterized.TestCase): + """Test cases for stateful random-number generator operators.""" + + @parameterized.parameters(ALGS) + def testSimple(self, alg): + """A simple test.""" + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=0, alg=alg) + gen.normal(shape=(3,)) + gen.uniform(shape=(3,), minval=0, maxval=10, dtype=dtypes.uint32) + gen.uniform_full_int(shape=(3,)) + + @parameterized.parameters(ALGS) + def testDefun(self, alg): + """Test for defun.""" + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=0, alg=alg) + @def_function.function + def f(): + x = gen.normal(shape=(3,)) + y = gen.uniform(shape=(3,), minval=0, maxval=10, dtype=dtypes.uint32) + z = gen.uniform_full_int(shape=(3,)) + return (x, y, z) + f() + + def _compareToKnownOutputs(self, g, counter, key, expect): + """Compares against known outputs for specific counter and key inputs.""" + def uint32s_to_uint64(a, b): + return b << 32 | a + + def uint32s_to_uint64s(ls): + return [uint32s_to_uint64(ls[2 * i], ls[2 * i + 1]) + for i in range(len(ls) // 2)] + + ctr_len = len(counter) + counter = uint32s_to_uint64s(counter) + key = uint32s_to_uint64s(key) + state = counter + key + g.reset(state) + got = g.uniform_full_int(shape=(ctr_len,), dtype=dtypes.uint32) + self.assertAllEqual(expect, got) + g.reset(state) + got = g.uniform_full_int(shape=(ctr_len // 2,), dtype=dtypes.uint64) + self.assertAllEqual(uint32s_to_uint64s(expect), got) + + def testThreefry2x32(self): + """Tests ThreeFry2x32 conforms to known results. + """ + # Based on + # https://github.com/google/jax/blob/8565a3486adf16beb388b2364c9cd930d7a0d92d/tests/random_test.py#L65-L85 + # which is in turn based on + # https://github.com/DEShawResearch/Random123-Boost/blob/65e3d874b67aa7b3e02d5ad8306462f52d2079c0/libs/random/test/test_threefry.cpp#L30-L32 + + with ops.device(xla_device_name()): + g = random.Generator.from_seed(seed=0, alg=random.RNG_ALG_THREEFRY) + self._compareToKnownOutputs( + g, + [0x00000000, 0x00000000], [0x00000000, 0x00000000], + [0x6b200159, 0x99ba4efe]) + self._compareToKnownOutputs( + g, + [0xffffffff, 0xffffffff], [0xffffffff, 0xffffffff], + [0x1cb996fc, 0xbb002be7]) + self._compareToKnownOutputs( + g, + [0x243f6a88, 0x85a308d3], [0x13198a2e, 0x03707344], + [0xc4923a9c, 0x483df7a0]) + + def testPhilox4x32(self): + """Tests Philox4x32 conforms to known results. + """ + # Based on + # https://github.com/DEShawResearch/Random123-Boost/blob/65e3d874b67aa7b3e02d5ad8306462f52d2079c0/libs/random/test/test_philox.cpp#L50-L52 + + with ops.device(xla_device_name()): + g = random.Generator.from_seed(seed=0, alg=random.RNG_ALG_PHILOX) + self._compareToKnownOutputs( + g, + [0x00000000, 0x00000000, 0x00000000, 0x00000000], + [0x00000000, 0x00000000], + [0x6627e8d5, 0xe169c58d, 0xbc57ac4c, 0x9b00dbd8]) + self._compareToKnownOutputs( + g, + [0xffffffff, 0xffffffff, 0xffffffff, 0xffffffff], + [0xffffffff, 0xffffffff], + [0x408f276d, 0x41c83b0e, 0xa20bc7c6, 0x6d5451fd]) + self._compareToKnownOutputs( + g, + [0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344], + [0xa4093822, 0x299f31d0], + [0xd16cfe09, 0x94fdcceb, 0x5001e420, 0x24126ea1]) + + @parameterized.parameters(INTS) + def testXLAEqualsCPU(self, dtype): + """Tests that XLA and CPU kernels generate the same integers.""" + seed = 1234 + shape = [315, 49] + with ops.device("/device:CPU:0"): + cpu_gen = random.Generator.from_seed(seed=seed, alg=random.RNG_ALG_PHILOX) + with ops.device(xla_device_name()): + xla_gen = random.Generator.from_seed(seed=seed, alg=random.RNG_ALG_PHILOX) + # Repeat multiple times to make sure that the state after + # number-generation are the same between CPU and XLA. + for _ in range(5): + with ops.device("/device:CPU:0"): + # Test both number-generation and skip + cpu = cpu_gen.uniform_full_int(shape=shape, dtype=dtype) + cpu_gen.skip(100) + with ops.device(xla_device_name()): + xla = xla_gen.uniform_full_int(shape=shape, dtype=dtype) + xla_gen.skip(100) + self.assertAllEqual(cpu, xla) + self.assertAllEqual(cpu_gen.state, xla_gen.state) + + def testXLAEqualsCPUAroundCounterOverflow(self): + """Tests XLA and CPU kernels generate the same integers in overflow case. + + Specifically this tests the case where the counter is incremented past + what can fit within 64 bits of the 128 bit Philox counter. + """ + dtype = dtypes.uint64 + seed = 2**64 - 10 + shape = [315, 49] + with ops.device("/device:CPU:0"): + cpu_gen = random.Generator.from_seed(seed=seed, alg=random.RNG_ALG_PHILOX) + with ops.device(xla_device_name()): + xla_gen = random.Generator.from_seed(seed=seed, alg=random.RNG_ALG_PHILOX) + # Repeat multiple times to make sure that the state after + # number-generation are the same between CPU and XLA. + for _ in range(5): + with ops.device("/device:CPU:0"): + # Test both number-generation and skip + cpu = cpu_gen.uniform_full_int(shape=shape, dtype=dtype) + cpu_gen.skip(100) + with ops.device(xla_device_name()): + xla = xla_gen.uniform_full_int(shape=shape, dtype=dtype) + xla_gen.skip(100) + self.assertAllEqual(cpu, xla) + self.assertAllEqual(cpu_gen.state, xla_gen.state) + self.assertAllEqual(cpu, xla) + + def _testRngIsNotConstant(self, rng, dtype): + # Tests that 'rng' does not always return the same value. + # The random-number generator, if working correctly, should produce the + # same output multiple times with low probability. + x = rng(dtype).numpy() + y = rng(dtype).numpy() + self.assertFalse(np.array_equal(x, y)) + + def check_dtype(self, dtype): + device = xla_device() + if device.device_type == "TPU" and dtype == dtypes.float64: + self.skipTest("TPU doesn't support float64.") + + @parameterized.parameters(list(itertools.product(ALGS, INTS + FLOATS))) + def testUniformIsNotConstant(self, alg, dtype): + self.check_dtype(dtype) + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=1234, alg=alg) + def rng(dtype): + maxval = dtype.max + return gen.uniform(shape=[2], dtype=dtype, maxval=maxval) + + self._testRngIsNotConstant(rng, dtype) + + @parameterized.parameters(list(itertools.product(ALGS, FLOATS))) + def testNormalIsNotConstant(self, alg, dtype): + self.check_dtype(dtype) + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=1234, alg=alg) + def rng(dtype): + return gen.normal(shape=[2], dtype=dtype) + + self._testRngIsNotConstant(rng, dtype) + + @parameterized.parameters(list(itertools.product(ALGS, INTS + FLOATS))) + def testUniformIsInRange(self, alg, dtype): + self.check_dtype(dtype) + minval = 2 + maxval = 33 + size = 1000 + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=1234, alg=alg) + x = gen.uniform( + shape=[size], dtype=dtype, minval=minval, maxval=maxval).numpy() + self.assertTrue(np.all(x >= minval)) + self.assertTrue(np.all(x <= maxval)) + + @parameterized.parameters(list(itertools.product(ALGS, FLOATS))) + def testNormalIsFinite(self, alg, dtype): + self.check_dtype(dtype) + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=1234, alg=alg) + x = gen.normal(shape=[10000], dtype=dtype).numpy() + self.assertTrue(np.all(np.isfinite(x))) + + @parameterized.parameters(list(itertools.product( + ALGS, INTS + FLOATS, (12, 13, 123, 4321)))) + def testDistributionOfUniform(self, alg, dtype, seed): + """Use Pearson's Chi-squared test to test for uniformity.""" + self.check_dtype(dtype) + three_fry = random_ops_util.Algorithm.THREEFRY.value + auto_select = random_ops_util.Algorithm.AUTO_SELECT.value + is_tpu = xla_device().device_type == "TPU" + is_megacore = "megacore" in os.environ.get("TEST_TARGET", "").lower() + # TODO(b/244649364): Investigate why these combinations fail. + if ((alg, dtype, seed) in [(three_fry, dtypes.int64, 123), + (three_fry, dtypes.uint64, 123)] or + is_tpu and + (alg, dtype, seed) in [(auto_select, dtypes.int64, 123), + (auto_select, dtypes.uint64, 123)] or + is_megacore and + (alg, dtype, seed) in [(auto_select, dtypes.int32, 123), + (auto_select, dtypes.uint32, 123), + (auto_select, dtypes.int32, 12), + (auto_select, dtypes.uint32, 12)]): + self.skipTest( + "This (device, alg, dtype, seed) combination fails (b/244649364).") + with ops.device(xla_device_name()): + n = 1000 + gen = random.Generator.from_seed(seed=seed, alg=alg) + maxval = 1 + if dtype.is_integer: + maxval = 100 + t = gen.uniform(shape=[n], maxval=maxval, dtype=dtype) + x = t.numpy().astype(float) + if maxval > 1: + # Normalize y to range [0, 1). + x = x / maxval + # Tests that the values are distributed amongst 10 bins with equal + # probability. 16.92 is the Chi^2 value for 9 degrees of freedom with + # p=0.05. This test is probabilistic and would be flaky if the random + # seed were not fixed. + val = random_test_util.chi_squared(x, 10) + self.assertLess(val, 16.92) + + @parameterized.parameters(list(itertools.product(ALGS, FLOATS))) + def testDistributionOfNormal(self, alg, dtype): + """Use Anderson-Darling test to test distribution appears normal.""" + self.check_dtype(dtype) + with ops.device(xla_device_name()): + n = 1000 + gen = random.Generator.from_seed(seed=1234, alg=alg) + x = gen.normal(shape=[n], dtype=dtype).numpy() + # The constant 2.492 is the 5% critical value for the Anderson-Darling + # test where the mean and variance are known. This test is probabilistic + # so to avoid flakiness the seed is fixed. + self.assertLess( + random_test_util.anderson_darling(x.astype(float)), 2.492) + + @parameterized.parameters(list(itertools.product(ALGS, FLOATS))) + def testTruncatedNormal(self, alg, dtype): + self.check_dtype(dtype) + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=123, alg=alg) + n = 100000 + y = gen.truncated_normal(shape=[n], dtype=dtype).numpy() + random_test_util.test_truncated_normal( + self.assertEqual, self.assertAllClose, n, y, + mean_atol=2e-3, median_atol=4e-3, + variance_rtol=1e-2 if dtype == dtypes.bfloat16 else 5e-3) + + @test_util.disable_mlir_bridge( + "b/180412086: MLIR bridge gives wrong error messages.") + def testErrors(self): + """Tests that proper errors are raised. + """ + shape = [2, 3] + with ops.device(xla_device_name()): + gen = random.Generator.from_seed(seed=1234, alg=random.RNG_ALG_THREEFRY) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + r"algorithm.* must be of shape \[\], not"): + gen_stateful_random_ops.stateful_standard_normal_v2( + gen.state.handle, [0, 0], shape) + with self.assertRaisesWithPredicateMatch( + TypeError, "EagerTensor of dtype int64"): + gen_stateful_random_ops.stateful_standard_normal_v2( + gen.state.handle, 1.1, shape) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + "Unsupported algorithm id"): + gen_stateful_random_ops.stateful_standard_normal_v2( + gen.state.handle, 123, shape) + with self.assertRaisesWithPredicateMatch(errors_impl.InvalidArgumentError, + "Unsupported algorithm id"): + gen_stateful_random_ops.rng_read_and_skip( + gen.state.handle, alg=123, delta=10) + var = variables.Variable([0, 0], dtype=dtypes.uint32) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + "Trying to read variable .* Expected int64 got"): + gen_stateful_random_ops.stateful_standard_normal_v2( + var.handle, random.RNG_ALG_THREEFRY, shape) + var = variables.Variable([[0]], dtype=dtypes.int64) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + "RNG state must have one and only one dimension, not"): + gen_stateful_random_ops.stateful_standard_normal_v2( + var.handle, random.RNG_ALG_THREEFRY, shape) + var = variables.Variable([0], dtype=dtypes.int64) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + "The size of the state must be at least"): + gen_stateful_random_ops.stateful_standard_normal_v2( + var.handle, random.RNG_ALG_THREEFRY, shape) + var = variables.Variable([0, 0], dtype=dtypes.int64) + with self.assertRaisesWithPredicateMatch( + errors_impl.InvalidArgumentError, + "The size of the state must be at least"): + gen_stateful_random_ops.stateful_standard_normal_v2( + var.handle, random.RNG_ALG_PHILOX, shape) + + +if __name__ == "__main__": + ops.enable_eager_execution() + config.set_soft_device_placement(False) + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/stateless_random_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stateless_random_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..bf4638299f8d7c155157508a18f2b0508fbb7972 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stateless_random_ops_test.py @@ -0,0 +1,457 @@ +# 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 stateless random-number generation ops.""" + +import functools + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.client import device_lib +from tensorflow.python.eager import def_function +from tensorflow.python.framework import config +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import test_util +from tensorflow.python.kernel_tests.random import util as \ +random_test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_stateless_random_ops_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops_util +from tensorflow.python.ops import stateless_random_ops as stateless +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +def xla_device(): + devices = device_lib.list_local_devices() + + def find_type(device_type): + for d in devices: + if d.device_type == device_type: + return d + return None + + d = find_type('TPU') or find_type('XLA_GPU') or find_type('XLA_CPU') + if d is None: + raise ValueError('Cannot find any XLA device. Available devices:\n%s' % + devices) + return d + + +def _allowed_types(include_int=False): + allowed_types = { + dtypes.float64, dtypes.float32, dtypes.float16, dtypes.bfloat16 + } + if include_int: + allowed_types.update({dtypes.int32, dtypes.int64}) + return allowed_types + + +class StatelessRandomOpsTest(xla_test.XLATestCase, parameterized.TestCase): + """Test cases for stateless random-number generator operators.""" + + def _random_types(self, include_int=False): + return self.all_tf_types & _allowed_types(include_int) + + @test_util.run_v2_only + def testForcedCompile(self): + """Tests whole-function forced-compilation. + + This test checks that stateless_random_* can be used in forced-compilation + scenarios (e.g. TPU). The new version of stateless_random_* requires the + intermediate tensor `alg` to be compile-time constant, so we need to check + that this requirement won't prevent `seed` from depending on variables. + """ + if config.list_logical_devices('TPU'): + self.skipTest('To accommodate OSS, experimental_compile support for TPU ' + 'is not linked in.') + # GPU doesn't support int32 variables, so we use int64. + v = variables.Variable([1, 2], dtype=dtypes.int64) + + @def_function.function(experimental_compile=True) + def f(): + key, counter = ( + gen_stateless_random_ops_v2.stateless_random_get_key_counter( + seed=math_ops.cast(v.read_value(), dtypes.int32))) + alg = gen_stateless_random_ops_v2.stateless_random_get_alg() + return gen_stateless_random_ops_v2.stateless_random_normal_v2( + shape=[], key=key, counter=counter, alg=alg) + + f() + + @test_util.run_v2_only + def testGetKeyCounterAlg(self): + seed = [1, 2] + key, counter = gen_stateless_random_ops_v2.stateless_random_get_key_counter( + seed) + self.assertAllEqual(key.shape, [1]) + self.assertAllEqual(counter.shape, [2]) + alg = gen_stateless_random_ops_v2.stateless_random_get_alg() + self.assertAllEqual(alg.shape, []) + + @parameterized.named_parameters( + ('_%s_%s' % (op_id, alg_id), op, alg_group) # pylint: disable=g-complex-comprehension + for alg_id, alg_group in enumerate([ + [ + random_ops_util.Algorithm.PHILOX, + random_ops_util.Algorithm.PHILOX.value, + 'philox', + ], + [ + random_ops_util.Algorithm.THREEFRY, + random_ops_util.Algorithm.THREEFRY.value, + 'threefry', + ], + [ + random_ops_util.Algorithm.AUTO_SELECT, + random_ops_util.Algorithm.AUTO_SELECT.value, + 'auto_select', + None, + ], + ]) + for op_id, op in enumerate([ + stateless.stateless_random_normal, + stateless.stateless_truncated_normal, + functools.partial( + stateless.stateless_random_uniform, + dtype=dtypes.uint32, + minval=None, + maxval=None, + ), + functools.partial( + stateless.stateless_random_uniform, dtype=dtypes.int32, maxval=100 + ), + functools.partial( + stateless.stateless_random_uniform, dtype=dtypes.float32 + ), + ]) + ) + @test_util.run_v2_only + def testAlg(self, op, alg_group): + """Tests all values of `alg`.""" + if config.list_logical_devices('TPU') or config.list_logical_devices('GPU'): + self.skipTest('Only _cpu tests linked in support for jit_compile on CPU.') + seed = [1, 2] + shape = [2, 3] + outputs = [] + for alg in alg_group: + with ops.device('CPU'): + output = def_function.function(jit_compile=True)(op)( + shape=shape, seed=seed, alg=alg) + self.assertEqual(output.shape, shape) + outputs.append(output) + x = outputs[0] + for y in outputs[1:]: + self.assertAllEqual(x, y) + + def testLargeNormal(self): + """Tests an OOM bug of StatelessRandomNormalV2 on TPU.""" + with self.session() as sess, self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + key, counter, alg = (gen_stateless_random_ops_v2. + stateless_random_get_key_counter_alg(seed_t)) + x = gen_stateless_random_ops_v2.stateless_random_normal_v2( + shape=[1024, 32000], key=key, counter=counter, dtype=dtypes.float32, + alg=alg) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + self.assertAllEqual([1024, 32000], y.shape) + key, counter = (gen_stateless_random_ops_v2. + stateless_random_get_key_counter(seed_t)) + alg = gen_stateless_random_ops_v2.stateless_random_get_alg() + x = gen_stateless_random_ops_v2.stateless_random_normal_v2( + shape=[1024, 32000], key=key, counter=counter, dtype=dtypes.float32, + alg=alg) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + self.assertAllEqual([1024, 32000], y.shape) + + @parameterized.named_parameters( + (f'_{op_name}_{shape}_{dtype.name}', stateless_op, shape, dtype) # pylint: disable=g-complex-comprehension + for dtype in _allowed_types() for shape in ((), (3,), (2, 5)) + for op_name, stateless_op in ( + ('uniform', stateless.stateless_random_uniform), + ('normal', stateless.stateless_random_normal), + )) + def testDeterminism(self, stateless_op, shape, dtype): + # Stateless values should be equal iff the seeds are equal (roughly) + seeds = [(x, y) for x in range(-2, 3) for y in range(-2, 3)] * 3 # pylint: disable=g-complex-comprehension + with self.session(), self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + pure = stateless_op(shape, seed=seed_t, dtype=dtype) + values = [(seed, pure.eval(feed_dict={seed_t: seed})) for seed in seeds] + for s0, v0 in values: + for s1, v1 in values: + if s0 == s1: + self.assertAllEqual(v0, v1) + else: + # The resolutions of float16 and bfloat16 are too low, so + # in some cases (e.g. scalar shape) different seeds may + # lead to the same output. So we skip those dtypes. + if not (dtype in (dtypes.bfloat16, dtypes.float16) and shape == ()): # pylint: disable=g-explicit-bool-comparison + self.assertNotAllEqual(v0, v1) + + def testRandomUniformIsInRange(self): + with self.session() as sess, self.test_scope(): + for dtype in self._random_types(include_int=True): + maxval = 1 + if dtype.is_integer: + maxval = 100 + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + x = stateless.stateless_random_uniform( + shape=[1000], seed=seed_t, maxval=maxval, dtype=dtype) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + self.assertTrue(np.all(y >= 0)) + self.assertTrue(np.all(y < maxval)) + + @parameterized.named_parameters( + (f'_{alg.name}_{dtype.name}_{seed}', alg, dtype, seed) # pylint: disable=g-complex-comprehension + for seed in ([1, 2], [12, 23], [123, 456], [565656, 121212]) + for dtype in _allowed_types(include_int=True) + for alg in list(random_ops_util.Algorithm) + ) + def testDistributionOfStatelessRandomUniform(self, alg, dtype, seed): + """Use Pearson's Chi-squared test to test for uniformity.""" + philox = random_ops_util.Algorithm.PHILOX + auto_select = random_ops_util.Algorithm.AUTO_SELECT + device = xla_device() + if 'CPU' in device.device_type: + device_type = 'CPU' + elif 'GPU' in device.device_type: + device_type = 'GPU' + elif device.device_type == 'TPU': + device_type = 'TPU' + else: + device_type = None + bad_combos1 = [ + (dtypes.int32, [123, 456]), + (dtypes.int64, [123, 456]), + (dtypes.float16, [565656, 121212]), + (dtypes.bfloat16, [1, 2]), + ] + bad_combos2 = [ + (dtypes.int32, [1, 2]), + (dtypes.int32, [12, 23]), + ] + # TODO(b/244649364): Investigate why these combinations fail. + if (device_type in ('CPU', 'GPU') and alg in (philox, auto_select) and + (dtype, seed) in bad_combos1 or device_type == 'TPU' and + (alg == philox and + (dtype, seed) in bad_combos1 or alg == auto_select and + (dtype, seed) in bad_combos2)): + self.skipTest( + 'This (device, alg, dtype, seed) combination fails (b/244649364).') + with self.session() as sess, self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + n = 1000 + maxval = 1 + if dtype.is_integer: + maxval = 100 + x = stateless.stateless_random_uniform( + shape=[n], seed=seed_t, maxval=maxval, dtype=dtype, alg=alg) + y = sess.run(x, {seed_t: seed}) + # Convert y to float and normalize its value to range [0, 1) when + # maxval != 1. + y = y.astype(float) / maxval + # Tests that the values are distributed amongst 10 bins with equal + # probability. 27.88 is the Chi^2 value for 9 degrees of freedom with + # p=0.001. This test is probabilistic and would be flaky if the random + # seed were not fixed. + bins = 10 + self.assertLess(random_test_util.chi_squared(y, bins), 27.88) + + def testRandomNormalIsFinite(self): + with self.session() as sess, self.test_scope(): + for dtype in self._random_types(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + x = stateless.stateless_random_normal( + shape=[10000], seed=seed_t, dtype=dtype) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + self.assertTrue(np.all(np.isfinite(y))) + + @parameterized.named_parameters( + (f'_{dtype.name}_{seed}', dtype, seed) # pylint: disable=g-complex-comprehension + for seed in ([1, 2], [12, 23], [25252, 314159]) + for dtype in _allowed_types() + ) + def testDistributionOfStatelessRandomNormal(self, dtype, seed): + """Use Anderson-Darling test to test distribution appears normal.""" + with self.session() as sess, self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + n = 1000 + x = stateless.stateless_random_normal(shape=[n], seed=seed_t, dtype=dtype) + y = sess.run(x, {seed_t: seed}) + # The constant 2.492 is the 5% critical value for the Anderson-Darling + # test where the mean and variance are known. This test is probabilistic + # so to avoid flakiness the seed is fixed. + self.assertLess(random_test_util.anderson_darling(y.astype(float)), 2.492) + + @parameterized.named_parameters( + (f'_{dtype.name}', dtype) for dtype in _allowed_types()) + def testTruncatedNormal(self, dtype): + with self.session() as sess, self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + n = 10000000 + x = stateless.stateless_truncated_normal( + shape=[n], seed=seed_t, dtype=dtype) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + if dtype == dtypes.float16: + mean_atol = 2e-3 + else: + mean_atol = 5e-4 + + if dtype == dtypes.float16: + median_atol = 2e-3 + else: + median_atol = 8e-4 + + if dtype == dtypes.bfloat16: + variance_rtol = 6e-3 + elif dtype == dtypes.float16: + variance_rtol = 3e-3 + else: + variance_rtol = 1e-3 + + random_test_util.test_truncated_normal( + self.assertEqual, + self.assertAllClose, + n, + y, + mean_atol=mean_atol, + median_atol=median_atol, + variance_rtol=variance_rtol) + + def _testParameterizedTruncatedNormal(self, + means, + stddevs, + minvals, + maxvals, + variance_rtol=None): + if 'CPU' in xla_device().device_type: + n = int(1e7) + else: + n = int(10e7) + for dtype in self._random_types(): + with self.session() as sess, self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + x = stateless.stateless_parameterized_truncated_normal( + shape=[n], + seed=seed_t, + means=means, + stddevs=stddevs, + minvals=minvals, + maxvals=maxvals) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + if variance_rtol is None: + variance_rtol = 6e-3 if dtype == dtypes.bfloat16 else 1e-3 + random_test_util.test_truncated_normal( + self.assertEqual, + self.assertAllClose, + n, + y, + means=means, + stddevs=stddevs, + minvals=minvals, + maxvals=maxvals, + mean_atol=1e-3, + median_atol=1e-3, + variance_rtol=variance_rtol) + + def testParameterizedTruncatedNormalDefault(self): + self._testParameterizedTruncatedNormal(0., 1., -2., 2.) + + def testParameterizedTruncatedNormalShifted(self): + self._testParameterizedTruncatedNormal(-1., 1., -2., 2.) + + def testParameterizedTruncatedNormalRightTail(self): + self.skipTest('b/276957102') + self._testParameterizedTruncatedNormal(0., 1., 4., 20., variance_rtol=2e-2) + + def testParameterizedTruncatedNormalLeftTail(self): + self.skipTest('b/276957102') + self._testParameterizedTruncatedNormal( + 0., 1., -20., -4., variance_rtol=5e-2) + + def testParameterizedTruncatedNormalLeftTailTwoSidedBounds(self): + self._testParameterizedTruncatedNormal( + 0., 1., -6., -3., variance_rtol=5e-2) + + def testParameterizedTruncatedNormalSmallStddev(self): + self._testParameterizedTruncatedNormal(0., 0.1, 0.05, 0.10) + + def testParameterizedTruncatedNormalBroadcast(self): + with self.session() as sess, self.test_scope(): + seed_t = array_ops.placeholder(dtypes.int32, shape=[2]) + means = array_ops.zeros([2], dtype=dtypes.float32) + stddevs = array_ops.ones([3, 1], dtype=dtypes.float32) + minvals = -array_ops.ones([5, 1, 1], dtype=dtypes.float32) + maxvals = array_ops.ones([7, 1, 1, 1], dtype=dtypes.float32) + shape = [11, 7, 5, 3, 2] + x = stateless.stateless_parameterized_truncated_normal( + shape=shape, + seed=seed_t, + means=means, + stddevs=stddevs, + minvals=minvals, + maxvals=maxvals) + y = sess.run(x, {seed_t: [0x12345678, 0xabcdef1]}) + self.assertEqual((11, 7, 5, 3, 2), y.shape) + + +class StatelessRandomOpsBenchmark(test.Benchmark): + """Microbenchmarks for the stateless random ops.""" + + def _benchmarkUniform(self, name, dtype, use_xla_jit): + + def builder_fn(): + shape = (10, 1000, 1000) + seed_var = variables.Variable((312, 456), + dtype=dtypes.int32, + name='input') + random_t = stateless.stateless_random_uniform( + shape, seed=seed_var, dtype=dtype) + return '%s.shape%s' % (name, shape), [random_t] + + xla_test.Benchmark(self, builder_fn, use_xla_jit=use_xla_jit, device='cpu') + + def benchmarkUniformF16(self): + self._benchmarkUniform( + 'uniform_f16', dtype=dtypes.float16, use_xla_jit=False) + + def benchmarkUniformF32(self): + self._benchmarkUniform( + 'uniform_f32', dtype=dtypes.float32, use_xla_jit=False) + + def benchmarkUniformF64(self): + self._benchmarkUniform( + 'uniform_f64', dtype=dtypes.float64, use_xla_jit=False) + + def benchmarkUniformF16XLA(self): + self._benchmarkUniform( + 'uniform_f16', dtype=dtypes.float16, use_xla_jit=True) + + def benchmarkUniformF32XLA(self): + self._benchmarkUniform( + 'uniform_f32', dtype=dtypes.float32, use_xla_jit=True) + + def benchmarkUniformF64XLA(self): + self._benchmarkUniform( + 'uniform_f64', dtype=dtypes.float64, use_xla_jit=True) + + +if __name__ == '__main__': + config.set_soft_device_placement(False) + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/stochastic_cast_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stochastic_cast_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..879b2536ad18b460488115a51828ef0aa587ecb4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/stochastic_cast_op_test.py @@ -0,0 +1,111 @@ +# Copyright 2023 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 stochastic cast op generation ops.""" + +import math + +from absl.testing import parameterized + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import stochastic_cast_op +from tensorflow.python.platform import test + + +def _allowed_from_types(): + return { + dtypes.float64, + dtypes.float32, + dtypes.float16, + dtypes.bfloat16, + dtypes.half, + } + + +def _return_saturate_value(is_negative=False, dtype=dtypes.int32): + if dtype is dtypes.int32: + if is_negative: + return -(2**31) + return 2**31 - 1 + if dtype is dtypes.int16: + if is_negative: + return -(2**15) + return 2**15 - 1 + if dtype is dtypes.int8: + if is_negative: + return -(2**7) + return 2**7 - 1 + + +class StochasticCastOpTest(xla_test.XLATestCase, parameterized.TestCase): + """Test cases for stochastic cast operator.""" + + # pylint: disable=g-complex-comprehension + @parameterized.named_parameters( + ( + f"_{value}_from_{from_dtype.name}_to_{to_dtype.name}", + value, + from_dtype, + to_dtype, + ) + for value in [0.0025, 0.125, 0.625, 8.5] + for from_dtype in _allowed_from_types() + for to_dtype in stochastic_cast_op.allowed_to_types(is_integer=True) + ) + # pylint: enable=g-complex-comprehension + def testStochasticCastOpResultProbability(self, value, from_dtype, to_dtype): + test_value = value + with self.session() as sess, self.test_scope(): + input_t = constant_op.constant(test_value, from_dtype, [1000, 1000]) + op = stochastic_cast_op.stochastic_cast( + input_t, to_dtype, [12345, 12345], "auto_select" + ) + result = sess.run(op) + expected = (test_value - math.floor(test_value)) / ( + math.ceil(test_value) - test_value + ) + actual = (result == math.ceil(test_value)).sum() / ( + result == math.floor(test_value) + ).sum() + self.assertNear(expected, actual, 0.05) + + # pylint: disable=g-complex-comprehension + + @parameterized.named_parameters( + ( + f"_{value}_from_{from_dtype.name}_to_{to_dtype.name}", + value, + from_dtype, + to_dtype, + ) + for value in [2**33, -(2**34), 2**35, -(2**36)] + for from_dtype in _allowed_from_types() + for to_dtype in stochastic_cast_op.allowed_to_types(is_integer=True) + ) + # pylint: enable=g-complex-comprehension + def testStochasticCastOpSaturateOutOfRange(self, value, from_dtype, to_dtype): + test_value = value + with self.session() as sess, self.test_scope(): + input_t = constant_op.constant(test_value, from_dtype, []) + op = stochastic_cast_op.stochastic_cast( + input_t, to_dtype, [12345, 12345], "auto_select" + ) + result = sess.run(op) + self.assertEqual(result, _return_saturate_value(value < 0, to_dtype)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/svd_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/svd_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7c0031a60a794500f54bdace96bab2a8284bcc7a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/svd_op_test.py @@ -0,0 +1,91 @@ +# Copyright 2019 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.svd.""" + +import itertools + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import tensor_shape +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_linalg_ops +from tensorflow.python.ops import linalg_ops +from tensorflow.python.platform import test + + +class SvdOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def _compute_usvt(self, s, u, v): + m = u.shape[-1] + n = v.shape[-1] + if m <= n: + v = v[..., :m] + else: + u = u[..., :n] + + return np.matmul(u * s[..., None, :], np.swapaxes(v, -1, -2)) + + def _testSvdCorrectness(self, dtype, shape): + np.random.seed(1) + x_np = np.random.uniform(low=-1.0, high=1.0, size=shape).astype(dtype) + m, n = shape[-2], shape[-1] + _, s_np, _ = np.linalg.svd(x_np) + with self.session() as sess: + x_tf = array_ops.placeholder(dtype) + with self.test_scope(): + s, u, v = linalg_ops.svd(x_tf, full_matrices=True) + s_val, u_val, v_val = sess.run([s, u, v], feed_dict={x_tf: x_np}) + u_diff = np.matmul(u_val, np.swapaxes(u_val, -1, -2)) - np.eye(m) + v_diff = np.matmul(v_val, np.swapaxes(v_val, -1, -2)) - np.eye(n) + # Check u_val and v_val are orthogonal matrices. + self.assertLess(np.linalg.norm(u_diff), 1e-2) + self.assertLess(np.linalg.norm(v_diff), 1e-2) + # Check that the singular values are correct, i.e., close to the ones from + # numpy.lingal.svd. + self.assertLess(np.linalg.norm(s_val - s_np), 1e-2) + # The tolerance is set based on our tests on numpy's svd. As our tests + # have batch dimensions and all our operations are on float32, we set the + # tolerance a bit larger. Numpy's svd calls LAPACK's svd, which operates + # on double precision. + self.assertLess( + np.linalg.norm(self._compute_usvt(s_val, u_val, v_val) - x_np), 2e-2) + + # Check behavior with compute_uv=False. We expect to still see 3 outputs, + # with a sentinel scalar 0 in the last two outputs. + with self.test_scope(): + no_uv_s, no_uv_u, no_uv_v = gen_linalg_ops.svd( + x_tf, full_matrices=True, compute_uv=False) + no_uv_s_val, no_uv_u_val, no_uv_v_val = sess.run( + [no_uv_s, no_uv_u, no_uv_v], feed_dict={x_tf: x_np}) + self.assertAllClose(no_uv_s_val, s_val, atol=1e-4, rtol=1e-4) + self.assertEqual(no_uv_u_val.shape, tensor_shape.TensorShape([0])) + self.assertEqual(no_uv_v_val.shape, tensor_shape.TensorShape([0])) + + SIZES = [1, 2, 5, 10, 32, 64] + DTYPES = [np.float32] + PARAMS = itertools.product(SIZES, DTYPES) + + @parameterized.parameters(*PARAMS) + def testSvd(self, n, dtype): + for batch_dims in [(), (3,)] + [(3, 2)] * (n < 10): + self._testSvdCorrectness(dtype, batch_dims + (n, n)) + self._testSvdCorrectness(dtype, batch_dims + (2 * n, n)) + self._testSvdCorrectness(dtype, batch_dims + (n, 2 * n)) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_array_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_array_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..03a16cd7c9e5694e488ea1b0e891ac7b5d0f8b43 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_array_ops_test.py @@ -0,0 +1,1169 @@ +# 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. +# ============================================================================== +"""Functional tests for XLA TensorArray Ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.compiler.xla import xla +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.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_util +from tensorflow.python.ops import gen_data_flow_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import resource_variable_ops +from tensorflow.python.ops import tensor_array_grad # pylint: disable=unused-import +from tensorflow.python.ops import tensor_array_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import test + + +def _make_converter(dtype): + def _converter(x): + return np.asarray(x).astype(dtype.as_numpy_dtype) + return _converter + + +# This lets me define `fn` repeatedly to pass to xla.compile. +# +# pylint: disable=function-redefined +@test_util.run_v1_only("b/") # Support TF2 list operations +@test_util.with_control_flow_v2 +class TensorArrayTest(xla_test.XLATestCase): + + @test_util.disable_control_flow_v2("Tries to evaluate flow") + def testTensorArrayWriteRead(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + + w0 = ta.write(0, [[4.0, 5.0]]) + w1 = w0.write(1, [[1.0, 3.0]]) + w2 = w1.write(2, [[7.0, -8.5]]) + + r0 = w2.read(0) + r1 = w2.read(1) + r2 = w2.read(2) + flow = w2.flow + return [r0, r1, r2, flow] + + d0, d1, d2, flow_val = self.evaluate(xla.compile(fn)) + self.assertAllEqual([[4.0, 5.0]], d0) + self.assertAllEqual([[1.0, 3.0]], d1) + self.assertAllEqual([[7.0, -8.5]], d2) + self.assertAllEqual([], flow_val.shape) + + def _testTensorArrayWritePack(self, tf_dtype): + with self.session(), self.test_scope(): + convert = _make_converter(tf_dtype) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + + w0 = ta.write(0, convert([[4.0, 5.0]])) + w1 = w0.write(1, convert([[6.0, 7.0]])) + w2 = w1.write(2, convert([[8.0, 9.0]])) + + return w2.stack() + + self.assertAllEqual( + convert([[[4.0, 5.0]], [[6.0, 7.0]], [[8.0, 9.0]]]), + self.evaluate(xla.compile(fn)[0])) + + def testTensorArrayWritePack(self): + for dtype in self.numeric_tf_types: + self._testTensorArrayWritePack(dtype) + + def testEmptyTensorArrayPack(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + + empty_element = np.zeros((0, 1), dtype=np.float32) + w0 = ta.write(0, empty_element) + w1 = w0.write(1, empty_element) + w2 = w1.write(2, empty_element) + + return w2.stack() + + self.assertAllEqual([3, 0, 1], self.evaluate(xla.compile(fn)[0]).shape) + + def _testTensorArrayWriteConcat(self, tf_dtype): + with self.session(), self.test_scope(): + convert = _make_converter(tf_dtype) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + + w0 = ta.write(0, convert([[4.0, 5.0], [104.0, 105.0]])) + w1 = w0.write(1, convert([[6.0, 7.0], [106.0, 107.0]])) + w2 = w1.write(2, convert([[8.0, 9.0], [124.0, 125.0]])) + + return w2.concat() + + self.assertAllEqual( + convert([[4.0, 5.0], [104.0, 105.0], [6.0, 7.0], [106.0, 107.0], + [8.0, 9.0], [124.0, 125.0]]), + self.evaluate(xla.compile(fn)[0])) + + @test_util.disable_control_flow_v2("b/122315751 (concat)") + def testTensorArrayWriteConcat(self): + for dtype in self.numeric_tf_types: + self._testTensorArrayWriteConcat(dtype) + + def _testTensorArrayUnpackRead(self, tf_dtype): + with self.session() as session, self.test_scope(): + convert = _make_converter(tf_dtype) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + + # Unpack a vector into scalars + w0 = ta.unstack(convert([1.0, 2.0, 3.0])) + r0 = w0.read(0) + r1 = w0.read(1) + r2 = w0.read(2) + + return [r0, r1, r2] + + d0, d1, d2 = self.evaluate(xla.compile(fn)) + self.assertAllEqual(convert(1.0), d0) + self.assertAllEqual(convert(2.0), d1) + self.assertAllEqual(convert(3.0), d2) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + + # Unpack a matrix into vectors. + w1 = ta.unstack( + convert([[1.0, 1.03125], [2.0, 2.03125], [3.0, 3.03125]])) + r0 = w1.read(0) + r1 = w1.read(1) + r2 = w1.read(2) + return [r0, r1, r2] + + d0, d1, d2 = self.evaluate(xla.compile(fn)) + + self.assertAllEqual(convert([1.0, 1.03125]), d0) + self.assertAllEqual(convert([2.0, 2.03125]), d1) + self.assertAllEqual(convert([3.0, 3.03125]), d2) + + def fn(): + # Reset ta because we're going to change the shape, else shape + # inference will throw an error. + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + + # Try unpacking an empty matrix, which should not cause an error. + w2 = ta.unstack(convert([[], [], []])) + r0 = w2.read(0) + r1 = w2.read(1) + r2 = w2.read(2) + return [r0, r1, r2] + + d0, d1, d2 = self.evaluate(xla.compile(fn)) + self.assertAllEqual(convert([]), d0) + self.assertAllEqual(convert([]), d1) + self.assertAllEqual(convert([]), d2) + + def _testTensorArrayUnpackReadMaybeLegacy(self): + for dtype in self.numeric_tf_types: + self._testTensorArrayUnpackRead(dtype) + + def testTensorArrayUnpackRead(self): + self._testTensorArrayUnpackReadMaybeLegacy() + + def _testTensorArraySplitRead(self, tf_dtype): + with self.session() as session, self.test_scope(): + convert = _make_converter(tf_dtype) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + + # Split an empty vector. + lengths = constant_op.constant([0, 0, 0]) + w0 = ta.split(convert([]), lengths=lengths) + r0 = w0.read(0) + r1 = w0.read(1) + r2 = w0.read(2) + return [r0, r1, r2] + + d0, d1, d2 = self.evaluate(xla.compile(fn)) + + self.assertAllEqual(convert([]), d0) + self.assertAllEqual(convert([]), d1) + self.assertAllEqual(convert([]), d2) + + def fn(): + # Split a vector. + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + lengths = constant_op.constant([1, 1, 1]) + w0 = ta.split(convert([1.0, 2.0, 3.0]), lengths=lengths) + r0 = w0.read(0) + r1 = w0.read(1) + r2 = w0.read(2) + return [r0, r1, r2] + + d0, d1, d2 = self.evaluate(xla.compile(fn)) + + self.assertAllEqual(convert([1.0]), d0) + self.assertAllEqual(convert([2.0]), d1) + self.assertAllEqual(convert([3.0]), d2) + + def fn(): + # Split a matrix. + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=3) + lengths = constant_op.constant([1, 1, 1]) + w0 = ta.split( + convert([[1.0, 101.0], [2.0, 121.0], [3.0, 127.0]]), + lengths=lengths) + r0 = w0.read(0) + r1 = w0.read(1) + r2 = w0.read(2) + return [r0, r1, r2] + + d0, d1, d2 = self.evaluate(xla.compile(fn)) + self.assertAllEqual(convert([[1.0, 101.0]]), d0) + self.assertAllEqual(convert([[2.0, 121.0]]), d1) + self.assertAllEqual(convert([[3.0, 127.0]]), d2) + + @test_util.disable_control_flow_v2("b/122315872 (split)") + def testTensorArraySplitRead(self): + for dtype in self.numeric_tf_types: + self._testTensorArraySplitRead(dtype) + + @test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2") + def testTensorGradArrayWriteRead(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + + w0 = ta.write(0, [[4.0]]) + w1 = w0.write(1, [[1.0]]) + w2 = w1.write(2, [[-3.0]]) + + g_ta = w2.grad("grad") + + g_w0 = g_ta.write(0, [[5.0]]) + g_w1 = g_w0.write(1, [[2.0]]) + g_w2 = g_w1.write(2, [[-2.0]]) + + r0 = w2.read(0) + r1 = w2.read(1) + r2 = w2.read(2) + + g_r0 = g_w2.read(0) + g_r1 = g_w2.read(1) + g_r2 = g_w2.read(2) + + return [r0, r1, r2, g_r0, g_r1, g_r2] + + d0, d1, d2, g_d0, g_d1, g_d2 = self.evaluate(xla.compile(fn)) + self.assertAllEqual([[4.0]], d0) + self.assertAllEqual([[1.0]], d1) + self.assertAllEqual([[-3.0]], d2) + self.assertAllEqual([[5.0]], g_d0) + self.assertAllEqual([[2.0]], g_d1) + self.assertAllEqual([[-2.0]], g_d2) + + @test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2") + def testTensorGradArrayDynamicWriteRead(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + + w0 = ta.write(0, [[4.0]]) + w1 = w0.write(1, [[1.0]]) + w2 = w1.write(2, [[-3.0]]) + + g_ta = w2.grad("grad") # Get gradient array here so we know the shape + + s = w2.size() + g_s = g_ta.size() + + g_w0 = g_ta.write(0, [[5.0]]) + g_w1 = g_w0.write(1, [[2.0]]) + g_w2 = g_w1.write(2, [[-2.0]]) + + r0 = w2.read(0) + r1 = w2.read(1) + r2 = w2.read(2) + + g_r0 = g_w2.read(0) + g_r1 = g_w2.read(1) + g_r2 = g_w2.read(2) + + return [r0, r1, r2, g_r0, g_r1, g_r2, s, g_s] + + d0, d1, d2, g_d0, g_d1, g_d2, vs, g_vs = self.evaluate(xla.compile(fn)) + self.assertAllEqual([[4.0]], d0) + self.assertAllEqual([[1.0]], d1) + self.assertAllEqual([[-3.0]], d2) + self.assertAllEqual([[5.0]], g_d0) + self.assertAllEqual([[2.0]], g_d1) + self.assertAllEqual([[-2.0]], g_d2) + self.assertAllEqual(3, vs) + self.assertAllEqual(3, g_vs) + + @test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2") + def testTensorGradAccessTwiceReceiveSameObject(self): + with self.session() as session, self.test_scope(): + ta_out = {} + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=3, + element_shape=[1, 2]) + + g_ta_0 = ta.grad("grad") + g_ta_1 = ta.grad("grad") + + ta_out[0] = g_ta_0.handle + ta_out[1] = g_ta_1.handle + + with ops.control_dependencies([g_ta_0.write(0, [[4.0, 5.0]]).flow]): + # Write with one gradient handle, read with another copy of it + r1_0 = g_ta_1.read(0) + + with ops.control_dependencies([g_ta_0.handle.op, g_ta_1.handle.op]): + return [r1_0] + + [d_r1_0] = self.evaluate(xla.compile(fn)) + self.assertAllEqual([[4.0, 5.0]], d_r1_0) + + # Can't assert this because adding a side output like we have here fails + # as follows: + # + # ValueError: Operation u'TensorArrayGrad/TensorArrayGradV3' has been + # marked as not fetchable. + # + # On the other hand, legitimately returning the handle from the + # xla.compile function fails because we don't support DT_RESOURCE outputs + # from XLA clusters. + # + # self.assertAllEqual(ta_out[0], ta_out[1]) + + @test_util.disable_control_flow_v2("b/124334470") + def testTensorArrayWriteWrongIndexOrDataTypeFails(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + return ta.write(-1, constant_op.constant(7)).flow + + # Test writing the wrong datatype. + # TODO(b/129870929): Remove InvalidArgumentError/second regexp after all + # callers provide proper init dtype. + with self.assertRaisesRegex( + (ValueError, errors.InvalidArgumentError), r"(" + r"conversion requested dtype float32 for Tensor with dtype int32" + r"|" + r"TensorArray dtype is float but op has dtype int32" + r")"): + xla.compile(fn)[0].eval() + + @test_util.disable_control_flow_v2("b/124334096 verify dtype") + def testTensorArrayReadWrongIndexOrDataTypeFails(self): + # Find two different floating point types, create an array of + # the first type, but try to read the other type. + if len(self.float_types) > 1: + dtype1, dtype2 = list(self.float_types)[:2] + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtype1, tensor_array_name="foo", size=3) + + w0 = ta.write(0, math_ops.cast([[4.0, 5.0]], dtype1)) + + # Test reading wrong datatype. + return gen_data_flow_ops.tensor_array_read_v3( + handle=w0.handle, index=0, dtype=dtype2, flow_in=w0.flow) + + with self.assertRaisesOpError("TensorArray dtype is "): + self.evaluate(xla.compile(fn)) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtype1, tensor_array_name="foo", size=3) + + w0 = ta.write(0, math_ops.cast([[4.0, 5.0]], dtype1)) + + # Test reading from a different index than the one we wrote to + with ops.control_dependencies([w0.read(1)]): + return 1.0 + + xla.compile(fn)[0].eval() + + @test_util.disable_control_flow_v2("b/122315872 (split)") + def testTensorArraySplitIncompatibleShapesFails(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=3, + infer_shape=False) + return ta.split([1.0, 2.0, 3.0], 1).flow + + with self.assertRaisesWithPredicateMatch( + ValueError, r"Shape must be rank 1 but is rank 0"): + xla.compile(fn)[0].eval() + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=3, + infer_shape=False) + return ta.split([1.0, 2.0, 3.0], [1, 2, 3]).flow + + with self.assertRaisesOpError( + r"lengths must be equal: 1 vs. 2"): + xla.compile(fn)[0].eval() + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=3, + infer_shape=False) + return ta.split(1.0, [1]).flow + + with self.assertRaisesOpError( + r"value must have rank >= 1"): + xla.compile(fn)[0].eval() + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=2, + infer_shape=False) + + return ta.split([1.0], [1]).flow + + with self.assertRaisesOpError( + r"TensorArray's size is not equal to the size of lengths " + r"\(1 vs. 2\)"): + xla.compile(fn)[0].eval() + + def _testTensorArrayWriteGradientAddMultipleAdds(self, dtype): + with self.session(), self.test_scope(): + c = lambda x: np.asarray(x, dtype=dtype.as_numpy_dtype) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtype, tensor_array_name="foo", size=3, infer_shape=False) + + w0 = ta.write(2, c(3.0)) + w1 = w0.write(2, c(4.0)) + + ta_grad = w1.grad("grad") + + w0_grad = ta_grad.write(2, c(3.0)) + w1_grad = w0_grad.write(2, c(4.0)) + w2_grad = w1_grad.write(2, c(5.0)) + + return w2_grad.read(2) + + # Assert that aggregation works correctly + self.assertAllEqual(c(12.00), xla.compile(fn)[0]) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtype, tensor_array_name="foo", size=3, infer_shape=False) + + w0 = ta.write(2, c(3.0)) + w1 = w0.write(2, c(4.0)) + + ta_grad = w1.grad("grad") + # Using differing shapes causes an exception + wb0_grad = ta_grad.write(1, c(1.0)) + wb1_grad = wb0_grad.write(1, c([1.0])) + + return wb1_grad.flow + + with self.assertRaisesOpError( + r"Mismatched TensorArray sizes"): + xla.compile(fn)[0].eval() + + @test_util.disable_control_flow_v2("TensorArray.grad is not supported in v2") + def testTensorArrayWriteGradientAddMultipleAdds(self): + for dtype in self.numeric_tf_types: + self._testTensorArrayWriteGradientAddMultipleAdds(dtype) + + def testMultiTensorArray(self): + with self.session(), self.test_scope(): + + def fn(): + h1 = tensor_array_ops.TensorArray( + size=1, dtype=dtypes.float32, tensor_array_name="foo") + w1 = h1.write(0, 4.0) + r1 = w1.read(0) + + h2 = tensor_array_ops.TensorArray( + size=1, dtype=dtypes.float32, tensor_array_name="bar") + + w2 = h2.write(0, 5.0) + r2 = w2.read(0) + return r1 + r2 + + self.assertAllClose(9.0, self.evaluate(xla.compile(fn)[0])) + + def _testTensorArrayGradientWriteReadType(self, dtype): + with self.session() as session, self.test_scope(): + c = lambda x: np.array(x, dtype=dtype) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.as_dtype(dtype), + tensor_array_name="foo", + size=3, + infer_shape=False) + + value_0 = constant_op.constant(c([[4.0, 5.0]])) + value_1 = constant_op.constant(c([[3.0, 3.5]])) + + w0 = ta.write(0, value_0) + w1 = w0.write(1, value_1) + r0 = w1.read(0) + r1 = w1.read(1) + r0_2 = w1.read(0) + + # Test individual components' gradients + grad_just_r0 = gradients_impl.gradients( + ys=[r0], xs=[value_0], grad_ys=[c([[2.0, 3.0]])]) + grad_r0_r0_2 = gradients_impl.gradients( + ys=[r0, r0_2], + xs=[value_0], + grad_ys=[c([[2.0, 3.0]]), c([[1.0, -1.0]])]) + grad_just_r1 = gradients_impl.gradients( + ys=[r1], xs=[value_1], grad_ys=[c([[-2.0, -4.0]])]) + # Test combined gradients + grad = gradients_impl.gradients( + ys=[r0, r0_2, r1], + xs=[value_0, value_1], + grad_ys=[c([[2.0, 3.0]]), + c([[1.0, -1.0]]), + c([[-2.0, -10.0]])]) + + return [grad_just_r0, grad_r0_r0_2, grad_just_r1, grad] + + [grad_just_r0_vals, grad_r0_r0_2_vals, grad_just_r1_vals, + grad_vals] = self.evaluate(xla.compile(fn)) + + self.assertAllEqual(c([[2.0, 3.0]]), grad_just_r0_vals[0]) + + self.assertAllEqual(c([[3.0, 2.0]]), grad_r0_r0_2_vals[0]) + + self.assertAllEqual(c([[-2.0, -4.0]]), grad_just_r1_vals[0]) + + self.assertEqual(len(grad_vals), 2) + self.assertAllEqual(c([[3.0, 2.0]]), grad_vals[0]) + self.assertAllEqual(c([[-2.0, -10.0]]), grad_vals[1]) + + def testTensorArrayGradientWriteRead(self): + for dtype in self.float_types: + self._testTensorArrayGradientWriteReadType(dtype) + for dtype in self.complex_types: + self._testTensorArrayGradientWriteReadType(dtype) + + def _testTensorArrayGradientWritePackConcatAndRead(self): + with self.session() as sess, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=2, + clear_after_read=False) + + value_0 = constant_op.constant([-1.0, 1.0]) + value_1 = constant_op.constant([-10.0, 10.0]) + + w0 = ta.write(0, value_0) + w1 = w0.write(1, value_1) + p0 = w1.stack() + r0 = w1.read(0) + s0 = w1.concat() + + # Test gradient accumulation between read(0), pack(), and concat(). + with ops.control_dependencies([p0, r0, s0]): + return gradients_impl.gradients( + ys=[p0, r0, s0], + xs=[value_0, value_1], + grad_ys=[ + [[2.0, 3.0], [4.0, 5.0]], # stack gradient + [-0.5, 1.5], # read(0) gradient + [20.0, 30.0, 40.0, 50.0], # concat gradient + ]) + + grad_vals = self.evaluate(xla.compile(fn)) # 2 + 2 entries + + self.assertAllClose([2.0 - 0.5 + 20.0, 3.0 + 1.5 + 30.0], grad_vals[0]) + self.assertAllEqual([4.0 + 40.0, 5.0 + 50.0], grad_vals[1]) + + @test_util.disable_control_flow_v2("b/122315751 (concat)") + def testTensorArrayGradientWritePackConcatAndRead(self): + self._testTensorArrayGradientWritePackConcatAndRead() + + def testTensorArrayReadTwice(self): + with self.session(), self.test_scope(): + + def fn(): + value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) + + ta_readtwice = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=2, + clear_after_read=False) + w_readtwice = ta_readtwice.unstack(value) + r0_readtwice = w_readtwice.read(0) + with ops.control_dependencies([r0_readtwice]): + r1_readtwice = w_readtwice.read(0) + + return [r0_readtwice, r1_readtwice] + + self.assertAllEqual([1.0, -1.0], self.evaluate(xla.compile(fn))[0]) + + def _testTensorArrayGradientUnpackRead(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=2, + clear_after_read=False) + + value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) + + w = ta.unstack(value) + r0 = w.read(0) + r0_1 = w.read(0) + r1 = w.read(1) + + # Test combined gradients + aggregation of read(0). + return gradients_impl.gradients( + ys=[r0, r0_1, r1], + xs=[value], + grad_ys=[[2.0, 3.0], [-1.5, 1.5], [4.0, 5.0]]) + + grad_vals = self.evaluate(xla.compile(fn)) + + self.assertEqual(len(grad_vals), 1) + self.assertAllEqual([[2.0 - 1.5, 3.0 + 1.5], [4.0, 5.0]], grad_vals[0]) + + def testTensorArrayGradientUnpackRead(self): + self._testTensorArrayGradientUnpackRead() + + @test_util.disable_control_flow_v2("b/122315751(concat), b/122315872(split)") + def testTensorArrayGradientSplitConcat(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=2) + + value = constant_op.constant([[1.0, -1.0], [10.0, -10.0], + [100.0, -100.0], [1000.0, -1000.0]]) + + w = ta.split(value, [2, 2]) + r = w.concat() + + # Test combined gradients + return gradients_impl.gradients( + ys=[r], + xs=[value], + grad_ys=[[[2.0, -2.0], [20.0, -20.0], [200.0, -200.0], + [2000.0, -2000.0]]]) + + grad_vals = self.evaluate(xla.compile(fn)) + + self.assertEqual(len(grad_vals), 1) + self.assertAllEqual([[2.0, -2.0], [20.0, -20.0], [200.0, -200.0], + [2000.0, -2000.0]], + grad_vals[0]) + + def testCloseTensorArray(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + with ops.control_dependencies([ta.close()]): + return 1.0 + + self.evaluate(xla.compile(fn)[0]) + + def testSizeTensorArray(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + return ta.size() + + self.assertAllEqual(3, self.evaluate(xla.compile(fn))[0]) + + def testWriteCloseTensorArray(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, + tensor_array_name="foo", + size=3, + infer_shape=False) + w0 = ta.write(0, [[4.0, 5.0]]) + w1 = w0.write(1, [[3.0, 1.0]]) + with ops.control_dependencies([w1.close()]): + return 1.0 + + self.evaluate(xla.compile(fn)) + + # TODO(phawkins): implement while loops. + # def _testWhileLoopWritePackGradients(self, dynamic_size, dtype): + # np_dtype = dtype.as_numpy_dtype + # with self.session() as session, self.test_scope(): + # v0 = array_ops.identity(np.arange(3 * 5, dtype=np_dtype).reshape(3, 5)) + # var = variables.Variable(np.arange(100, 105, dtype=np_dtype)) + # state0 = array_ops.identity(np.array([1] * 5, dtype=np_dtype)) + # ta = tensor_array_ops.TensorArray( + # dtype=dtype, + # tensor_array_name="foo", + # size=0 if dynamic_size else 3, + # dynamic_size=dynamic_size) + # time_0 = array_ops.identity(0) + + # def body(time, ta_t, state): + # sliced = array_ops.slice( + # v0, begin=array_ops_stack.stack([time, 0]), size=[1, -1]) + # sliced = array_ops.squeeze(sliced) + # out = sliced + var + state + # state += sliced + # ta_t = ta_t.write(time, out) + # return (time + 1, ta_t, state) + + # (unused_0, h_final, unused_2) = control_flow_ops.while_loop( + # cond=lambda time, unused_1, unused_2: time < 3, + # body=body, + # loop_vars=(time_0, ta, state0), + # shape_invariants=(time_0.get_shape(), tensor_shape.unknown_shape(), + # tensor_shape.unknown_shape()), + # parallel_iterations=3) + # vout = h_final.stack() + + # grad_val = -np.arange(3 * 5, dtype=np_dtype).reshape(3, 5) + # v0_grad = gradients_impl.gradients([vout], [v0], [grad_val])[0] + # state0_grad = gradients_impl.gradients([vout], [state0], [grad_val])[0] + # var_grad = gradients_impl.gradients([vout], [var], [grad_val])[0] + + # self.evaluate(variables.global_variables_initializer()) + # state0_t, var_t, v0_t, vout_t, v0_grad_t, var_grad_t, state0_grad_t = ( + # self.evaluate([state0, var, v0, vout, v0_grad, var_grad, state0_grad]) + # ) + # just_v0_grad_t, = self.evaluate([v0_grad]) + + # # state = [ state0 | state0 + v0[0] | state0 + v0[0] + v0[1] ] + # # vout = [ v0[0] + var + state[0] | + # # v0[1] + var + state[1] | + # # v0[2] + var + state[2] ] + # # = [ v0[0] + var + state0 | + # # v0[1] + var + state0 + v0[0] | + # # v0[2] + var + state0 + v0[0] + v0[1] ] + # # + # # d(vout[0])/d(v0) = [1 | 0 | 0 ] + # # d(vout[1])/d(v0) = [1 | 1 | 0 ] + # # d(vout[2])/d(v0) = [1 | 1 | 1 ] + # # d(vout)/d(var) = [1 | 1 | 1] + # # d(vout)/d(state0) = [ 1 | 1 | 1 ] + + # state_per_time = np.array( + # [state0_t, state0_t + v0_t[0, :], + # state0_t + v0_t[0, :] + v0_t[1, :]]) + + # # Compare forward prop + # self.assertAllClose(v0_t + var_t + state_per_time, vout_t) + + # # Compare backward prop + # expected_v0_grad_t = np.array([ + # grad_val[0, :] + grad_val[1, :] + grad_val[2, :], + # grad_val[1, :] + grad_val[2, :], grad_val[2, :] + # ]) + + # self.assertAllEqual(expected_v0_grad_t, v0_grad_t) + # self.assertAllEqual(expected_v0_grad_t, just_v0_grad_t) + # self.assertAllClose(grad_val.sum(axis=0), var_grad_t) + # self.assertAllClose(grad_val.sum(axis=0), state0_grad_t) + + # def testWhileLoopWritePackGradients(self): + # self._testWhileLoopWritePackGradients( + # dynamic_size=False, dtype=dtypes.float32) + # # TODO(ebrevdo): re-enable when While supports non-float32 gradients. + # # self._testWhileLoopWritePackGradients( + # # dynamic_size=False, dtype=tf.int64) + + # def testWhileLoopDynamicWritePackGradients(self): + # self._testWhileLoopWritePackGradients( + # dynamic_size=True, dtype=dtypes.float32) + + # def testGradSerialTwoLoops(self): + # with self.session(), self.test_scope(): + # num_steps = 100 + # acc = tensor_array_ops.TensorArray( + # dtype=dtypes.float32, + # size=num_steps, + # clear_after_read=False, + # element_shape=tensor_shape.scalar()) + # i = constant_op.constant(0, name="i") + # x = constant_op.constant(2.0, name="x") + + # c = lambda i, acc: i < 5 + + # def b(i, acc): + # x1 = cond.cond( + # math_ops.equal(i, 0), lambda: x, + # lambda: math_ops.multiply(acc.read(i - 1), 2.0)) + # return i + 1, acc.write(i, x1) + + # i1, acc1 = control_flow_ops.while_loop(c, b, [i, acc]) + + # z = constant_op.constant(0.0) + + # def fn(i, acc): + # return i + 1, acc.write(i, z) + + # _, acc2 = control_flow_ops.while_loop(lambda i, acc: i < num_steps, fn, + # [i1, acc1]) + + # r = acc2.stack() + # grad = gradients_impl.gradients(r, [x])[0] + # self.assertAllClose(31.0, self.evaluate(grad)) + + def testSumOfTwoReadVariablesWithoutRepeatGrad(self): + with self.session() as session, self.test_scope(): + g0 = -(np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1) + + def fn(): + a = array_ops.identity( + np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1) + b = array_ops.identity( + np.arange(3 * 5, dtype=np.float32).reshape(3, 5) + 1 + 3 * 5) + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) + ta = ta.write(0, a, name="write_a") + ta = ta.write(1, b, name="write_b") + c = ( + ta.read(0, name="read_a_0") + # a + b + ta.read(1, name="read_b_0")) + grad_a = gradients_impl.gradients([c], [a], [g0])[0] # d(a+b)/da = 1 + grad_b = gradients_impl.gradients([c], [b], [g0])[0] # d(a+b)/db = 1 + + return [grad_a, grad_b] + + grad_a, grad_b = xla.compile(fn) + + # Test gradients calculated individually + grad_a_t, = self.evaluate([grad_a]) + self.assertAllEqual(grad_a_t, g0) + + grad_b_t, = self.evaluate([grad_b]) + self.assertAllEqual(grad_b_t, g0) + + # Test gradients calculated jointly. + joint_grad_a_t, joint_grad_b_t = self.evaluate([grad_a, grad_b]) + self.assertAllEqual(joint_grad_a_t, g0) + self.assertAllEqual(joint_grad_b_t, g0) + + def testWriteShape(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + c0 = constant_op.constant([4.0, 5.0]) + w0 = ta.write(0, c0) + r0 = w0.read(0) + + return [c0, r0] + + c0, r0 = xla.compile(fn) + + self.assertAllEqual(c0.get_shape(), r0.get_shape()) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + c1 = constant_op.constant([6.0, 7.0]) + w0 = ta.write(0, c0) + w1 = w0.write(1, c1) + r0 = w1.read(0) + r1 = w1.read(1) + + return [r0, c1, r1] + + [r0, c1, r1] = xla.compile(fn) + + self.assertAllEqual(c0.get_shape(), r0.get_shape()) + self.assertAllEqual(c1.get_shape(), r1.get_shape()) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=3) + w0 = ta.write(0, c0) + c2 = constant_op.constant([4.0, 5.0, 6.0]) + return w0.write(0, c2).flow + + with self.assertRaises(ValueError): + self.evaluate(xla.compile(fn)) + + def _testGradientWhenNotAllComponentsRead(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray(dtype=dtypes.float32, size=2) + x = constant_op.constant([2.0, 3.0]) + w = ta.unstack(x) + r0 = w.read(0) + # Calculate (dr0/dx0, dr0/dx1). since r0 = x0, gradients are (1, 0). + return gradients_impl.gradients(ys=[r0], xs=[x], grad_ys=[1.0]) + + grad_r0_vals = self.evaluate(xla.compile(fn))[0] + self.assertAllEqual(grad_r0_vals, [1.0, 0.0]) + + def testGradientWhenNotAllComponentsRead(self): + self._testGradientWhenNotAllComponentsRead() + + def _testTensorArrayEvalEmpty(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, size=0, infer_shape=False) + return ta.stack() + + with self.assertRaisesWithPredicateMatch( + errors.InvalidArgumentError, "Uninitialized TensorArray passed to " + "TensorArrayStack/TensorArrayGatherV3"): + xla.compile(fn)[0].eval() + + @test_util.disable_control_flow_v2("b/124335246") + def testTensorArrayEvalEmpty(self): + self._testTensorArrayEvalEmpty() + + def _testTensorArrayEvalEmptyWithDefault(self): + with self.session(), self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, size=0, infer_shape=True) + size = ta.size() + ta = ta.unstack(array_ops.zeros([0, 3, 5])) + return [size, ta.stack()] + + [size, stack] = self.evaluate(xla.compile(fn)) + self.assertEqual(0, size) + self.assertAllEqual([0, 3, 5], stack.shape) + # Concatenating zero tensors along their first dimension gives a + # first dimension of zero + if not control_flow_util.ENABLE_CONTROL_FLOW_V2: + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, size=0, infer_shape=True) + ta = ta.unstack(array_ops.zeros([0, 3, 5])) + return ta.concat() + + # TODO(b/122315751): Enable this. + self.assertAllEqual([0, 5], self.evaluate(xla.compile(fn))[0].shape) + + def testTensorArrayEvalEmptyWithDefault(self): + self._testTensorArrayEvalEmptyWithDefault() + + def _testTensorArrayScatterRead(self, tf_dtype): + with self.session() as session, self.test_scope(): + convert = _make_converter(tf_dtype) + id0 = array_ops.placeholder(dtypes.int32) + id1 = array_ops.placeholder(dtypes.int32) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=tf_dtype, tensor_array_name="foo", size=10) + + indices = constant_op.constant([1, 8]) + value = constant_op.constant(convert([[1.0, 5.0], [10.0, 20.0]])) + + w = ta.scatter(indices, value) + r0 = w.read(id0) + r1 = w.read(id1) + + return [r0, r1] + + # Test aggregation of read + read_vals = session.run(xla.compile(fn), feed_dict={id0: 1, id1: 8}) + self.assertAllEqual(convert([1.0, 5.0]), read_vals[0]) + self.assertAllEqual(convert([10.0, 20.0]), read_vals[1]) + + @test_util.disable_control_flow_v2("b/122315734 (scatter)") + def testTensorArrayScatterRead(self): + for dtype in self.numeric_tf_types: + self._testTensorArrayScatterRead(dtype) + self._testTensorArrayScatterRead(dtypes.bool) + + @test_util.disable_control_flow_v2("b/122315734 (scatter)") + def testTensorArrayScatterReadAndGradients(self): + with self.session() as session, self.test_scope(): + id0 = array_ops.placeholder(dtypes.int32) + id1 = array_ops.placeholder(dtypes.int32) + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=10) + + indices = constant_op.constant([1, 8]) + value = constant_op.constant([[1.0, -1.0], [10.0, -10.0]]) + + w = ta.scatter(indices, value) + r0 = w.read(id0) + r1 = w.read(id1) + + # Test combined gradients + aggregation of read(0). + grad = gradients_impl.gradients( + ys=[r0, r1], xs=[value], grad_ys=[[2.0, 3.0], [4.0, 5.0]]) + return [[r0, r1], grad] + + read_vals, grad_vals = session.run( + xla.compile(fn), feed_dict={ + id0: 1, + id1: 8 + }) + + self.assertEqual(len(read_vals), 2) + self.assertEqual(len(grad_vals), 1) + self.assertAllEqual([1.0, -1.0], read_vals[0]) + self.assertAllEqual([10.0, -10.0], read_vals[1]) + self.assertAllEqual([[2.0, 3.0], [4.0, 5.0]], grad_vals[0]) + + @test_util.disable_control_flow_v2("b/122315378 (gather)") + def testTensorArrayWriteGatherAndGradients(self): + with self.session() as session, self.test_scope(): + + def fn(): + ta = tensor_array_ops.TensorArray( + dtype=dtypes.float32, tensor_array_name="foo", size=10) + + values = constant_op.constant([[1.0 * x, -1.0 * x] for x in range(10)]) + indices = constant_op.constant([1, 8]) + + w = ta.unstack(values) + g = w.gather(indices) + + # Test combined gradients + aggregation of read(0). + grad = gradients_impl.gradients( + ys=[g], xs=[values], grad_ys=[[[2.0, 3.0], [4.0, 5.0]]]) + return [[g], grad] + + g_vals, grad_vals = self.evaluate(xla.compile(fn)) + + # Gradients for 8 of the 10 unread components are zero. + expected_grad = np.zeros((10, 2)) + expected_grad[1] = [2.0, 3.0] + expected_grad[8] = [4.0, 5.0] + + self.assertEqual(len(g_vals), 1) + self.assertEqual(len(grad_vals), 1) + self.assertAllEqual([[1.0, -1.0], [8.0, -8.0]], g_vals[0]) + self.assertAllEqual(expected_grad, grad_vals[0]) + + def testTensorArrayIdentity(self): + with self.session() as session, self.test_scope(): + tensor_arrays = {} + + v0 = resource_variable_ops.ResourceVariable(0.0) + v1 = resource_variable_ops.ResourceVariable(0.0) + + def fn(): + ta0 = tensor_array_ops.TensorArray( + dtype=dtypes.float32, size=2, infer_shape=False) + ta1 = tensor_array_ops.TensorArray( + dtype=dtypes.int32, size=4, infer_shape=True) + + ta0 = ta0.write(0, 0.) + ta1 = ta1.write(0, 1) + + with ops.control_dependencies([v0.assign_add(1.0)]): + ta0 = ta0.identity() + + with ops.control_dependencies([v1.assign_add(1.0)]): + ta1 = ta1.identity() + + read0 = ta0.read(0) + read1 = ta1.read(0) + + size0 = ta0.size() + size1 = ta1.size() + + tensor_arrays[0] = ta0 + tensor_arrays[1] = ta1 + + return [read0, read1, size0, size1, v0, v1] + + self.evaluate(variables.global_variables_initializer()) + + read0_v, read1_v, size0_v, size1_v, v0, v1 = self.evaluate( + xla.compile(fn)) + + # Tests correct properties on new TensorArrays. + self.assertEqual(dtypes.float32, tensor_arrays[0].dtype) + self.assertEqual(dtypes.int32, tensor_arrays[1].dtype) + + # Tests that the control dependencies was added and executed. + self.assertEqual(1.0, v0) + self.assertEqual(1.0, v1) + + # Tests correct TensorArray. + self.assertEqual(read0_v, 0) + self.assertEqual(read1_v, 1) + self.assertEqual(size0_v, 2) + self.assertEqual(size1_v, 4) + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_float_32_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_float_32_test.py new file mode 100644 index 0000000000000000000000000000000000000000..fe41be2b649fb8f914b583c7459f38a5b7d34064 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_float_32_test.py @@ -0,0 +1,134 @@ +# Copyright 2023 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 that the PrecisionConfig is set if TF32 is disabled.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_function +from tensorflow.python.framework import config +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 math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import googletest +from tensorflow.python.platform import sysconfig + + +class TensorFloat32Test(xla_test.XLATestCase): + + def tearDown(self): + super().tearDown() + config.enable_tensor_float_32_execution(True) + + def _test_fn(self, fn, inputs): + with ops.device('device:{}:0'.format(self.device)): + # Test with TF32 disabled + config.enable_tensor_float_32_execution(False) + compiled_fn = def_function.function(fn, jit_compile=True) + hlo_text = compiled_fn.experimental_get_compiler_ir(*inputs)(stage='hlo') + self.assertIn('operand_precision={highest,highest}', hlo_text) + + # Test the output is sufficiently precise by comparing with FP64 results + out = compiled_fn(*inputs) + sys_details = sysconfig.get_build_info() + if sys_details['is_rocm_build']: # MIOpen does not support fp64 data type + f32_out = compiled_fn(*[math_ops.cast(x, 'float32') for x in inputs]) + self.assertAllClose(out, f32_out, rtol=1e-5, atol=1e-5) + else: + f64_out = compiled_fn(*[math_ops.cast(x, 'float64') for x in inputs]) + # This test compares the F32 output of the model with the F64 output. + # oneDNN or YNNPACK algorithms may loose some precision due to + # significant accumulations for large inputs. Therefore, we need to + # adjust the tolerance accordingly in these cases. + rtol_val, atol_val = ( + (3e-4, 1e-5) + if test_util.IsCPUTargetAvailable('x86') + or test_util.IsCPUTargetAvailable('arm') + or test_util.IsCPUTargetAvailable('aarch64') + else (1e-5, 1e-5) + ) + self.assertAllClose(out, f64_out, rtol=rtol_val, atol=atol_val) + + # Test with TF32 enabled. Recompile fn because enabling TF32 does not + # reset function cache. + config.enable_tensor_float_32_execution(True) + compiled_fn = def_function.function(fn, jit_compile=True) + hlo_text = compiled_fn.experimental_get_compiler_ir(*inputs)(stage='hlo') + # operand_precision is not in HLO if it's the default value. + self.assertNotIn('operand_precision', hlo_text) + + # On Ampere GPUs and above, which support TF32, test TF32 is used by + # asserting outputs are not close to FP64 result + if test_util.is_gpu_available(min_cuda_compute_capability=(8, 0)): + out = compiled_fn(*inputs) + f64_out = compiled_fn(*[math_ops.cast(x, 'float64') for x in inputs]) + self.assertNotAllClose(out, f64_out, rtol=1e-5, atol=1e-5) + + def test_matmul(self): + x = array_ops.fill((1024, 1024), 1 + 2**-12) + y = array_ops.fill((1024, 1024), 1.0) + + def matmul(x, y): + return math_ops.matmul(x, y) + + self._test_fn(matmul, [x, y]) + + def test_batch_matmul(self): + x = array_ops.fill((2, 1024, 1024), 1 + 2**-12) + y = array_ops.fill((2, 1024, 1024), 1.0) + + def batch_matmul(x, y): + return math_ops.matmul(x, y) + + self._test_fn(batch_matmul, [x, y]) + + def test_conv2d(self): + x = array_ops.fill((16, 40, 40, 64), 1 + 2**-12) + y = array_ops.fill((3, 3, 64, 64), 1.0) + + def conv2d(x, y): + return nn_ops.conv2d(x, y, [1, 1, 1, 1], padding='SAME') + + self._test_fn(conv2d, [x, y]) + + def test_conv2d_backprop_input(self): + y = array_ops.fill((3, 3, 64, 64), 1 + 2**-12) + out_backprop = array_ops.fill((16, 40, 40, 64), 1.0) + + def conv2d_backprop_input(y, out_backprop): + return nn_ops.conv2d_backprop_input( + (16, 40, 40, 64), y, out_backprop, [1, 1, 1, 1], padding='SAME' + ) + + self._test_fn(conv2d_backprop_input, [y, out_backprop]) + + def test_conv2d_backprop_filter(self): + x = array_ops.fill((16, 40, 40, 64), 1 + 2**-12) + out_backprop = array_ops.fill((16, 40, 40, 64), 1.0) + + def conv2d_backprop_filter(x, out_backprop): + return nn_ops.conv2d_backprop_filter( + x, (3, 3, 64, 64), out_backprop, [1, 1, 1, 1], padding='SAME' + ) + + self._test_fn(conv2d_backprop_filter, [x, out_backprop]) + + +if __name__ == '__main__': + ops.enable_eager_execution() + # Enable determinism, since otherwise the autotuner may nondeterministically + # chooses either a TF32 or non-TF32 algorithm + config.enable_op_determinism() + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_list_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_list_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2098536286bb850d5f8c1645008220f62768ab0d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tensor_list_ops_test.py @@ -0,0 +1,253 @@ +# 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 ops which manipulate lists of tensors via bridge.""" + +# pylint: disable=g-bad-name +import os + +from absl.testing import parameterized +import numpy as np +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import list_ops +from tensorflow.python.platform import test + + +class ListOpsTest(parameterized.TestCase, xla_test.XLATestCase): + + def testElementShape(self): + with self.session() as sess, self.test_scope(): + dim = array_ops.placeholder(dtypes.int32) + l = list_ops.empty_tensor_list( + element_shape=(dim, 15), + element_dtype=dtypes.float32, + max_num_elements=20) + e32 = list_ops.tensor_list_element_shape(l, shape_type=dtypes.int32) + e64 = list_ops.tensor_list_element_shape(l, shape_type=dtypes.int64) + self.assertAllEqual(sess.run(e32, {dim: 10}), (10, 15)) + self.assertAllEqual(sess.run(e64, {dim: 7}), (7, 15)) + + def testPushPop(self): + with self.session() as sess, self.test_scope(): + l = list_ops.empty_tensor_list( + element_shape=(7, 15), + element_dtype=dtypes.float32, + max_num_elements=10) + l = list_ops.tensor_list_push_back( + l, constant_op.constant(1.0, shape=(7, 15))) + l = list_ops.tensor_list_push_back( + l, constant_op.constant(2.0, shape=(7, 15))) + l, e2 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + _, e1 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + self.assertAllEqual(sess.run(e2), 2.0 * np.ones((7, 15))) + self.assertAllEqual(sess.run(e1), 1.0 * np.ones((7, 15))) + + def testDoNotConstantFoldVariants(self): + with self.session() as sess, self.test_scope(): + val = array_ops.placeholder(dtype=dtypes.float32) + l = list_ops.empty_tensor_list( + element_shape=(7, 15), + element_dtype=dtypes.float32, + max_num_elements=10) + # Note: Pushing a Placeholder will force the constant folding code + # to build a Const node with a DT_VARIANT output. This tests that XLA + # passes a cf_consider_fn which prevent folding such nodes. + l = list_ops.tensor_list_push_back( + l, array_ops.fill(value=val, dims=(7, 15))) + l = list_ops.tensor_list_push_back( + l, constant_op.constant(2.0, shape=(7, 15))) + l, e2 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + _, e1 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + self.assertAllEqual(sess.run(e2, {val: 1.0}), 2.0 * np.ones((7, 15))) + self.assertAllEqual(sess.run(e1, {val: 1.0}), 1.0 * np.ones((7, 15))) + + def testPushPopSeparateLists(self): + with self.session() as sess, self.test_scope(): + l = list_ops.empty_tensor_list( + element_shape=[], + element_dtype=dtypes.float32, + max_num_elements=20) + l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) + l2 = list_ops.tensor_list_push_back(l, constant_op.constant(2.0)) + l3 = list_ops.tensor_list_push_back(l, constant_op.constant(3.0)) + _, e11 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + l2, e21 = list_ops.tensor_list_pop_back(l2, element_dtype=dtypes.float32) + l2, e22 = list_ops.tensor_list_pop_back(l2, element_dtype=dtypes.float32) + l3, e31 = list_ops.tensor_list_pop_back(l3, element_dtype=dtypes.float32) + l3, e32 = list_ops.tensor_list_pop_back(l3, element_dtype=dtypes.float32) + result = sess.run([e11, [e21, e22], [e31, e32]]) + self.assertEqual(result, [1.0, [2.0, 1.0], [3.0, 1.0]]) + + def testEmptyTensorListNoMax(self): + with self.session() as sess, self.test_scope(): + l = list_ops.empty_tensor_list( + element_shape=(7, 15), element_dtype=dtypes.float32) + l = list_ops.tensor_list_push_back( + l, constant_op.constant(1.0, shape=(7, 15))) + _, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + with self.assertRaisesRegex(errors.InvalidArgumentError, + "Set the max number of elements"): + self.assertAllEqual(sess.run(e), 1.0 * np.ones((7, 15))) + + def testEmptyTensorListMax(self): + with self.session() as sess, self.test_scope(): + l = list_ops.empty_tensor_list( + element_shape=(10, 15), element_dtype=dtypes.float32, + max_num_elements=2) + l = list_ops.tensor_list_push_back( + l, array_ops.fill(value=3.0, dims=(10, 15))) + _, e = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + self.assertAllEqual(sess.run(e), 3.0 * np.ones((10, 15))) + + def testListFromTensor(self): + with self.session(), self.test_scope(): + t = constant_op.constant([1.0, 2.0]) + l = list_ops.tensor_list_from_tensor(t, element_shape=[]) + e = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) + self.assertAllEqual(e, 1.0) + l, e0 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + self.assertAllEqual(e0, 2.0) + l, e1 = list_ops.tensor_list_pop_back(l, element_dtype=dtypes.float32) + self.assertAllEqual(e1, 1.0) + self.assertAllEqual(list_ops.tensor_list_length(l), 2) + + def testGetSet(self): + with self.session(), self.test_scope(): + t = constant_op.constant([1.0, 2.0]) + l = list_ops.tensor_list_from_tensor(t, element_shape=[]) + e0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) + self.assertAllEqual(e0, 1.0) + l = list_ops.tensor_list_set_item(l, 0, 3.0) + t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) + self.assertAllEqual(t, [3.0, 2.0]) + + def testSetDoesNotUpdatePushIndex(self): + with self.session(), self.test_scope(): + l = list_ops.empty_tensor_list( + element_shape=[], element_dtype=dtypes.float32, max_num_elements=2) + # SetItem should not change the push index. + l = list_ops.tensor_list_set_item(l, 1, 3.) + l = list_ops.tensor_list_push_back(l, 5.) + l = list_ops.tensor_list_push_back(l, 7.) + t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) + self.assertAllEqual(t, [5., 7.]) + + def testGetSetReserved(self): + with self.session(), self.test_scope(): + l = list_ops.tensor_list_reserve( + element_dtype=dtypes.float32, element_shape=[], num_elements=2) + e0 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) + self.assertAllEqual(e0, 0.0) + l = list_ops.tensor_list_set_item(l, 0, 3.0) + t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) + self.assertAllEqual(t, [3.0, 0.0]) + + def testSetStackReservedUnknownElementShape(self): + with self.session(), self.test_scope(): + l = list_ops.tensor_list_reserve( + element_dtype=dtypes.float32, element_shape=None, num_elements=2) + l = list_ops.tensor_list_set_item(l, 0, [3.0, 4.0]) + t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) + self.assertAllEqual(t, [[3.0, 4.0], [0., 0.]]) + + def testPushInEmptyListWithUnknownElementShape(self): + with self.session(), self.test_scope(): + l = list_ops.empty_tensor_list( + element_dtype=dtypes.float32, element_shape=None, max_num_elements=2) + l = list_ops.tensor_list_push_back(l, [3.0, 4.0]) + # Pushing an element with a different shape should raise an error. + with self.assertRaisesRegex(errors.InternalError, "shape"): + l = list_ops.tensor_list_push_back(l, 5.) + self.evaluate( + list_ops.tensor_list_stack(l, element_dtype=dtypes.float32)) + + def testGetSetReservedNonScalar(self): + with self.session() as sess, self.test_scope(): + l = list_ops.tensor_list_reserve( + element_dtype=dtypes.float32, + element_shape=(7, 15), + num_elements=2) + l = list_ops.tensor_list_set_item( + l, 0, constant_op.constant(1.0, shape=(7, 15))) + e1 = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) + e2 = list_ops.tensor_list_get_item(l, 1, element_dtype=dtypes.float32) + self.assertAllEqual(sess.run(e1), np.ones((7, 15))) + self.assertAllEqual(sess.run(e2), np.zeros((7, 15))) + + def testStack(self): + with self.session(), self.test_scope(): + l = list_ops.empty_tensor_list( + element_dtype=dtypes.float32, + element_shape=[], + max_num_elements=2) + l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) + e = list_ops.tensor_list_get_item(l, 0, element_dtype=dtypes.float32) + self.assertAllEqual(e, 1.0) + l = list_ops.tensor_list_push_back(l, constant_op.constant(2.0)) + t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) + self.assertAllEqual(t.shape.as_list(), [None]) + self.assertAllEqual(t, [1.0, 2.0]) + + @parameterized.named_parameters( + ("FlatList", [1.0, 2.0, 3.0], [], [0, 2], [1.0, 3.0]), + ("NestedList", [[1.0, 2.0], [3.0, 4.0], [5.0, 6.0] + ], [2], [1], [[3.0, 4.0]]), + ("EmptyIndices", [1.0, 2.0, 3.0], [], [], []), + ) + def testGather(self, input_list, element_shape, indices, output): + with self.session(), self.test_scope(): + tensor_list = list_ops.tensor_list_from_tensor( + input_list, element_shape=element_shape) + gather_t = list_ops.tensor_list_gather( + tensor_list, indices, element_dtype=dtypes.float32) + self.assertAllEqual(gather_t, output) + + def testStackWithUninitializedTensors(self): + with self.session(), self.test_scope(): + l = list_ops.tensor_list_reserve( + element_dtype=dtypes.float32, element_shape=[], num_elements=3) + t = list_ops.tensor_list_stack(l, element_dtype=dtypes.float32) + self.assertAllEqual(t, [0., 0., 0.]) + + def testZerosLikeForTensorList(self): + with self.session(), self.test_scope(): + l = list_ops.empty_tensor_list( + element_dtype=dtypes.float32, + element_shape=[], + max_num_elements=2) + l = list_ops.tensor_list_push_back(l, constant_op.constant(1.0)) + z = array_ops.zeros_like(l) + z = list_ops.tensor_list_stack(z, element_dtype=dtypes.float32) + self.assertAllEqual(z.shape.as_list(), [None]) + self.assertAllEqual(z, [0.0, 0.0]) + + def testInvalidSplitLength(self): + with self.session(), self.test_scope(): + tensor_list_split = list_ops.tensor_list_split( + tensor=[1], element_shape=[-1], lengths=[0] + ) + with self.assertRaisesRegex( + errors.UnimplementedError, "All lengths must be positive" + ): + self.evaluate(tensor_list_split) + + +if __name__ == "__main__": + os.environ["TF_XLA_FLAGS"] = ("--tf_xla_min_cluster_size=2 " + + os.environ.get("TF_XLA_FLAGS", "")) + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/ternary_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ternary_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce2c187294aa8ef2115d15d3a3145ccc1d1b727 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/ternary_ops_test.py @@ -0,0 +1,272 @@ +# 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. +# ============================================================================== +"""Test cases for ternary operators.""" + +from absl.testing import parameterized +import numpy as np +import scipy.special as sps + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import test_util +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 googletest + + +class TernaryOpsTest(xla_test.XLATestCase, parameterized.TestCase): + + def _testTernary(self, op, a, b, c, expected, rtol=1e-3, atol=1e-6): + with self.session() as session: + with self.test_scope(): + pa = array_ops.placeholder(dtypes.as_dtype(a.dtype), a.shape, name="a") + pb = array_ops.placeholder(dtypes.as_dtype(b.dtype), b.shape, name="b") + pc = array_ops.placeholder(dtypes.as_dtype(c.dtype), c.shape, name="c") + output = op(pa, pb, pc) + result = session.run(output, {pa: a, pb: b, pc: c}) + self.assertAllClose(result, expected, rtol=rtol, atol=atol) + return result + + @parameterized.parameters( + {'start': 1, 'end': 2, 'num': 1}, + {'start': 1, 'end': 4, 'num': 3}, + {'start': 0, 'end': 41, 'num': 42}) + @test_util.disable_mlir_bridge( + 'TODO(b/156174708): Dynamic result types not supported') + def testLinspace(self, start, end, num): + expected = np.linspace(start, end, num, dtype=np.float32) + result = self._testTernary( + math_ops.linspace, + np.float32(start), + np.float32(end), + np.int32(num), + expected) + # According to linspace spec, start has to be the first element and end has + # to be last element. + self.assertEqual(result[-1], expected[-1]) + self.assertEqual(result[0], expected[0]) + + def testRange(self): + self._testTernary( + math_ops.range, + np.int32(1), + np.int32(2), + np.int32(1), + expected=np.array([1], dtype=np.int32)) + self._testTernary( + math_ops.range, + np.int32(1), + np.int32(7), + np.int32(2), + expected=np.array([1, 3, 5], dtype=np.int32)) + + def testSelect(self): + for dtype in self.numeric_types: + self._testTernary( + array_ops.where, + np.array(False), + np.array(2, dtype=dtype), + np.array(7, dtype=dtype), + expected=np.array(7, dtype=dtype)) + + self._testTernary( + array_ops.where, + np.array(True), + np.array([1, 2, 3, 4], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([1, 2, 3, 4], dtype=dtype)) + + self._testTernary( + array_ops.where, + np.array(False), + np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype), + np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype), + expected=np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype)) + + self._testTernary( + array_ops.where, + np.array([0, 1, 1, 0], dtype=np.bool_), + np.array([1, 2, 3, 4], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([5, 2, 3, 8], dtype=dtype)) + + self._testTernary( + array_ops.where, + np.array([0, 1, 0], dtype=np.bool_), + np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype), + np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype), + expected=np.array([[7, 8], [3, 4], [11, 12]], dtype=dtype)) + + def testSelectV2(self): + for dtype in self.numeric_types: + self._testTernary( + array_ops.where_v2, + np.array(False), + np.array(2, dtype=dtype), + np.array(7, dtype=dtype), + expected=np.array(7, dtype=dtype)) + + self._testTernary( + array_ops.where_v2, + np.array(True), + np.array([1, 2, 3, 4], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([1, 2, 3, 4], dtype=dtype)) + + self._testTernary( + array_ops.where_v2, + np.array(False), + np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype), + np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype), + expected=np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype)) + + self._testTernary( + array_ops.where_v2, + np.array([0, 1, 1, 0], dtype=np.bool_), + np.array([1, 2, 3, 4], dtype=dtype), + np.array([5, 6, 7, 8], dtype=dtype), + expected=np.array([5, 2, 3, 8], dtype=dtype)) + + # Broadcast the condition + self._testTernary( + array_ops.where_v2, + np.array([0, 1], dtype=np.bool_), + np.array([[1, 2], [3, 4], [5, 6]], dtype=dtype), + np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype), + expected=np.array([[7, 2], [9, 4], [11, 6]], dtype=dtype)) + + # Broadcast the then branch to the else + self._testTernary( + array_ops.where_v2, + np.array([[0, 1], [1, 0], [1, 1]], dtype=np.bool_), + np.array([[1, 2]], dtype=dtype), + np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype), + expected=np.array([[7, 2], [1, 10], [1, 2]], dtype=dtype)) + + # Broadcast the else branch to the then + self._testTernary( + array_ops.where_v2, + np.array([[1, 0], [0, 1], [0, 0]], dtype=np.bool_), + np.array([[7, 8], [9, 10], [11, 12]], dtype=dtype), + np.array([[1, 2]], dtype=dtype), + expected=np.array([[7, 2], [1, 10], [1, 2]], dtype=dtype)) + + # Broadcast the then/else branches to the condition + self._testTernary( + array_ops.where_v2, + np.array([[1, 0], [0, 1], [1, 1]], dtype=np.bool_), + np.array(7, dtype=dtype), + np.array(8, dtype=dtype), + expected=np.array([[7, 8], [8, 7], [7, 7]], dtype=dtype)) + self._testTernary( + array_ops.where_v2, + np.array([[1, 0], [0, 1], [0, 0]], dtype=np.bool_), + np.array(7, dtype=dtype), + np.array([8, 9], dtype=dtype), + expected=np.array([[7, 9], [8, 7], [8, 9]], dtype=dtype)) + + def testSlice(self): + for dtype in self.numeric_types: + self._testTernary( + array_ops.slice, + np.array([[], [], []], dtype=dtype), + np.array([1, 0], dtype=np.int32), + np.array([2, 0], dtype=np.int32), + expected=np.array([[], []], dtype=dtype), + ) + + self._testTernary( + array_ops.slice, + np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], dtype=dtype), + np.array([0, 1], dtype=np.int32), + np.array([2, 1], dtype=np.int32), + expected=np.array([[2], [5]], dtype=dtype), + ) + + def testClipByValue(self): + for dtype in ( + self.numeric_types - self.complex_types - self.unsigned_int_types + ): + test_cases = [ + (np.array([2, 4, 5], dtype=dtype), dtype(7)), # + (dtype(1), np.array([2, 4, 5], dtype=dtype)), # + ( + np.array([-2, 7, 7], dtype=dtype), + np.array([-2, 9, 8], dtype=dtype), + ), + ] + x = np.array([-2, 10, 6], dtype=dtype) + for lower, upper in test_cases: + self._testTernary( + gen_math_ops._clip_by_value, + x, + lower, + upper, + expected=np.minimum(np.maximum(x, lower), upper)) + + def testBetaincSanity(self): + # This operation is only supported for float32 and float64. + for dtype in self.numeric_types & {np.float32, np.float64}: + # Sanity check a few identities: + # - betainc(a, b, 0) == 0 + # - betainc(a, b, 1) == 1 + # - betainc(a, 1, x) == x ** a + # Compare against the implementation in SciPy. + a = np.array([.3, .4, .2, .2], dtype=dtype) + b = np.array([1., 1., .4, .4], dtype=dtype) + x = np.array([.3, .4, .0, .1], dtype=dtype) + expected = sps.betainc(a, b, x) + self._testTernary( + math_ops.betainc, a, b, x, expected, rtol=5e-5, atol=6e-5 + ) + + @parameterized.parameters( + { + 'sigma': 1e15, + 'rtol': 1e-6, + 'atol': 1e-4 + }, + { + 'sigma': 30, + 'rtol': 1e-6, + 'atol': 2e-3 + }, + { + 'sigma': 1e-8, + 'rtol': 5e-4, + 'atol': 3e-4 + }, + { + 'sigma': 1e-16, + 'rtol': 1e-6, + 'atol': 2e-4 + }, + ) + def testBetainc(self, sigma, rtol, atol): + # This operation is only supported for float32 and float64. + for dtype in self.numeric_types & {np.float32, np.float64}: + # Randomly generate a, b, x in the numerical domain of betainc. + # Compare against the implementation in SciPy. + a = np.abs(np.random.randn(10, 10) * sigma).astype(dtype) # in (0, infty) + b = np.abs(np.random.randn(10, 10) * sigma).astype(dtype) # in (0, infty) + x = np.random.rand(10, 10).astype(dtype) # in (0, 1) + expected = sps.betainc(a, b, x, dtype=dtype) + self._testTernary( + math_ops.betainc, a, b, x, expected, rtol=rtol, atol=atol) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/test_utils.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/test_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..5a6e81ac0f90c28ea4e706d65b7697614b125c99 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/test_utils.py @@ -0,0 +1,91 @@ +# 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 helping test ops.""" + +import numpy as np +from six.moves import range + + +def ConvertBetweenDataFormats(x, data_format_src, data_format_dst): + """Converts 4D/5D tensor between data formats.""" + + valid_data_formats = ["NHWC", "NCHW", "HWNC", "HWCN", "NDHWC", "NCDHW"] + if len(data_format_src) != len(data_format_dst): + raise ValueError( + "data_format_src and data_format_dst must have the same dimension, got" + " %s and %s." % (len(data_format_src), len(data_format_dst)) + ) + if data_format_src not in valid_data_formats: + raise ValueError("data_format_src must be of %s, got %s." % + (valid_data_formats, data_format_src)) + if data_format_dst not in valid_data_formats: + raise ValueError("data_format_dst must be of %s, got %s." % + (valid_data_formats, data_format_dst)) + if len(x.shape) != 4 and len(x.shape) != 5: + raise ValueError("x must be 4D or 5D, got shape %s." % x.shape) + if len(x.shape) != len(data_format_src): + raise ValueError( + "x must be the same dimensions as data_format_src (%s), got shape %s." + % (len(data_format_src), x.shape) + ) + + if data_format_src == data_format_dst: + return x + + dim_map = {d: i for i, d in enumerate(data_format_src)} + transpose_dims = [dim_map[d] for d in data_format_dst] + return np.transpose(x, transpose_dims) + + +def PermuteDimsBetweenDataFormats(dims, data_format_src, data_format_dst): + """Get new shape for converting between data formats.""" + + valid_data_formats = ["NHWC", "NCHW", "HWNC", "HWCN", "NDHWC", "NCDHW"] + if len(data_format_src) != len(data_format_dst): + raise ValueError( + "data_format_src and data_format_dst must have the same dimension, got" + " %s and %s." % (len(data_format_src), len(data_format_dst)) + ) + if data_format_src not in valid_data_formats: + raise ValueError("data_format_src must be of %s, got %s." % + (valid_data_formats, data_format_src)) + if data_format_dst not in valid_data_formats: + raise ValueError("data_format_dst must be of %s, got %s." % + (valid_data_formats, data_format_dst)) + if len(dims) != 4 and len(dims) != 5: + raise ValueError("dims must be of length 4 or 5, got %s." % dims) + if len(dims) != len(data_format_src): + raise ValueError( + "dims must be the same dimensions as data_format_src (%s), got %s." + % (len(data_format_src), dims) + ) + + if data_format_src == data_format_dst: + return dims + + dim_map = {d: i for i, d in enumerate(data_format_src)} + permuted_dims = [dims[dim_map[d]] for d in data_format_dst] + return permuted_dims + + +_JIT_WARMUP_ITERATIONS = 10 + + +def RunWithWarmup(sess, op_to_run, feed_dict, options=None, run_metadata=None): + """Runs a graph a few times to ensure that its clusters are compiled.""" + for _ in range(0, _JIT_WARMUP_ITERATIONS): + sess.run(op_to_run, feed_dict, options=options) + return sess.run( + op_to_run, feed_dict, options=options, run_metadata=run_metadata) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/tridiagonal_matmul_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tridiagonal_matmul_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..02988b2579373a9d9e93a269e5e39cb00c22941d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tridiagonal_matmul_ops_test.py @@ -0,0 +1,174 @@ +# Copyright 2022 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 tridiagonal_matmul_ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.eager import def_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 array_ops +from tensorflow.python.ops import array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.ops import gradient_checker_v2 +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import stateless_random_ops as random +from tensorflow.python.ops.linalg import linalg_impl +from tensorflow.python.platform import googletest + + +class TridiagonalMatMulOpsTest(xla_test.XLATestCase): + + @def_function.function(jit_compile=True) + def _jit_tridiagonal_matmul(self, diagonals, rhs, diagonals_format): + return linalg_impl.tridiagonal_matmul( + diagonals, rhs, diagonals_format=diagonals_format) + + @def_function.function(jit_compile=False) + def _tridiagonal_matmul(self, diagonals, rhs, diagonals_format): + return linalg_impl.tridiagonal_matmul( + diagonals, rhs, diagonals_format=diagonals_format) + + def _testAllFormats(self, + superdiag, + maindiag, + subdiag, + rhs, + dtype=dtypes.float64): + superdiag_extended = np.pad(superdiag, [0, 1], 'constant') + subdiag_extended = np.pad(subdiag, [1, 0], 'constant') + + diags_compact = np.stack([superdiag_extended, maindiag, subdiag_extended]) + diags_matrix = np.diag(superdiag, 1) + np.diag(maindiag, 0) + np.diag( + subdiag, -1) + + with self.test_scope(): + diags_sequence_op = (constant_op.constant(superdiag_extended, dtype), + constant_op.constant(maindiag, dtype), + constant_op.constant(subdiag_extended, dtype)) + diags_compact_op = constant_op.constant(diags_compact, dtype) + diags_matrix_op = constant_op.constant(diags_matrix, dtype) + rhs_op = constant_op.constant(rhs, dtype) + + rhs_batch_op = array_ops_stack.stack([rhs_op, 2 * rhs_op]) + diags_compact_batch_op = array_ops_stack.stack( + [diags_compact_op, 2 * diags_compact_op]) + diags_matrix_batch_op = array_ops_stack.stack( + [diags_matrix_op, 2 * diags_matrix_op]) + diags_sequence_batch_op = [ + array_ops_stack.stack([x, 2 * x]) for x in diags_sequence_op + ] + + results = [ + self._jit_tridiagonal_matmul( + diags_sequence_op, rhs_op, diagonals_format='sequence'), + self._jit_tridiagonal_matmul( + diags_compact_op, rhs_op, diagonals_format='compact'), + self._jit_tridiagonal_matmul( + diags_matrix_op, rhs_op, diagonals_format='matrix') + ] + + results_batch = [ + self._jit_tridiagonal_matmul( + diags_sequence_batch_op, + rhs_batch_op, + diagonals_format='sequence'), + self._jit_tridiagonal_matmul( + diags_compact_batch_op, rhs_batch_op, diagonals_format='compact'), + self._jit_tridiagonal_matmul( + diags_matrix_batch_op, rhs_batch_op, diagonals_format='matrix') + ] + + expected = self._tridiagonal_matmul( + diags_sequence_op, rhs_op, diagonals_format='sequence') + expected_batch = np.stack([expected, 4 * expected]) + for result in results: + self.assertAllClose(result, expected) + for result in results_batch: + self.assertAllClose(result, expected_batch) + + def _makeTridiagonalMatrix(self, superdiag, maindiag, subdiag): + super_pad = [[0, 0], [0, 1], [1, 0]] + sub_pad = [[0, 0], [1, 0], [0, 1]] + + super_part = array_ops.pad(array_ops.matrix_diag(superdiag), super_pad) + main_part = array_ops.matrix_diag(maindiag) + sub_part = array_ops.pad(array_ops.matrix_diag(subdiag), sub_pad) + return super_part + main_part + sub_part + + def _gradientTest(self, diags, rhs, dtype=dtypes.float64): + + def reference_matmul(diags, rhs): + matrix = self._makeTridiagonalMatrix(diags[..., 0, :-1], diags[..., 1, :], + diags[..., 2, 1:]) + return math_ops.matmul(matrix, rhs) + + with self.session(), self.test_scope(): + diags = constant_op.constant(diags, dtype=dtype) + rhs = constant_op.constant(rhs, dtype=dtype) + grad_reference, _ = gradient_checker_v2.compute_gradient( + reference_matmul, [diags, rhs]) + grad_theoretical, grad_numerical = gradient_checker_v2.compute_gradient( + linalg_impl.tridiagonal_matmul, [diags, rhs]) + self.assertAllClose(grad_theoretical, grad_numerical) + self.assertAllClose(grad_theoretical, grad_reference) + + def test2x2(self): + self._testAllFormats( + superdiag=[1], maindiag=[2, 3], subdiag=[4], rhs=[[2, 1], [4, 3]]) + + def test3x3(self): + for dtype in [dtypes.float32, dtypes.float64]: + self._testAllFormats( + superdiag=[1, 2], + maindiag=[1, 2, 1], + subdiag=[2, 1], + rhs=[[1, 1], [2, 2], [3, 3]], + dtype=dtype) + + def testNDimensional(self): + with self.test_scope(): + shape = [77, 10, 3, 5, 7] + superdiag = random.stateless_random_uniform( + shape=shape[:-1], dtype=dtypes.float32, seed=[5, 10]) + maindiag = random.stateless_random_uniform( + shape=shape[:-1], dtype=dtypes.float32, seed=[5, 11]) + subdiag = random.stateless_random_uniform( + shape=shape[:-1], dtype=dtypes.float32, seed=[5, 12]) + rhs = random.stateless_random_uniform( + shape=shape, dtype=dtypes.float32, seed=[5, 13]) + + expected = self._tridiagonal_matmul((superdiag, maindiag, subdiag), + rhs, + diagonals_format='sequence') + + real = self._jit_tridiagonal_matmul((superdiag, maindiag, subdiag), + rhs, + diagonals_format='sequence') + + self.assertAllClose(expected, real) + + def testGradientSmall(self): + self._gradientTest([[[1, 2, 0], [1, 2, 3], [0, 1, 2]]], + [[[1, 2], [3, 4], [5, 6]]], + dtype=dtypes.float64) + + # testComplex is skipped as complex type is not yet supported. + + +if __name__ == '__main__': + ops.enable_eager_execution() + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/tridiagonal_solve_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tridiagonal_solve_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..af9d55ce4feb408881c28a760fa1066c2476114a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/tridiagonal_solve_ops_test.py @@ -0,0 +1,508 @@ +# Copyright 2019 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 tridiagonal solve ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gradients as gradient_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops.linalg import linalg_impl +from tensorflow.python.platform import test + +_sample_diags = np.array([[2, 1, 4, 0], [1, 3, 2, 2], [0, 1, -1, 1]], + dtype=np.float32) +_sample_rhs = np.array([1, 2, 3, 4], dtype=np.float32) +_sample_result = np.array([-9, 5, -4, 4], dtype=np.float32) + + +def _tfconst(array): + return constant_op.constant(array, dtype=dtypes.float32) + + +def _tf_ones(shape): + return array_ops.ones(shape, dtype=dtypes.float64) + + +class TridiagonalSolveOpsTest(xla_test.XLATestCase): + """Test for tri-diagonal matrix related ops.""" + + def testTridiagonalSolverSolves1Rhs(self): + np.random.seed(19) + + batch_size = 8 + num_dims = 11 + + diagonals_np = np.random.normal(size=(batch_size, 3, + num_dims)).astype(np.float32) + rhs_np = np.random.normal(size=(batch_size, num_dims, 1)).astype(np.float32) + + with self.session() as sess, self.test_scope(): + diags = array_ops.placeholder( + shape=(batch_size, 3, num_dims), dtype=dtypes.float32) + rhs = array_ops.placeholder( + shape=(batch_size, num_dims, 1), dtype=dtypes.float32) + x_np = sess.run( + linalg_impl.tridiagonal_solve(diags, rhs, partial_pivoting=False), + feed_dict={ + diags: diagonals_np, + rhs: rhs_np + })[:, :, 0] + + superdiag_np = diagonals_np[:, 0] + diag_np = diagonals_np[:, 1] + subdiag_np = diagonals_np[:, 2] + + y = np.zeros((batch_size, num_dims), dtype=np.float32) + + for i in range(num_dims): + if i == 0: + y[:, i] = ( + diag_np[:, i] * x_np[:, i] + superdiag_np[:, i] * x_np[:, i + 1]) + elif i == num_dims - 1: + y[:, i] = ( + subdiag_np[:, i] * x_np[:, i - 1] + diag_np[:, i] * x_np[:, i]) + else: + y[:, i] = ( + subdiag_np[:, i] * x_np[:, i - 1] + diag_np[:, i] * x_np[:, i] + + superdiag_np[:, i] * x_np[:, i + 1]) + + self.assertAllClose(y, rhs_np[:, :, 0], rtol=1e-4, atol=1e-4) + + def testTridiagonalSolverSolvesKRhs(self): + np.random.seed(19) + + batch_size = 8 + num_dims = 11 + num_rhs = 5 + + diagonals_np = np.random.normal(size=(batch_size, 3, + num_dims)).astype(np.float32) + rhs_np = np.random.normal(size=(batch_size, num_dims, + num_rhs)).astype(np.float32) + + with self.session() as sess, self.test_scope(): + diags = array_ops.placeholder( + shape=(batch_size, 3, num_dims), dtype=dtypes.float32) + rhs = array_ops.placeholder( + shape=(batch_size, num_dims, num_rhs), dtype=dtypes.float32) + x_np = sess.run( + linalg_impl.tridiagonal_solve(diags, rhs, partial_pivoting=False), + feed_dict={ + diags: diagonals_np, + rhs: rhs_np + }) + + superdiag_np = diagonals_np[:, 0] + diag_np = diagonals_np[:, 1] + subdiag_np = diagonals_np[:, 2] + + for eq in range(num_rhs): + y = np.zeros((batch_size, num_dims), dtype=np.float32) + for i in range(num_dims): + if i == 0: + y[:, i] = ( + diag_np[:, i] * x_np[:, i, eq] + + superdiag_np[:, i] * x_np[:, i + 1, eq]) + elif i == num_dims - 1: + y[:, i] = ( + subdiag_np[:, i] * x_np[:, i - 1, eq] + + diag_np[:, i] * x_np[:, i, eq]) + else: + y[:, i] = ( + subdiag_np[:, i] * x_np[:, i - 1, eq] + + diag_np[:, i] * x_np[:, i, eq] + + superdiag_np[:, i] * x_np[:, i + 1, eq]) + + self.assertAllClose(y, rhs_np[:, :, eq], rtol=1e-4, atol=1e-4) + + # All the following is adapted from tridiagonal_solve_op_test.py + def _test(self, + diags, + rhs, + expected, + diags_format="compact", + transpose_rhs=False): + with self.session() as sess, self.test_scope(): + self.assertAllClose( + sess.run( + linalg_impl.tridiagonal_solve( + _tfconst(diags), + _tfconst(rhs), + diags_format, + transpose_rhs, + conjugate_rhs=False, + partial_pivoting=False)), + np.asarray(expected, dtype=np.float32)) + + def _testWithDiagonalLists(self, + diags, + rhs, + expected, + diags_format="compact", + transpose_rhs=False): + with self.session() as sess, self.test_scope(): + self.assertAllClose( + sess.run( + linalg_impl.tridiagonal_solve([_tfconst(x) for x in diags], + _tfconst(rhs), + diags_format, + transpose_rhs, + conjugate_rhs=False, + partial_pivoting=False)), + sess.run(_tfconst(expected))) + + def testReal(self): + self._test(diags=_sample_diags, rhs=_sample_rhs, expected=_sample_result) + + # testComplex is skipped as complex type is not yet supported. + + def test3x3(self): + self._test( + diags=[[2.0, -1.0, 0.0], [1.0, 3.0, 1.0], [0.0, -1.0, -2.0]], + rhs=[1.0, 2.0, 3.0], + expected=[-3.0, 2.0, 7.0]) + + def test2x2(self): + self._test( + diags=[[2.0, 0.0], [1.0, 3.0], [0.0, 1.0]], + rhs=[1.0, 4.0], + expected=[-5.0, 3.0]) + + def test1x1(self): + self._test(diags=[[0], [3], [0]], rhs=[6], expected=[2]) + + def test0x0(self): + self._test( + diags=np.zeros(shape=(3, 0), dtype=np.float32), + rhs=np.zeros(shape=(0, 1), dtype=np.float32), + expected=np.zeros(shape=(0, 1), dtype=np.float32)) + + def test2x2WithMultipleRhs(self): + self._test( + diags=[[2, 0], [1, 3], [0, 1]], + rhs=[[1, 2, 3], [4, 8, 12]], + expected=[[-5, -10, -15], [3, 6, 9]]) + + def test1x1WithMultipleRhs(self): + self._test(diags=[[0], [3], [0]], rhs=[[6, 9, 12]], expected=[[2, 3, 4]]) + + # test1x1NotInvertible is skipped as runtime error not raised for now. + + # test2x2NotInvertible is skipped as runtime error not raised for now. + + @test_util.disable_mlir_bridge("Error messages differ") + def testPartialPivotingRaises(self): + np.random.seed(0) + batch_size = 8 + num_dims = 11 + num_rhs = 5 + + diagonals_np = np.random.normal(size=(batch_size, 3, + num_dims)).astype(np.float32) + rhs_np = np.random.normal(size=(batch_size, num_dims, + num_rhs)).astype(np.float32) + + with self.session() as sess, self.test_scope(): + with self.assertRaisesRegex( + errors_impl.UnimplementedError, + "Current implementation does not yet support pivoting."): + diags = array_ops.placeholder( + shape=(batch_size, 3, num_dims), dtype=dtypes.float32) + rhs = array_ops.placeholder( + shape=(batch_size, num_dims, num_rhs), dtype=dtypes.float32) + sess.run( + linalg_impl.tridiagonal_solve(diags, rhs, partial_pivoting=True), + feed_dict={ + diags: diagonals_np, + rhs: rhs_np + }) + + # testCaseRequiringPivotingLastRows is skipped as pivoting is not supported + # for now. + + # testNotInvertible is skipped as runtime error not raised for now. + + def testDiagonal(self): + self._test( + diags=[[0, 0, 0, 0], [1, 2, -1, -2], [0, 0, 0, 0]], + rhs=[1, 2, 3, 4], + expected=[1, 1, -3, -2]) + + def testUpperTriangular(self): + self._test( + diags=[[2, 4, -1, 0], [1, 3, 1, 2], [0, 0, 0, 0]], + rhs=[1, 6, 4, 4], + expected=[13, -6, 6, 2]) + + def testLowerTriangular(self): + self._test( + diags=[[0, 0, 0, 0], [2, -1, 3, 1], [0, 1, 4, 2]], + rhs=[4, 5, 6, 1], + expected=[2, -3, 6, -11]) + + def testWithTwoRightHandSides(self): + self._test( + diags=_sample_diags, + rhs=np.transpose([_sample_rhs, 2 * _sample_rhs]), + expected=np.transpose([_sample_result, 2 * _sample_result])) + + def testBatching(self): + self._test( + diags=np.array([_sample_diags, -_sample_diags]), + rhs=np.array([_sample_rhs, 2 * _sample_rhs]), + expected=np.array([_sample_result, -2 * _sample_result])) + + def testWithTwoBatchingDimensions(self): + self._test( + diags=np.array([[_sample_diags, -_sample_diags, _sample_diags], + [-_sample_diags, _sample_diags, -_sample_diags]]), + rhs=np.array([[_sample_rhs, 2 * _sample_rhs, 3 * _sample_rhs], + [4 * _sample_rhs, 5 * _sample_rhs, 6 * _sample_rhs]]), + expected=np.array( + [[_sample_result, -2 * _sample_result, 3 * _sample_result], + [-4 * _sample_result, 5 * _sample_result, -6 * _sample_result]])) + + def testBatchingAndTwoRightHandSides(self): + rhs = np.transpose([_sample_rhs, 2 * _sample_rhs]) + expected_result = np.transpose([_sample_result, 2 * _sample_result]) + self._test( + diags=np.array([_sample_diags, -_sample_diags]), + rhs=np.array([rhs, 2 * rhs]), + expected=np.array([expected_result, -2 * expected_result])) + + def testSequenceFormat(self): + self._testWithDiagonalLists( + diags=[[2, 1, 4], [1, 3, 2, 2], [1, -1, 1]], + rhs=[1, 2, 3, 4], + expected=[-9, 5, -4, 4], + diags_format="sequence") + + def testSequenceFormatWithDummyElements(self): + dummy = 20 # Should be ignored by the solver. + self._testWithDiagonalLists( + diags=[ + [2, 1, 4, dummy], + [1, 3, 2, 2], + [dummy, 1, -1, 1], + ], + rhs=[1, 2, 3, 4], + expected=[-9, 5, -4, 4], + diags_format="sequence") + + def testSequenceFormatWithBatching(self): + self._testWithDiagonalLists( + diags=[[[2, 1, 4], [-2, -1, -4]], [[1, 3, 2, 2], [-1, -3, -2, -2]], + [[1, -1, 1], [-1, 1, -1]]], + rhs=[[1, 2, 3, 4], [1, 2, 3, 4]], + expected=[[-9, 5, -4, 4], [9, -5, 4, -4]], + diags_format="sequence") + + def testMatrixFormat(self): + self._test( + diags=[[1, 2, 0, 0], [1, 3, 1, 0], [0, -1, 2, 4], [0, 0, 1, 2]], + rhs=[1, 2, 3, 4], + expected=[-9, 5, -4, 4], + diags_format="matrix") + + def testMatrixFormatWithMultipleRightHandSides(self): + self._test( + diags=[[1, 2, 0, 0], [1, 3, 1, 0], [0, -1, 2, 4], [0, 0, 1, 2]], + rhs=[[1, -1], [2, -2], [3, -3], [4, -4]], + expected=[[-9, 9], [5, -5], [-4, 4], [4, -4]], + diags_format="matrix") + + def testMatrixFormatWithBatching(self): + self._test( + diags=[[[1, 2, 0, 0], [1, 3, 1, 0], [0, -1, 2, 4], [0, 0, 1, 2]], + [[-1, -2, 0, 0], [-1, -3, -1, 0], [0, 1, -2, -4], [0, 0, -1, + -2]]], + rhs=[[1, 2, 3, 4], [1, 2, 3, 4]], + expected=[[-9, 5, -4, 4], [9, -5, 4, -4]], + diags_format="matrix") + + def testRightHandSideAsColumn(self): + self._test( + diags=_sample_diags, + rhs=np.transpose([_sample_rhs]), + expected=np.transpose([_sample_result]), + diags_format="compact") + + def testTransposeRhs(self): + self._test( + diags=_sample_diags, + rhs=np.array([_sample_rhs, 2 * _sample_rhs]), + expected=np.array([_sample_result, 2 * _sample_result]).T, + transpose_rhs=True) + + # testConjugateRhs is skipped as complex type is not yet supported. + + # testAjointRhs is skipped as complex type is not yet supported + + def testTransposeRhsWithRhsAsVector(self): + self._test( + diags=_sample_diags, + rhs=_sample_rhs, + expected=_sample_result, + transpose_rhs=True) + + # testConjugateRhsWithRhsAsVector is skipped as complex type is not yet + # supported. + + def testTransposeRhsWithRhsAsVectorAndBatching(self): + self._test( + diags=np.array([_sample_diags, -_sample_diags]), + rhs=np.array([_sample_rhs, 2 * _sample_rhs]), + expected=np.array([_sample_result, -2 * _sample_result]), + transpose_rhs=True) + + # Gradient tests + + def _gradientTest( + self, + diags, + rhs, + y, # output = reduce_sum(y * tridiag_solve(diags, rhs)) + expected_grad_diags, # expected gradient of output w.r.t. diags + expected_grad_rhs, # expected gradient of output w.r.t. rhs + diags_format="compact", + transpose_rhs=False, + feed_dict=None): + expected_grad_diags = np.array(expected_grad_diags).astype(np.float32) + expected_grad_rhs = np.array(expected_grad_rhs).astype(np.float32) + with self.session() as sess, self.test_scope(): + diags = _tfconst(diags) + rhs = _tfconst(rhs) + y = _tfconst(y) + + x = linalg_impl.tridiagonal_solve( + diags, + rhs, + diagonals_format=diags_format, + transpose_rhs=transpose_rhs, + conjugate_rhs=False, + partial_pivoting=False) + + res = math_ops.reduce_sum(x * y) + actual_grad_diags = sess.run( + gradient_ops.gradients(res, diags)[0], feed_dict=feed_dict) + actual_rhs_diags = sess.run( + gradient_ops.gradients(res, rhs)[0], feed_dict=feed_dict) + self.assertAllClose(expected_grad_diags, actual_grad_diags) + self.assertAllClose(expected_grad_rhs, actual_rhs_diags) + + def testGradientSimple(self): + self._gradientTest( + diags=_sample_diags, + rhs=_sample_rhs, + y=[1, 3, 2, 4], + expected_grad_diags=[[-5, 0, 4, 0], [9, 0, -4, -16], [0, 0, 5, 16]], + expected_grad_rhs=[1, 0, -1, 4]) + + def testGradientWithMultipleRhs(self): + self._gradientTest( + diags=_sample_diags, + rhs=[[1, 2], [2, 4], [3, 6], [4, 8]], + y=[[1, 5], [2, 6], [3, 7], [4, 8]], + expected_grad_diags=[[-20, 28, -60, 0], [36, -35, 60, 80], + [0, 63, -75, -80]], + expected_grad_rhs=[[0, 2], [1, 3], [1, 7], [0, -10]]) + + def _makeDataForGradientWithBatching(self): + y = np.array([1, 3, 2, 4]).astype(np.float32) + grad_diags = np.array([[-5, 0, 4, 0], [9, 0, -4, -16], + [0, 0, 5, 16]]).astype(np.float32) + grad_rhs = np.array([1, 0, -1, 4]).astype(np.float32) + + diags_batched = np.array( + [[_sample_diags, 2 * _sample_diags, 3 * _sample_diags], + [4 * _sample_diags, 5 * _sample_diags, + 6 * _sample_diags]]).astype(np.float32) + rhs_batched = np.array([[_sample_rhs, -_sample_rhs, _sample_rhs], + [-_sample_rhs, _sample_rhs, + -_sample_rhs]]).astype(np.float32) + y_batched = np.array([[y, y, y], [y, y, y]]).astype(np.float32) + expected_grad_diags_batched = np.array( + [[grad_diags, -grad_diags / 4, grad_diags / 9], + [-grad_diags / 16, grad_diags / 25, + -grad_diags / 36]]).astype(np.float32) + expected_grad_rhs_batched = np.array( + [[grad_rhs, grad_rhs / 2, grad_rhs / 3], + [grad_rhs / 4, grad_rhs / 5, grad_rhs / 6]]).astype(np.float32) + + return (y_batched, diags_batched, rhs_batched, expected_grad_diags_batched, + expected_grad_rhs_batched) + + def testGradientWithBatchDims(self): + y, diags, rhs, expected_grad_diags, expected_grad_rhs = ( + self._makeDataForGradientWithBatching()) + + self._gradientTest( + diags=diags, + rhs=rhs, + y=y, + expected_grad_diags=expected_grad_diags, + expected_grad_rhs=expected_grad_rhs) + + # testGradientWithUnknownShapes is skipped as shapes should be fully known. + + def _assertRaises(self, diags, rhs, diags_format="compact"): + with self.assertRaises(ValueError): + linalg_impl.tridiagonal_solve(diags, rhs, diags_format) + + # Invalid input shapes + def testInvalidShapesCompactFormat(self): + + def test_raises(diags_shape, rhs_shape): + self._assertRaises(_tf_ones(diags_shape), _tf_ones(rhs_shape), "compact") + + test_raises((5, 4, 4), (5, 4)) + test_raises((5, 3, 4), (4, 5)) + test_raises((5, 3, 4), (5)) + test_raises((5), (5, 4)) + + def testInvalidShapesSequenceFormat(self): + + def test_raises(diags_tuple_shapes, rhs_shape): + diagonals = tuple(_tf_ones(shape) for shape in diags_tuple_shapes) + self._assertRaises(diagonals, _tf_ones(rhs_shape), "sequence") + + test_raises(((5, 4), (5, 4)), (5, 4)) + test_raises(((5, 4), (5, 4), (5, 6)), (5, 4)) + test_raises(((5, 3), (5, 4), (5, 6)), (5, 4)) + test_raises(((5, 6), (5, 4), (5, 3)), (5, 4)) + test_raises(((5, 4), (7, 4), (5, 4)), (5, 4)) + test_raises(((5, 4), (7, 4), (5, 4)), (3, 4)) + + def testInvalidShapesMatrixFormat(self): + + def test_raises(diags_shape, rhs_shape): + self._assertRaises(_tf_ones(diags_shape), _tf_ones(rhs_shape), "matrix") + + test_raises((5, 4, 7), (5, 4)) + test_raises((5, 4, 4), (3, 4)) + test_raises((5, 4, 4), (5, 3)) + + # Tests involving placeholder with an unknown dimension are all skipped. + # Dimensions have to be all known statically. + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/unary_ops_composition_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unary_ops_composition_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..04a048a078789e255756d9c6a6d7b6ea1f85010e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unary_ops_composition_test.cc @@ -0,0 +1,134 @@ +/* Copyright 2019 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 +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/tsl/lib/core/status_test_util.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/device_factory.h" +#include "tensorflow/core/framework/fake_input.h" +#include "tensorflow/core/framework/node_def_builder.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/kernels/ops_testutil.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/util/port.h" + +namespace tensorflow { +namespace { + +static bool Initialized = [] { + tensorflow::GetXlaDeviceFlags()->tf_xla_enable_xla_devices = true; + return true; +}(); + +class UnaryOpsCompositionTest : public OpsTestBase { + protected: + template + void RunComposedOp(const std::vector op_names, + T input_scalar_value, T expected_scalar_value) { + std::string xla_device_name = + tensorflow::IsGoogleCudaEnabled() ? DEVICE_XLA_GPU : DEVICE_XLA_CPU; + SetDevice(DeviceType(xla_device_name), + std::unique_ptr(DeviceFactory::NewDevice( + xla_device_name, {}, "/job:a/replica:0/task:0"))); + + TF_ASSERT_OK(NodeDefBuilder("unary_op_composition", "_UnaryOpsComposition") + .Input(FakeInput(DataTypeToEnum::v())) + .Attr("T", DataTypeToEnum::v()) + .Attr("op_names", op_names) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + + // We're using an XLA device here which allocates XlaTensors. We can't + // inspect XlaTensors directly so we create the input on the host and copy + // it over to the XLA device. We do the inverse on the output. + + TensorShape shape({}); + + AllocatorAttributes host_alloc_attrs; + host_alloc_attrs.set_gpu_compatible(true); + host_alloc_attrs.set_on_host(true); + Allocator* cpu_allocator = device_->GetAllocator(host_alloc_attrs); + + DataType dtype = DataTypeToEnum::value; + + Tensor input_on_host(cpu_allocator, dtype, shape); + test::FillValues(&input_on_host, {input_scalar_value}); + + Tensor* input = AddInput(dtype, shape); + + DeviceContext* device_context = + device_->tensorflow_accelerator_device_info()->default_context; + + CHECK_OK(device_context->CopyCPUTensorToDeviceSync(&input_on_host, device_, + input)); + + TF_ASSERT_OK(RunOpKernel()); + + Tensor expected_tensor(cpu_allocator, dtype, shape); + test::FillValues(&expected_tensor, {expected_scalar_value}); + + Tensor* output = GetOutput(0); + Tensor output_on_host(cpu_allocator, output->dtype(), output->shape()); + + CHECK_OK(device_context->CopyDeviceTensorToCPUSync( + output, "output 0", device_, &output_on_host)); + + test::ExpectClose(expected_tensor, output_on_host, /*atol=*/1e-5, + /*rtol=*/1e-5); + } +}; + +TEST_F(UnaryOpsCompositionTest, Compose_Sqrt_Sqrt_F) { + RunComposedOp({"Sqrt", "Sqrt"}, 81.0, 3.0); +} + +TEST_F(UnaryOpsCompositionTest, Compose_Sqrt_Sqrt_D) { + RunComposedOp({"Sqrt", "Sqrt"}, 81.0, 3.0); +} + +TEST_F(UnaryOpsCompositionTest, Compose_Sqrt_Sin_F) { + RunComposedOp({"Sqrt", "Sin"}, 81.0, std::sin(9.0f)); +} + +TEST_F(UnaryOpsCompositionTest, Compose_Cos_Acos_F) { + RunComposedOp({"Cos", "Acos"}, 0.5, std::acos(std::cos(0.5f))); +} + +TEST_F(UnaryOpsCompositionTest, Compose_Tanh_Relu_F) { + RunComposedOp({"Tanh", "Relu"}, 0.5, std::max(0.0f, std::tanh(0.5f))); +} + +TEST_F(UnaryOpsCompositionTest, Compose_Tanh_Relu_D) { + RunComposedOp({"Tanh", "Relu"}, 0.5, std::max(0.0, std::tanh(0.5))); +} + +TEST_F(UnaryOpsCompositionTest, Compose_Tanh_Relu6_F) { + RunComposedOp({"Relu6"}, 11.0f, 6.0f); +} +} // namespace +} // end namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/unary_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unary_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ff92cff5f3d961691045f8836c959699c6b001ee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unary_ops_test.py @@ -0,0 +1,1074 @@ +# 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 XLA JIT compiler.""" + +import unittest + +import numpy as np +import six + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.ops import bitwise_ops +from tensorflow.python.ops import gen_functional_ops +from tensorflow.python.ops import gen_nn_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import nn_ops +from tensorflow.python.platform import googletest + + +def nhwc_to_format(x, data_format): + """Converts a numpy array from NHWC format to `data_format`.""" + rank = len(x.shape) + if data_format == "NCHW": + return np.transpose(x, [0, rank - 1] + list(range(1, rank - 1))) + elif data_format == "NHWC": + return x + else: + raise ValueError("Unknown format {}".format(data_format)) + + +class UnaryOpsTest(xla_test.XLATestCase): + """Test cases for unary operators.""" + + def _assertOpOutputMatchesExpected( + self, op, inp, expected, equality_test=None, rtol=1e-3, atol=1e-5 + ): + """Verifies that 'op' produces 'expected' when fed input 'inp' . + + Args: + op: operator to test + inp: numpy input array to use as input to 'op'. + expected: numpy array representing the expected output of 'op'. + equality_test: either None, or a function that tests two numpy arrays for + equality. If None, self.assertAllClose is used. + rtol: relative tolerance for equality test. + atol: absolute tolerance for equality test. + """ + with self.session() as session: + with self.test_scope(): + pinp = array_ops.placeholder( + dtypes.as_dtype(inp.dtype), inp.shape, name="a" + ) + output = op(pinp) + result = session.run(output, {pinp: inp}) + if equality_test is None: + self.assertEqual(output.dtype, expected.dtype) + self.assertAllCloseAccordingToType( + expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03 + ) + else: + equality_test(result, expected, rtol=rtol, atol=atol) + + def ListsAreClose(self, result, expected, rtol, atol): + """Tests closeness of two lists of floats.""" + self.assertEqual(len(result), len(expected)) + for i in range(len(result)): + self.assertAllClose(result[i], expected[i], rtol, atol) + + def AssertCloseAndSorted(self, result, expected, rtol, atol): + """Tests that result and expected are both close and sorted.""" + self.assertAllClose(result, expected, rtol, atol) + self.assertAllEqual(np.sort(result), result) + + def AssertAllEqual(self, result, expected, rtol, atol): + """Tests that result and expected are exactly equal.""" + self.assertAllEqual(result, expected) + + def testAllTypeOps(self): + for dtype in self.numeric_types - {np.int8, np.uint8}: + self._assertOpOutputMatchesExpected( + array_ops.diag, + np.array([1, 2, 3, 4], dtype=dtype), + np.array( + [[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]], + dtype=dtype, + ), + ) + self._assertOpOutputMatchesExpected( + array_ops.diag_part, + np.arange(36).reshape([2, 3, 2, 3]).astype(dtype), + np.array([[0, 7, 14], [21, 28, 35]], dtype=dtype), + ) + self._assertOpOutputMatchesExpected( + array_ops.diag, + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array( + [ + [[[1, 0], [0, 0]], [[0, 2], [0, 0]]], + [[[0, 0], [3, 0]], [[0, 0], [0, 4]]], + ], + dtype=dtype, + ), + ) + + self._assertOpOutputMatchesExpected( + array_ops.identity, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[-1, 1]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + array_ops.prevent_gradient, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[-1, 1]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + array_ops.squeeze, + np.array([[[[[]]]]], dtype=dtype), + expected=np.array([], dtype=dtype), + ) + self._assertOpOutputMatchesExpected( + array_ops.squeeze, + np.array([[[1], [2]]], dtype=dtype), + expected=np.array([1, 2], dtype=dtype), + ) + self._assertOpOutputMatchesExpected( + array_ops.squeeze, + np.array([[[1]], [[2]]], dtype=dtype), + expected=np.array([1, 2], dtype=dtype), + ) + self._assertOpOutputMatchesExpected( + array_ops.squeeze, + np.array([[[1, 2], [3, 4]]], dtype=dtype), + expected=np.array([[1, 2], [3, 4]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + array_ops.stop_gradient, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[-1, 1]], dtype=dtype), + ) + + def testLog(self): + for dtype in self.float_types - {dtypes.bfloat16.as_numpy_dtype}: + tol = 1e-4 if dtype == np.float32 else 1e-9 + # pylint: disable=invalid-unary-operand-type + x = np.linspace(-np.e, np.e, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.log, x, expected=np.log(x), atol=tol, rtol=tol + ) + + x = np.linspace(0.0, np.e * 1e-30, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.log, x, expected=np.log(x), atol=tol, rtol=tol + ) + + x = np.linspace(0.0, np.pi * 1e30, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.log, x, expected=np.log(x), atol=tol, rtol=tol + ) + + def testSin(self): + for dtype in self.float_types - {dtypes.bfloat16.as_numpy_dtype}: + tol = 1e-6 if dtype == np.float32 else 1e-12 + + x = np.linspace(-4 * np.e, 4 * np.e, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.sin, x, expected=np.sin(x), rtol=tol, atol=tol + ) + + x = np.linspace(0.0, np.e * 1e-30, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.sin, x, expected=np.sin(x), rtol=tol, atol=tol + ) + + if dtype == np.float64: + x = np.linspace(0.0, np.e * 1e8, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.sin, x, expected=np.sin(x), rtol=tol, atol=1e-5 + ) + + def testCos(self): + for dtype in self.float_types - {dtypes.bfloat16.as_numpy_dtype}: + tol = 1e-6 if dtype == np.float32 else 1e-12 + + x = np.linspace(-4 * np.e, 4 * np.e, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.cos, x, expected=np.cos(x), rtol=tol, atol=tol + ) + + x = np.linspace(0.0, np.e * 1e-30, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.cos, x, expected=np.cos(x), rtol=tol, atol=tol + ) + + if dtype == np.float64: + x = np.linspace(0.0, np.e * 1e8, num=1000, dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.cos, x, expected=np.cos(x), rtol=tol, atol=1e-5 + ) + + def testSigmoidNumericalStability(self): + for dtype in self.float_types: + if dtype != np.float16: + self._assertOpOutputMatchesExpected( + lambda x: math_ops.sigmoid(x) / math_ops.log1p(math_ops.exp(x)), + np.array([-40, 40], dtype=dtype), + expected=np.array([1.0, 0.025], dtype=dtype), + ) + + def testQuantizeAndDequantize(self): + for dtype in self.float_types: + + def quantize_and_dequantize_v2(x): + return array_ops.quantize_and_dequantize( + x, -127, 127, signed_input=True, num_bits=8 + ) + + def quantize_and_dequantize_v3(x): + return array_ops.quantize_and_dequantize_v3( + x, -127, 127, num_bits=8, signed_input=True, range_given=False + ) + + def quantize_and_dequantize_v4(x): + return array_ops.quantize_and_dequantize_v2( + x, -127, 127, signed_input=True, num_bits=8 + ) + + test_fns = ( + quantize_and_dequantize_v2, + quantize_and_dequantize_v3, + quantize_and_dequantize_v4, + ) + for test_fn in test_fns: + self._assertOpOutputMatchesExpected( + test_fn, + np.array([-1, -0.5, 0, 0.3], dtype=dtype), + expected=np.array([-1.0, -0.5, 0.0, 0.296875], dtype=dtype), + ) + + def quantize_and_dequantize_v2_round_half_up(x): + return array_ops.quantize_and_dequantize( + x, + -1.0, + 1.0, + signed_input=True, + num_bits=8, + range_given=True, + round_mode="HALF_UP", + ) + + self._assertOpOutputMatchesExpected( + quantize_and_dequantize_v2_round_half_up, + np.array([-0.8, -0.4, 0, 0.3, 0.8, -2, 33], dtype=dtype), + expected=np.array( + [ + -102.0 / 127, + -51.0 / 127, + 0, + 38.0 / 127, + 102.0 / 127, + -128.0 / 127, + 1, + ], + dtype=dtype, + ), + ) + + def quantize_and_dequantize_v2_round_half_to_even(x): + return array_ops.quantize_and_dequantize( + x, + -1.0, + 1.0, + signed_input=True, + num_bits=8, + range_given=True, + round_mode="HALF_TO_EVEN", + ) + + self._assertOpOutputMatchesExpected( + quantize_and_dequantize_v2_round_half_to_even, + np.array([-0.8, -0.4, 0, 0.3, 0.8, -2, 33], dtype=dtype), + expected=np.array( + [ + -102.0 / 127, + -51.0 / 127, + 0, + 38.0 / 127, + 102.0 / 127, + -128.0 / 127, + 1, + ], + dtype=dtype, + ), + ) + + def testComplexOps(self): + for dtype in self.complex_types: + + self._assertOpOutputMatchesExpected( + math_ops.acosh, + np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype), + expected=np.arccosh( + np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype) + ), + ) + + self._assertOpOutputMatchesExpected( + math_ops.asinh, + np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype), + expected=np.arcsinh( + np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype) + ), + ) + + self._assertOpOutputMatchesExpected( + math_ops.atanh, + np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype), + expected=np.arctanh( + np.array([0.1, 0.2j, 0.3 - 0.1j, 0.4 + 0.5j], dtype=dtype) + ), + ) + + self._assertOpOutputMatchesExpected( + math_ops.cosh, + np.array([1j, 2 - 3j, 3, 4 + 2j], dtype=dtype), + expected=np.cosh(np.array([1j, 2 - 3j, 3, 4 + 2j], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.sinh, + np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype), + expected=np.sinh(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.exp, + np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype), + expected=np.exp(np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.expm1, + np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype), + expected=np.expm1(np.array([[-1 + 2j, 3j, 2 - 3j]], dtype=dtype)), + rtol=1e-6, + atol=1e-6, + ) + + # For real part close to zero, or imaginary part close to a multiple of + # pi. + + self._assertOpOutputMatchesExpected( + math_ops.expm1, + np.array( + [[ + 1e-11 + 1j, + -1e-11 - 1j, + 1.0 + 1e-11j, + -1.0 - 1e-11j, + 1e-13j + 1e-13j, + ]], + dtype=dtype, + ), + expected=np.expm1( + np.array( + [[ + 1e-11 + 1j, + -1e-11 - 1j, + 1.0 + 1e-11j, + -1.0 - 1e-11j, + 1e-13j + 1e-13j, + ]], + dtype=dtype, + ), + dtype=dtype, + ), + rtol=1e-09, + atol=1e-20, + ) + + self._assertOpOutputMatchesExpected( + math_ops.reciprocal, + np.array([[1, 2j, 2 + 3j]], dtype=dtype), + expected=1.0 / np.array([[1, 2j, 2 + 3j]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + math_ops.log, + np.array([[5j, 3 - 2j]], dtype=dtype), + expected=np.log(np.array([[5j, 3 - 2j]], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.sin, + np.array([[5j, 3 - 2j]], dtype=dtype), + expected=np.sin(np.array([[5j, 3 - 2j]], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.cos, + np.array([[5j, 3 - 2j]], dtype=dtype), + expected=np.cos(np.array([[5j, 3 - 2j]], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.log1p, + np.array([[1e-14, 1e-15j, 0.6 - 0.3j]], dtype=dtype), + expected=np.log1p( + np.array([[1e-14, 1e-15j, 0.6 - 0.3j]], dtype=dtype) + ), + rtol=1e-4, + atol=1e-6, + ) + + val = np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype) + self._assertOpOutputMatchesExpected( + math_ops.rsqrt, val, expected=1 / np.sqrt(val) + ) + + self._assertOpOutputMatchesExpected( + math_ops.sigmoid, val, expected=1 / (1 + np.exp(-val)) + ) + + self._assertOpOutputMatchesExpected( + math_ops.sqrt, val, expected=np.sqrt(val) + ) + + self._assertOpOutputMatchesExpected( + math_ops.tanh, + np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype), + expected=np.tanh(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.tan, + np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype), + expected=np.tan(np.array([1, 2j, 2 - 3j, 4 + 5j], dtype=dtype)), + ) + + ctypes = {np.complex64: np.float32, np.complex128: np.float64} + self._assertOpOutputMatchesExpected( + math_ops.abs, + np.array([[3 - 4j, -1j, np.inf]], dtype=dtype), + expected=np.array([[5, 1, np.inf]], dtype=ctypes[dtype]), + ) + + self._assertOpOutputMatchesExpected( + math_ops.negative, + np.array([[-1 + 2j, -3j]], dtype=dtype), + expected=np.array([[1 - 2j, 3j]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + math_ops.square, + np.array([[-2 - 3j, 3 + 4j, 5j]], dtype=dtype), + expected=np.array([[-2 - 3j, 3 + 4j, 5j]], dtype=dtype) ** 2, + ) + + self._assertOpOutputMatchesExpected( + array_ops.zeros_like, + np.array([[4j, 3 - 2j], [2, -1j]], dtype=dtype), + expected=np.array([[0, 0], [0, 0]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + array_ops.ones_like, + np.array([[-4j, 3 + 2j], [2, -1j]], dtype=dtype), + expected=np.array([[1, 1], [1, 1]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + math_ops.angle, + np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), + expected=np.angle(np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype)), + ) + + self._assertOpOutputMatchesExpected( + math_ops.conj, + np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), + expected=np.array([1 - 3j, -4 - 7j, 2.7, 3j], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + math_ops.imag, + np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), + expected=np.array([3, 7, 0, -3], dtype=ctypes[dtype]), + ) + + self._assertOpOutputMatchesExpected( + math_ops.real, + np.array([1 + 3j, -4 + 7j, 2.7, -3j], dtype=dtype), + expected=np.array([1, -4, 2.7, 0], dtype=ctypes[dtype]), + ) + + def testIntOps(self): + for dtype in self.int_types - self.unsigned_int_types: + self._assertOpOutputMatchesExpected( + bitwise_ops.invert, + np.array([0, -1, 1, 16, 42], dtype=dtype), + expected=np.array([-1, 0, -2, -17, -43], dtype=dtype), + ) + + # Test population_count for array inputs. + raw_inputs = [ + 0, + 1, + -1, + 3, + -3, + 5, + -5, + 14, + -14, + 127, + 128, + 255, + 256, + 65535, + 65536, + 2**31 - 1, + 2**31, + 2**32 - 1, + 2**32, + -(2**32) + 1, + -(2**32), + -(2**63) + 1, + 2**63 - 1, + ] + # Only choose inputs which fit in the int dtype. + raw_inputs = list( + filter( + lambda x: np.iinfo(dtype).min <= x <= np.iinfo(dtype).max, + raw_inputs, + ) + ) + inputs = np.array(raw_inputs, dtype=dtype) + + def count_bits(x): + return sum(bin(z).count("1") for z in six.iterbytes(x.tobytes())) + + truth = [count_bits(x) for x in inputs] + self._assertOpOutputMatchesExpected( + bitwise_ops.population_count, + inputs, + expected=np.array(truth, dtype=np.uint8), + equality_test=self.AssertAllEqual, + ) + + # Test population_count for scalar inputs. + for raw_inp in raw_inputs: + inp = dtype(raw_inp) + truth = count_bits(inp) + self._assertOpOutputMatchesExpected( + bitwise_ops.population_count, + inp, + expected=np.uint8(truth), + equality_test=self.AssertAllEqual, + ) + + def testNumericOps(self): + for dtype in self.numeric_types - {np.int8, np.uint8}: + self._assertOpOutputMatchesExpected( + math_ops.abs, + np.array([[2, -1]], dtype=dtype), + expected=np.array([[2, 1]], dtype=np.real(dtype(0)).dtype), + ) + + self._assertOpOutputMatchesExpected( + math_ops.negative, + np.array([[-1, 1]], dtype=dtype), + expected=np.array([[1, -1]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + math_ops.square, + np.array([[-2, 3]], dtype=dtype), + expected=np.array([[4, 9]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + array_ops.zeros_like, + np.array([[4, 3], [2, 1]], dtype=dtype), + expected=np.array([[0, 0], [0, 0]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + array_ops.ones_like, + np.array([[4, 3], [2, 1]], dtype=dtype), + expected=np.array([[1, 1], [1, 1]], dtype=dtype), + ) + + # TODO(phawkins): these tests fail unless fastmath optimizations + # are disabled. Use more robust IsInf/IsNaN detection and enable these + # tests. + @unittest.skip("test case fails in fast-math mode") + def testIsInfAndIsNan(self): + for dtype in self.float_types: + self._assertOpOutputMatchesExpected( + math_ops.is_inf, + np.array( + [[-np.inf, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]], dtype=dtype + ), + expected=np.array([[1, 0, 0, 0, 0, 0, 0, 1, 0]], dtype=np.bool_), + ) + self._assertOpOutputMatchesExpected( + math_ops.is_nan, + np.array( + [[-np.inf, -2, -1, 0, 0.5, 1, 2, np.inf, np.nan]], dtype=dtype + ), + expected=np.array([[0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=np.bool_), + ) + self._assertOpOutputMatchesExpected( + math_ops.sign, + np.array([[np.nan]], dtype=dtype), + expected=np.array([[0.0]], dtype=dtype), + ) + + def testLogicalOps(self): + self._assertOpOutputMatchesExpected( + math_ops.logical_not, + np.array([[True, False], [False, True]], dtype=np.bool_), + expected=np.array([[False, True], [True, False]], dtype=np.bool_), + ) + + def testBiasAddGrad(self): + self._assertOpOutputMatchesExpected( + gen_nn_ops.bias_add_grad, + np.array([[1.0, 2.0], [3.0, 4.0]], dtype=np.float32), + expected=np.array([4.0, 6.0], dtype=np.float32), + ) + + self._assertOpOutputMatchesExpected( + lambda x: gen_nn_ops.bias_add_grad(x, data_format="NCHW"), + np.array( + [[[1.0, 2.0], [3.0, 4.0]], [[5.0, 6.0], [7.0, 8.0]]], + dtype=np.float32, + ), + expected=np.array([14.0, 22.0], dtype=np.float32), + ) + + def testBitcast(self): + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.int32), + np.array([1, 0x3F800000], np.int32), + expected=np.array([1, 0x3F800000], np.int32), + ) + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.float32), + np.array([1, 0x3F800000], np.int32), + expected=np.array([1e-45, 1.0], np.float32), + ) + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.int32), + np.array([1e-45, 1.0], np.float32), + expected=np.array([1, 0x3F800000], np.int32), + ) + if np.int64 in self.numeric_types: + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.int64), + np.array([1, 0x100000003F800000], np.uint64), + expected=np.array([1, 0x100000003F800000], np.int64), + ) + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.uint64), + np.array([1, 0x100000003F800000], np.int64), + expected=np.array([1, 0x100000003F800000], np.uint64), + ) + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.float64), + np.array( + [0, 0x3FF0000000000000, 0xC3AF161421C8E000, 0x4032000000000007], + np.uint64, + ), + expected=np.array( + [0, 1.0, -1.12e18, 18.000000000000024869], np.float64 + ), + atol=0, + ) + + def testBitcastInt8ToFloat(self): + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.float32), + np.array([[1, 0, 0, 0], [0xD0, 0x0F, 0x49, 0x40]]).astype(np.int8), + expected=np.array([1e-45, 3.14159], np.float32), + ) + self._assertOpOutputMatchesExpected( + lambda x: array_ops.bitcast(x, dtypes.np.int8), + np.array([1e-45, 3.14159], np.float32), + expected=np.array([[1, 0, 0, 0], [0xD0, 0x0F, 0x49, 0x40]]).astype( + np.int8 + ), + ) + + def testInvertPermutation(self): + for np_dtype in [np.int32, np.int64]: + self._assertOpOutputMatchesExpected( + array_ops.invert_permutation, + np.array([1, 2, 0], np_dtype), + expected=np.array([2, 0, 1], dtype=np_dtype), + ) + + def testInvertPermutationTwiceIsNoop(self): + + def invert_twice(x): + return array_ops.invert_permutation(array_ops.invert_permutation(x)) + + for np_dtype in [np.int32, np.int64]: + self._assertOpOutputMatchesExpected( + invert_twice, + np.array([1, 2, 0], np_dtype), + expected=np.array([1, 2, 0], dtype=np_dtype), + ) + + def testRank(self): + rank_op = lambda x: array_ops.rank_internal(x, optimize=False) + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + rank_op, dtype(7), expected=np.int32(0) + ) + self._assertOpOutputMatchesExpected( + rank_op, np.array([[], []], dtype=dtype), expected=np.int32(2) + ) + self._assertOpOutputMatchesExpected( + rank_op, np.array([0, 1], dtype=dtype), expected=np.int32(1) + ) + self._assertOpOutputMatchesExpected( + rank_op, np.array([[0, 1]], dtype=dtype), expected=np.int32(2) + ) + self._assertOpOutputMatchesExpected( + rank_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.int32(2) + ) + + def testShape(self): + shape_op = lambda x: array_ops.shape_internal(x, optimize=False) + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + shape_op, dtype(7), expected=np.array([], dtype=np.int32) + ) + self._assertOpOutputMatchesExpected( + shape_op, + np.array([[], []], dtype=dtype), + expected=np.array([2, 0], dtype=np.int32), + ) + self._assertOpOutputMatchesExpected( + shape_op, + np.array([0, 1], dtype=dtype), + expected=np.array([2], dtype=np.int32), + ) + self._assertOpOutputMatchesExpected( + shape_op, + np.array([[0, 1]], dtype=dtype), + expected=np.array([1, 2], dtype=np.int32), + ) + self._assertOpOutputMatchesExpected( + shape_op, + np.array([[0], [1], [4]], dtype=dtype), + expected=np.array([3, 1], dtype=np.int32), + ) + + def testSize(self): + size_op = lambda x: array_ops.size_internal(x, optimize=False) + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + size_op, dtype(7), expected=np.int32(1) + ) + self._assertOpOutputMatchesExpected( + size_op, np.array([[], []], dtype=dtype), expected=np.int32(0) + ) + self._assertOpOutputMatchesExpected( + size_op, np.array([0, 1], dtype=dtype), expected=np.int32(2) + ) + self._assertOpOutputMatchesExpected( + size_op, np.array([[0, 1]], dtype=dtype), expected=np.int32(2) + ) + self._assertOpOutputMatchesExpected( + size_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.int32(3) + ) + + def testSizeWithInt64OutType(self): + + def size_op(x): + return array_ops.size_internal(x, optimize=False, out_type=np.int64) + + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + size_op, np.array([[0], [1], [4]], dtype=dtype), expected=np.int64(3) + ) + + def testUnpack(self): + self._assertOpOutputMatchesExpected( + array_ops_stack.unstack, + np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32), + expected=[ + np.array([1.0, 2.0], dtype=np.float32), + np.array([3.0, 4.0], dtype=np.float32), + np.array([5.0, 6.0], dtype=np.float32), + ], + equality_test=self.ListsAreClose, + ) + + self._assertOpOutputMatchesExpected( + lambda x: array_ops_stack.unstack(x, axis=1), + np.array([[1.0, 2.0], [3.0, 4.0], [5.0, 6.0]], dtype=np.float32), + expected=[ + np.array([1.0, 3.0, 5.0], dtype=np.float32), + np.array([2.0, 4.0, 6.0], dtype=np.float32), + ], + equality_test=self.ListsAreClose, + ) + + def testDepthToSpace(self): + + def make_op(data_format): + + def op(x): + return array_ops.depth_to_space( + x, block_size=2, data_format=data_format + ) + + return op + + for dtype in self.numeric_types: + for data_format in ["NCHW", "NHWC"]: + self._assertOpOutputMatchesExpected( + make_op(data_format), + nhwc_to_format( + np.array([[[[1, 2, 3, 4]]]], dtype=dtype), data_format + ), + expected=nhwc_to_format( + np.array([[[[1], [2]], [[3], [4]]]], dtype=dtype), data_format + ), + ) + + self._assertOpOutputMatchesExpected( + make_op(data_format), + nhwc_to_format( + np.array( + [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]], dtype=dtype + ), + data_format, + ), + expected=nhwc_to_format( + np.array( + [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]], + dtype=dtype, + ), + data_format, + ), + ) + + self._assertOpOutputMatchesExpected( + make_op(data_format), + nhwc_to_format( + np.array( + [[ + [[1, 2, 3, 4], [5, 6, 7, 8]], + [[9, 10, 11, 12], [13, 14, 15, 16]], + ]], + dtype=dtype, + ), + data_format, + ), + expected=nhwc_to_format( + np.array( + [[ + [[1], [2], [5], [6]], + [[3], [4], [7], [8]], + [[9], [10], [13], [14]], + [[11], [12], [15], [16]], + ]], + dtype=dtype, + ), + data_format, + ), + ) + + self._assertOpOutputMatchesExpected( + make_op("NCHW_VECT_C"), + np.arange(32, dtype=dtype).reshape((1, 8, 1, 1, 4)), + expected=np.array( + [[ + [ + [[0, 1, 2, 3], [8, 9, 10, 11]], + [[16, 17, 18, 19], [24, 25, 26, 27]], + ], + [ + [[4, 5, 6, 7], [12, 13, 14, 15]], + [[20, 21, 22, 23], [28, 29, 30, 31]], + ], + ]], + dtype=dtype, + ), + ) + + def testSpaceToDepth(self): + + def make_op(data_format): + + def op(x): + return array_ops.space_to_depth( + x, block_size=2, data_format=data_format + ) + + return op + + for dtype in self.numeric_types: + for data_format in ["NCHW", "NHWC"]: + self._assertOpOutputMatchesExpected( + make_op(data_format), + nhwc_to_format( + np.array([[[[1], [2]], [[3], [4]]]], dtype=dtype), data_format + ), + expected=nhwc_to_format( + np.array([[[[1, 2, 3, 4]]]], dtype=dtype), data_format + ), + ) + + self._assertOpOutputMatchesExpected( + make_op(data_format), + nhwc_to_format( + np.array( + [[[[1, 2, 3], [4, 5, 6]], [[7, 8, 9], [10, 11, 12]]]], + dtype=dtype, + ), + data_format, + ), + expected=nhwc_to_format( + np.array( + [[[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]]], dtype=dtype + ), + data_format, + ), + ) + + self._assertOpOutputMatchesExpected( + make_op(data_format), + nhwc_to_format( + np.array( + [[ + [[1], [2], [5], [6]], + [[3], [4], [7], [8]], + [[9], [10], [13], [14]], + [[11], [12], [15], [16]], + ]], + dtype=dtype, + ), + data_format, + ), + expected=nhwc_to_format( + np.array( + [[ + [[1, 2, 3, 4], [5, 6, 7, 8]], + [[9, 10, 11, 12], [13, 14, 15, 16]], + ]], + dtype=dtype, + ), + data_format, + ), + ) + + self._assertOpOutputMatchesExpected( + make_op("NCHW_VECT_C"), + np.arange(32, dtype=dtype).reshape((1, 2, 2, 2, 4)), + expected=np.array( + [[ + [[[0, 1, 2, 3]]], + [[[16, 17, 18, 19]]], + [[[4, 5, 6, 7]]], + [[[20, 21, 22, 23]]], + [[[8, 9, 10, 11]]], + [[[24, 25, 26, 27]]], + [[[12, 13, 14, 15]]], + [[[28, 29, 30, 31]]], + ]], + dtype=dtype, + ), + ) + + def _assertSoftplusMatchesExpected( + self, features, dtype, equality_test=None, rtol=1e-6, atol=9.1e-6 + ): + features = np.array(features, dtype=dtype) + zero = np.asarray(0).astype(dtype) + expected = np.logaddexp(zero, features).astype(dtype) + self._assertOpOutputMatchesExpected( + nn_ops.softplus, + features, + expected=expected, + equality_test=equality_test, + rtol=rtol, + atol=atol, + ) + + def testSoftplus(self): + for dtype in self.float_types & {dtypes.float32, dtypes.float64}: + self._assertSoftplusMatchesExpected([[-2, 0, 8]], dtype) + self._assertSoftplusMatchesExpected( + [[-9, 7, -5, 3, -1], [1, -3, 5, -7, 9]], dtype + ) + if dtype == dtypes.bfloat16.as_numpy_dtype: + log_eps = np.log(np.finfo(np.float32).eps) + else: + log_eps = np.log(np.finfo(dtype).eps) + one = dtype(1) + ten = dtype(10) + self._assertSoftplusMatchesExpected( + [ + log_eps, + log_eps - one, + log_eps + one, + log_eps - ten, + log_eps + ten, + -log_eps, + -log_eps - one, + -log_eps + one, + -log_eps - ten, + -log_eps + ten, + ], + dtype, + ) + + self._assertSoftplusMatchesExpected( + [0.69302183, 0.69324386], + dtype, + equality_test=self.AssertCloseAndSorted, + rtol=9e-5, + atol=9e-5, + ) + + def testToBool(self): + for dtype in self.numeric_types - self.complex_types: + self._assertOpOutputMatchesExpected( + gen_functional_ops.to_bool, + np.array(5, dtype=dtype), + expected=np.array(True), + ) + + self._assertOpOutputMatchesExpected( + gen_functional_ops.to_bool, + np.array(0, dtype=dtype), + expected=np.array(False), + ) + + self._assertOpOutputMatchesExpected( + gen_functional_ops.to_bool, + np.array([], dtype=dtype), + expected=np.array(False), + ) + + self._assertOpOutputMatchesExpected( + gen_functional_ops.to_bool, + np.array([1, 2, 3], dtype=dtype), + expected=np.array(True), + ) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/unique_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unique_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..5d81bf1b21bd0551171043e67c71908d12f090e7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unique_ops_test.py @@ -0,0 +1,46 @@ +# Copyright 2023 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 unique ops.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_array_ops +from tensorflow.python.platform import googletest + + +class UniqueTest(xla_test.XLATestCase): + + def testNegativeAxis(self): + """Verifies that an axis with negative index is converted to positive.""" + with self.session() as session: + with self.test_scope(): + px = array_ops.placeholder(dtypes.float32, [2, 1, 1], name="x") + axis = constant_op.constant([-1], dtype=dtypes.int32) + output = gen_array_ops.unique_v2(px, axis) + result = session.run( + output, {px: np.array([[[-2.0]], [[10.0]]], dtype=np.float32)} + ) + self.assertAllEqual( + result.y, np.array([[[-2.0]], [[10.0]]], dtype=np.float32) + ) + self.assertAllEqual(result.idx, np.array([0], dtype=np.int32)) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/unstack_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unstack_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2eade41730b8dc956979e22eb32b3d7577d41b98 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/unstack_test.py @@ -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. +# ============================================================================== +"""Tests for tensorflow.compiler.tests.unstack.""" + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.platform import test + + +class UnstackOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def _test(self, size): + with self.session() as sess: + x_tf = array_ops.placeholder(np.float32, shape=[size, 512]) + with self.test_scope(): + ret = array_ops_stack.unstack(x_tf) + ret_vals = sess.run([ret], feed_dict={x_tf: np.zeros([size, 512])}) + self.assertLen(ret_vals[0], size) + for ret_val in ret_vals[0]: + self.assertTrue(np.all(ret_val == 0.)) + + def testLarge2000(self): + self._test(2000) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/variable_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/variable_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..752618923c7f53c599cfd09b46e7a9355940afce --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/variable_ops_test.py @@ -0,0 +1,554 @@ +# 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 reading and writing variables.""" +import re + +import numpy as np + +from tensorflow.compiler.tests import xla_test +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.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import gen_state_ops +from tensorflow.python.ops import init_ops +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 import variables +from tensorflow.python.platform import googletest +from tensorflow.python.training.gradient_descent import GradientDescentOptimizer + + +class VariableOpsTest(xla_test.XLATestCase): + """Test cases for resource variable operators.""" + + def testWriteEmptyShape(self): + # Verifies that we can pass an uninitialized variable with an empty shape, + # assign it a value, and successfully return it. + for dtype in self.numeric_types: + with self.session() as sess, self.test_scope(): + zeros = np.zeros([3, 0], dtype=dtype) + v = resource_variable_ops.ResourceVariable(zeros) + p = array_ops.placeholder(dtype) + x = v.assign(p) + with ops.control_dependencies([x]): + y = v.read_value() + self.assertAllClose(zeros, sess.run(y, {p: zeros})) + + def testOneWriteOneOutput(self): + # Regression test for a bug where computations with one non-constant + # output and one variable update were mishandled. + for dtype in self.numeric_types: + init = np.array([[1, 2j], [3, 4]]).astype(dtype) + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + sess.run(variables.variables_initializer([v])) + p = array_ops.placeholder(dtype) + x = v.assign_add(p) + with ops.control_dependencies([x]): + y = v.read_value() + self.assertAllClose( + np.array([[2, 1 + 2j], [4, 5]]).astype(dtype), + sess.run(y, {p: [[1, 1], [1, 1]]})) + + def testSparseRead0DIndices(self): + for dtype in self.numeric_types: + init = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8j, 9, 10, + 11]]).astype(dtype) + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + sess.run(variables.variables_initializer([v])) + x = v.sparse_read(2) + self.assertAllClose( + np.array([8j, 9, 10, 11]).astype(dtype), self.evaluate(x)) + + def testSparseRead1DIndices(self): + for dtype in self.numeric_types: + init = np.array([[0, 1, 2, 3], [4, 5, 6j, 7], [8, 9, 10, + 11]]).astype(dtype) + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + sess.run(variables.variables_initializer([v])) + x = v.sparse_read([2, 1]) + self.assertAllClose( + np.array([[8, 9, 10, 11], [4, 5, 6j, 7]]).astype(dtype), + self.evaluate(x)) + + def testSparseRead2DIndices(self): + for dtype in self.numeric_types: + init = np.array([[0, 1, 2j, 3], [4, 5, 6, 7], [8, 9, 10, + 11]]).astype(dtype) + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + sess.run(variables.variables_initializer([v])) + x = v.sparse_read([[2, 1], [0, 2]]) + self.assertAllClose( + np.array([[[8, 9, 10, 11], [4, 5, 6, 7]], + [[0, 1, 2j, 3], [8, 9, 10, 11]]]).astype(dtype), + self.evaluate(x)) + + def testSparseRead2DIndices3DTensor(self): + for dtype in self.numeric_types: + init = np.array([[[0, 1, 2], [3, 4, 5]], [[10, 11, 12], [13, 14, 15]], + [[20, 21, 22], [23, 24j, 25]], + [[30, 31, 32], [33, 34, 35]]]).astype(dtype) + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + sess.run(variables.variables_initializer([v])) + x = v.sparse_read([[2, 1], [3, 0]]) + self.assertAllClose( + np.array( + [[[[20, 21, 22], [23, 24j, 25]], [[10, 11, 12], [13, 14, 15]]], + [[[30, 31, 32], [33, 34, 35]], [[0, 1, 2], [3, 4, 5]]] + ],).astype(dtype), self.evaluate(x)) + + def testShape(self): + for dtype in self.numeric_types: + init = np.ones([2, 3]).astype(dtype) + with self.session() as session, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + session.run(variables.variables_initializer([v])) + h = v.handle + s32, s64 = session.run([ + resource_variable_ops.variable_shape(h), + resource_variable_ops.variable_shape(h, out_type=dtypes.int64) + ]) + self.assertEqual(s32.dtype, np.int32) + self.assertEqual(s64.dtype, np.int64) + self.assertAllEqual(s32, [2, 3]) + self.assertAllEqual(s64, [2, 3]) + + def testInvalidShape(self): + pattern = re.compile("shapes must be equal", re.IGNORECASE) + # test invalid shape on assign_add in XLA + with self.assertRaisesRegex(Exception, pattern): + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable([0, 1, 2, 3]) + sess.run(variables.variables_initializer([v])) + x = v.assign_add(1) + sess.run(x) + + # test invalid shape raised on assign_sub in XLA + with self.assertRaisesRegex(Exception, pattern): + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable([0, 1, 2, 3]) + sess.run(variables.variables_initializer([v])) + x = v.assign_sub(1) + sess.run(x) + + def testReadWrite(self): + """Tests initialization, reading, and writing a resource variable.""" + for dtype in self.numeric_types: + with self.session() as session: + with self.test_scope(): + with variable_scope.variable_scope("ascope", use_resource=True): + x = variable_scope.get_variable( + "x", + shape=[], + dtype=dtype, + initializer=init_ops.constant_initializer(2)) + a = x.read_value() + with ops.control_dependencies([a]): + b = state_ops.assign(x, dtype(47)) + with ops.control_dependencies([b]): + c = x.read_value() + with ops.control_dependencies([c]): + d = state_ops.assign_add(x, np.array(6 + 2j).astype(dtype)) + with ops.control_dependencies([d]): + e = state_ops.assign_sub(x, dtype(3)) + with ops.control_dependencies([e]): + f = x.read_value() + + session.run(variables.global_variables_initializer()) + v1, v2, v3 = session.run([a, c, f]) + self.assertAllClose(dtype(2), v1) + self.assertAllClose(dtype(47), v2) + self.assertAllClose(np.array(50 + 2j).astype(dtype), v3) + + def testTraining(self): + """Tests a gradient descent step for a simple model.""" + with self.session() as session: + with self.test_scope(): + with variable_scope.variable_scope("ascope", use_resource=True): + w = variable_scope.get_variable( + "w", + shape=[4, 2], + dtype=dtypes.float32, + initializer=init_ops.constant_initializer( + np.array([[1, 2], [3, 4], [5, 6], [7, 8]], dtype=np.float32))) + b = variable_scope.get_variable( + "b", + shape=[2], + dtype=dtypes.float32, + initializer=init_ops.constant_initializer( + np.array([2, 3], dtype=np.float32))) + + x = array_ops.placeholder(dtypes.float32, shape=[1, 4]) + y = math_ops.matmul(x, w) + b + loss = math_ops.reduce_sum(y) + optimizer = GradientDescentOptimizer(0.1) + train = optimizer.minimize(loss) + + session.run(variables.global_variables_initializer()) + session.run(train, {x: np.array([[7, 3, 5, 9]], dtype=np.float32)}) + vw, vb = session.run([w, b]) + self.assertAllClose( + np.array( + [[0.3, 1.3], [2.7, 3.7], [4.5, 5.5], [6.1, 7.1]], + dtype=np.float32), + vw, + rtol=1e-4) + self.assertAllClose(np.array([1.9, 2.9], dtype=np.float32), vb, rtol=1e-4) + + def testWriteOfAliasedTensor(self): + for dtype in self.numeric_types: + init = np.array([[1, 2j], [3, 4]]).astype(dtype) + update = np.array([[7, 1j], [2, 11]]).astype(dtype) + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable(init) + sess.run(variables.variables_initializer([v])) + p = array_ops.placeholder(dtype) + q = array_ops.identity(p) + x = v.read_value() + # Writes the value of 'p' to 'v', but keeps a reference to the original + # value of 'v' so the variable update cannot reuse its buffer. + with ops.control_dependencies([x]): + y = v.assign(q) + result = sess.run([x, y, q], {p: update}) + self.assertAllClose(init, result[0]) + self.assertAllClose(update, result[1]) + self.assertAllClose(update, result[2]) + + def testScatterAdd(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[2, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[1], [7]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_add( + handle, [0], constant_op.constant([[2]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertAllEqual(self.evaluate(read), [[3], [7]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterSub") + def testScatterSub(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[2, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[4], [1]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_sub( + handle, [1], constant_op.constant([[2]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertAllEqual(self.evaluate(read), [[4], [-1]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterMul") + def testScatterMul(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[1]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_mul( + handle, [0], constant_op.constant([[5]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[5]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterDiv") + def testScatterDiv(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_div( + handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertAllEqual(self.evaluate(read), [[2]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterMin") + def testScatterMin(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_min( + handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[3]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterMax") + def testScatterMax(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_max( + handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[6]]) + + def testScatterUpdate(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_update( + handle, [0], constant_op.constant([[3]], dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[3]]) + + def testScatterScalarUpdate(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_update( + handle, [0], constant_op.constant(3, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[3]]) + + def testScatterAddScalarUpdate(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[1]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_add( + handle, [0], constant_op.constant(2, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[3]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterSub") + def testScatterSubScalar(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[1]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_sub( + handle, [0], constant_op.constant(2, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[-1]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterMul") + def testScatterMulScalar(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[1]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_mul( + handle, [0], constant_op.constant(5, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[5]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterDiv") + def testScatterDivScalar(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_div( + handle, [0], constant_op.constant(3, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[2]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterMin") + def testScatterMinScalar(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_min( + handle, [0], constant_op.constant(3, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[3]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterMax") + def testScatterMaxScalar(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.int32, shape=[1, 1]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([[6]], dtype=dtypes.int32))) + sess.run( + resource_variable_ops.resource_scatter_max( + handle, [0], constant_op.constant(3, dtype=dtypes.int32))) + read = resource_variable_ops.read_variable_op(handle, dtype=dtypes.int32) + self.assertEqual(self.evaluate(read), [[6]]) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterNdAdd") + def testScatterNdAddOps(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.float32, shape=[8]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([1] * 8, dtype=dtypes.float32))) + indices = constant_op.constant([[4], [3], [1], [7]], dtype=dtypes.int32) + updates = constant_op.constant([9, 10, 11, 12], dtype=dtypes.float32) + expected = np.array([1, 12, 1, 11, 10, 1, 1, 13]) + sess.run(gen_state_ops.resource_scatter_nd_add(handle, indices, updates)) + read = resource_variable_ops.read_variable_op( + handle, dtype=dtypes.float32) + self.assertAllClose(expected, self.evaluate(read)) + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceScatterNdUpdateAdd") + def testScatterNdUpdateAddOps(self): + with self.session() as sess, self.test_scope(): + handle = resource_variable_ops.var_handle_op( + dtype=dtypes.float32, shape=[8]) + sess.run( + resource_variable_ops.assign_variable_op( + handle, constant_op.constant([1] * 8, dtype=dtypes.float32))) + indices = constant_op.constant([[4], [3], [1], [7]], dtype=dtypes.int32) + updates = constant_op.constant([9, 10, 11, 12], dtype=dtypes.float32) + expected = np.array([1, 11, 1, 10, 9, 1, 1, 12]) + sess.run( + gen_state_ops.resource_scatter_nd_update(handle, indices, updates)) + read = resource_variable_ops.read_variable_op( + handle, dtype=dtypes.float32) + self.assertAllClose(expected, self.evaluate(read)) + + +class StridedSliceAssignChecker(object): + """Compares the results of a slice assignment using Tensorflow and numpy.""" + + def __init__(self, test, x, dtype): + self.dtype = dtype + self.test = test + self.x_np = np.array(x).astype(dtype) + # Randomly start on mode 0 or 1. + self.which_mode = np.random.randint(2, size=1)[0] + + def __setitem__(self, index, value): + self.which_mode = 1 - self.which_mode + value = np.array(value).astype(self.dtype) + + with self.test.session() as sess, self.test.test_scope(): + x = constant_op.constant(self.x_np, dtype=self.dtype) + var = resource_variable_ops.ResourceVariable(x) + sess.run(variables.variables_initializer([var])) + + if self.which_mode == 0: + val = sess.run(var[index].assign(value)) + else: + assert self.which_mode == 1 + val = sess.run(state_ops.assign(var[index], value)) + valnp = np.copy(self.x_np) + valnp[index] = np.array(value) + self.test.assertAllEqual(val, valnp) + + +class SliceAssignTest(xla_test.XLATestCase): + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support ResourceStridedSliceAssign") + def testSliceAssign(self): + for dtype in self.numeric_types: + checker = StridedSliceAssignChecker( + self, [[1, 2, 3], [4, 5, 6]], dtype=dtype) + # No-op assignment + checker[:] = [[10, 20, 30], [40, 50, 60]] + # Checks trivial (1,1) shape tensor + checker[1:2, 1:2] = [[66]] + # shrink shape changes + checker[1:2, 1] = [66] + checker[1, 1:2] = [66] + if dtype != dtypes.bfloat16.as_numpy_dtype: + # TODO(b/68813416): valnp call above results in an ndarray and not a + # number for bfloat16s. + checker[1, 1] = 66 + # newaxis shape changes + checker[:, None, :] = [[[10, 20, 30]], [[40, 50, 50]]] + # shrink and newaxis + checker[None, None, 0, 0:1] = [[[99]]] + # Non unit strides + checker[::1, 1::-1] = [[3, 33], [4, 44]] + # degenerate interval + checker[8:10, 0] = [] + checker[8:10, 8:10] = [[]] + + # Assign vector to scalar (rank-0) using newaxis + checker2 = StridedSliceAssignChecker(self, 222, dtype=dtype) + if dtype != dtypes.bfloat16.as_numpy_dtype: + # TODO(b/68813416): valnp call above results in an ndarray and not a + # number for bfloat16s. + checker2[()] = 6 # no indices + checker2[...] = 6 # ellipsis + checker2[None] = [6] # new axis + + @test_util.disable_mlir_bridge("TODO: MLIR bridge does not yet" + "support uninitialized resource variable") + def testUninitialized(self): + with self.assertRaisesRegex(errors.FailedPreconditionError, + "uninitialized"): + with self.session() as sess, self.test_scope(): + v = resource_variable_ops.ResourceVariable([1, 2]) + sess.run(v[:].assign([1, 2])) + + +if __name__ == "__main__": + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/where_op_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/where_op_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e6eeb89d0f08f538de844ba15eaa03a695d688a0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/where_op_test.py @@ -0,0 +1,132 @@ +# Copyright 2020 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 where op.""" + +# pylint: disable=g-direct-tensorflow-import +from tensorflow.compiler.tests import xla_test +from tensorflow.python.framework import config +from tensorflow.python.framework import dtypes +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import test +from tensorflow.python.tpu import tpu +# pylint: enable=g-direct-tensorflow-import + + +class WhereOpTest(xla_test.XLATestCase): + + def __init__(self, method_name="runTest"): + super(WhereOpTest, self).__init__(method_name) + if config.list_logical_devices("TPU"): + with self.session() as sess: + sess.run(tpu.initialize_system()) + + def testWhere(self): + """Test first form of where (return indices).""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.bool) + true_vals = array_ops.where(x) + + # Output of the computation is dynamic. + feed = [[True, False, False], [False, True, True]] + self.assertAllEqual([[0, 0], [1, 1], [1, 2]], + sess.run(true_vals, {x: feed})) + + def testWhereGather(self): + """Test where followed by a gather.""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.bool) + value = array_ops.constant([[0, 1], [2, 3]], dtypes.float32) + true_vals = array_ops.where(x) + + # Gather 0, 2, 3. + gathered = array_ops.gather_nd(value, true_vals) + + feed = [[True, False], [True, True]] + self.assertAllEqual([0, 2, 3], sess.run(gathered, {x: feed})) + + def testWhereGatherReduce(self): + """Test where followed by a gather and a reduce.""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.bool) + value = array_ops.constant([[0, 1], [2, 3]], dtypes.float32) + indices = array_ops.where(x) + + # Reduce to 5 + gathered = array_ops.gather_nd(value, indices) + reduction = math_ops.reduce_sum(gathered) + + feed = [[True, False], [True, True]] + self.assertAllEqual(5, sess.run(reduction, {x: feed})) + + def testWhere1D(self): + """Test first form of where (return indices).""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.bool) + result = array_ops.where(x) + + # Output of the computation is dynamic. + feed = [True, False, True] + self.assertAllEqual([[0], [2]], sess.run(result, {x: feed})) + + def testWhereInt(self): + """Test Where with integers.""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.int32) + result = array_ops.where(x) + + # Output of the computation is dynamic. + feed = [-1, 0, 1] + self.assertAllEqual([[0], [2]], sess.run(result, {x: feed})) + + def testWhereFloat(self): + """Test Where with floats.""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.float32) + result = array_ops.where(x) + + # Output of the computation is dynamic. + feed = [-1.0, -0.0, 0.0, 1.0] + self.assertAllEqual([[0], [3]], sess.run(result, {x: feed})) + + def testWhereComplex(self): + """Test Where with floats.""" + + with self.session() as sess: + with self.test_scope(): + x = array_ops.placeholder(dtypes.complex64) + result = array_ops.where(x) + + # Output of the computation is dynamic. + feed = [ + -1.0 + 0.0j, -0.0 + 0.0j, 0.0 - 0.0j, 1.0 - 1.0j, 1.0 + 0.0j, + 0.0 + 1.0j + ] + self.assertAllEqual([[0], [3], [4], [5]], sess.run(result, {x: feed})) + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/while_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/while_test.py new file mode 100644 index 0000000000000000000000000000000000000000..2bdbf02f04f7f4d76b982bb0c6bf658838dc310f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/while_test.py @@ -0,0 +1,265 @@ +# 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 while loops in XLA.""" + +import os + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.python.framework import constant_op +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import function +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import control_flow_ops +from tensorflow.python.ops import gradients_impl +from tensorflow.python.ops import map_fn +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import while_loop +from tensorflow.python.platform import test + + +class WhileTest(xla_test.XLATestCase): + + def testSingletonLoopHandrolled(self): + # Define a function for the loop body + @function.Defun(dtypes.int32) + def loop_body(step): + step_out = step + constant_op.constant(1, dtype=dtypes.int32) + return step_out + + # Define a function for the loop condition + @function.Defun(dtypes.int32) + def loop_cond(step): + return step < 10 + + with self.session() as sess: + init_index = array_ops.placeholder(dtypes.int32, []) + with self.test_scope(): + loop_outputs = xla.while_loop([init_index], loop_cond, loop_body) + + result = sess.run(loop_outputs, {init_index: 0}) + self.assertAllClose(result, [10], rtol=1e-3) + + def testCountingLoopHandrolled(self): + # Define a function for the loop body + @function.Defun(dtypes.int32, dtypes.float32) + def loop_body(step, rsum): + step_out = step + constant_op.constant(1, dtype=dtypes.int32) + sum_out = rsum + constant_op.constant(1.5, dtype=dtypes.float32) + return step_out, sum_out + + # Define a function for the loop condition + @function.Defun(dtypes.int32, dtypes.float32) + def loop_cond(step, rsum): + del rsum + return step < 10 + + with self.session() as sess: + init_index = array_ops.placeholder(dtypes.int32, []) + init_sum = array_ops.placeholder(dtypes.float32, []) + with self.test_scope(): + loop_outputs = xla.while_loop([init_index, init_sum], loop_cond, + loop_body) + + result = sess.run(loop_outputs, {init_index: 0, init_sum: 0.0}) + self.assertAllClose(result, [10, 15.0], rtol=1e-3) + no_iters_result = sess.run(loop_outputs, {init_index: 10, init_sum: 0.0}) + self.assertAllClose(no_iters_result, [10, 0.0], rtol=1e-3) + + def testCountingLoopHandrolledC64(self): + # Define a function for the loop body + @function.Defun(dtypes.int32, dtypes.complex64) + def loop_body(step, rsum): + step_out = step + constant_op.constant(1, dtype=dtypes.int32) + sum_out = rsum + constant_op.constant(1.5 + 2j, dtype=dtypes.complex64) + return step_out, sum_out + + # Define a function for the loop condition + @function.Defun(dtypes.int32, dtypes.complex64) + def loop_cond(step, rsum): + del rsum + return step < 10 + + with self.session() as sess: + init_index = array_ops.placeholder(dtypes.int32, []) + init_sum = array_ops.placeholder(dtypes.complex64, []) + with self.test_scope(): + loop_outputs = xla.while_loop([init_index, init_sum], loop_cond, + loop_body) + + result = sess.run(loop_outputs, {init_index: 0, init_sum: 0.0}) + self.assertAllClose(result[1], np.complex64(15 + 20j), rtol=1e-3) + no_iters_result = sess.run(loop_outputs, {init_index: 10, init_sum: 0.0}) + self.assertAllClose(no_iters_result[1], np.complex64(0), rtol=1e-3) + + def testLoopWithConstantOutput(self): + # Define a function for the loop body + @function.Defun(dtypes.int32, dtypes.int32) + def loop_body(step, x): + del x + step_out = step + constant_op.constant(1, dtype=dtypes.int32) + return (step_out, 7) + + # Define a function for the loop condition + @function.Defun(dtypes.int32, dtypes.int32) + def loop_cond(step, x): + del x + return step < 10 + + with self.session() as sess: + init_index = array_ops.placeholder(dtypes.int32, []) + with self.test_scope(): + loop_outputs = xla.while_loop([init_index, 42], loop_cond, loop_body) + + result = sess.run(loop_outputs, {init_index: 0}) + self.assertAllClose(result, [10, 7], rtol=1e-3) + + def _testMaxItersSimple(self): + if is_compile_on_demand(): + self.skipTest("list_ops are not supported in cpu_ondemand") + with self.session() as sess, self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + v = constant_op.constant(1.0) + p = array_ops.placeholder(dtype=dtypes.int32) + + def create_while_loop(): + iterations = array_ops.size(p, name="iterations") + r = while_loop.while_loop( + lambda *_: True, + lambda i, x: (i + 1, v * x), (0, 1.0), + maximum_iterations=iterations, + name="outer") + return array_ops.identity(r[1]) + + output = create_while_loop() + output = gradients_impl.gradients(output, v)[0] + + result = sess.run(output, feed_dict={p: [0, 0, 0]}) + print(result) + xla_context.Exit() + + def testMaxItersSimple(self): + self.skipTest("Fails with v1 control flow") + # This fails with old control. + # self._testMaxItersSimple() + + @test_util.enable_control_flow_v2 + def testMaxItersSimpleV2(self): + self._testMaxItersSimple() + + def _testNestedWhileLoopWithMaxItersFromOuterContext(self): + if is_compile_on_demand(): + self.skipTest("list_ops are not supported in cpu_ondemand") + with self.session() as sess, self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + v = constant_op.constant(1.0) + p = array_ops.placeholder(dtype=dtypes.int32) + + def mid_body_builder(iterations): + + def mid_body(i, x): + r = while_loop.while_loop( + lambda *_: True, + lambda i, x: (i + 1, v * x), (0, x), + maximum_iterations=iterations, + name="inner") + return (i + 1, gradients_impl.gradients(x + r[1], v)[0]) + + return mid_body + + def outer_body(i, x): + iterations = array_ops.size(p, name="iterations") + return (i + 1, x + while_loop.while_loop( + lambda *_: True, + mid_body_builder(iterations), (0, x), + maximum_iterations=iterations, + name="mid")[1]) + + def create_while_loop(): + r = while_loop.while_loop( + lambda *_: True, + outer_body, (0, 1.0), + maximum_iterations=5, + name="outer") + return array_ops.identity(r[1]) + + # p:placeholder + # j = 0 + # i, x = 0, 1. + # while j++ < 5: + # i1, x1 = 0, x + # while i1++ < len(p): + # i2, x2 = 0, x1 + # while i2++ < len(p): + # x2 = v * x2 + # x1 = grad(x1 + x2, v) + # x = x1 + # output = x + output = create_while_loop() + sess.run(output, feed_dict={p: [0, 0, 0]}) + xla_context.Exit() + + def testNestedWhileLoopWithMaxItersFromOuterContext(self): + self._testNestedWhileLoopWithMaxItersFromOuterContext() + + @test_util.enable_control_flow_v2 + def testNestedWhileLoopWithMaxItersFromOuterContextV2(self): + self._testNestedWhileLoopWithMaxItersFromOuterContext() + + @test_util.enable_control_flow_v2 + def testMap(self): + if is_compile_on_demand(): + self.skipTest("list_ops are not supported in cpu_ondemand") + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + nums = [1, 2, 3, 4, 5, 6] + elems = constant_op.constant(nums, name="data") + r = map_fn.map_fn(lambda x: math_ops.multiply(math_ops.add(x, 3), 2), + elems) + self.assertAllEqual(r, np.array([(x + 3) * 2 for x in nums])) + xla_context.Exit() + + @test_util.enable_control_flow_v2 + def testMapBackPropFalse(self): + if is_compile_on_demand(): + self.skipTest("list_ops are not supported in cpu_ondemand") + with self.session(), self.test_scope(): + xla_context = control_flow_ops.XLAControlFlowContext() + xla_context.Enter() + nums = [1, 2, 3, 4, 5, 6] + elems = constant_op.constant(nums, name="data") + r = map_fn.map_fn( + lambda x: math_ops.multiply(math_ops.add(x, 3), 2), + elems, + back_prop=False) + self.assertAllEqual(r, np.array([(x + 3) * 2 for x in nums])) + xla_context.Exit() + + +def is_compile_on_demand(): + return ("TF_XLA_FLAGS" in os.environ and + "tf_xla_compile_on_demand" in os.environ["TF_XLA_FLAGS"]) + + +if __name__ == "__main__": + os.environ["TF_XLA_FLAGS"] = ("--tf_xla_min_cluster_size=2 " + + os.environ.get("TF_XLA_FLAGS", "")) + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_call_module_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_call_module_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0e4746b73362c63760b65feadeffe8a80f09ac7b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_call_module_test.py @@ -0,0 +1,1600 @@ +# Copyright 2022 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 XLA call module op wrapper.""" + +import os +import re +from typing import Optional, Sequence +import unittest + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.mlir.stablehlo import stablehlo +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.ops import gen_xla_ops +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.core.protobuf import config_pb2 +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +from tensorflow.python.platform import googletest +from tensorflow.python.platform import test + + +def serialize(module_str: str) -> tuple[str, int]: + target = stablehlo.get_minimum_version() + byte_str = stablehlo.serialize_portable_artifact_str(module_str, target) + return byte_str, xla.call_module_maximum_supported_version() + + +class XlaCallModuleOpTest(xla_test.XLATestCase, parameterized.TestCase): + + def _assertOpOutputMatchesExpected(self, + op, + args, + expected, + equality_fn=None): + """Asserts op(*args) == expected.""" + with self.test_scope(): + tf_func = def_function.function(op, autograph=False, jit_compile=True) + result = tf_func(*args) + + if not equality_fn: + equality_fn = self.assertAllClose + equality_fn(result, expected, rtol=1e-3) + + def testing_platform(self): + """Current testing platform, one of CPU, GPU, TPU.""" + if self.device in ['CPU', 'XLA_CPU']: + return 'CPU' + elif self.device in ['GPU', 'XLA_GPU']: + if test.is_built_with_rocm(): + return 'ROCM' + else: + return 'CUDA' + elif self.device in ['TPU', 'XLA_TPU']: + return 'TPU' + else: + assert False, f'Unexpected {self.device=}' + + def test_basic(self): + x = np.array([1., 2., 3.], dtype=np.float32) + + def f(x): + # sin(cos(x)) + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg0: tensor<3xf32>) -> tensor<3xf32> { + %0 = stablehlo.cosine %arg0 : tensor<3xf32> + %1 = stablehlo.sine %0 : tensor<3xf32> + return %1 : tensor<3xf32> + } +} +""") + return xla.call_module([x], version=version, + module=module, Tout=[x.dtype], Sout=[x.shape], + platforms=[self.testing_platform()]) + + self._assertOpOutputMatchesExpected(f, (x,), (np.sin(np.cos(x)),)) + + def test_basic_with_token_v8(self): + x = np.array([1.0, 2.0, 3.0], dtype=np.float32) + + def f(x): + # sin(cos(x)) + module, _ = serialize(""" +module @jit_f.0 { + func.func public @main(%arg0: !stablehlo.token, %arg1: tensor<3xf32>) -> (!stablehlo.token, tensor<3xf32>) { + %0 = stablehlo.cosine %arg1 : tensor<3xf32> + %1 = stablehlo.sine %0 : tensor<3xf32> + return %arg0, %1 : !stablehlo.token, tensor<3xf32> + } +} +""") + return xla.call_module( + [x], + version=8, # Version 8 uses only one prefix token + module=module, + Tout=[x.dtype], + Sout=[x.shape], + has_token_input_output=True, # Version 8 cares about this + platforms=[self.testing_platform()], + ) + + self._assertOpOutputMatchesExpected(f, (x,), (np.sin(np.cos(x)),)) + + def test_basic_with_multiple_tokens(self): + x = np.array([1.0, 2.0, 3.0], dtype=np.float32) + + def f(x): + # sin(cos(x)) + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg0: !stablehlo.token {jax.token = true}, %arg1: !stablehlo.token {jax.token = true}, %arg2: tensor<3xf32>) -> (!stablehlo.token, !stablehlo.token, tensor<3xf32>) { + %0 = stablehlo.cosine %arg2 : tensor<3xf32> + %1 = stablehlo.sine %0 : tensor<3xf32> + return %arg0, %arg1, %1 : !stablehlo.token, !stablehlo.token, tensor<3xf32> + } +} +""") + return xla.call_module( + [x], + version=version, + module=module, + Tout=[x.dtype], + Sout=[x.shape], + platforms=[self.testing_platform()], + ) + + self._assertOpOutputMatchesExpected(f, (x,), (np.sin(np.cos(x)),)) + + def test_basic_with_tokens_preceeded_by_other_args(self): + x = np.array([1.0, 2.0, 3.0], dtype=np.float32) + + def f(x): + # sin(cos(x)) + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg0: tensor, %arg1: !stablehlo.token {jax.token = true}, %arg2: !stablehlo.token {jax.token = true}, %arg3: tensor<3xf32>) -> (!stablehlo.token, !stablehlo.token, tensor<3xf32>) { + %0 = stablehlo.cosine %arg3 : tensor<3xf32> + %1 = stablehlo.sine %0 : tensor<3xf32> + return %arg1, %arg2, %1 : !stablehlo.token, !stablehlo.token, tensor<3xf32> + } +} +""") + return xla.call_module( + [np.int32(0), x], + version=version, + module=module, + Tout=[x.dtype], + Sout=[x.shape], + platforms=[self.testing_platform()], + ) + + self._assertOpOutputMatchesExpected(f, (x,), (np.sin(np.cos(x)),)) + + def test_compare(self): + x = np.uint32(2) + res = np.bool_(True) + + def f(x): + # return x >= 1 + module, version = serialize(""" +module @jit_f_jax.0 { + func.func public @main(%arg0: tensor) -> tensor { + %0 = stablehlo.constant dense<1> : tensor + %1 = "stablehlo.compare"(%arg0, %0) {compare_type = #stablehlo, comparison_direction = #stablehlo} : (tensor, tensor) -> tensor + return %1 : tensor + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_multiple_args_results(self): + x = np.array([1., 2., 3.], dtype=np.float32) + y = np.array([11., 12., 13., 14.], dtype=np.float64) + + def f(x, y): + # (sin(x), cos(y)) + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg0: tensor<3xf32>, %arg1: tensor<4xf64>) -> (tensor<3xf32>, tensor<4xf64>) { + %0 = stablehlo.sine %arg0 : tensor<3xf32> + %1 = stablehlo.cosine %arg1 : tensor<4xf64> + return %0, %1 : tensor<3xf32>, tensor<4xf64> + } +} +""") + return xla.call_module([x, y], version=version, + module=module, + Tout=[x.dtype, y.dtype], + Sout=[x.shape, y.shape], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x, y), (np.sin(x), np.cos(y))) + + # TODO(b/305813026): asan test failure for the i64 test variant. + @parameterized.named_parameters( + dict(testcase_name='_' + dim_var_type, + dim_var_type=dim_var_type) + for dim_var_type in ('i32',) + ) + def test_poly_basic(self, *, dim_var_type: str): + x = np.arange(6, dtype=np.float32).reshape((2, 3)) + + def f(x): # x: f32[2, b] + # (sin(x), x.shape[1]) + module, version = serialize(f""" +module @jit_f.0 attributes {{jax.uses_shape_polymorphism = true}} {{ + func.func public @main(%arg1: tensor<2x?xf32>) -> (tensor<2x?xf32>, tensor<{dim_var_type}>) {{ + %arg0_new_i32 = "stablehlo.get_dimension_size"(%arg1) {{dimension = 1 : i64}} : (tensor<2x?xf32>) -> tensor + %arg0_new = stablehlo.convert %arg0_new_i32 : (tensor) -> tensor<{dim_var_type}> + %0, %1 = call @dyn_main(%arg0_new, %arg1) : (tensor<{dim_var_type}>, tensor<2x?xf32>) -> (tensor<2x?xf32>, tensor<{dim_var_type}>) + return %0, %1 : tensor<2x?xf32>, tensor<{dim_var_type}> + }} + func.func private @dyn_main(%arg0: tensor<{dim_var_type}> {{jax.global_constant = "b"}}, %arg1: tensor<2x?xf32>) -> (tensor<2x?xf32>, tensor<{dim_var_type}>) {{ + %0 = stablehlo.sine %arg1 : tensor<2x?xf32> + return %0, %arg0 : tensor<2x?xf32>, tensor<{dim_var_type}> + }} +}} +""") + return xla.call_module([x], + module=module, version=version, + Tout=[x.dtype, np.int32], + Sout=[(None, 3), ()], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (np.sin(x), x.shape[1])) + + def test_wrong_actual_args_errors(self): + x = np.arange(6, dtype=np.float32).reshape((3, 2)) + y = np.arange(6, dtype=np.int32).reshape((2, 3)) + + # x: f32[a, 2], return x + module, version = serialize(""" +module @jit_f.0 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg0: tensor, %arg1: tensor<*xi32>) -> tensor { + return %arg0 : tensor + } +} +""") + + def f(x, y): + return xla.call_module( + [x, y], + module=module, + version=version, + Tout=[x.dtype], + Sout=[(None, 2)], + platforms=[self.testing_platform()], + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (x,)) + + x_bad_etype = x.astype(np.int32) + with self.assertRaisesRegex( + errors.InvalidArgumentError, + re.escape( + 'invalid refinement for argument 0, refinement element types must' + ' match in tensor -> tensor<3x2xi32>' + ), + ): + self._assertOpOutputMatchesExpected(f, (x_bad_etype, y), (x_bad_etype,)) + + y_bad_etype = y.astype(np.float32) + with self.assertRaisesRegex( + errors.InvalidArgumentError, + re.escape( + 'invalid refinement for argument 1, refinement element types must' + ' match in tensor<*xi32> -> tensor<2x3xf32>' + ), + ): + self._assertOpOutputMatchesExpected(f, (x, y_bad_etype), (x,)) + + x_bad_shape = np.arange(15, dtype=np.float32).reshape(5, 3) + with self.assertRaisesRegex( + errors.InvalidArgumentError, + re.escape( + 'invalid refinement for argument 0, refinement dimension sizes must' + ' match for static dimensions in tensor -> tensor<5x3xf32>' + ), + ): + self._assertOpOutputMatchesExpected(f, (x_bad_shape, y), (x_bad_shape,)) + + @parameterized.named_parameters( + dict(testcase_name='_' + platform_idx_type, + platform_idx_type=platform_idx_type) + for platform_idx_type in ('i32', 'i64') + ) + def test_platforms_basic(self, *, platform_idx_type: str): + x = np.float32(0.) + + # returns x + 2. on CPU, x + 3. on GPU (CUDA or ROCM) and x + 4. on TPU + module, version = serialize(f""" +module @jit_f.0 {{ + func.func public @main(%arg_platform_idx: tensor<{platform_idx_type}> {{jax.global_constant = "_platform_index"}}, %arg0: tensor) -> tensor {{ + %0 = stablehlo.convert %arg_platform_idx : (tensor<{platform_idx_type}>) -> tensor + %to_add = "stablehlo.case"(%0) ({{ + %cpu_val = stablehlo.constant dense<2.> : tensor + stablehlo.return %cpu_val : tensor + }}, {{ + %gpu_val = stablehlo.constant dense<3.> : tensor + stablehlo.return %gpu_val : tensor + }}, {{ + %tpu_val = stablehlo.constant dense<4.> : tensor + stablehlo.return %tpu_val : tensor + }}) : (tensor) -> tensor + %1 = stablehlo.add %arg0, %to_add : tensor + return %1 : tensor + }} +}} +""") + + platforms = ['CPU', 'CUDA', 'ROCM', 'TPU'] + def f(x): + return xla.call_module([x], version=version, + module=module, + Tout=[np.float32], + Sout=[()], + platforms=platforms) + + expected_value = ( + x + dict(CPU=2.0, CUDA=3.0, ROCM=3.0, TPU=4.0)[self.testing_platform()] + ) + self._assertOpOutputMatchesExpected(f, (x,), (expected_value,)) + + def test_platforms_unknown_custom_call(self): + # One of the platform branches ("ROCM") has custom call unknown to other + # platforms. + if self.testing_platform() == 'ROCM': + raise unittest.SkipTest('Not intended for ROCM') + x = np.float32(0.) + + # returns x + 2. on CPU, x + 3. on GPU, and x + 4. on TPU + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg_platform_idx: tensor {jax.global_constant = "_platform_index"}, %arg0: tensor) -> tensor { + %to_add = "stablehlo.case"(%arg_platform_idx) ({ + %cpu_val = stablehlo.constant dense<2.> : tensor + stablehlo.return %cpu_val : tensor + }, { + %gpu_val = stablehlo.constant dense<3.> : tensor + stablehlo.return %gpu_val : tensor + }, { + %tpu_val = stablehlo.constant dense<4.> : tensor + stablehlo.return %tpu_val : tensor + }, { + %rocm_val = stablehlo.custom_call @non_existent_target(%arg0) : (tensor) -> tensor + stablehlo.return %rocm_val : tensor + }) : (tensor) -> tensor + %0 = stablehlo.add %arg0, %to_add : tensor + return %0 : tensor + } +} +""") + + platforms = ['CPU', 'CUDA', 'TPU', 'ROCM'] + def f(x): + return xla.call_module([x], version=version, + module=module, + Tout=[np.float32], + Sout=[()], + platforms=platforms) + + expected_value = ( + x + dict(CPU=2.0, CUDA=3.0, TPU=4.0)[self.testing_platform()] + ) + self._assertOpOutputMatchesExpected(f, (x,), (expected_value,)) + + def test_platforms_and_poly(self): + x = np.arange(6, dtype=np.float32) + # returns x + 2. on CPU, x + 3. on GPU (CUDA or ROCM) and x + 4. on TPU + + module, version = serialize(""" +module @jit_f_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_platform_idx: tensor {jax.global_constant = "_platform_index"}, %arg0: tensor) -> (tensor) { + %0 = stablehlo.get_dimension_size %arg0, dim = 0 : (tensor) -> tensor + %5 = call @_wrapped_jax_export_main(%arg_platform_idx, %0, %arg0) : (tensor, tensor, tensor) -> tensor + return %5 : tensor + } + + func.func private @_wrapped_jax_export_main(%arg_platform_idx: tensor {jax.global_constant = "_platform_index"}, %arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> (tensor) { + %to_add = "stablehlo.case"(%arg_platform_idx) ({ + %cpu_val = stablehlo.constant dense<2.> : tensor + stablehlo.return %cpu_val : tensor + }, { + %gpu_val = stablehlo.constant dense<3.> : tensor + stablehlo.return %gpu_val : tensor + }, { + %tpu_val = stablehlo.constant dense<4.> : tensor + stablehlo.return %tpu_val : tensor + }) : (tensor) -> tensor + %1 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %3 = stablehlo.dynamic_broadcast_in_dim %to_add, %1, dims = [] : (tensor, tensor<1xi32>) -> tensor + %4 = stablehlo.add %3, %arg1 : tensor + return %4 : tensor + } +} +""") + platforms = ['CPU', 'CUDA', 'ROCM', 'TPU'] + def f(x): + return xla.call_module([x], version=version, + module=module, + Tout=[np.float32], + Sout=[()], + platforms=platforms) + + expected_value = ( + x + dict(CPU=2.0, CUDA=3.0, ROCM=3.0, TPU=4.0)[self.testing_platform()] + ) + self._assertOpOutputMatchesExpected(f, (x,), (expected_value,)) + + def test_platforms_and_poly_and_tokens(self): + x = np.arange(6, dtype=np.float32) + # returns x + 2. on CPU, x + 3. on GPU (CUDA or ROCM) and x + 4. on TPU + + module, version = serialize(""" +module @jit_f_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_platform_idx: tensor {jax.global_constant = "_platform_index"}, %arg_tok: !stablehlo.token {jax.token = true}, %arg0: tensor) -> (!stablehlo.token, tensor) { + %0 = stablehlo.get_dimension_size %arg0, dim = 0 : (tensor) -> tensor + %5:2 = call @_wrapped_jax_export_main(%arg_platform_idx, %0, %arg_tok, %arg0) : (tensor, tensor, !stablehlo.token, tensor) -> (!stablehlo.token, tensor) + return %5#0, %5#1 : !stablehlo.token, tensor + } + + func.func private @_wrapped_jax_export_main(%arg_platform_idx: tensor {jax.global_constant = "_platform_index"}, %arg0: tensor {jax.global_constant = "b"}, %arg_tok: !stablehlo.token {jax.token = true}, %arg1: tensor) -> (!stablehlo.token, tensor) { + %to_add = "stablehlo.case"(%arg_platform_idx) ({ + %cpu_val = stablehlo.constant dense<2.> : tensor + stablehlo.return %cpu_val : tensor + }, { + %gpu_val = stablehlo.constant dense<3.> : tensor + stablehlo.return %gpu_val : tensor + }, { + %tpu_val = stablehlo.constant dense<4.> : tensor + stablehlo.return %tpu_val : tensor + }) : (tensor) -> tensor + %1 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %3 = stablehlo.dynamic_broadcast_in_dim %to_add, %1, dims = [] : (tensor, tensor<1xi32>) -> tensor + %4 = stablehlo.add %3, %arg1 : tensor + return %arg_tok, %4 : !stablehlo.token, tensor + } +} +""") + platforms = ['CPU', 'CUDA', 'ROCM', 'TPU'] + def f(x): + return xla.call_module([x], version=version, + module=module, + Tout=[np.float32], + Sout=[()], + platforms=platforms) + + expected_value = ( + x + dict(CPU=2.0, CUDA=3.0, ROCM=3.0, TPU=4.0)[self.testing_platform()] + ) + self._assertOpOutputMatchesExpected(f, (x,), (expected_value,)) + + # A module used for testing errors related to use of "platforms". + platforms_errors_module_str = """ + module @jit_f.0 { + func.func public @main(%arg_platform_idx: tensor, %arg0: tensor) -> tensor { + return %arg0 : tensor + } + } +""" + + def platforms_errors_helper( + self, + *, + module_str: str, + platforms: Sequence[str] = ('CPU', 'CUDA', 'ROCM', 'TPU'), + disabled_checks: Sequence[str] = (), + expected_error: Optional[Exception] = None, + expected_error_message: str = '', + ): + module, version = serialize(module_str) + x = np.float32(0.0) + + def f(x): + return xla.call_module( + [x], + version=version, + module=module, + Tout=[np.float32], + Sout=[()], + platforms=platforms, + disabled_checks=disabled_checks, + ) + + if expected_error is None: + self._assertOpOutputMatchesExpected(f, (x,), (x,)) + else: + with self.assertRaisesRegex(expected_error, expected_error_message): + self._assertOpOutputMatchesExpected(f, (x,), (x,)) + + def platforms_errors_singleton_platform(self): + # With singleton `platforms`, there should be no platform_index argument + self.platforms_errors_helper( + module_str=self.platforms_errors_module_str, + platforms=(self.testing_platform(),), + expected_error=errors.InvalidArgumentError, + expected_error_message=( + 'Incorrect number of arguments passed to XlaCallModule = 1. The' + ' module main function takes 2 arguments of which 0 platform index' + ' arguments, 0 dimension arguments and 0 token arguments.' + ), + ) + + def platforms_errors_no_platform_index_arg(self): + module_str = self.platforms_errors_module_str.replace( + '%arg_platform_idx: tensor, %arg0: tensor', '' + ) + self.platforms_errors_helper( + module_str=module_str, + expected_error=errors.InvalidArgumentError, + expected_error_message=( + 'The module should have a platform index argument but it has no ' + 'arguments' + ), + ) + + def platforms_errors_platform_index_i16(self): + module_str = self.platforms_errors_module_str.replace('i32', 'i16') + self.platforms_errors_helper( + module_str=module_str, + expected_error=errors.InvalidArgumentError, + expected_error_message=( + 'Module argument at index 0 should be a 0-dimensional ' + '32-bit or 64-bit integer-tensor platform index argument ' + '.* has type tensor' + ), + ) + + def platforms_errors_platform_index_non_scalar(self): + module_str = self.platforms_errors_module_str.replace( + 'tensor', 'tensor<1xi32>' + ) + self.platforms_errors_helper( + module_str=module_str, + expected_error=errors.InvalidArgumentError, + expected_error_message=( + 'Module argument at index 0 should be a 0-dimensional ' + '32-bit integer-tensor platform index argument .* has type ' + 'tensor<1xi32>' + ), + ) + + def platforms_errors_platform_index_unranked(self): + module_str = self.platforms_errors_module_str.replace( + 'tensor', 'tensor<*xi32>' + ) + self.platforms_errors_helper( + module_str=module_str, + expected_error=errors.InvalidArgumentError, + expected_error_message=( + 'Module argument at index 0 should be a 0-dimensional ' + '32-bit integer-tensor platform index argument' + ), + ) + + def platforms_errors_different_from_current(self): + platform_check_disabled_by_flags = ( + '--tf_xla_call_module_disabled_checks=platform' + in os.getenv('TF_XLA_FLAGS', '') + ) + self.platforms_errors_helper( + module_str=self.platforms_errors_module_str, + platforms=['RANDOM_PLATFORM_1', 'RANDOM_PLATFORM_2'], + expected_error=( + None if platform_check_disabled_by_flags else errors.NotFoundError + ), + expected_error_message='current platform .* is not among the platforms' + ) + + def platforms_errors_dissabled_check(self): + self.platforms_errors_helper( + module_str=self.platforms_errors_module_str, + platforms=('RANDOM_PLATFORM_1', 'RANDOM_PLATFORM_2'), + disabled_checks=(xla.call_module_disable_check_platform(),), + expected_error=None, + expected_error_message='current platform .* is not among the platforms' + ) + + def platforms_errors_empty(self): + self.platforms_errors_helper( + module_str=self.platforms_errors_module_str, + platforms=[], + disabled_checks=[xla.call_module_disable_check_platform()], + expected_error=None, + expected_error_message='current platform .* is not among the platforms' + ) + + def test_shape_assertion_success(self): + x = np.ones((3, 5), dtype=np.int32) + res = np.int32(x.shape[0]) + + def f(x): # x: f32[b, 5] and b = 3 + # return x.shape[0] + module, version = serialize(""" +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %b = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %3 = stablehlo.constant dense<3> : tensor + %ok = stablehlo.compare EQ, %b, %3, SIGNED : (tensor, tensor) -> tensor + stablehlo.custom_call @shape_assertion(%ok) { + error_message = "The error message", + has_side_effect = true + } : (tensor) -> () + return %b : tensor + } + +} +""") + return xla.call_module([x,], version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_shape_assertion_failure(self): + x = np.ones((3, 5), dtype=np.int32) + res = np.int32(x.shape[0]) + + def f(x): # x: f32[b, 5] and b = 3, with a constraint b == 4. + # return x.shape[0] + module, version = serialize(""" +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %b = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %4 = stablehlo.constant dense<4> : tensor + %5 = stablehlo.constant dense<5> : tensor + %11 = stablehlo.constant dense<11> : tensor + %ok = stablehlo.compare EQ, %b, %4, SIGNED : (tensor, tensor) -> tensor + stablehlo.custom_call @shape_assertion(%ok, %b, %4, %5, %4, %5, %4, %5, %4, %5, %4, %5, %11) { + error_message = "Expecting {0} == {1}. Extra {2,=5}, {3}, {{0}, {4}, {5}, {6}, {7}, {11}.", + has_side_effect = true + } : (tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor, tensor) -> () + return %b : tensor + } +} +""") + return xla.call_module([x,], version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()],) + + # This test runs as part of two targets, with and without + # disabling shape_assertions. + disabled_shape_assertions_check = ( + '--tf_xla_call_module_disabled_checks=shape_assertions' + in os.getenv('TF_XLA_FLAGS', '')) + if disabled_shape_assertions_check: + # No error even though the constraint is false. + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + else: + with self.assertRaisesRegex( + errors.InvalidArgumentError, + re.escape('Expecting 3 == 4. Extra 5 , 4, {0}, 5, 4, 5, 4, 11.')): + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_invalid_shape_assertion(self): + arg_i1 = np.bool_(True) + arg_i32 = np.int32(2) + res = arg_i32 + + # This test runs as part of two targets, with and without + # disabling shape_assertions. + disabled_shape_assertions_check = ( + '--tf_xla_call_module_disabled_checks=shape_assertions' + in os.getenv('TF_XLA_FLAGS', '')) + if disabled_shape_assertions_check: + self.skipTest('Test is N/A when shape_assertions are disabled') + + subtest_count = 1 + def one_subtest(error_msg: str, module_str: str): + def f(*args): + module, version = serialize(module_str) + return xla.call_module( + list(args), + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + ) + + nonlocal subtest_count + subtest_count += 1 + with self.subTest(count=subtest_count, error_msg=error_msg): + with self.assertRaisesRegex(errors.InvalidArgumentError, error_msg): + self._assertOpOutputMatchesExpected(f, (arg_i1, arg_i32), (res,)) + + one_subtest( + 'expects assert_what .* to be a constant of type tensor', + """ +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_i1: tensor, %arg_i32: tensor) -> tensor { + %ok = stablehlo.constant dense<0> : tensor + stablehlo.custom_call @shape_assertion(%ok) { + error_message = "Some error", + has_side_effect = true + } : (tensor) -> () + return %arg_i32 : tensor + } +} +""", + ) + + one_subtest( + 'expects static assert_what', + """ +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_i1: tensor, %arg_i32: tensor) -> tensor { + stablehlo.custom_call @shape_assertion(%arg_i1) { + error_message = "Some error", + has_side_effect = true + } : (tensor) -> () + return %arg_i32 : tensor + } +} +""", + ) + + one_subtest( + '`shape_assertion` custom calls must set `has_side_effect = true`.', + """ +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_i1: tensor, %arg_i32: tensor) -> tensor { + %ok = stablehlo.constant dense : tensor + stablehlo.custom_call @shape_assertion(%ok) { + error_message = "Some error", + has_side_effect = false + } : (tensor) -> () + return %arg_i32 : tensor + } +} +""", + ) + + one_subtest( + 'expects error_message .* Found specifier {0}', + """ +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_i1: tensor, %arg_i32: tensor) -> tensor { + %ok = stablehlo.constant dense : tensor + stablehlo.custom_call @shape_assertion(%ok) { + error_message = "Some error {0}", + has_side_effect = true + } : (tensor) -> () + return %arg_i32 : tensor + } +} +""", + ) + + one_subtest( + 'expects static error_message_input', + """ +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_i1: tensor, %arg_i32: tensor) -> tensor { + %ok = stablehlo.constant dense : tensor + stablehlo.custom_call @shape_assertion(%ok, %arg_i32) { + error_message = "Some error {0}", + has_side_effect = true + } : (tensor, tensor) -> () + return %arg_i32 : tensor + } +} +""", + ) + + one_subtest( + 'expects error_message_input .* to be a constant of type tensor', + """ +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg_i1: tensor, %arg_i32: tensor) -> tensor { + %ok = stablehlo.constant dense : tensor + %c = stablehlo.constant dense<2.0> : tensor + stablehlo.custom_call @shape_assertion(%ok, %c) { + error_message = "Some error {0}", + has_side_effect = true + } : (tensor, tensor) -> () + return %arg_i32 : tensor + } +} +""", + ) + + def test_dynamic_iota(self): + x = np.ones((3, 5), dtype=np.int32) + res = np.arange(x.shape[0], dtype=np.int32) + + def f(x): # x: f32[b, 5] + # return np.arange(x.shape[0], dtype=np.int32) + module, version = serialize(""" +module @jit_fun.1 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %1 = "stablehlo.dynamic_iota"(%0) {iota_dimension = 0 : i64} : (tensor<1xi32>) -> tensor + return %1 : tensor + } +} +""") + return xla.call_module([x,], version=version, + module=module, + Tout=[res.dtype], + Sout=[(None,)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_build_graph_with_any_platform(self): + """We can construct the tf.Graph on all platforms.""" + x = np.float32(0.) + + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg_platform_idx: tensor, %arg0: tensor) -> tensor { + return %arg0 : tensor + } +} +""") + platforms = ['TPU'] # the module is compilable only on TPU + def f(x): + return xla.call_module([x], version=version, + module=module, + Tout=[np.float32], + Sout=[()], + platforms=platforms) + tf_graph = def_function.function(f).get_concrete_function(x).graph + self.assertIn('XlaCallModule', str(tf_graph.as_graph_def())) + + def test_dynamic_reshape(self): + x = np.ones((4, 3), dtype=np.float32) + res = x.reshape((-1,)) + + def f(x): # x: f32[b, 3] + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = stablehlo.constant dense<3> : tensor + %1 = stablehlo.multiply %arg0, %0 : tensor + %2 = stablehlo.reshape %1 : (tensor) -> tensor<1xi32> + %3 = stablehlo.dynamic_reshape %arg1, %2 : (tensor, tensor<1xi32>) -> tensor + return %3 : tensor + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[(None,)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_dynamic_gather(self): + x = np.ones((3, 4), dtype=np.float32) + res = np.ones((3, 2), dtype=np.float32) + + def f(x): # x: f32[b, 4] + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = stablehlo.constant dense<0> : tensor + %1 = stablehlo.constant dense<0> : tensor<1xi64> + %2 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %3 = stablehlo.constant dense<2> : tensor<1xi32> + %4 = stablehlo.concatenate %2, %3, dim = 0 : (tensor<1xi32>, tensor<1xi32>) -> tensor<2xi32> + %5 = "stablehlo.dynamic_gather"(%arg1, %1, %4) {dimension_numbers = #stablehlo.gather, indices_are_sorted = true} : (tensor, tensor<1xi64>, tensor<2xi32>) -> tensor + return %5 : tensor + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[(None, 2)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_real_dynamic_slice(self): + x = np.ones((3, 4), dtype=np.float32) + res = x[-1, :] + + def f(x): # x: f32[b, 4] + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor<4xf32> { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor<4xf32> + return %0 : tensor<4xf32> + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor<4xf32> { + %0 = stablehlo.constant dense<-1> : tensor + %1 = stablehlo.add %arg0, %0 : tensor + %2 = stablehlo.reshape %1 : (tensor) -> tensor<1xi32> + %3 = stablehlo.constant dense<0> : tensor<1xi32> + %4 = stablehlo.concatenate %2, %3, dim = 0 : (tensor<1xi32>, tensor<1xi32>) -> tensor<2xi32> + %5 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %6 = stablehlo.constant dense<4> : tensor<1xi32> + %7 = stablehlo.concatenate %5, %6, dim = 0 : (tensor<1xi32>, tensor<1xi32>) -> tensor<2xi32> + %10 = stablehlo.constant dense<1> : tensor<2xi32> + %11 = stablehlo.real_dynamic_slice %arg1, %4, %7, %10 : (tensor, tensor<2xi32>, tensor<2xi32>, tensor<2xi32>) -> tensor<1x4xf32> + %12 = stablehlo.reshape %11 : (tensor<1x4xf32>) -> tensor<4xf32> + return %12 : tensor<4xf32> + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[x.dtype], + Sout=[(4,)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_dynamic_update_slice(self): + x = np.ones((3, 4), dtype=np.float32) + idx = np.int32(-2) + res = x # The update should be a nop + + def f(x, idx): # x: f32[b, 4] idx: i32 + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor, %arg2: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1, %arg2) : (tensor, tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor, %arg2: tensor) -> tensor { + %0 = stablehlo.constant dense<0> : tensor + %1 = stablehlo.compare LT, %arg2, %0, SIGNED : (tensor, tensor) -> tensor + %2 = stablehlo.add %arg2, %arg0 : tensor + %3 = stablehlo.select %1, %2, %arg2 : tensor, tensor + %4 = stablehlo.constant dense<0> : tensor + %5 = stablehlo.dynamic_update_slice %arg1, %arg1, %3, %4 : (tensor, tensor, tensor, tensor) -> tensor + return %5 : tensor + } +} +""") + return xla.call_module([x, idx], version=version, + module=module, + Tout=[res.dtype], + Sout=[(None, 4)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x, idx), (res,)) + + def test_dynamic_broadcast_in_dim(self): + x = np.ones((3, 4), dtype=np.float32) + y = np.ones((2, 3, 4), dtype=np.float32) + res = (np.broadcast_to(x, y.shape), x + y) + + def f(x, y): # x: f32[b, 4] y: f32[2, b, 4] + # return (np.broadcast_to(x, y.shape), x + y) + module, version = serialize(""" +module @jit_fun.0 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor, %arg2: tensor<2x?x4xf32>) -> (tensor<2x?x4xf32>, tensor<2x?x4xf32>) { + %arg0_new = "stablehlo.get_dimension_size"(%arg2) {dimension = 1 : i64} : (tensor<2x?x4xf32>) -> tensor + %0, %1 = call @dyn_main(%arg0_new, %arg1, %arg2) : (tensor, tensor, tensor<2x?x4xf32>) -> (tensor<2x?x4xf32>, tensor<2x?x4xf32>) + return %0, %1 : tensor<2x?x4xf32>, tensor<2x?x4xf32> + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor, %arg2: tensor<2x?x4xf32>) -> (tensor<2x?x4xf32>, tensor<2x?x4xf32>) { + %0 = stablehlo.constant dense<2> : tensor<1xi32> + %2 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %3 = stablehlo.constant dense<4> : tensor<1xi32> + %4 = "stablehlo.concatenate"(%0, %2, %3) {dimension = 0 : i64} : (tensor<1xi32>, tensor<1xi32>, tensor<1xi32>) -> tensor<3xi32> + %5 = "stablehlo.dynamic_broadcast_in_dim"(%arg1, %4) {broadcast_dimensions = array} : (tensor, tensor<3xi32>) -> tensor<2x?x4xf32> + %6 = stablehlo.add %5, %arg2 : (tensor<2x?x4xf32>, tensor<2x?x4xf32>) -> tensor<2x?x4xf32> + return %5, %6 : tensor<2x?x4xf32>, tensor<2x?x4xf32> + } +} +""") + return xla.call_module([x, y], version=version, + module=module, + Tout=[res[0].dtype, res[1].dtype], + Sout=[(2, None, 4), (2, None, 4)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x, y), res) + + @unittest.skip('TODO(necula): test is flaky') + def test_reduce(self): + x = np.arange(5, dtype=np.int32) + res = np.sum(x) * x.shape[0] + + def f(x): # x: i32[b] + module, version = serialize(""" +module @jit_fun attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg2) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = stablehlo.constant dense<0> : tensor + %1 = stablehlo.reduce(%arg1 init: %0) across dimensions = [0] : (tensor, tensor) -> tensor + reducer(%arg2: tensor, %arg3: tensor) { + %4 = stablehlo.add %arg2, %arg3 : tensor + "stablehlo.return"(%4) : (tensor) -> () + } + %2 = stablehlo.multiply %1, %arg0 : tensor + return %2 : tensor + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_reduce_broadcast(self): + x = np.broadcast_to(np.arange(3, dtype=np.float32).reshape(3, 1), (3, 5)) + res = np.arange(3, dtype=np.float32).reshape(3, 1) * 5 + + def f(x): # x: f32[b, 5] + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = stablehlo.constant dense<0.000000e+00> : tensor + %1 = stablehlo.reduce(%arg1 init: %0) across dimensions = [1] : (tensor, tensor) -> tensor + reducer(%arg2: tensor, %arg3: tensor) { + %6 = stablehlo.add %arg2, %arg3 : tensor + stablehlo.return %6 : tensor + } + %2 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %3 = stablehlo.constant dense<1> : tensor<1xi32> + %4 = stablehlo.concatenate %2, %3, dim = 0 : (tensor<1xi32>, tensor<1xi32>) -> tensor<2xi32> + %5 = stablehlo.dynamic_broadcast_in_dim %1, %4, dims = [0] : (tensor, tensor<2xi32>) -> tensor + return %5 : tensor + } +} +""") + return xla.call_module([x,], version=version, + module=module, + Tout=[res.dtype], + Sout=[(None, 1)], + platforms=[self.testing_platform()],) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_call(self): + """A chain of calls.""" + x = np.ones((5,), dtype=np.float32) + res = np.arange(x.shape[0], dtype=np.int32) + + def f(x): # x: f32[b] + module, version = serialize(""" +module @jit_fun_3 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = call @f(%arg0, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @f(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + %0 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %1 = "stablehlo.dynamic_iota"(%0) {iota_dimension = 0 : i64} : (tensor<1xi32>) -> tensor + return %1 : tensor + } +} +""") + return xla.call_module([x,], version=version, + module=module, + Tout=[res.dtype], + Sout=[()], + platforms=[self.testing_platform()]) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_identity(self): + x = np.ones((5,), dtype=np.float32) + res = x + + def f(x): # x: f32[b] + module, version = serialize(""" +module @jit_fun_3 attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> tensor { + return %arg1 : tensor + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[()], + platforms=[self.testing_platform()]) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_while(self): + """A while loop with carryied dynamic shapes.""" + x = np.ones((5,), dtype=np.float32) + # Compute the result in Python first + res0 = np.copy(x) + for _ in range(5): + res0 += np.arange(x.shape[0], dtype=np.float32) + res1 = np.int64(5) + + def f(x): # x: f32[b] + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg1: tensor) -> (tensor, tensor) { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0, %1 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> (tensor, tensor) + return %0, %1 : tensor, tensor + } + func.func private @dyn_main(%arg0: tensor {jax.global_constant = "b"}, %arg1: tensor) -> (tensor, tensor) { + %0 = stablehlo.constant dense<0> : tensor + %1:2 = "stablehlo.while"(%arg1, %0) ({ + ^bb0(%arg2: tensor, %arg3: tensor): + %2 = stablehlo.constant dense<5> : tensor + %3 = stablehlo.compare LT, %arg3, %2, SIGNED : (tensor, tensor) -> tensor + stablehlo.return %3 : tensor + }, { + ^bb0(%arg2: tensor, %arg3: tensor): + %2 = stablehlo.reshape %arg0 : (tensor) -> tensor<1xi32> + %3 = stablehlo.dynamic_iota %2, dim = 0 : (tensor<1xi32>) -> tensor + %4 = stablehlo.add %arg2, %3 : tensor + %5 = stablehlo.constant dense<1> : tensor + %6 = stablehlo.add %arg3, %5 : tensor + stablehlo.return %4, %6 : tensor, tensor + }) : (tensor, tensor) -> (tensor, tensor) + return %1#0, %1#1 : tensor, tensor + } +} +""") + return xla.call_module([x,], version=version, + module=module, + Tout=[res0.dtype, res1.dtype], + Sout=[(None,), res1.shape], + platforms=[self.testing_platform()]) + + self._assertOpOutputMatchesExpected(f, (x,), (res0, res1)) + + def test_skip_shape_refinement(self): + # We skipped the shape refinement, but there are dynamic shapes. + x = np.ones((5,), dtype=np.float32) + res = x + + module_attrs = '' # attribute is missing + def f(x): # x: f32[b] + module, version = serialize(f""" +module @jit_fun_3 {module_attrs} {{ + func.func public @main(%arg1: tensor) -> tensor {{ + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {{dimension = 0 : i64}} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + }} + func.func private @dyn_main(%arg0: tensor {{jax.global_constant = "b"}}, %arg1: tensor) -> tensor {{ + return %arg1 : tensor + }} +}} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[()], + platforms=[self.testing_platform()]) + + module_attrs = '' # attribute is missing + with self.assertRaisesRegex(errors.InvalidArgumentError, + 'Module has dynamic shapes'): + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + module_attrs = 'attributes {jax.uses_shape_polymorphism = false}' + with self.assertRaisesRegex(errors.InvalidArgumentError, + 'Module has dynamic shapes'): + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_uses_shape_polymorphism_before_version_8(self): + x = np.ones((5,), dtype=np.float32) + res = x + + def f(x): # x: f32[b] + # No `uses_shape_polymorphism` attribute, but it default for version 7 + version = 7 + module, _ = serialize(""" +module @jit_fun_3 { + func.func public @main(%arg1: tensor) -> tensor { + %arg0_new = "stablehlo.get_dimension_size"(%arg1) {dimension = 0 : i64} : (tensor) -> tensor + %0 = call @dyn_main(%arg0_new, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } + func.func private @dyn_main(%arg0: tensor, %arg1: tensor) -> tensor { + return %arg1 : tensor + } +} +""") + return xla.call_module([x], version=version, + module=module, + Tout=[res.dtype], + Sout=[()], + platforms=[self.testing_platform()]) + + self._assertOpOutputMatchesExpected(f, (x,), (res,)) + + def test_tf_call_function(self): + """A TensorFlow function call inside StableHLO.""" + x = np.int32(2) + y = np.int32(3) + res = x + y + + @function.Defun(dtypes.int32, dtypes.int32) + def foo(x, y): + return x + y + + def f(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 0} + } : (tensor, tensor) -> tensor + return %0 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + function_list=(foo,), + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (res,)) + + def test_tf_call_function_multiple_funcs(self): + """Multiple TensorFlow function calls inside StableHLO.""" + x = np.int32(2) + y = np.int32(3) + res = (x + y) + (x + y) + + @function.Defun(dtypes.int32, dtypes.int32) + def foo(x, y): + return x + y + + @function.Defun(dtypes.int32, dtypes.int32) + def bar(x, y): + return foo(x, y) + + def f(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 0} + } : (tensor, tensor) -> tensor + %1 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 1} + } : (tensor, tensor) -> tensor + %2 = stablehlo.custom_call @tf.call_tf_function(%0, %1) { + tf.backend_config = {called_index = 1} + } : (tensor, tensor) -> tensor + return %2 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + function_list=(foo, bar), + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (res,)) + + def test_shape_polymorphic_tf_call_function(self): + """A TensorFlow function call inside StableHLO.""" + x = np.full((2,), 2, dtype=np.int32) + y = np.full((2,), 3, dtype=np.int32) + res = x + y + + @function.Defun(dtypes.int32, dtypes.int32) + def foo(x, y): + return x + y + + def f(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax attributes {jax.uses_shape_polymorphism = true} { + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.get_dimension_size %arg0, dim = 0 : (tensor) -> tensor + %1 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1, %0) { + tf.backend_config = {called_index = 0}, + indices_of_shape_operands = dense<[2]> : tensor<1xi64> + } : (tensor, tensor, tensor) -> tensor + return %1 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + function_list=(foo,), + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (res,)) + + def test_tf_call_function_with_token(self): + """A TensorFlow function call inside StableHLO.""" + x = np.int32(2) + y = np.int32(3) + res = x + y + + @function.Defun(dtypes.int32, dtypes.int32) + def foo(x, y): + return x + y + + def f(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func public @main(%arg0: !stablehlo.token, %arg1: tensor, %arg2: tensor) -> (!stablehlo.token, tensor) { + %0:2 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1, %arg2) { + tf.backend_config = {called_index = 0, has_token_input_output = true} + } : (!stablehlo.token, tensor, tensor) -> (!stablehlo.token, tensor) + return %0#0, %0#1 : !stablehlo.token, tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + function_list=(foo,), + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (res,)) + + def test_tf_call_function_nested(self): + """Nested XlaCallModule inside TensorFlow function calls.""" + x = np.int32(2) + y = np.int32(3) + res = x + y + + @function.Defun(dtypes.int32, dtypes.int32) + def add(x, y): + return x + y + + @function.Defun(dtypes.int32, dtypes.int32) + def nested_xla_call(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 0} + } : (tensor, tensor) -> tensor + return %0 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + function_list=(add,), + ) + + @function.Defun(dtypes.int32, dtypes.int32) + def call(x, y): + return nested_xla_call(x, y) + + def f(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 0} + } : (tensor, tensor) -> tensor + return %0 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res.dtype], + Sout=[res.shape], + platforms=[self.testing_platform()], + function_list=(call,), + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (res,)) + + def test_tf_call_function_nested_func_renaming(self): + """Multiple custom calls with identically named private functions.""" + x = np.int32(2) + y = np.int32(3) + res0 = x + y + res1 = x - y + + # Verify that multiple inner TF function calls with the same private + # functions are properly renamed during StableHLO import. This test case is + # carefully constructed such that one outer XlaCallModule op has two custom + # calls, each of which has the same private "@call" function with different + # body. This is to catch bugs in the func renaming logic. + + @function.Defun(dtypes.int32, dtypes.int32) + def add(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func private @call(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.add %arg0, %arg1 : tensor + return %0 : tensor + } + + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = func.call @call(%arg0, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res0.dtype], + Sout=[res0.shape], + platforms=[self.testing_platform()], + ) + + @function.Defun(dtypes.int32, dtypes.int32) + def subtract(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func private @call(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = stablehlo.subtract %arg0, %arg1 : tensor + return %0 : tensor + } + + func.func public @main(%arg0: tensor, %arg1: tensor) -> tensor { + %0 = func.call @call(%arg0, %arg1) : (tensor, tensor) -> tensor + return %0 : tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res1.dtype], + Sout=[res1.shape], + platforms=[self.testing_platform()], + ) + + def f(x, y): + module, version = serialize(""" +module @jit_fun_flat_jax { + func.func public @main(%arg0: tensor, %arg1: tensor) -> (tensor, tensor) { + %0 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 0} + } : (tensor, tensor) -> tensor + %1 = stablehlo.custom_call @tf.call_tf_function(%arg0, %arg1) { + tf.backend_config = {called_index = 1} + } : (tensor, tensor) -> tensor + return %0, %1 : tensor, tensor + } +} +""") + return xla.call_module( + [x, y], + version=version, + module=module, + Tout=[res0.dtype, res1.dtype], + Sout=[res0.shape, res1.shape], + platforms=[self.testing_platform()], + function_list=(add, subtract), + ) + + self._assertOpOutputMatchesExpected(f, (x, y), (res0, res1)) + + def test_op_backward_compatibility(self): + """Test for ensuring XlaCallModuleOp backward compatibility.""" + x = np.array([1.0, 2.0, 3.0], dtype=np.float32) + + def f(x): + # sin(cos(x)) + module, version = serialize(""" +module @jit_f.0 { + func.func public @main(%arg0: tensor<3xf32>) -> tensor<3xf32> { + %0 = stablehlo.cosine %arg0 : tensor<3xf32> + %1 = stablehlo.sine %0 : tensor<3xf32> + return %1 : tensor<3xf32> + } +} +""") + # Create the raw XlaCallModule op directly instead of calling + # `xla.call_module`, which handles default values for unpresent + # attributes. + return gen_xla_ops.xla_call_module( + [x], + version=version, + module=module, + Tout=[x.dtype], + Sout=[x.shape], + platforms=[self.testing_platform()], + ) + + self._assertOpOutputMatchesExpected(f, (x,), (np.sin(np.cos(x)),)) + + def test_op_backward_incompatibility(self): + """Test for ensuring XlaCallModuleOp with invalid bytecode.""" + x = np.array([1.0, 2.0, 3.0], dtype=np.float32) + + def f(x): + # Use an invalid MLIR string that will fail to parse when loading the + # call module op, emulating a backward incompatibility. + corrupted_module = 'stablehlo.invalid_op' + return gen_xla_ops.xla_call_module( + [x], + version=xla.call_module_maximum_supported_version(), + module=corrupted_module, + Tout=[x.dtype], + Sout=[x.shape], + platforms=[self.testing_platform()], + ) + + # Expect any error message to be included after `:` + with self.assertRaisesRegex( + errors.InvalidArgumentError, + 'Cannot deserialize computation: .+', + ): + f(x) + + +if __name__ == '__main__': + ops.enable_eager_execution( + config=config_pb2.ConfigProto(log_device_placement=True) + ) + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_custom_call_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_custom_call_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..1a15a55bd710a7167e751c651bbc327613cdee91 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_custom_call_ops_test.py @@ -0,0 +1,99 @@ +# Copyright 2022 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 XLA custom call op wrapper.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.python import xla +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors_impl +from tensorflow.python.framework import ops +from tensorflow.python.framework import tensor_spec +from tensorflow.python.ops import random_ops +from tensorflow.python.platform import test + + +class XlaCustomCallOpTest(xla_test.XLATestCase): + + def testXlaCustomCallOp(self): + with ops.device('device:{}:0'.format(self.device)): + + def f(x, y): + return xla.custom_call( + args=(x, y), + target_name='my_call', + dtype=dtypes.int32, + shape=(3, 4, 5), + backend_config='my_backend_config') + + compiled_f = def_function.function(f, jit_compile=True) + + x = random_ops.random_normal([1, 2, 3], dtype=dtypes.float32) + y = random_ops.random_normal([], dtype=dtypes.float32) + hlo = compiled_f.experimental_get_compiler_ir(x, y)(stage='hlo') + self.assertIn('s32[3,4,5]{2,1,0} custom-call(f32[1,2,3]{2,1,0}', hlo) + self.assertIn('custom_call_target="my_call"', hlo) + self.assertIn('backend_config="my_backend_config"', hlo) + + def testXlaCustomCallOpDoesntExist(self): + with ops.device('device:{}:0'.format(self.device)): + + def f(): + return xla.custom_call( + args=(1, 2), + target_name='my_non_existing_call_target', + dtype=dtypes.int32, + shape=(), + backend_config='my_backend_config', + ) + + with self.assertRaises(errors_impl.OpError): + compiled_f = def_function.function(f, jit_compile=True) + compiled_f() + + def testXlaCustomCallV2Op(self): + with ops.device('device:{}:0'.format(self.device)): + + def f(x, y): + return xla.custom_call_v2( + 'my_call', + (x, y), + ( + tensor_spec.TensorSpec((2, 3), dtypes.int32), + tensor_spec.TensorSpec((5,), dtypes.float32), + ), + has_side_effect=True, + backend_config='my_backend_config', + ) + + compiled_f = def_function.function(f, jit_compile=True) + + x = random_ops.random_normal([7, 11], dtype=dtypes.float32) + y = random_ops.random_normal([13, 17, 19], dtype=dtypes.float32) + hlo = compiled_f.experimental_get_compiler_ir(x, y)(stage='hlo') + self.assertContainsInOrder([ + '= (s32[2,3]{1,0}, f32[5]{0}) custom-call(', + 'f32[7,11]{1,0}', + 'f32[13,17,19]{2,1,0}', + 'custom_call_target="my_call"', + 'custom_call_has_side_effect=true', + 'api_version=API_VERSION_STATUS_RETURNING_UNIFIED', + 'backend_config="my_backend_config"', + ], hlo) + + +if __name__ == '__main__': + ops.enable_eager_execution() + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_device_gpu_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_device_gpu_test.py new file mode 100644 index 0000000000000000000000000000000000000000..ebe210e76fa08a840ab1396e238d901af1808b0a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_device_gpu_test.py @@ -0,0 +1,50 @@ +# 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. +# ============================================================================== +"""Test cases for XLA devices.""" + +from tensorflow.python.client import session as session_lib +from tensorflow.python.eager import context +from tensorflow.python.framework import config +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.ops import array_ops +from tensorflow.python.platform import test + + +class XlaDeviceGpuTest(test.TestCase): + + def __init__(self, method_name="runTest"): + super(XlaDeviceGpuTest, self).__init__(method_name) + context.context().enable_xla_devices() + + def testCopiesToAndFromGpuWork(self): + """Tests that copies between GPU and XLA devices work.""" + if not config.list_physical_devices("GPU"): + return + + with session_lib.Session() as sess: + x = array_ops.placeholder(dtypes.float32, [2]) + with ops.device("GPU"): + y = x * 2 + with ops.device("device:XLA_CPU:0"): + z = y * y + with ops.device("GPU"): + w = y + z + result = sess.run(w, {x: [1.5, 0.5]}) + self.assertAllClose(result, [12., 2.], rtol=1e-3) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_device_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_device_test.py new file mode 100644 index 0000000000000000000000000000000000000000..6a3881128e9109c3f7be0a830342a12b31bf0736 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_device_test.py @@ -0,0 +1,84 @@ +# 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. +# ============================================================================== +"""Test cases for XLA devices.""" + +import numpy as np + +from tensorflow.compiler.tests import xla_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 gen_control_flow_ops +from tensorflow.python.platform import test + + +class XlaDeviceTest(xla_test.XLATestCase): + + def testCopies(self): + """Tests that copies onto and off XLA devices work.""" + shapes = [[0], [1], [1, 0], [1024, 0], [1024, 1], [3, 777], [777, 3], + [16384, 1], [1, 16384], [1, 20000, 1, 1]] + with self.session() as sess: + for dtype in self.numeric_types: + for shape in shapes: + with ops.device("CPU"): + x = array_ops.placeholder(dtype, shape) + with self.test_scope(): + y = x + x + with ops.device("CPU"): + z = array_ops.identity(y) + + inputs = np.random.randint(-100, 100, shape).astype(dtype) + result = sess.run(z, {x: inputs}) + self.assertAllCloseAccordingToType(result, inputs + inputs) + + def testCopiesOfUnsupportedTypesFailGracefully(self): + """Tests that copies of unsupported types don't crash.""" + test_types = set([ + np.uint8, np.uint16, np.uint32, np.uint64, np.int8, np.int16, np.int32, + np.int64, np.float16, np.float32, np.float16, + dtypes.bfloat16.as_numpy_dtype + ]) + shape = (10, 10) + with self.session() as sess: + for unsupported_dtype in test_types - self.all_types: + with ops.device("CPU"): + x = array_ops.placeholder(unsupported_dtype, shape) + with self.test_scope(): + y, = array_ops.identity_n([x]) + with ops.device("CPU"): + z = array_ops.identity(y) + + inputs = np.random.randint(-100, 100, shape) + inputs = inputs.astype(unsupported_dtype) + # Execution should either succeed or raise an InvalidArgumentError, + # but not crash. Even "unsupported types" may succeed here since some + # backends (e.g., the CPU backend) are happy to handle buffers of + # unsupported types, even if they cannot compute with them. + try: + sess.run(z, {x: inputs}) + except errors.InvalidArgumentError: + pass + + def testControlTrigger(self): + with self.session() as sess: + with self.test_scope(): + x = gen_control_flow_ops.control_trigger() + self.evaluate(x) + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_dump_to_sponge_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_dump_to_sponge_test.py new file mode 100644 index 0000000000000000000000000000000000000000..adb4275476cdebe975e77f1872b6d5931bf3f16b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_dump_to_sponge_test.py @@ -0,0 +1,47 @@ +# 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. +# ============================================================================== +"""Test cases for debug XLA dumps.""" + +import glob +import os + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class XlaDumpToSpongeTest(xla_test.XLATestCase): + """Test that ensures --XLA_FLAGS=--dump_to_xla=sponge produces output.""" + + def _compute(self): + with self.session() as sess, self.device_scope(): + data = np.array([0], dtype=np.float32) + indices = np.array([0], dtype=np.int32) + d = array_ops.placeholder(data.dtype, shape=data.shape) + i = array_ops.placeholder(indices.dtype, shape=indices.shape) + sess.run(math_ops.segment_max_v2(data, indices, 1), {d: data, i: indices}) + + def testDumpToSponge(self): + os.environ['XLA_FLAGS'] = '--xla_dump_to=sponge' + self._compute() + out_dir = os.environ['TEST_UNDECLARED_OUTPUTS_DIR'] + self.assertNotEmpty(glob.glob(os.path.join(out_dir, 'module_0*'))) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_dump_to_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_dump_to_test.py new file mode 100644 index 0000000000000000000000000000000000000000..e00fc57db64b118ed589a3342332f8a82225df59 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_dump_to_test.py @@ -0,0 +1,47 @@ +# 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. +# ============================================================================== +"""Test cases for debug XLA dumps.""" + +import glob +import os + +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.platform import googletest + + +class XlaDumpToDirTest(xla_test.XLATestCase): + """Test that ensures --XLA_FLAGS=--dump_to_xla= produces output.""" + + def _compute(self): + with self.session() as sess, self.device_scope(): + data = np.array([0], dtype=np.float32) + indices = np.array([0], dtype=np.int32) + d = array_ops.placeholder(data.dtype, shape=data.shape) + i = array_ops.placeholder(indices.dtype, shape=indices.shape) + sess.run(math_ops.segment_max_v2(data, indices, 1), {d: data, i: indices}) + + def testDumpToTempDir(self): + tmp_dir = self.create_tempdir().full_path + os.environ['XLA_FLAGS'] = '--xla_dump_to=' + tmp_dir + self._compute() + self.assertNotEmpty(glob.glob(os.path.join(tmp_dir, 'module_0*'))) + + +if __name__ == '__main__': + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_ops_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_ops_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d99501cd7d1fecc601bdde59ce0a3b74a252fcf6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_ops_test.py @@ -0,0 +1,1362 @@ +# 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 XLA op wrappers.""" + +import functools + +from absl.testing import parameterized +import numpy as np + +from tensorflow.compiler.tests import xla_test +from tensorflow.compiler.tf2xla.ops import gen_xla_ops +from tensorflow.compiler.tf2xla.python import xla +from xla import xla_data_pb2 +from tensorflow.python.eager import def_function +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import errors +from tensorflow.python.framework import function +from tensorflow.python.framework import ops +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 array_ops_stack # pylint: disable=g-direct-tensorflow-import +from tensorflow.python.ops import random_ops_util +from tensorflow.python.platform import googletest + + +class XlaOpsNumericalTest(xla_test.XLATestCase, parameterized.TestCase): + + def _assertOpOutputMatchesExpected( + self, op, args, expected, equality_fn=None + ): + with self.session() as session: + with self.test_scope(): + placeholders = [ + array_ops.placeholder(dtypes.as_dtype(arg.dtype), arg.shape) + for arg in args + ] + feeds = {placeholders[i]: args[i] for i in range(0, len(args))} + output = op(*placeholders) + result = session.run(output, feeds) + if not equality_fn: + equality_fn = lambda x, y: self.assertAllClose(x, y, rtol=1e-3) + equality_fn(result, expected) + + def testAdd(self): + if xla_test.test.is_built_with_rocm(): + self.skipTest('Broken with rocm') + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + xla.add, + args=( + np.array([1, 2, 3], dtype=dtype), + np.array([4, 5, 6], dtype=dtype), + ), + expected=np.array([5, 7, 9], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + lambda x, y: xla.add(x, y, broadcast_dims=(0,)), + args=( + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([7, 11], dtype=dtype), + ), + expected=np.array([[8, 9], [14, 15]], dtype=dtype), + ) + + self._assertOpOutputMatchesExpected( + lambda x, y: xla.add(x, y, broadcast_dims=(1,)), + args=( + np.array([[1, 2], [3, 4]], dtype=dtype), + np.array([7, 11], dtype=dtype), + ), + expected=np.array([[8, 13], [10, 15]], dtype=dtype), + ) + + def testBroadcast(self): + for dtype in self.numeric_types: + v = np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]) + self._assertOpOutputMatchesExpected( + lambda x: xla.broadcast(x, (7, 42)), + args=(v,), + expected=np.tile(v, (7, 42, 1, 1)), + ) + + @test_util.disable_mlir_bridge('Not supported yet') + def testGather(self): + operand = np.arange(10, dtype=np.int32).reshape([2, 5]) + start_indices = np.array([2], np.int32) + slice_sizes = np.array([1, 3], np.int32) + + def gather(operand, start_indices): + dimension_numbers = xla_data_pb2.GatherDimensionNumbers() + dimension_numbers.offset_dims.extend([1]) + dimension_numbers.collapsed_slice_dims.extend([0]) + dimension_numbers.start_index_map.extend([0]) + dimension_numbers.index_vector_dim = 1 + return xla.gather(operand, start_indices, dimension_numbers, slice_sizes) + + self._assertOpOutputMatchesExpected( + gather, args=(operand, start_indices), expected=np.array([[5, 6, 7]]) + ) + + def testShiftRightLogical(self): + self._assertOpOutputMatchesExpected( + xla.shift_right_logical, + args=(np.array([-1, 16], dtype=np.int32), np.int32(4)), + expected=np.array([0x0FFFFFFF, 1], dtype=np.int32), + ) + + self._assertOpOutputMatchesExpected( + xla.shift_right_logical, + args=(np.array([0xFFFFFFFF, 16], dtype=np.uint32), np.uint32(4)), + expected=np.array([0x0FFFFFFF, 1], dtype=np.uint32), + ) + + def testShiftRightArithmetic(self): + self._assertOpOutputMatchesExpected( + xla.shift_right_arithmetic, + args=(np.array([-1, 16], dtype=np.int32), np.int32(4)), + expected=np.array([-1, 1], dtype=np.int32), + ) + + self._assertOpOutputMatchesExpected( + xla.shift_right_arithmetic, + args=(np.array([0xFFFFFFFF, 16], dtype=np.uint32), np.uint32(4)), + expected=np.array([0xFFFFFFFF, 1], dtype=np.uint32), + ) + + PRECISION_VALUES = ( + None, + xla_data_pb2.PrecisionConfig.DEFAULT, + xla_data_pb2.PrecisionConfig.HIGH, + xla_data_pb2.PrecisionConfig.HIGHEST, + ) + + @parameterized.parameters(*PRECISION_VALUES) + def testConv(self, precision): + for dtype in set(self.float_types).intersection( + set([dtypes.bfloat16.as_numpy_dtype, np.float32]) + ): + def conv_1d_fn(lhs, rhs): + dnums = xla_data_pb2.ConvolutionDimensionNumbers() + num_spatial_dims = 1 + dnums.input_batch_dimension = 0 + dnums.input_feature_dimension = 1 + dnums.output_batch_dimension = 0 + dnums.output_feature_dimension = 1 + dnums.kernel_output_feature_dimension = 0 + dnums.kernel_input_feature_dimension = 1 + dnums.input_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) + dnums.kernel_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) + dnums.output_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) + precision_config = None + if precision: + precision_config = xla_data_pb2.PrecisionConfig() + precision_config.operand_precision.extend([precision, precision]) + return xla.conv( + lhs, + rhs, + window_strides=(1,), + padding=((2, 1),), + lhs_dilation=(1,), + rhs_dilation=(2,), + dimension_numbers=dnums, + precision_config=precision_config, + ) + + self._assertOpOutputMatchesExpected( + conv_1d_fn, + args=( + np.array([[[3, 4, 5, 6]]], dtype=dtype), + np.array([[[-2, -3]]], dtype=dtype), + ), + expected=np.array([[[-9, -12, -21, -26, -10]]], dtype=dtype), + ) + + def testConvPreferredElementType(self): + dtype = np.float16 + preferred_element_type = np.float32 + + def conv_1d_fn(lhs, rhs): + dnums = xla_data_pb2.ConvolutionDimensionNumbers() + num_spatial_dims = 1 + dnums.input_batch_dimension = 0 + dnums.input_feature_dimension = 1 + dnums.output_batch_dimension = 0 + dnums.output_feature_dimension = 1 + dnums.kernel_output_feature_dimension = 0 + dnums.kernel_input_feature_dimension = 1 + dnums.input_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) + dnums.kernel_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) + dnums.output_spatial_dimensions.extend(range(2, 2 + num_spatial_dims)) + precision_config = None + return xla.conv( + lhs, + rhs, + window_strides=(1,), + padding=((2, 1),), + lhs_dilation=(1,), + rhs_dilation=(2,), + dimension_numbers=dnums, + precision_config=precision_config, + preferred_element_type=preferred_element_type, + ) + + self._assertOpOutputMatchesExpected( + conv_1d_fn, + args=( + np.array([[[3, 4, 5, 6]]], dtype=dtype), + np.array([[[-2, -3]]], dtype=dtype), + ), + expected=np.array( + [[[-9, -12, -21, -26, -10]]], dtype=preferred_element_type + ), + ) + + @parameterized.parameters(*PRECISION_VALUES) + def testDotGeneral(self, precision): + for dtype in self.float_types: + + def dot_fn(lhs, rhs): + dnums = xla_data_pb2.DotDimensionNumbers() + dnums.lhs_contracting_dimensions.append(2) + dnums.rhs_contracting_dimensions.append(1) + dnums.lhs_batch_dimensions.append(0) + dnums.rhs_batch_dimensions.append(0) + precision_config = None + if precision: + precision_config = xla_data_pb2.PrecisionConfig() + precision_config.operand_precision.extend([precision, precision]) + return xla.dot_general( + lhs, rhs, dimension_numbers=dnums, precision_config=precision_config + ) + + lhs = np.array( + [ + [[1, 2], [3, 4]], + [[5, 6], [7, 8]], + ], + dtype=dtype, + ) + rhs = np.array( + [ + [[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]], + ], + dtype=dtype, + ) + self._assertOpOutputMatchesExpected( + dot_fn, + args=(lhs, rhs), + expected=np.array( + [ + [[9, 12, 15], [19, 26, 33]], + [[95, 106, 117], [129, 144, 159]], + ], + dtype=dtype, + ), + ) + + def testDotGeneralInt8xInt8ToInt32(self): + def dot_fn(lhs, rhs): + dnums = xla_data_pb2.DotDimensionNumbers() + dnums.lhs_contracting_dimensions.append(2) + dnums.rhs_contracting_dimensions.append(1) + dnums.lhs_batch_dimensions.append(0) + dnums.rhs_batch_dimensions.append(0) + return xla.dot_general( + lhs, rhs, dimension_numbers=dnums, preferred_element_type=np.int32 + ) + + lhs = np.array( + [ + [[1, 2], [3, 4]], + [[5, 6], [7, 8]], + ], + dtype=np.int8, + ) + rhs = np.array( + [ + [[1, 2, 3], [4, 5, 6]], + [[7, 8, 9], [10, 11, 12]], + ], + dtype=np.int8, + ) + self._assertOpOutputMatchesExpected( + dot_fn, + args=(lhs, rhs), + expected=np.array( + [ + [[9, 12, 15], [19, 26, 33]], + [[95, 106, 117], [129, 144, 159]], + ], + dtype=np.int32, + ), + ) + + def testNeg(self): + for dtype in self.numeric_types - {np.uint8, np.int8}: + self._assertOpOutputMatchesExpected( + xla.neg, + args=(np.array([1, 2, 3], dtype=dtype),), + expected=np.array([-1, -2, -3], dtype=dtype), + ) + + def testPad(self): + for dtype in self.numeric_types: + + def pad_fn(x): + return xla.pad( + x, + padding_value=7, + padding_low=[2, 1], + padding_high=[1, 2], + padding_interior=[1, 0], + ) + + self._assertOpOutputMatchesExpected( + pad_fn, + args=(np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]),), + expected=np.array( + [ + [7, 7, 7, 7, 7], + [7, 7, 7, 7, 7], + [7, 0, 1, 7, 7], + [7, 7, 7, 7, 7], + [7, 2, 3, 7, 7], + [7, 7, 7, 7, 7], + ], + dtype=dtype, + ), + ) + + def testSetDynamicDimensionSize(self): + dynamic_size = 7 + + # XLA doesn't support this for bfloat16. + for dtype in set(self.numeric_types).intersection( + set([np.int32, np.float32, np.float64, np.complex64]) + ): + def xla_set_dynamic_dimension_size_fn(x): + # Tell XLA to cut the array to size=dynamic_size. + return gen_xla_ops.xla_set_dynamic_dimension_size( + x, dim_index=0, size=dynamic_size + ) + + a = np.arange(10, dtype=np.int32).astype(dtype) + expected = a[:dynamic_size] + + self._assertOpOutputMatchesExpected( + xla_set_dynamic_dimension_size_fn, args=(a,), expected=expected + ) + + def testPadNegative(self): + for dtype in self.numeric_types: + + def pad_fn(x): + return xla.pad( + x, + padding_value=7, + padding_low=[0, -1], + padding_high=[1, -2], + padding_interior=[1, 2], + ) + + self._assertOpOutputMatchesExpected( + pad_fn, + args=(np.arange(6, dtype=np.int32).astype(dtype).reshape([2, 3]),), + expected=np.array( + [[7, 7, 1, 7], [7, 7, 7, 7], [7, 7, 4, 7], [7, 7, 7, 7]], + dtype=dtype, + ), + ) + + @parameterized.parameters( + random_ops_util.Algorithm.THREEFRY, + random_ops_util.Algorithm.PHILOX, + random_ops_util.Algorithm.AUTO_SELECT, + ) + def testRngBitGeneratorIsDeterministic(self, algorithm): + dtype = np.uint32 + key = np.array([1, 2], dtype=np.uint64) + shape = (10, 12) + + def rng_fun_is_deterministic(k): + res1 = xla.rng_bit_generator(algorithm, k, shape, dtype=dtype) + res2 = xla.rng_bit_generator(algorithm, k, shape, dtype=dtype) + return (res1[0] - res2[0], res1[1] - res2[1]) + + self._assertOpOutputMatchesExpected( + rng_fun_is_deterministic, + args=(key,), + expected=( + np.zeros(key.shape, dtype=key.dtype), + np.zeros(shape, dtype=dtype), + ), + ) + + def testReduce(self): + for dtype in set(self.numeric_types).intersection( + set([dtypes.bfloat16.as_numpy_dtype, np.float32]) + ): + + @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop + def sum_reducer(x, y): + return x + y + + def sum_reduction(dims): + def fn(x): + return xla.reduce( + x, init_value=0, dimensions_to_reduce=dims, reducer=sum_reducer # pylint: disable=cell-var-from-loop + ) + + return fn + + self._assertOpOutputMatchesExpected( + sum_reduction(dims=[]), + args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), + expected=np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]), + ) + self._assertOpOutputMatchesExpected( + sum_reduction(dims=[0]), + args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), + expected=np.array([12, 15, 18, 21], dtype=dtype), + ) + self._assertOpOutputMatchesExpected( + sum_reduction(dims=[1]), + args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), + expected=np.array([6, 22, 38], dtype=dtype), + ) + self._assertOpOutputMatchesExpected( + sum_reduction(dims=[0, 1]), + args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), + expected=dtype(66), + ) + + @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop + def mul_reducer(x, y): + return x * y + + def mul_reduction(dims): + def fn(x): + return xla.reduce( + x, init_value=1, dimensions_to_reduce=dims, reducer=mul_reducer # pylint: disable=cell-var-from-loop + ) + + return fn + + self._assertOpOutputMatchesExpected( + mul_reduction(dims=[0]), + args=(np.arange(12, dtype=np.int32).astype(dtype).reshape([3, 4]),), + expected=np.array([0, 45, 120, 231], dtype=dtype), + ) + + IS_XLA_VARIADIC_REDUCE_V2 = [True, False] + + @parameterized.parameters(IS_XLA_VARIADIC_REDUCE_V2) + def testVariadicReduceKahanSum(self, is_v2): + for dtype in set(self.numeric_types).intersection( + set([np.float32, np.complex64]) + ): + @def_function.function + def kahan_sum_reducer(t0, t1): + (s0, c0), (s1, c1) = t0, t1 + s0minusc = s0 - (c0 + c1) + t = s1 + s0minusc + c = (t - s1) - s0minusc + s = t + return s, c + + def kahan_sum_reduction(dims, output_idx): + def fn(x): + arg = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop + reducer = kahan_sum_reducer.get_concrete_function( # pylint: disable=cell-var-from-loop + (arg, arg), (arg, arg) + ) + + if is_v2: + return xla.variadic_reduce( + (x, array_ops.zeros_like(x)), + init_values=(arg, arg), + dimensions_to_reduce=dims, + reducer=reducer, + )[output_idx] + else: + return gen_xla_ops.xla_variadic_reduce( + (x, array_ops.zeros_like(x)), + init_value=(arg, arg), + dimensions_to_reduce=dims, + reducer=reducer, + )[output_idx] + + return fn + + xs = np.array([1e5, np.pi, -1e5, np.exp(1.0)]) + xs = np.array([xs, xs[::-1] / 3, xs / 7], dtype) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[], output_idx=0), args=(xs,), expected=xs + ) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[], output_idx=1), + args=(xs,), + expected=np.zeros_like(xs), + ) + shuffle_indices = np.argsort(np.random.randn(xs.shape[0])) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[0], output_idx=0), + args=(xs[shuffle_indices],), + expected=np.array( + [ + np.exp(1) / 3 + 1e5 * 8 / 7, + np.pi * 8 / 7 - 1e5 / 3, + -1e5 * 8 / 7 + np.pi / 3, + np.exp(1) * 8 / 7 + 1e5 / 3, + ], + dtype=dtype, + ), + ) + error_term_equality = functools.partial( + self.assertAllClose, rtol=1e-3, atol=0.005 + ) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[0], output_idx=1), + args=(xs[shuffle_indices],), + expected=np.zeros_like(xs[0]), + equality_fn=error_term_equality, + ) + shuffle_indices = np.argsort(np.random.randn(xs.shape[1])) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[1], output_idx=0), + args=(xs[:, shuffle_indices],), + expected=np.array( + [ + np.pi + np.exp(1.0), + (np.pi + np.exp(1.0)) / 3, + (np.pi + np.exp(1.0)) / 7, + ], + dtype=dtype, + ), + ) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[1], output_idx=1), + args=(xs[:, shuffle_indices],), + expected=np.zeros_like(xs[:, 0]), + equality_fn=error_term_equality, + ) + # Now, shuffle both dims. + xs = xs[np.argsort(np.random.randn(xs.shape[0]))] + xs = xs[:, np.argsort(np.random.randn(xs.shape[1]))] + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[0, 1], output_idx=0), + args=(xs,), + expected=dtype((np.pi + np.exp(1.0)) * 31 / 21), + ) + self._assertOpOutputMatchesExpected( + kahan_sum_reduction(dims=[0, 1], output_idx=1), + args=(xs,), + expected=dtype(0), + equality_fn=error_term_equality, + ) + + @parameterized.parameters(IS_XLA_VARIADIC_REDUCE_V2) + def testVariadicReduceSingleOp(self, is_v2): + @def_function.function + def reducer_add(op_element, acc_val): + return (op_element + acc_val,) + + for dtype in set(self.numeric_types): + values = np.array([[1, 3, 5], [4, 6, 8]], dtype=dtype) + init_val = np.array(0, dtype=dtype) + arg_spec = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop + reducer_func = reducer_add.get_concrete_function(arg_spec, arg_spec) + + def reduce(values, *, dimensions_to_reduce): + if is_v2: + return xla.variadic_reduce( + (values,), + (init_val,), # pylint: disable=cell-var-from-loop + dimensions_to_reduce=dimensions_to_reduce, + reducer=reducer_func, # pylint: disable=cell-var-from-loop + )[0] + else: + return gen_xla_ops.xla_variadic_reduce( + (values,), + (init_val,), # pylint: disable=cell-var-from-loop + dimensions_to_reduce=dimensions_to_reduce, + reducer=reducer_func, # pylint: disable=cell-var-from-loop + )[0] + + # Reduce dimension 0 + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=(0,)), + args=(values,), + expected=np.array([5, 9, 13], dtype=dtype), + ) + + # Reduce dimension 1 + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=(1,)), + args=(values,), + expected=np.array([9, 18], dtype=dtype), + ) + + # Reduce dimensions 0 and 1 + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=(0, 1)), + args=(values,), + expected=np.array(27, dtype=dtype), + ) + + def testVariadicReduceV2DifferentTypes(self): + # Two ops, with different dtypes + @def_function.function + def reducer_add(op_element_1, op_element_2, acc_val_1, acc_val_2): + return (op_element_1 + acc_val_1, op_element_2 + acc_val_2) + + for dtype in set(self.numeric_types): + values_1 = np.array([[1, 3, 5], [4, 6, 8]], dtype=dtype) + values_2 = values_1.astype(np.int32) + + init_val_1 = np.array(0, dtype=dtype) # pylint: disable=cell-var-from-loop + init_val_2 = init_val_1.astype(np.int32) + + arg_spec_1 = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop + arg_spec_2 = array_ops.zeros([], np.int32) + reducer_func = reducer_add.get_concrete_function( + arg_spec_1, arg_spec_2, arg_spec_1, arg_spec_2 + ) # pylint: disable=cell-var-from-loop + + def reduce(*values, dimensions_to_reduce): + return xla.variadic_reduce( + values, + ( + init_val_1, # pylint: disable=cell-var-from-loop + init_val_2, # pylint: disable=cell-var-from-loop + ), + dimensions_to_reduce=dimensions_to_reduce, + reducer=reducer_func, # pylint: disable=cell-var-from-loop + ) + + # Reduce dimension 0 + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=(0,)), + args=(values_1, values_2), + expected=( + np.array([5, 9, 13], dtype=dtype), + np.array([5, 9, 13], dtype=np.int32), + ), + ) + + # Reduce dimension 1 + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=(1,)), + args=(values_1, values_2), + expected=( + np.array([9, 18], dtype=dtype), + np.array([9, 18], dtype=np.int32), + ), + ) + + # Reduce dimensions 0 and 1 + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=(0, 1)), + args=(values_1, values_2), + expected=(np.array(27, dtype=dtype), np.array(27, dtype=np.int32)), + ) + + # Reduce not dimensions + self._assertOpOutputMatchesExpected( + functools.partial(reduce, dimensions_to_reduce=()), + args=(values_1, values_2), + expected=(values_1, values_2), + ) + + @test_util.disable_mlir_bridge('Not supported yet') + def testScatter(self): + test_array = np.arange(9).astype(np.int32).reshape((3, 3)) + scatter_indices = np.array([0, 2], dtype=np.int32) + updates = np.array([[10, 20, 30], [70, 80, 90]], dtype=np.int32) + + dnums = xla_data_pb2.ScatterDimensionNumbers() + dnums.update_window_dims.append(1) + dnums.inserted_window_dims.append(0) + dnums.scatter_dims_to_operand_dims.append(0) + dnums.index_vector_dim = 1 + + add_numbers = function.Defun(np.int32, np.int32)(lambda x, y: x + y) + + def test_fn( + scatter_input, + scatter_indices, + scatter_updates, + ): + return gen_xla_ops.xla_scatter( + scatter_input, + scatter_indices, + scatter_updates, + add_numbers, + dnums.SerializeToString(), + indices_are_sorted=False, + ) + + expected = np.array([[10, 21, 32], [3, 4, 5], [76, 87, 98]], dtype=np.int32) + self._assertOpOutputMatchesExpected( + test_fn, + args=(test_array, scatter_indices, updates), + expected=expected, + ) + + def testSelectAndScatter(self): + for dtype in set(self.numeric_types).intersection( + set([dtypes.bfloat16.as_numpy_dtype, np.float32]) + ): + + @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop + def add_scatter(x, y): + return x + y + + @function.Defun(dtype, dtype) # pylint: disable=cell-var-from-loop + def ge_select(x, y): + return x >= y + + def test_fn(operand, source): + return xla.select_and_scatter( + operand, + window_dimensions=[2, 3, 1, 1], + window_strides=[2, 2, 1, 1], + padding=[[0, 0]] * 4, + source=source, + init_value=0, + select=ge_select, # pylint: disable=cell-var-from-loop + scatter=add_scatter, # pylint: disable=cell-var-from-loop + ) + + self._assertOpOutputMatchesExpected( + test_fn, + args=( + np.array( + [ + [7, 2, 5, 3, 8], + [3, 8, 9, 3, 4], + [1, 5, 7, 5, 6], + [0, 6, 2, 10, 2], + ], + dtype=dtype, + ).reshape((4, 5, 1, 1)), + np.array([[2, 6], [3, 1]], dtype=dtype).reshape((2, 2, 1, 1)), + ), + expected=np.array( + [ + [0, 0, 0, 0, 0], + [0, 0, 8, 0, 0], + [0, 0, 3, 0, 0], + [0, 0, 0, 1, 0], + ], + dtype=dtype, + ).reshape((4, 5, 1, 1)), + ) + + def testTranspose(self): + for dtype in self.numeric_types: + v = np.arange(4, dtype=np.int32).astype(dtype).reshape([2, 2]) + self._assertOpOutputMatchesExpected( + lambda x: xla.transpose(x, [1, 0]), args=(v,), expected=v.T + ) + + def testDynamicSlice(self): + for dtype in self.numeric_types: + self._assertOpOutputMatchesExpected( + xla.dynamic_slice, + args=( + np.arange(1000, dtype=np.int32) + .astype(dtype) + .reshape([10, 10, 10]), + np.array([5, 7, 3]), + np.array([2, 3, 2]), + ), + expected=np.array( + np.array([ + [[573, 574], [583, 584], [593, 594]], + [[673, 674], [683, 684], [693, 694]], + ]), + dtype=dtype, + ), + ) + + def testDynamicSliceWithIncorrectStartIndicesShape(self): + with self.session() as session: + with self.test_scope(): + output = xla.dynamic_slice( + np.arange(1000, dtype=np.int32).reshape([10, 10, 10]), + np.array([5, 7]), + np.array([2, 3, 4]), + ) + with self.assertRaises(errors.InvalidArgumentError) as invalid_arg_error: + session.run(output) + self.assertRegex( + invalid_arg_error.exception.message, + ( + r'has mismatched number of slice sizes \(3\) and number of start' + r' indices \(2\)' + ), + ) + + def testDynamicSliceWithIncorrectSizeIndicesShape(self): + with self.session() as session: + with self.test_scope(): + output = xla.dynamic_slice( + np.arange(1000, dtype=np.int32).reshape([10, 10, 10]), + np.array([5, 7, 3]), + np.array([2, 3]), + ) + with self.assertRaises(errors.InvalidArgumentError) as invalid_arg_error: + session.run(output) + self.assertRegex( + invalid_arg_error.exception.message, + ( + r'has mismatched number of slice sizes \(2\) and number of start' + r' indices \(3\)' + ), + ) + + def test_optimization_barrier(self): + args = ( + np.array([[5, 6, 7]], dtype=np.float32), + np.array([[1, 2, 3]], dtype=int), + ) + + self._assertOpOutputMatchesExpected( + xla.optimization_barrier, args=args, expected=args + ) + + def test_reduce_precision(self): + arg = np.array([1 + 2**-2 + 2**-4, 128, 256], dtype=np.float32) + expected = np.array([1 + 2**-2, 128, float('Inf')], dtype=np.float32) + exponent_bits = 4 + mantissa_bits = 2 + self._assertOpOutputMatchesExpected( + lambda x: xla.reduce_precision(x, exponent_bits, mantissa_bits), + args=(arg,), + expected=expected, + equality_fn=self.assertAllEqual, + ) + + arg = np.array([4], dtype=np.float32) + expected = np.array([4], dtype=np.float32) + # Test passing numbers that cannot fit in a 32-bit integer. + exponent_bits = 2**33 + mantissa_bits = 2**33 + self._assertOpOutputMatchesExpected( + lambda x: xla.reduce_precision(x, exponent_bits, mantissa_bits), + args=(arg,), + expected=expected, + equality_fn=self.assertAllEqual, + ) + + +class XlaOpsShapeInferenceTest(xla_test.XLATestCase, parameterized.TestCase): + + def testDotShapeInference(self): + a = array_ops.placeholder(np.float32, shape=(1, 2, 3, 4)) + b = array_ops.placeholder(np.float32, shape=(4, 5, 2, 6)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(1) + dim_nums.rhs_contracting_dimensions.append(2) + dim_nums.lhs_batch_dimensions.append(3) + dim_nums.rhs_batch_dimensions.append(0) + + c = xla.dot_general(a, b, dim_nums) + self.assertEqual(c.shape, tensor_shape.TensorShape([4, 1, 3, 5, 6])) + + def testDotDifferentNumberOfContractingDimensions(self): + a = array_ops.placeholder(np.float32, shape=(4, 4, 4, 4)) + b = array_ops.placeholder(np.float32, shape=(4, 4, 4, 4)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(2) + dim_nums.rhs_contracting_dimensions.append(2) + dim_nums.rhs_contracting_dimensions.append(3) + + with self.assertRaisesRegex( + ValueError, + 'Must specify the same number of contracting ' + 'dimensions for lhs and rhs. Got: 1 and 2', + ): + xla.dot_general(a, b, dim_nums) + + def testDotDifferentContractingDimensionsSizes(self): + a = array_ops.placeholder(np.float32, shape=(2, 2, 2, 2)) + b = array_ops.placeholder(np.float32, shape=(4, 4, 4, 4)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(2) + dim_nums.rhs_contracting_dimensions.append(3) + + with self.assertRaisesRegex( + ValueError, 'Dimensions must be equal, but are 2 and 4' + ): + xla.dot_general(a, b, dim_nums) + + def testDotDifferentNumberOfBatchDimensions(self): + a = array_ops.placeholder(np.float32, shape=(4, 4, 4, 4)) + b = array_ops.placeholder(np.float32, shape=(4, 4, 4, 4)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_batch_dimensions.append(2) + dim_nums.rhs_batch_dimensions.append(2) + dim_nums.rhs_batch_dimensions.append(3) + + with self.assertRaisesRegex( + ValueError, + 'Must specify the same number of batch ' + 'dimensions for lhs and rhs. Got: 1 and 2', + ): + xla.dot_general(a, b, dim_nums) + + def testDotDifferentBatchDimensionsSizes(self): + a = array_ops.placeholder(np.float32, shape=(2, 2, 2, 2)) + b = array_ops.placeholder(np.float32, shape=(4, 4, 4, 2)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(2) + dim_nums.rhs_contracting_dimensions.append(3) + dim_nums.lhs_batch_dimensions.append(0) + dim_nums.rhs_batch_dimensions.append(0) + + with self.assertRaisesRegex( + ValueError, 'Dimensions must be equal, but are 2 and 4' + ): + xla.dot_general(a, b, dim_nums) + + def testDotUnknownNonContractingDimension(self): + a = array_ops.placeholder(np.float32, shape=(None, 16)) + b = array_ops.placeholder(np.float32, shape=(16, 2)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(1) + dim_nums.rhs_contracting_dimensions.append(0) + + c = xla.dot_general(a, b, dim_nums) + self.assertEqual(c.shape.as_list(), [None, 2]) + + def testDotUnknownContractingDimension(self): + a = array_ops.placeholder(np.float32, shape=(3, None)) + b = array_ops.placeholder(np.float32, shape=(None, 2)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(1) + dim_nums.rhs_contracting_dimensions.append(0) + + c = xla.dot_general(a, b, dim_nums) + self.assertEqual(c.shape.as_list(), [3, 2]) + + def testDotUnknownAndKnownContractingDimension(self): + a = array_ops.placeholder(np.float32, shape=(3, 4)) + b = array_ops.placeholder(np.float32, shape=(None, 2)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(1) + dim_nums.rhs_contracting_dimensions.append(0) + + c = xla.dot_general(a, b, dim_nums) + self.assertEqual(c.shape.as_list(), [3, 2]) + + def testDotUnknownBatchDimension(self): + a = array_ops.placeholder(np.float32, shape=(None, 3, 4)) + b = array_ops.placeholder(np.float32, shape=(None, 4)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(2) + dim_nums.rhs_contracting_dimensions.append(1) + dim_nums.lhs_batch_dimensions.append(0) + dim_nums.rhs_batch_dimensions.append(0) + + c = xla.dot_general(a, b, dim_nums) + self.assertEqual(c.shape.as_list(), [None, 3]) + + def testDotUnknownAndKnownBatchDimension(self): + a = array_ops.placeholder(np.float32, shape=(2, 3, 4)) + b = array_ops.placeholder(np.float32, shape=(None, 4)) + + dim_nums = xla_data_pb2.DotDimensionNumbers() + dim_nums.lhs_contracting_dimensions.append(2) + dim_nums.rhs_contracting_dimensions.append(1) + dim_nums.lhs_batch_dimensions.append(0) + dim_nums.rhs_batch_dimensions.append(0) + + c = xla.dot_general(a, b, dim_nums) + self.assertEqual(c.shape.as_list(), [2, 3]) + + def testDynamicSlice(self): + start = array_ops.placeholder(np.int32, shape=(2, 3, 4)) + + # If slice_sizes are known, the operand shape does not matter. + # The shape of the output is equal to slice_sizes. + slice_sizes = np.array([1, 2, 4], dtype=np.int32) + for a_shape in [(2, 3, 4), (None, 3, 4), None]: + a = array_ops.placeholder(np.float32, shape=a_shape) + res = xla.dynamic_slice(a, start, slice_sizes) + self.assertEqual(res.shape.as_list(), [1, 2, 4]) + + # The first two dimension slice sizes are known + slice_sizes = array_ops_stack.stack( + [1, 2, array_ops.placeholder(np.int32, [])] + ) + for a_shape in [(2, 3, 4), (None, 3, 4), None]: + a = array_ops.placeholder(np.float32, shape=a_shape) + res = xla.dynamic_slice(a, start, slice_sizes) + self.assertEqual(res.shape.as_list(), [1, 2, None]) + + # If slice_sizes has known rank and dimension, but is not a constant + # then output has the same rank, but with unknown dimensions. + slice_sizes = array_ops.placeholder(np.int32, [3]) + for a_shape in [(2, 3, 4), (None, 3, 4), None]: + a = array_ops.placeholder(np.float32, shape=a_shape) + res = xla.dynamic_slice(a, start, slice_sizes) + self.assertEqual(res.shape.as_list(), [None, None, None]) + + # slice sizes has known rank, but unknown dimensions. + # then the output has the same rank as the operand, but with unknown + # dimensions. + slice_sizes = array_ops.placeholder(np.int32, [None]) + for a_shape in [(2, 3, 4), (None, 3, 4)]: + a = array_ops.placeholder(np.float32, shape=a_shape) + res = xla.dynamic_slice(a, start, slice_sizes) + self.assertEqual(res.shape.as_list(), [None, None, None]) + + a = array_ops.placeholder(np.float32, shape=None) + slice_sizes = array_ops.placeholder(np.int32, [None]) + res = xla.dynamic_slice(a, start, slice_sizes) + self.assertIsNone(res.shape.rank) + + def testDynamicUpdateSlice(self): + a = array_ops.placeholder(np.float32, shape=(2, 3, 4)) + upd = array_ops.placeholder(np.float32, shape=(1, 2, 3)) + start_indices = array_ops.placeholder(np.int32, shape=(3,)) + + res = xla.dynamic_update_slice(a, upd, start_indices) + self.assertEqual(res.shape.as_list(), [2, 3, 4]) + + a = array_ops.placeholder(np.float32, shape=(None, 3, None)) + res = xla.dynamic_update_slice(a, upd, start_indices) + self.assertEqual(res.shape.as_list(), [None, 3, None]) + + def testPadShapeInference(self): + a = array_ops.placeholder(np.float32, shape=(2, 3)) + + c = xla.pad( + a, + padding_value=7, + padding_low=[2, 1], + padding_high=[1, 2], + padding_interior=[1, 4], + ) + + self.assertEqual(c.shape, tensor_shape.TensorShape([6, 14])) + + c = xla.pad( + a, + padding_value=7, + padding_low=[2, -2], + padding_high=[1, -2], + padding_interior=[1, 2], + ) + + self.assertEqual(c.shape, tensor_shape.TensorShape([6, 3])) + + c = xla.pad( + array_ops.placeholder(np.float32, shape=(None, 2)), + padding_value=7, + padding_low=[0, 1], + padding_high=[0, 2], + padding_interior=[0, 4], + ) + self.assertEqual(c.shape.as_list(), [None, 9]) + + # 0-sized input dimension and interior padding + c = xla.pad( + array_ops.placeholder(np.float32, shape=(2, 0)), + padding_value=7, + padding_low=[2, 1], + padding_high=[1, 1], + padding_interior=[1, 2], + ) + + self.assertEqual(c.shape, tensor_shape.TensorShape([6, 2])) + + with self.assertRaisesRegex( + ValueError, 'padding_value input must be scalar, found rank 1 ' + ): + xla.pad( + a, + padding_value=[0, 1], + padding_low=[0, 0], + padding_high=[0, 0], + padding_interior=[0, 0], + ) + + with self.assertRaisesRegex( + ValueError, 'padding_low must be a 1D tensor of size 2 ' + ): + xla.pad( + a, + padding_value=7, + padding_low=[0, 0, 0], + padding_high=[0, 0], + padding_interior=[0, 0], + ) + + with self.assertRaisesRegex( + ValueError, 'padding_high must be a 1D tensor of size 2 ' + ): + xla.pad( + a, + padding_value=7, + padding_low=[0, 0], + padding_high=[0, 0, 0], + padding_interior=[0, 0], + ) + + with self.assertRaisesRegex( + ValueError, 'padding_interior must be a 1D tensor of size 2 ' + ): + xla.pad( + a, + padding_value=7, + padding_low=[0, 0], + padding_high=[0, 0], + padding_interior=[0], + ) + + with self.assertRaisesRegex( + ValueError, + 'padding_interior must contain only non-negative values, found -2 ', + ): + xla.pad( + a, + padding_value=7, + padding_low=[0, 0], + padding_high=[0, 0], + padding_interior=[-2, 0], + ) + + with self.assertRaisesRegex( + ValueError, 'resulting padded dimension has negative size -1 ' + ): + xla.pad( + a, + padding_value=7, + padding_low=[-3, 0], + padding_high=[0, 0], + padding_interior=[0, 0], + ) + + def testVariadicReduceV2SingleArg(self): + @def_function.function + def reducer_add(op_element, acc_val): + return (op_element + acc_val,) + + dtype = np.float32 + arg_spec = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop + reducer_func = reducer_add.get_concrete_function(arg_spec, arg_spec) + + res = xla.variadic_reduce( + (array_ops.placeholder(np.float32, shape=(3, 4, 5)),), + (array_ops.placeholder(np.float32, shape=()),), + dimensions_to_reduce=(1,), + reducer=reducer_func, + ) + self.assertLen(res, 1) + self.assertEqual(res[0].shape, tensor_shape.TensorShape([3, 5])) + + def testVariadicReduceV2MultipleArgs(self): + @def_function.function + def reducer_adds( + op_element_1, + op_element_2, + op_element_3, + acc_val_1, + acc_val_2, + acc_val_3, + ): + return ( + op_element_1 + acc_val_1, + op_element_2 + acc_val_2, + op_element_3 + acc_val_3, + ) + + dtype = np.float32 + arg1_spec = array_ops.zeros([], dtype) # pylint: disable=cell-var-from-loop + arg2_spec = array_ops.zeros([], np.int32) + arg3_spec = array_ops.zeros([], np.int32) + reducer_func = reducer_adds.get_concrete_function( + arg1_spec, arg2_spec, arg3_spec, arg1_spec, arg2_spec, arg3_spec + ) + + def reduce_with_shapes(shape1, shape2, shape3, dimensions_to_reduce=(1,)): + inputs = ( + array_ops.placeholder(np.float32, shape=shape1), + array_ops.placeholder(np.int32, shape=shape2), + array_ops.placeholder(np.int32, shape=shape3), + ) + init_values = ( + array_ops.placeholder(np.float32, shape=()), + array_ops.placeholder(np.int32, shape=()), + array_ops.placeholder(np.int32, shape=()), + ) + + return xla.variadic_reduce( + inputs, + init_values, + dimensions_to_reduce=dimensions_to_reduce, + reducer=reducer_func, + ) + + def assert_output_shapes(output, expected_shape): + self.assertLen(output, 3) + self.assertEqual(output[0].shape.as_list(), list(expected_shape)) + self.assertEqual(output[1].shape.as_list(), list(expected_shape)) + self.assertEqual(output[2].shape.as_list(), list(expected_shape)) + + output = reduce_with_shapes((3, 4, 5), (3, 4, 5), (3, 4, 5)) + assert_output_shapes(output, (3, 5)) + + output = reduce_with_shapes( + (3, 4, 5), (3, 4, 5), (3, 4, 5), dimensions_to_reduce=() + ) + assert_output_shapes(output, (3, 4, 5)) + + output = reduce_with_shapes(None, (3, None, 5), (None, 4, 5)) + assert_output_shapes(output, (3, 5)) + + output = reduce_with_shapes(None, (3, None, 5), None) + assert_output_shapes(output, (3, 5)) + + output = reduce_with_shapes(None, (None, None, 5), None) + assert_output_shapes(output, (None, 5)) + + output = reduce_with_shapes(None, None, None) + self.assertLen(output, 3) + self.assertIsNone(output[0].shape.rank) + self.assertIsNone(output[1].shape.rank) + self.assertIsNone(output[2].shape.rank) + + with self.assertRaisesRegex( + ValueError, 'All inputs must have the same shape' + ): + reduce_with_shapes((3, 4, 5), (13, 4, 5), (3, 4, 5)) + + with self.assertRaisesRegex( + ValueError, 'All inputs must have the same shape' + ): + reduce_with_shapes((None, 4, 5), (3, None, 5), (13, 4, 5)) + + with self.assertRaisesRegex( + ValueError, 'All inputs must have the same shape' + ): + reduce_with_shapes((None, 4, 5), (3, None, 5), (13, 4, 5)) + + @parameterized.product( + algorithm=[random_ops_util.Algorithm.THREEFRY, + random_ops_util.Algorithm.PHILOX, + random_ops_util.Algorithm.AUTO_SELECT], + dtype=[np.uint8, np.uint64], + ) + def testRngBitGenerator(self, algorithm, dtype): + initial_state = array_ops.placeholder(np.uint64, shape=(2,)) + shape = (2, 3) + res = xla.rng_bit_generator(algorithm, initial_state, shape, dtype=dtype) + + self.assertEqual(res[0].shape, initial_state.shape) + self.assertEqual(res[1].shape, shape) + + # The initial_state has unknown dimension size + initial_state = array_ops.placeholder(np.uint64, shape=(None,)) + shape = (2, 3) + res = xla.rng_bit_generator(algorithm, initial_state, shape, dtype=dtype) + + self.assertEqual(res[0].shape.as_list(), initial_state.shape.as_list()) + self.assertEqual(res[1].shape, shape) + + # The initial_state has unknown rank + initial_state = array_ops.placeholder(np.uint64, shape=None) + shape = (2, 3) + res = xla.rng_bit_generator(algorithm, initial_state, shape, dtype=dtype) + + self.assertEqual(res[0].shape.as_list(), [None]) + self.assertEqual(res[1].shape, shape) + + # The output shape has unknown dimension + initial_state = array_ops.placeholder(np.uint64, shape=(None,)) + shape = (None, 3) + with self.assertRaisesRegex( + TypeError, 'Failed to convert elements .* to Tensor' + ): + _ = xla.rng_bit_generator(algorithm, initial_state, shape, dtype=dtype) + + def testGatherShapeInference(self): + operand = np.arange(10, dtype=np.int32).reshape([2, 5]) + start_indices = np.array([2], np.int32) + slice_sizes = np.array([1, 3], np.int32) + dimension_numbers = xla_data_pb2.GatherDimensionNumbers( + offset_dims=[1], + collapsed_slice_dims=[0], + start_index_map=[0], + index_vector_dim=1, + ) + + res = xla.gather(operand, start_indices, dimension_numbers, slice_sizes) + self.assertEqual(res.shape, tensor_shape.TensorShape([1, 3])) + + def testGatherShapeInferenceDynamicSlice(self): + operand = np.arange(12, dtype=np.int32).reshape([3, 2, 2]) + start_indices = array_ops.placeholder(np.int32, shape=(3, None, 2)) + slice_sizes = np.array([1, 2, 2], np.int32) + dimension_numbers = xla_data_pb2.GatherDimensionNumbers( + offset_dims=[2, 3], + collapsed_slice_dims=[0], + start_index_map=[0, 1], + index_vector_dim=2, + ) + + res = xla.gather(operand, start_indices, dimension_numbers, slice_sizes) + self.assertEqual(res.shape, tensor_shape.TensorShape([3, None, 2, 2])) + + def testGatherShapeInferenceDynamicInput(self): + operand = array_ops.placeholder(np.int32, shape=(None, 5)) + start_indices = np.array([2], np.int32) + slice_sizes = np.array([1, 3], np.int32) + dimension_numbers = xla_data_pb2.GatherDimensionNumbers() + + res = xla.gather(operand, start_indices, dimension_numbers, slice_sizes) + self.assertEqual(res.shape, tensor_shape.unknown_shape()) + + def testGatherShapeInferenceUnknownSliceSizes(self): + operand = np.arange(10, dtype=np.int32).reshape([2, 5]) + start_indices = np.array([2], np.int32) + slice_sizes = array_ops.placeholder(np.int32, shape=(2,)) + dimension_numbers = xla_data_pb2.GatherDimensionNumbers() + + res = xla.gather(operand, start_indices, dimension_numbers, slice_sizes) + self.assertEqual(res.shape, tensor_shape.unknown_shape()) + + +if __name__ == '__main__': + # This test is using Tensorflow sessions which are not compatible with eager + # mode. + ops.disable_eager_execution() + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_test.py new file mode 100644 index 0000000000000000000000000000000000000000..abace973a292486c9fda35e77718da00dd9f6419 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_test.py @@ -0,0 +1,398 @@ +# 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. +# ============================================================================== +"""Definition of XLA test case.""" + +from collections.abc import Iterator +import contextlib +import os +import random +import re + +import numpy as np + +from tensorflow.core.framework import types_pb2 +from tensorflow.core.protobuf import config_pb2 +from tensorflow.core.protobuf import rewriter_config_pb2 +from tensorflow.python.client import session +from tensorflow.python.compiler.xla import jit +from tensorflow.python.eager import context +from tensorflow.python.framework import dtypes +from tensorflow.python.framework import ops +from tensorflow.python.framework import random_seed +from tensorflow.python.framework import test_util +from tensorflow.python.ops import array_ops +from tensorflow.python.ops import variables +from tensorflow.python.platform import flags +from tensorflow.python.platform import test +from tensorflow.python.platform import tf_logging as logging + +FLAGS = flags.FLAGS + +flags.DEFINE_string( + 'test_device', + None, + 'Tensorflow device on which to place operators under test', +) +flags.DEFINE_string('types', None, 'Types to test. Comma-separated list.') +flags.DEFINE_string( + 'disabled_manifest', + None, + 'Path to a file with a list of tests that should not run.', +) +flags.DEFINE_string( + 'tf_xla_flags', + None, + 'Value to set the TF_XLA_FLAGS environment variable to', +) + + +def parse_disabled_manifest(manifest_content): + comments_re = re.compile('#.*$') + disabled_tests = [] + disabled_method_types = [] + for l in manifest_content.splitlines(): + stripped = comments_re.sub('', l).strip() + if not stripped: + continue + entry = stripped.split(' ') + if len(entry) == 1: + disabled_tests.append(entry[0]) + elif len(entry) == 2: + disabled_method_types.append((entry[0], entry[1].strip().split(','))) + else: + raise ValueError('Bad entry in manifest file.') + + disabled_regex = '|'.join(disabled_tests) + method_types_filter = {} + for method, types in disabled_method_types: + method_types_filter[method] = set([ + dtypes.as_dtype(types_pb2.DataType.Value(name)).as_numpy_dtype + for name in types + ]) + return disabled_regex, method_types_filter + + +class TPURewriteSession(session.Session): + """Tensorflow session that runs tpu.rewrite() on ops on run().""" + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.topology = None + + def run(self, fetches, feed_dict=None, options=None, run_metadata=None): + from tensorflow.python.tpu import tpu # pylint: disable=g-import-not-at-top + + if self.topology is None: + self.topology = super().run(tpu.initialize_system()) + assert self.topology is not None + fetch_mapper = session._FetchMapper.for_fetch(fetches) + new_fetches = [] + for fetch in fetch_mapper.unique_fetches(): + if isinstance(fetch, ops.Operation): + fetch = tpu.rewrite(lambda fetch=fetch: fetch) + new_fetches.append(fetch) + rewritten_fetches = fetch_mapper.build_results(new_fetches) + return super().run(rewritten_fetches, feed_dict, options, run_metadata) + + +class XLATestCase(test.TestCase): + """XLA test cases are parameterized test cases.""" + + def __init__(self, method_name='runTest'): + super(XLATestCase, self).__init__(method_name) + if 'XLA' in FLAGS.test_device: + context.context().enable_xla_devices() + + # Check if the mlir bridge has been explicitly enabled or disabled. If + # is_mlir_bridge_enabled() returns None, the user did not explicitly enable + # or disable the bridge so do not update enable_mlir_bridge. + if test_util.is_mlir_bridge_enabled(): + context.context().enable_mlir_bridge = True + elif test_util.is_mlir_bridge_enabled() is not None: + context.context().enable_mlir_bridge = False + + self.device = FLAGS.test_device + self.has_custom_call = self.device == 'XLA_CPU' + + # Some tests (e.g. ftrl_ops) only work if the program goes through the + # _TPUCompileMLIR op. They will set this flag to True. + # TODO(kramm): Flip to true (and enable MLIR bridge) for more tests. + self.rewrite_ops_for_tpu = False + + self._all_tf_types = set([ + dtypes.as_dtype(types_pb2.DataType.Value(name)) + for name in FLAGS.types.split(',') + ]) + self.int_tf_types = set( + [dtype for dtype in self._all_tf_types if dtype.is_integer] + ) + self._float_tf_types = set( + [dtype for dtype in self._all_tf_types if dtype.is_floating] + ) + self.complex_tf_types = set( + [dtype for dtype in self._all_tf_types if dtype.is_complex] + ) + self._numeric_tf_types = set( + self.int_tf_types | self._float_tf_types | self.complex_tf_types + ) + self.quantized_tf_types = set( + dtype for dtype in self._all_tf_types if dtype.is_quantized + ) + + # Quantized types don't have a numpy equivalent, include them in + # all_tf_types but not in all_types. + # TODO(b/115960798): Parametrize tests on TF types instead of numpy types + # and remove all_types. + self._all_types = set( + dtype.as_numpy_dtype + for dtype in self._all_tf_types + if not dtype.is_quantized + ) + self._int_types = set([dtype.as_numpy_dtype for dtype in self.int_tf_types]) + self.signed_int_types = set( + dtype.as_numpy_dtype + for dtype in self.int_tf_types + if not dtype.is_unsigned + ) + self.unsigned_int_types = set( + dtype.as_numpy_dtype for dtype in self.int_tf_types if dtype.is_unsigned + ) + self._float_types = set( + [dtype.as_numpy_dtype for dtype in self._float_tf_types] + ) + self.complex_types = set( + [dtype.as_numpy_dtype for dtype in self.complex_tf_types] + ) + self._numeric_types = set( + self._int_types | self._float_types | self.complex_types + ) + + # Parse the manifest file, if any, into a regex identifying tests to + # disable + # TODO(xpan): Make it text proto if it doesn't scale. + # Each line of the manifest file specifies an entry. The entry can be + # 1) TestNameRegex // E.g. CumprodTest.* Or + # 2) TestName TypeName // E.g. AdamOptimizerTest.testSharing DT_BFLOAT16 + # The 1) disables the entire test. While 2) only filter some numeric types + # so that they are not used in those tests. + self.disabled_regex = None + self._method_types_filter = {} + + if FLAGS.disabled_manifest is not None: + with open(FLAGS.disabled_manifest, 'r') as manifest_file: + disabled_regex, self._method_types_filter = parse_disabled_manifest( + manifest_file.read() + ) + if disabled_regex: + self.disabled_regex = re.compile(disabled_regex) + + if FLAGS.tf_xla_flags is not None: + os.environ['TF_XLA_FLAGS'] = FLAGS.tf_xla_flags + + @property + def all_tf_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + tf_types = set( + [dtypes.as_dtype(t) for t in self._method_types_filter.get(name, set())] + ) + return self._all_tf_types - tf_types + + @property + def float_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + return self._float_types - self._method_types_filter.get(name, set()) + + @property + def float_tf_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + return self._float_tf_types - self._method_types_filter.get(name, set()) + + @property + def int_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + return self._int_types - self._method_types_filter.get(name, set()) + + @property + def numeric_tf_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + tf_types = set( + [dtypes.as_dtype(t) for t in self._method_types_filter.get(name, set())] + ) + return self._numeric_tf_types - tf_types + + @property + def numeric_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + return self._numeric_types - self._method_types_filter.get(name, set()) + + @property + def all_types(self): + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + return self._all_types - self._method_types_filter.get(name, set()) + + def setUp(self): + super(XLATestCase, self).setUp() + name = '{}.{}'.format(type(self).__name__, self._testMethodName) + if self.disabled_regex is not None and self.disabled_regex.match(name): + logging.info('Disabled test case: %s', name) + self.skipTest('{} is disabled by manifest.'.format(name)) + return + logging.info('Start test case: %s', name) + + random.seed(random_seed.DEFAULT_GRAPH_SEED) + np.random.seed(random_seed.DEFAULT_GRAPH_SEED) + + def tearDown(self): + super(XLATestCase, self).tearDown() + logging.info('End test case: %s', self._testMethodName) + + @contextlib.contextmanager + def session(self) -> Iterator[session.Session]: + """Custom implementation of session() for XLA tests. + + We override the standard Tensorflow session() since it is too + specific to CPU and GPU tests. In particular, we want to disable soft + placement and explicitly assign ops to devices under test. + + Yields: + A session to use when running a test case. + """ + graph = ops.Graph() + config = context.context().config + + # Grappler can constant fold TensorListFromTensor ops into DT_VARIANT + # constants which XLA does not understand. So disable constant folding in + # these tests. + config.graph_options.rewrite_options.constant_folding = ( + rewriter_config_pb2.RewriterConfig.OFF + ) + + if self.rewrite_ops_for_tpu: + session_type = TPURewriteSession + else: + session_type = session.Session + + with session_type(graph=graph, config=config) as sess, graph.as_default(): + yield sess + + def cached_session(self): + raise NotImplementedError( + 'cached_session not supported on XLATestCase, please use session' + ) + + def test_session(self): + raise NotImplementedError( + 'test_session not supported on XLATestCase, please use session' + ) + + @contextlib.contextmanager + def device_scope(self): + """Scope that runs tests on `self.device`. + + Yields: + A scope to apply to the operators under test. + """ + with ops.device('device:{}:0'.format(self.device)): + yield + + def assert_op_output_matches_expected( + self, op, inp, expected, local_session, + equality_test=None, rtol=1e-3, atol=1e-5 + ): + """Verifies that 'op' produces 'expected' when fed input 'inp' . + + Args: + op: operator to test + inp: numpy input array to use as input to 'op'. + expected: numpy array representing the expected output of 'op'. + local_session: The session to use for the test. + equality_test: either None, or a function that tests two numpy arrays for + equality. If None, self.assertAllClose is used. + rtol: relative tolerance for equality test. + atol: absolute tolerance for equality test. + """ + with self.test_scope(): + pinp = array_ops.placeholder( + dtypes.as_dtype(inp.dtype), inp.shape, name='a' + ) + output = op(pinp) + result = local_session.run(output, {pinp: inp}) + if equality_test is None: + self.assertEqual(output.dtype, expected.dtype) + self.assertAllCloseAccordingToType( + expected, result, rtol=rtol, atol=atol, bfloat16_rtol=0.03 + ) + else: + equality_test(result, expected, rtol=rtol, atol=atol) + + def test_scope(self): + """Deprecated alias of `device_scope`. + + This should be avoided as the name starts with `test`, so test runners + treat it as a test. This interferes with class decorators that operate on + each test method. + """ + return self.device_scope() + + +def Benchmark( + tf_bench, builder_fn, use_xla_jit, device, separate_compiled_gradients=False +): + """Build a graph and run benchmarks against it, with or without XLA. + + Args: + tf_bench: An instance of tf.test.Benchmark, used to run the benchmark. + builder_fn: A function that builds a graph when invoked, and returns (name, + fetches), where name is the name of the test, and fetches is a list of + tensors to fetch as output. + use_xla_jit: If true compile with the XLA JIT, otherwise use regular TF. + device: The tensorflow device to run on, e.g. "cpu", "gpu". + separate_compiled_gradients: If true put each gradient subgraph into a + separate compilation scope. This gives fine-grained control over which + portions of the graph will be compiled as a single unit. Compiling + gradients separately may yield better performance for some graphs. The + scope is named based on the scope of the forward computation as well as + the name of the gradients. As a result, the gradients will be compiled in + a scope that is separate from both the forward computation, and from other + gradients. + """ + + with ops.Graph().as_default(): + name = None + targets = [] + with ops.device(device): + fetches = [] + jit_scope = jit.experimental_jit_scope + with jit_scope( + compile_ops=use_xla_jit, + separate_compiled_gradients=separate_compiled_gradients, + ): + name, fetches = builder_fn() + + # We only want to benchmark the operations themselves, and not the data + # transfer of the result(s). Non-compiled identity ops ensure XLA + # doesn't know we're dropping the results, otherwise it might compile + # away the entire computation. + for fetch in fetches: + targets.append(array_ops.identity(fetch).op) + + # TODO(b/132430685): Should we allow soft placement here? + config = config_pb2.ConfigProto(allow_soft_placement=True) + with session.Session(config=config) as sess: + sess.run(variables.global_variables_initializer()) + xla = 'xla_' if use_xla_jit else '' + tf_bench.run_op_benchmark( + sess, targets, name='%s_%s%s' % (name, xla, device) + ) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_test_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_test_test.py new file mode 100644 index 0000000000000000000000000000000000000000..497c31d706c47673395d15bd1d4a76f183831eec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tests/xla_test_test.py @@ -0,0 +1,40 @@ +# 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 the XLATestCase test fixture base class.""" + +from tensorflow.compiler.tests import xla_test +from tensorflow.python.platform import test + + +class XlaTestCaseTestCase(test.TestCase): + + def testManifestEmptyLineDoesNotCatchAll(self): + manifest = """ +testCaseOne +""" + disabled_regex, _ = xla_test.parse_disabled_manifest(manifest) + self.assertEqual(disabled_regex, "testCaseOne") + + def testManifestWholeLineCommentDoesNotCatchAll(self): + manifest = """# I am a comment +testCaseOne +testCaseTwo +""" + disabled_regex, _ = xla_test.parse_disabled_manifest(manifest) + self.assertEqual(disabled_regex, "testCaseOne|testCaseTwo") + + +if __name__ == "__main__": + test.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..65f892b8df2fe2158c292aba1ecd448c530d56bf --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/BUILD @@ -0,0 +1,1111 @@ +# Description: +# Wrap NVIDIA TensorRT (http://developer.nvidia.com/tensorrt) with tensorflow +# and provide TensorRT operators and converter package. +# APIs are meant to change over time. + +load("@local_config_tensorrt//:build_defs.bzl", "if_tensorrt") +load("@rules_python//python:proto.bzl", "py_proto_library") +load("@xla//third_party/rules_python/python:py_library.bzl", "py_library") +load( + "@xla//xla/tsl/platform/default:cuda_build_defs.bzl", + "cuda_rpath_flags", +) +load( + "//tensorflow:tensorflow.bzl", + "VERSION", + "if_google", + "tf_copts", + "tf_cuda_library", + "tf_custom_op_library_additional_deps", + "tf_gen_op_wrapper_py", +) +load("//tensorflow:tensorflow.default.bzl", "pybind_extension", "tf_cuda_cc_test", "tf_custom_op_py_strict_library", "tf_gen_op_libs") +load( + "//tensorflow/core/platform:build_config.bzl", + "tf_additional_all_protos", + "tf_proto_library", +) + +# Platform specific build config +load( + "//tensorflow/core/platform:build_config_root.bzl", + "if_static", +) +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//visibility:public"], + features = [ + "-parse_headers", + ], + licenses = ["notice"], +) + +# Whether or not to use the EfficientNMSPlugin from NVIDIA OSS archive. +config_setting( + name = "use_efficient_nms_plugin", + define_values = {"use_efficient_nms_plugin": "1"}, +) + +# Config setting to conditionally link GPU targets. +alias( + name = "efficient_nms_plugin_wrapper", + actual = if_google( + "//third_party/tensorrt/plugin:nvinfer_plugin_nms", + "@tensorrt_oss_archive//:nvinfer_plugin_nms", + ), +) + +cc_library( + name = "efficient_nms_plugin", + deps = if_tensorrt([ + ":efficient_nms_plugin_wrapper", + ]), +) + +cc_library( + name = "tensorrt_stub", + srcs = if_tensorrt([ + "stub/nvinfer_stub.cc", + "stub/nvinfer_plugin_stub.cc", + ]), + linkopts = if_tensorrt(cuda_rpath_flags("tensorrt")), + textual_hdrs = glob(["stub/*.inc"]), + deps = if_tensorrt([ + "@local_config_tensorrt//:tensorrt_headers", + "//tensorflow/core:lib", + "@tsl//tsl/platform:dso_loader", + ]), +) + +alias( + name = "tensorrt_lib", + actual = select({ + "@local_config_tensorrt//:use_static_tensorrt": "@local_config_tensorrt//:tensorrt", + "//conditions:default": ":tensorrt_stub", + }), + visibility = ["//visibility:private"], +) + +tf_cuda_cc_test( + name = "tensorrt_test_cc", + size = "small", + srcs = [ + "tensorrt_test.cc", + ], + extra_copts = select({ + ":use_efficient_nms_plugin": ["-DTF_TRT_USE_EFFICIENT_NMS_PLUGIN=1"], + "//conditions:default": [], + }), + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":trt_logging", + ":utils", + "//tensorflow/core:lib", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core/platform:stream_executor", + "@xla//xla/stream_executor/gpu:gpu_init", + ] + if_tensorrt([ + ":tensorrt_lib", + ]) + select({ + ":use_efficient_nms_plugin": [":efficient_nms_plugin"], + "//conditions:default": [], + }), +) + +cc_library( + name = "trt_convert_api", + srcs = ["trt_convert_api.cc"], + hdrs = [ + "trt_convert_api.h", + ], + copts = tf_copts(), + features = ["-layering_check"], + deps = [ + ":trt_parameters", + ":trt_resources", + "//tensorflow/cc/tools:freeze_saved_model", + "//tensorflow/core:direct_session", + "//tensorflow/core:framework", + "//tensorflow/core/grappler:grappler_item_builder", + "//tensorflow/core/grappler/clusters:single_machine", + "//tensorflow/core/platform:logging", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +filegroup( + name = "headers", + srcs = [ + "trt_convert_api.h", + ], +) + +tf_cuda_cc_test( + name = "trt_convert_api_test", + size = "small", + srcs = ["trt_convert_api_test.cc"], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":common_utils", + ":testutils", + ":trt_conversion", + ":trt_convert_api", + ":trt_logging", + ":trt_op_kernels", + ":trt_resources", + ":utils", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:resource_variable_ops", + "//tensorflow/cc:scope", + "//tensorflow/core:array_ops_op_lib", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:direct_session", + "//tensorflow/core:framework", + "//tensorflow/core:function_ops_op_lib", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:math_ops_op_lib", + "//tensorflow/core:no_op_op_lib", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:state_ops_op_lib", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "//tensorflow/core/kernels:array", + "//tensorflow/core/kernels:assign_op", + "//tensorflow/core/kernels:ops_testutil", + "//tensorflow/core/kernels:partitioned_function_ops", + "//tensorflow/core/kernels:resource_variable_ops", + ], +) + +cc_library( + name = "common_utils", + srcs = ["common/utils.cc"], + hdrs = [ + "common/datavec.h", + "common/utils.h", + ], + copts = tf_copts(), + features = ["-layering_check"], + deps = [ + "//tensorflow/core:framework", + "//tensorflow/core/platform:logging", + "//tensorflow/core/profiler/lib:traceme", + ] + if_tensorrt([":tensorrt_lib"]), +) + +cc_library( + name = "testutils", + testonly = 1, + srcs = ["utils/trt_testutils.cc"], + hdrs = [ + "utils/trt_testutils.h", + ], + copts = tf_copts(), + features = ["-layering_check"], + visibility = ["//visibility:private"], + deps = [ + ":trt_conversion", + "//tensorflow/cc:cc_ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/framework:tensor_testutil", + "@com_google_absl//absl/strings", + "@com_google_googletest//:gtest", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_cc_test( + name = "testutils_test", + size = "small", + srcs = ["utils/trt_testutils_test.cc"], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":testutils", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test_main", + "//tensorflow/core/platform:protobuf", + ] + if_tensorrt([ + ":tensorrt_lib", + ]), +) + +cc_library( + name = "trt_op_kernels", + srcs = [ + "kernels/get_calibration_data_op.cc", + "kernels/trt_engine_op.cc", + ], + copts = tf_copts(), + features = ["-layering_check"], + visibility = ["//visibility:public"], + deps = [ + ":common_utils", + ":trt_allocator", + ":trt_conversion", + ":trt_engine_utils", + ":trt_logging", + ":trt_plugins", + ":trt_resources", + ":utils", + "//tensorflow/core:framework", + "//tensorflow/core:gpu_headers_lib", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:lib_proto_parsing", + "//tensorflow/core:stream_executor_headers_lib", + "//tensorflow/core/common_runtime:core_cpu_lib_no_ops", + "//tensorflow/core/grappler/costs:graph_properties", + "//tensorflow/core/platform:stream_executor", + "//tensorflow/core/profiler/lib:traceme", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/strings", + ] + if_tensorrt([ + ":tensorrt_lib", + "@local_config_cuda//cuda:cuda_headers", + ]) + tf_custom_op_library_additional_deps(), + alwayslink = 1, +) + +cc_library( + name = "trt_engine_resource_op_kernels", + srcs = ["kernels/trt_engine_resource_ops.cc"], + copts = tf_copts(), + features = ["-layering_check"], + visibility = ["//tensorflow/core:__subpackages__"], + deps = [ + ":trt_allocator", + ":trt_engine_instance_proto_cc", + ":trt_logging", + ":trt_plugins", + ":trt_resources", + "//tensorflow/core:framework", + "//tensorflow/core:gpu_headers_lib", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:lib_proto_parsing", + "//tensorflow/core/profiler/lib:traceme", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]) + tf_custom_op_library_additional_deps(), + alwayslink = 1, +) + +tf_cuda_cc_test( + name = "trt_engine_resource_ops_test", + size = "small", + srcs = ["kernels/trt_engine_resource_ops_test.cc"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":common_utils", + ":testutils", + ":trt_engine_instance_proto_cc", + ":trt_engine_resource_op_kernels", + ":trt_engine_resource_ops_op_lib", + ":trt_logging", + ":trt_resources", + ":utils", + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core/framework:fake_input", + "//tensorflow/core/kernels:ops_testutil", + "//tensorflow/core/kernels:resource_variable_ops", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/strings", + ], +) + +tf_cuda_cc_test( + name = "trt_engine_op_test", + size = "small", + srcs = ["kernels/trt_engine_op_test.cc"], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":testutils", + ":trt_conversion", + ":trt_op_kernels", + ":trt_op_libs", + ":trt_resources", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:scope", + "//tensorflow/core:core_cpu_lib", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core/framework:fake_input", + "//tensorflow/core/kernels:array", + "//tensorflow/core/kernels:function_ops", + "//tensorflow/core/kernels:ops_testutil", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@com_google_googletest//:gtest", + "@eigen_archive//:eigen3", + ] + if_tensorrt([ + "@local_config_cuda//cuda:cuda_headers", + ]), +) + +tf_gen_op_libs(op_lib_names = [ + "trt_engine_op", + "get_calibration_data_op", + "trt_engine_resource_ops", +]) + +cc_library( + name = "trt_op_libs", + deps = [ + ":get_calibration_data_op_op_lib", + ":trt_engine_op_op_lib", + ":trt_engine_utils", + ], +) + +tf_cuda_library( + name = "trt_engine_utils", + srcs = [ + "utils/trt_engine_utils.cc", + "utils/trt_shape_optimization_profiles.cc", + ], + hdrs = [ + "utils/trt_engine_utils.h", + "utils/trt_execution_context.h", + "utils/trt_shape_optimization_profiles.h", + ], + features = ["-layering_check"], + deps = [ + ":common_utils", + ":trt_allocator", + ":trt_logging", + ":trt_parameters", + ":utils", + "//tensorflow/core:framework", + "//tensorflow/core:framework_headers_lib", + "//tensorflow/core:lib", + "//tensorflow/core:stream_executor_headers_lib", + "//tensorflow/core/platform:status", + "//tensorflow/core/profiler/lib:traceme", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_library( + name = "trt_logging", + srcs = ["utils/trt_logger.cc"], + hdrs = ["utils/trt_logger.h"], + features = ["-layering_check"], + visibility = ["//visibility:public"], + deps = [ + ":common_utils", + ":logger_registry", + ":utils", + "//tensorflow/core:lib_proto_parsing", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_gen_op_wrapper_py( + name = "trt_ops", + extra_py_deps = [ + "//tensorflow/python:pywrap_tfe", + "//tensorflow/python/util:dispatch", + "//tensorflow/python/util:deprecation", + "//tensorflow/python/util:tf_export", + ], + py_lib_rule = py_library, + deps = [ + ":trt_engine_resource_ops_op_lib", + ":trt_op_libs", + ], +) + +tf_custom_op_py_strict_library( + name = "trt_ops_loader", + deps = [ + ":_pywrap_py_utils", + ":trt_ops", + "//tensorflow/python/framework:errors", + "//tensorflow/python/framework:for_generated_wrappers", + "//tensorflow/python/ops:resources", + ], +) + +tf_cuda_library( + name = "trt_parameters", + srcs = ["convert/trt_parameters.cc"], + hdrs = [ + "convert/trt_parameters.h", + ], + copts = tf_copts(), + deps = [ + ":utils", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_library( + name = "trt_resources", + srcs = [ + "utils/trt_int8_calibrator.cc", + "utils/trt_lru_cache.cc", + ], + hdrs = [ + "utils/trt_int8_calibrator.h", + "utils/trt_lru_cache.h", + "utils/trt_shape_optimization_profiles.h", + "utils/trt_tensor_proxy.h", + ], + features = ["-layering_check"], + deps = [ + ":common_utils", + ":trt_allocator", + ":trt_engine_utils", + ":trt_logging", + ":utils", + "//tensorflow/core:framework_headers_lib", + "//tensorflow/core:framework_lite", + "//tensorflow/core:gpu_runtime", + "//tensorflow/core:graph", + "//tensorflow/core:lib_proto_parsing", + "//tensorflow/core/grappler:op_types", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_library( + name = "trt_allocator", + srcs = ["utils/trt_allocator.cc"], + hdrs = ["utils/trt_allocator.h"], + features = ["-layering_check"], + deps = [ + "//tensorflow/core:framework_headers_lib", + "//tensorflow/core:framework_lite", + "//tensorflow/core:lib_proto_parsing", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_cc_test( + name = "trt_allocator_test", + size = "small", + srcs = ["utils/trt_allocator_test.cc"], + tags = [ + "no_windows", + "nomac", + ], + deps = [ + ":trt_allocator", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) + +tf_cuda_cc_test( + name = "trt_lru_cache_test", + size = "small", + srcs = ["utils/trt_lru_cache_test.cc"], + tags = [ + "no_windows", + "nomac", + ], + deps = [ + ":trt_resources", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) + +tf_cuda_cc_test( + name = "trt_shape_optimization_profiles_test", + size = "small", + srcs = ["utils/trt_shape_optimization_profiles_test.cc"], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":trt_resources", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) + +tf_cuda_library( + name = "logger_registry", + srcs = ["convert/logger_registry.cc"], + hdrs = [ + "convert/logger_registry.h", + ], + copts = tf_copts(), + features = ["-layering_check"], + deps = [ + "//tensorflow/core:lib", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_library( + name = "trt_weights", + srcs = ["convert/weights.cc"], + hdrs = [ + "convert/weights.h", + ], + copts = tf_copts(), + features = ["-layering_check"], + deps = [ + ":utils", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_library( + name = "op_converter", + srcs = [], + hdrs = [ + "convert/op_converter.h", + ], + deps = [ + ":trt_parameters", + ":trt_weights", + ] + if_tensorrt([":tensorrt_lib"]), +) + +# This rule contains static variables for the converter registry. Do not depend +# on it directly; use :op_converter_registry, and link against +# libtensorflow_framework.so for the registry symbols. The library +# libtensorflow_framework.so depends on this target so that users can +# register custom op converters without the need to incorporate Tensorflow into +# their build system. +tf_cuda_library( + name = "op_converter_registry_impl", + srcs = ["convert/op_converter_registry.cc"], + hdrs = [ + "convert/op_converter_registry.h", + ], + features = ["-layering_check"], + visibility = ["//tensorflow:__subpackages__"], + deps = [ + ":op_converter", + ":utils", + "//tensorflow/core:lib", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_library( + name = "op_converter_registry", + hdrs = [ + "convert/op_converter_registry.h", + ], + copts = tf_copts(), + deps = [ + ":op_converter", + ":utils", + "//tensorflow/core:lib", + "//tensorflow/core/platform:env", + "//tensorflow/core/platform:logging", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/strings", + ] + if_static([":op_converter_registry_impl"]), +) + +tf_cuda_cc_test( + name = "op_converter_registry_test", + size = "small", + srcs = ["convert/op_converter_registry_test.cc"], + features = ["-layering_check"], + tags = [ + "no_windows", + "nomac", + ], + deps = [ + ":op_converter_registry", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) + +tf_cuda_library( + name = "algorithm_selector", + srcs = [ + "convert/algorithm_selector.cc", + ], + hdrs = [ + "convert/algorithm_selector.h", + ], + features = ["-layering_check"], + deps = [":common_utils"] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_cc_test( + name = "algorithm_selector_test", + srcs = [ + "convert/algorithm_selector_test.cc", + ], + features = ["-layering_check"], + deps = [ + ":algorithm_selector", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ] + if_tensorrt([":tensorrt_lib"]), +) + +# Library for the node-level conversion portion of TensorRT operation creation +tf_cuda_library( + name = "trt_conversion", + srcs = [ + "convert/convert_graph.cc", + "convert/convert_nodes.cc", + "convert/ops/binary_ops.cc", + "convert/ops/data_format_vec_permute.cc", + "convert/ops/einsum.cc", + "convert/ops/fill_ops.cc", + "convert/ops/like_ops.cc", + "convert/ops/log_softmax.cc", + "convert/ops/quantization_ops.cc", + "convert/ops/selectv2.cc", + "convert/ops/slice_ops.cc", + "convert/ops/softmax.cc", + "convert/ops/tile.cc", + "convert/ops/unary_ops.cc", + "convert/ops/variable_ops.cc", + "convert/timing_cache.cc", + "convert/trt_optimization_pass.cc", + ], + hdrs = [ + "convert/convert_graph.h", + "convert/convert_nodes.h", + "convert/ops/layer_utils.h", + "convert/ops/quantization_ops.h", + "convert/ops/slice_ops.h", + "convert/timing_cache.h", + "convert/trt_optimization_pass.h", + ], + copts = tf_copts() + select({ + ":use_efficient_nms_plugin": ["-DTF_TRT_USE_EFFICIENT_NMS_PLUGIN=1"], + "//conditions:default": [], + }), + features = ["-layering_check"], + deps = [ + ":algorithm_selector", + ":common_utils", + ":logger_registry", + ":op_converter", + ":op_converter_registry", + ":segment", + ":trt_allocator", + ":trt_logging", + ":trt_parameters", + ":trt_plugins", + ":trt_resources", + ":trt_weights", + ":utils", + "//tensorflow/cc:array_ops", + "//tensorflow/core:framework", + "//tensorflow/core:framework_lite", + "//tensorflow/core:gpu_runtime", + "//tensorflow/core:graph", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:core_cpu", + "//tensorflow/core/grappler:devices", + "//tensorflow/core/grappler:grappler_item", + "//tensorflow/core/grappler:op_types", + "//tensorflow/core/grappler:utils", + "//tensorflow/core/grappler/clusters:cluster", + "//tensorflow/core/grappler/clusters:virtual_cluster", + "//tensorflow/core/grappler/costs:graph_properties", + "//tensorflow/core/grappler/optimizers:custom_graph_optimizer", + "//tensorflow/core/grappler/optimizers:custom_graph_optimizer_registry", + "//tensorflow/core/grappler/optimizers:meta_optimizer", + "//tensorflow/core/grappler/utils:functions", + "//tensorflow/core/profiler/lib:annotated_traceme", + "//tensorflow/core/profiler/lib:traceme", + "//tensorflow/core/public:release_version", + "//tensorflow/tools/graph_transforms:transform_utils", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]) + tf_custom_op_library_additional_deps() + select({ + ":use_efficient_nms_plugin": [":efficient_nms_plugin"], + "//conditions:default": [], + }), + alwayslink = 1, +) + +tf_cuda_cc_test( + name = "convert_graph_test", + size = "medium", + srcs = ["convert/convert_graph_test.cc"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":testutils", + ":trt_conversion", + ":trt_op_kernels", + ":trt_op_libs", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:direct_session", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core/grappler:grappler_item", + "//tensorflow/core/grappler/clusters:cluster", + "@com_google_absl//absl/strings", + "@com_google_googletest//:gtest", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_cuda_cc_test( + name = "convert_nodes_test", + size = "medium", + srcs = [ + "convert/convert_nodes_test.cc", + "convert/op_converter_test.cc", + ], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + # TODO(b/303453873): Re-enable test once TensorRT has been updated + "notap", + ], + deps = [ + ":testutils", + ":trt_conversion", + ":trt_engine_utils", + ":trt_logging", + ":trt_plugins", + ":utils", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:cc_ops_internal", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core/framework:tensor_testutil", + "//tensorflow/core/grappler/costs:graph_properties", + "//tensorflow/core/kernels:function_ops", + "//tensorflow/core/kernels:identity_op", + "//tensorflow/core/kernels:resource_variable_ops", + "//tensorflow/core/platform:status_matchers", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@com_google_googletest//:gtest", + ] + if_tensorrt([ + ":tensorrt_lib", + "@local_config_cuda//cuda:cuda_headers", + ]), +) + +tf_cuda_cc_test( + name = "convert_qdq_test", + size = "medium", + srcs = [ + "convert/ops/quantization_ops_test.cc", + ], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + "notap", # Fails w/ tensorrt 8.x + ], + deps = [ + ":testutils", + ":trt_conversion", + ":trt_convert_api", + ":trt_engine_utils", + ":trt_logging", + ":trt_op_kernels", + ":trt_plugins", + ":trt_resources", + ":utils", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:cc_ops_internal", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/compiler/jit:shape_inference", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core/framework:tensor_testutil", + "//tensorflow/core/kernels:array", + "//tensorflow/core/kernels:function_ops", + "//tensorflow/core/kernels:nn", + "//tensorflow/core/kernels:ops_testutil", + "//tensorflow/core/kernels:pooling_ops", + "//tensorflow/core/platform:status_matchers", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@com_google_googletest//:gtest", + ] + if_tensorrt([ + ":tensorrt_lib", + "@local_config_cuda//cuda:cuda_headers", + ]), +) + +# Library for the segmenting portion of TensorRT operation creation +cc_library( + name = "union_find", + srcs = ["segment/union_find.cc"], + hdrs = [ + "segment/union_find.h", + ], + copts = tf_copts(), + deps = [ + ":utils", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/types:optional", + ], +) + +cc_library( + name = "segment", + srcs = ["segment/segment.cc"], + hdrs = [ + "segment/segment.h", + ], + copts = tf_copts(), + deps = [ + ":common_utils", + ":union_find", + ":utils", + "//tensorflow/core:graph", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:lib_proto_parsing", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:core_cpu", + "//tensorflow/core/grappler/costs:graph_properties", + "//tensorflow/core/profiler/lib:traceme", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/types:optional", + "@com_google_protobuf//:protobuf_headers", + ], +) + +tf_cuda_cc_test( + name = "segment_test", + size = "small", + srcs = ["segment/segment_test.cc"], + features = ["-layering_check"], + tags = [ + "no_cuda_on_cpu_tap", + "no_windows", + "nomac", + ], + deps = [ + ":segment", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:scope", + "//tensorflow/core:core_cpu", + "//tensorflow/core:lib", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) + +tf_cuda_library( + name = "trt_plugins", + srcs = ["plugin/trt_plugin.cc"], + hdrs = ["plugin/trt_plugin.h"], + features = ["-layering_check"], + deps = [ + "//tensorflow/core:framework_lite", + "//tensorflow/core:lib_proto_parsing", + ] + if_tensorrt([":tensorrt_lib"]), +) + +cc_library( + name = "utils", + srcs = [ + "convert/utils.cc", + "utils/trt_experimental_features.cc", + ], + hdrs = [ + "common/utils.h", + "convert/utils.h", + "utils/trt_experimental_features.h", + "utils/trt_tensor_proxy.h", + ], + copts = tf_copts(), + features = ["-layering_check"], + deps = [ + "//tensorflow/core:framework", + "//tensorflow/core:graph", + "//tensorflow/core:lib", + "//tensorflow/core:lib_proto_parsing", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/strings", + ] + if_tensorrt([":tensorrt_lib"]), +) + +tf_proto_library( + name = "trt_engine_instance_proto", + srcs = ["utils/trt_engine_instance.proto"], + protodeps = tf_additional_all_protos(), +) + +tf_cuda_library( + name = "py_utils", + srcs = ["utils/py_utils.cc"], + hdrs = ["utils/py_utils.h"], + local_defines = select({ + "@local_config_tensorrt//:use_static_tensorrt": ["TF_USE_TENSORRT_STATIC=1"], + "//conditions:default": [], + }), + deps = if_tensorrt([ + ":common_utils", + ":tensorrt_lib", + ":op_converter_registry", + ]), +) + +pybind_extension( + name = "_pywrap_py_utils", + srcs = ["utils/py_utils_wrapper.cc"], + dynamic_deps = select({ + "//tensorflow:macos": ["//tensorflow:libtensorflow_framework.%s.dylib" % VERSION], + "//conditions:default": ["//tensorflow:libtensorflow_framework.so.%s" % VERSION], + "//tensorflow:windows": [], + }), + enable_stub_generation = True, + pytype_srcs = [ + "_pywrap_py_utils.pyi", + ], + static_deps = [ + "@bazel_tools//:__subpackages__", + "@boringssl//:__subpackages__", + "@com_github_googlecloudplatform_tensorflow_gcp_tools//:__subpackages__", + "@com_google_absl//:__subpackages__", + "@com_google_googleapis//:__subpackages__", + "@com_google_protobuf//:__subpackages__", + "@com_googlesource_code_re2//:__subpackages__", + "@curl//:__subpackages__", + "@eigen_archive//:__subpackages__", + "@farmhash_archive//:__subpackages__", + "@fft2d//:__subpackages__", + "@gif//:__subpackages__", + "@highwayhash//:__subpackages__", + "@hwloc//:__subpackages__", + "@jsoncpp_git//:__subpackages__", + "@libjpeg_turbo//:__subpackages__", + "@llvm_openmp//:__subpackages__", + "@llvm-project//:__subpackages__", + "@llvm_terminfo//:__subpackages__", + "@llvm_zlib//:__subpackages__", + "@local_config_cuda//:__subpackages__", + "@local_config_git//:__subpackages__", + "@local_config_rocm//:__subpackages__", + "@local_config_tensorrt//:__subpackages__", + "@ml_dtypes_py//ml_dtypes:__subpackages__", + "@platforms//:__subpackages__", + "@pybind11//:__subpackages__", + "@snappy//:__subpackages__", + "//:__subpackages__", + "@zlib//:__subpackages__", + "@tsl//tsl:__subpackages__", + "@xla//xla:__subpackages__", + ], + deps = [ + ":common_utils", + ":py_utils", + "//tensorflow/core/platform:env", + "//tensorflow/core/platform:logging", + "//tensorflow/core/platform:status", + "@pybind11", + ], +) + +# copybara:uncomment_begin(google-only) +# py_proto_library( +# name = "trt_engine_instance_proto_py_pb2", +# has_services = 0, +# deps = [":trt_engine_instance_proto"], +# ) +# copybara:uncomment_end diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/_pywrap_py_utils.pyi b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/_pywrap_py_utils.pyi new file mode 100644 index 0000000000000000000000000000000000000000..ef1308f70fbb82e5430fcdc31d9645c9a8e3e753 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/_pywrap_py_utils.pyi @@ -0,0 +1,19 @@ +# Copyright 2023 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. +# ============================================================================== + +def get_linked_tensorrt_version() -> tuple[int, int, int]: ... +def get_loaded_tensorrt_version() -> tuple[int, int, int]: ... +def get_registered_op_converters() -> list[str]: ... +def is_tensorrt_enabled() -> bool: ... diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/datavec.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/datavec.h new file mode 100644 index 0000000000000000000000000000000000000000..cd4c4ee7a5831f363cbfdd6d1c669c3972c3cfc7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/datavec.h @@ -0,0 +1,38 @@ +/* Copyright 2021 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_TF2TENSORRT_COMMON_DATAVEC_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_COMMON_DATAVEC_H_ + +#include + +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace tensorrt { + +// Input/output data format for OpConverterTest::BuildAndRun(). +struct InputOutputData { + size_t TotalBytes() const { return tensor.TotalBytes(); } + std::string name; + Tensor tensor; +}; + +using DataVec = std::vector; + +} // namespace tensorrt +} // namespace tensorflow +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..4ffff256589bdcdc2e261694f5a81ccf86faa9a9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/utils.cc @@ -0,0 +1,242 @@ +/* Copyright 2020 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/tf2tensorrt/common/utils.h" + +#include + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "absl/base/call_once.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/profiler/lib/traceme.h" +#include "third_party/tensorrt/NvInferPlugin.h" + +#endif + +namespace tensorflow { +namespace tensorrt { + +std::tuple GetLinkedTensorRTVersion() { +#if GOOGLE_CUDA && GOOGLE_TENSORRT + return std::tuple{NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, + NV_TENSORRT_PATCH}; +#else + return std::tuple{0, 0, 0}; +#endif +} + +std::tuple GetLoadedTensorRTVersion() { +#if GOOGLE_CUDA && GOOGLE_TENSORRT + int ver = getInferLibVersion(); + int major = ver / 1000; + ver = ver - major * 1000; + int minor = ver / 100; + int patch = ver - minor * 100; + return std::tuple{major, minor, patch}; +#else + return std::tuple{0, 0, 0}; +#endif +} + +} // namespace tensorrt +} // namespace tensorflow + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +namespace tensorflow { +namespace tensorrt { + +Status GetTrtBindingIndex(const char* tensor_name, int profile_index, + const nvinfer1::ICudaEngine* cuda_engine, + int* binding_index) { + tensorflow::profiler::TraceMe activity( + "GetTrtBindingIndex", tensorflow::profiler::TraceMeLevel::kInfo); + // If the engine has been built for K profiles, the first getNbBindings() / K + // bindings are used by profile number 0, the following getNbBindings() / K + // bindings are used by profile number 1 etc. + // + // GetBindingIndex(tensor_name) returns the binding index for the progile 0. + // We can also consider it as a "binding_index_within_profile". + *binding_index = cuda_engine->getBindingIndex(tensor_name); + if (*binding_index == -1) { + const string msg = absl::StrCat("Input node ", tensor_name, " not found"); + return errors::NotFound(msg); + } + int n_profiles = cuda_engine->getNbOptimizationProfiles(); + // If we have more then one optimization profile, then we need to shift the + // binding index according to the following formula: + // binding_index_within_engine = binding_index_within_profile + + // profile_index * bindings_per_profile + const int bindings_per_profile = cuda_engine->getNbBindings() / n_profiles; + *binding_index = *binding_index + profile_index * bindings_per_profile; + return OkStatus(); +} + +Status GetTrtBindingIndex(int network_input_index, int profile_index, + const nvinfer1::ICudaEngine* cuda_engine, + int* binding_index) { + const string input_name = + absl::StrCat(IONamePrefixes::kInputPHName, network_input_index); + return GetTrtBindingIndex(input_name.c_str(), profile_index, cuda_engine, + binding_index); +} + +namespace { + +void InitializeTrtPlugins(nvinfer1::ILogger* trt_logger) { +#if defined(PLATFORM_WINDOWS) + LOG_WARNING_WITH_PREFIX + << "Windows support is provided experimentally. No guarantee is made " + "regarding functionality or engineering support. Use at your own " + "risk."; +#endif + LOG(INFO) << "Linked TensorRT version: " + << absl::StrJoin(GetLinkedTensorRTVersion(), "."); + LOG(INFO) << "Loaded TensorRT version: " + << absl::StrJoin(GetLoadedTensorRTVersion(), "."); + + bool plugin_initialized = initLibNvInferPlugins(trt_logger, ""); + if (!plugin_initialized) { + LOG(ERROR) << "Failed to initialize TensorRT plugins, and conversion may " + "fail later."; + } + + int num_trt_plugins = 0; + nvinfer1::IPluginCreator* const* trt_plugin_creator_list = + getPluginRegistry()->getPluginCreatorList(&num_trt_plugins); + if (!trt_plugin_creator_list) { + LOG_WARNING_WITH_PREFIX << "Can not find any TensorRT plugins in registry."; + } else { + VLOG(1) << "Found the following " << num_trt_plugins + << " TensorRT plugins in registry:"; + for (int i = 0; i < num_trt_plugins; ++i) { + if (!trt_plugin_creator_list[i]) { + LOG_WARNING_WITH_PREFIX + << "TensorRT plugin at index " << i + << " is not accessible (null pointer returned by " + "getPluginCreatorList for this plugin)"; + } else { + VLOG(1) << " " << trt_plugin_creator_list[i]->getPluginName(); + } + } + } +} + +} // namespace + +void MaybeInitializeTrtPlugins(nvinfer1::ILogger* trt_logger) { + static absl::once_flag once; + absl::call_once(once, InitializeTrtPlugins, trt_logger); +} + +} // namespace tensorrt +} // namespace tensorflow + +namespace nvinfer1 { +std::ostream& operator<<(std::ostream& os, + const nvinfer1::TensorFormat& format) { + os << "nvinfer1::TensorFormat::"; + switch (format) { + case nvinfer1::TensorFormat::kLINEAR: + os << "kLINEAR"; + break; + + case nvinfer1::TensorFormat::kCHW2: + os << "kCHW2"; + break; + + case nvinfer1::TensorFormat::kHWC8: + os << "kHWC8"; + break; + + case nvinfer1::TensorFormat::kCHW4: + os << "kCHW4"; + break; + + case nvinfer1::TensorFormat::kCHW16: + os << "kCHW16"; + break; + + case nvinfer1::TensorFormat::kCHW32: + os << "kCHW32"; + break; + +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + case nvinfer1::TensorFormat::kDHWC8: + os << "kDHWC8"; + break; + + case nvinfer1::TensorFormat::kCDHW32: + os << "kCDHW32"; + break; + + case nvinfer1::TensorFormat::kHWC: + os << "kHWC"; + break; + + case nvinfer1::TensorFormat::kDLA_LINEAR: + os << "kDLA_LINEAR"; + break; + + case nvinfer1::TensorFormat::kDLA_HWC4: + os << "kDLA_HWC4"; + break; + + case nvinfer1::TensorFormat::kHWC16: + os << "kHWC16"; + break; +#endif + + default: + os << "unknown format"; + } + return os; +} + +std::ostream& operator<<(std::ostream& os, const nvinfer1::DataType& v) { + os << "nvinfer1::DataType::"; + switch (v) { + case nvinfer1::DataType::kFLOAT: + os << "kFLOAT"; + break; + case nvinfer1::DataType::kHALF: + os << "kHalf"; + break; +#if IS_TRT_VERSION_GE(8, 6, 0, 0) + case nvinfer1::DataType::kFP8: + os << "kFP8"; + break; +#endif + case nvinfer1::DataType::kINT8: + os << "kINT8"; + break; + case nvinfer1::DataType::kINT32: + os << "kINT32"; + break; + case nvinfer1::DataType::kBOOL: + os << "kBOOL"; + break; +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + case nvinfer1::DataType::kUINT8: + os << "kUINT8"; + break; +#endif + } + return os; +} +} // namespace nvinfer1 + +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..63a0da5c4c708786b4e9bcb1eb8f1d7b99170dc2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/common/utils.h @@ -0,0 +1,175 @@ +/* Copyright 2020 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_TF2TENSORRT_COMMON_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_COMMON_UTILS_H_ + +#include +#include + +#include "absl/strings/str_join.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +namespace tensorrt { +// Returns the compile time TensorRT library version information +// {Maj, Min, Patch}. +std::tuple GetLinkedTensorRTVersion(); + +// Returns the runtime time TensorRT library version information +// {Maj, Min, Patch}. +std::tuple GetLoadedTensorRTVersion(); +} // namespace tensorrt +} // namespace tensorflow + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/status.h" +#include "third_party/tensorrt/NvInfer.h" + +#define ERROR_LOC __FILE__, ":", __LINE__ + +#define TFTRT_INTERNAL_ERROR_AT_NODE(node) \ + return errors::Internal("TFTRT::", __FUNCTION__, "\n", ERROR_LOC, \ + " failed to add TRT layer, at: ", node); + +#define TFTRT_RETURN_ERROR_IF_NULLPTR(ptr, node) \ + if (ptr == nullptr) { \ + TFTRT_INTERNAL_ERROR_AT_NODE(node); \ + } + +// Use this macro within functions that return a Status or StatusOR to check +// boolean conditions. If the condition fails, it returns an +// errors::Internal message with the file and line number. +#define TRT_ENSURE(x) \ + if (!(x)) { \ + return errors::Internal(ERROR_LOC, " TRT_ENSURE failure"); \ + } + +// Checks that a Status or StatusOr object does not carry an error message. +// If it does have an error, returns an errors::Internal instance +// containing the error message, along with the file and line number. For +// pointer-containing StatusOr, use the below TRT_ENSURE_PTR_OK macro. +#define TRT_ENSURE_OK(x) \ + if (!x.ok()) { \ + return errors::Internal(ERROR_LOC, " TRT_ENSURE_OK failure:\n ", \ + x.status().ToString()); \ + } + +// Checks that a StatusOrobject does not carry an error, and that the +// contained T* is non-null. If it does have an error status, returns an +// errors::Internal instance containing the error message, along with the file +// and line number. +#define TRT_ENSURE_PTR_OK(x) \ + TRT_ENSURE_OK(x); \ + if (*x == nullptr) { \ + return errors::Internal(ERROR_LOC, " pointer had null value"); \ + } + +namespace tensorflow { +namespace tensorrt { + +#define IS_TRT_VERSION_GE(major, minor, patch, build) \ + ((NV_TENSORRT_MAJOR > major) || \ + (NV_TENSORRT_MAJOR == major && NV_TENSORRT_MINOR > minor) || \ + (NV_TENSORRT_MAJOR == major && NV_TENSORRT_MINOR == minor && \ + NV_TENSORRT_PATCH > patch) || \ + (NV_TENSORRT_MAJOR == major && NV_TENSORRT_MINOR == minor && \ + NV_TENSORRT_PATCH == patch && NV_TENSORRT_BUILD >= build)) + +#define LOG_WARNING_WITH_PREFIX LOG(WARNING) << "TF-TRT Warning: " + +// Initializes the TensorRT plugin registry if this hasn't been done yet. +void MaybeInitializeTrtPlugins(nvinfer1::ILogger* trt_logger); + +class IONamePrefixes { + public: + static constexpr const char* const kInputPHName = "TensorRTInputPH_"; + static constexpr const char* const kOutputPHName = "TensorRTOutputPH_"; +}; + +// Gets the binding index of a tensor in an engine. +// +// The binding index is looked up using the tensor's name and the profile index. +// Profile index should be set to zero, if we do not have optimization profiles. +Status GetTrtBindingIndex(const char* tensor_name, int profile_index, + const nvinfer1::ICudaEngine* cuda_engine, + int* binding_index); + +// Gets the binding index of a tensor in an engine. +// +// Same as above, but uses the network input index to identify the tensor. +Status GetTrtBindingIndex(int network_input_idx, int profile_index, + const nvinfer1::ICudaEngine* cuda_engine, + int* binding_index); +} // namespace tensorrt +} // namespace tensorflow + +namespace nvinfer1 { +// Prints nvinfer1::Dims or any drived type to the given ostream. Per GTest +// printing requirements, this must be in the nvinfer1 namespace. +inline std::ostream& operator<<(std::ostream& os, const nvinfer1::Dims& v) { + os << "nvinfer1::Dims["; + os << absl::StrJoin(std::vector(v.d, v.d + v.nbDims), ","); + os << "]"; + return os; +} + +// Returns true if any two derived nvinfer1::Dims type structs are equivalent. +inline bool operator==(const nvinfer1::Dims& lhs, const nvinfer1::Dims& rhs) { + if (rhs.nbDims != lhs.nbDims) { + return false; + } + for (int i = 0; i < lhs.nbDims; i++) { + if (rhs.d[i] != lhs.d[i]) { + return false; + } + } + return true; +} + +// Returns false if any 2 subclasses of nvinfer1::Dims are equivalent. +inline bool operator!=(const nvinfer1::Dims& lhs, const nvinfer1::Dims& rhs) { + return !(rhs == lhs); +} + +// Prints nvinfer1::INetworkDefinition* information to the given ostream. +inline std::ostream& operator<<(std::ostream& os, + nvinfer1::INetworkDefinition* n) { + os << "nvinfer1::INetworkDefinition{\n"; + std::vector layer_idxs(n->getNbLayers()); + std::iota(layer_idxs.begin(), layer_idxs.end(), 0); + os << absl::StrJoin(layer_idxs, "\n ", + [n](std::string* out, const int layer_idx) { + out->append(n->getLayer(layer_idx)->getName()); + }); + os << "}"; + return os; +} + +// Prints the TensorFormat enum name to the stream. +std::ostream& operator<<(std::ostream& os, + const nvinfer1::TensorFormat& format); + +// Prints the DataType enum name to the stream. +std::ostream& operator<<(std::ostream& os, const nvinfer1::DataType& data_type); + +} // namespace nvinfer1 + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_COMMON_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.cc new file mode 100644 index 0000000000000000000000000000000000000000..14277570881c2849227bb9be454f1851dddee4db --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.cc @@ -0,0 +1,271 @@ +/* Copyright 2022 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h" + +#include + +#include "absl/strings/str_format.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/core/util/env_var.h" +#include "third_party/tensorrt/NvInfer.h" + +// getAlgorithmIOInfo is deprecated in TRT >= 8, replaced by +// getAlgorithmIOInfoByIndex. +#if IS_TRT_VERSION_GE(8, 0, 0, 0) +#define ALGORITHM_IO_INFO_BY_IDX(alg, idx) *(alg).getAlgorithmIOInfoByIndex(idx) +#else +#define ALGORITHM_IO_INFO_BY_IDX(alg, idx) (alg).getAlgorithmIOInfo(idx) +#endif + +namespace nvinfer1 { + +std::ostream& operator<<(std::ostream& os, + const nvinfer1::IAlgorithmContext& ctx) { + os << "AlgorithmContext(name=" << ctx.getName() + << ",nbInputs=" << ctx.getNbInputs() << ",nbOutputs=" << ctx.getNbOutputs() + << ")"; + return os; +} + +std::ostream& operator<<(std::ostream& os, const nvinfer1::IAlgorithm& alg) { + const nvinfer1::IAlgorithmVariant& variant = alg.getAlgorithmVariant(); + os << "Algorithm(" << "variant.implementation=" << variant.getImplementation() + << ",variant.tactic=" << variant.getTactic() + << ",timingMSec=" << alg.getTimingMSec() + << ",workspaceSize=" << alg.getWorkspaceSize() << ")"; + return os; +} + +std::ostream& operator<<(std::ostream& os, + const nvinfer1::IAlgorithmIOInfo& info) { + os << "IOTensor(format=" << info.getTensorFormat() + << ",dtype=" << info.getDataType() << ",strides=" << info.getStrides() + << ")"; + return os; +} +} // namespace nvinfer1 + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +bool operator>=(const AlgorithmSelectorImpl::TRTVersion& lhs, + const AlgorithmSelectorImpl::TRTVersion& rhs) { + if (lhs[0] > rhs[0]) return true; + if (lhs[0] == rhs[0] && lhs[1] > rhs[1]) return true; + if (lhs[0] == rhs[0] && lhs[1] == rhs[1] && lhs[2] > rhs[2]) return true; + if (lhs[0] == rhs[0] && lhs[1] == rhs[1] && lhs[2] == rhs[2] && + lhs[3] >= rhs[3]) { + return true; + } + return false; +} + +bool AlgorithmSelectorImpl::IsTrtVersionGE(const TRTVersion& version) const { + return version_ >= version; +} + +bool AlgorithmSelectorImpl::IsShuffleLayer(ImplementationID id) const { + if (IsTrtVersionGE({8, 2, 0, 0})) { + return id == 0x80000000 + 13; + } + if (IsTrtVersionGE({8, 0, 0, 0})) { + return id == 0x80000000 + 14; + } + if (IsTrtVersionGE({7, 2, 0, 0})) { + return id == 0x80000000 + 16; + } + return id == 18; +} + +std::set +AlgorithmSelectorImpl::GetBannedTRT72TuringTactics() { + static const std::set banned_turing_72{ + // turing_fp16_s1688cudnn_fp16_128x128_ldg8_relu_f2f_exp_medium_nhwc_gelu_tn_v1 + -5927686925093575778, + // turing_fp16_s1688cudnn_fp16_128x128_ldg8_relu_f2f_exp_interior_nhwc_gelu_tn_v1 + -3848538574386518527, + // turing_fp16_s1688cudnn_fp16_128x128_ldg8_relu_f2f_exp_small_nhwc_gelu_tn_v1 + -959009792490796596}; + return banned_turing_72; +} + +bool AlgorithmSelectorImpl::IsBannedTactic(TacticID id) const { + // Disable problematic FP16-Turing tactics in TensorRT 7.2. + if (IsTrtVersionGE({7, 2, 0, 0}) && !IsTrtVersionGE({8, 0, 0, 0})) { + auto banned_turing_72 = GetBannedTRT72TuringTactics(); + return banned_turing_72.find(id) != banned_turing_72.end(); + } + return false; +} + +bool AlgorithmSelectorImpl::AllowShuffleAlgorithm( + TacticID tactic, nvinfer1::DataType input_dtype, + nvinfer1::TensorFormat input_format) const { + if (IsTrtVersionGE({8, 0, 0, 0}) && !IsTrtVersionGE({8, 0, 3, 0})) { + // Reject shuffle node when input format is linear row major INT8 + // format in TensorRT 8.0 GA. + return !(input_format == nvinfer1::TensorFormat::kLINEAR && + input_dtype == nvinfer1::DataType::kINT8); + } + + if (IsTrtVersionGE({7, 2, 0, 0}) && !IsTrtVersionGE({8, 0, 0, 0})) { + // For TRT 7.2, accept shuffle node when input format is not 32-wide + // channel vectorized row major FP32 format + return !(input_format == nvinfer1::TensorFormat::kCHW32 && + input_dtype == nvinfer1::DataType::kFLOAT); + } + return true; +} + +bool AlgorithmSelectorImpl::IsAlgorithmSelectorRequired() const { + // If we are in turing for TensorRT 7.2, we need the selector for shuffle and + // avoiding specific Turing tactics. + if (IsTrtVersionGE({7, 2, 0, 0}) && !IsTrtVersionGE({8, 0, 0, 0})) { + return true; + } + + // If we are in TensorRT 8.0 GA, we want to reject certain types of shuffles. + if (IsTrtVersionGE({8, 0, 0, 0}) && !IsTrtVersionGE({8, 0, 3, 0})) { + return true; + } + + return false; +} + +namespace { + +string FormatAlgorithmList(const nvinfer1::IAlgorithmContext& ctx, + absl::Span algs) { + return absl::StrFormat( + "%s:\n\t%s", absl::FormatStreamed(ctx), + absl::StrJoin( + algs, "\n\t", + [&ctx](std::string* out, const nvinfer1::IAlgorithm* const alg) { + absl::StrAppendFormat(out, "%s", absl::FormatStreamed(*alg)); + for (int i = 0; i < ctx.getNbInputs() + ctx.getNbOutputs(); i++) { + absl::StrAppendFormat( + out, "\n\t\t%s", + absl::FormatStreamed(ALGORITHM_IO_INFO_BY_IDX(*alg, i))); + } + })); +} + +} // namespace + +TftrtAlgorithmSelector::TftrtAlgorithmSelector() + : fixed_algorithm_idx_(GetFixedAlgorithmID()), + selector_(AlgorithmSelectorImpl::CompileTimeTRTVersion()) {} + +std::optional TftrtAlgorithmSelector::GetFixedAlgorithmID() { + int64_t trt_algorithm_idx = 0; + constexpr auto null_idx = + std::numeric_limits::min(); + Status status = tensorflow::ReadInt64FromEnvVar("TF_TRT_FIXED_ALGORITHM_ID", + /*default_val=*/null_idx, + &trt_algorithm_idx); + if (!status.ok()) { + LOG(ERROR) << status; + return std::nullopt; + } + if (trt_algorithm_idx != null_idx) { + return std::max(static_cast(trt_algorithm_idx), 0); + } + return std::nullopt; +} + +bool TftrtAlgorithmSelector::AlgorithmPolicy( + const nvinfer1::IAlgorithmContext& context, + const nvinfer1::IAlgorithm& alg) const { + const nvinfer1::IAlgorithmVariant& variant = alg.getAlgorithmVariant(); + + // Check if this tactic ID is banned. + TacticID tactic_id = variant.getTactic(); + if (selector_.IsBannedTactic(tactic_id)) { + return false; + } + + if (selector_.IsShuffleLayer(variant.getImplementation())) { + return selector_.AllowShuffleAlgorithm( + tactic_id, alg.getAlgorithmIOInfo(0).getDataType(), + alg.getAlgorithmIOInfo(0).getTensorFormat()); + } + return true; +} + +int32_t TftrtAlgorithmSelector::selectAlgorithms( + const nvinfer1::IAlgorithmContext& algoContext, + const nvinfer1::IAlgorithm* const* algoChoices, int32_t nbChoices, + int32_t* selection) noexcept { + if (fixed_algorithm_idx_) { + LOG(WARNING) << "Forcing TRT algorithm selection to: ID = " + << *fixed_algorithm_idx_; + selection[0] = std::min(*fixed_algorithm_idx_, nbChoices - 1); + return 1; + } + + int num_selections = 0; + + VLOG(1) << "Algorithm selection choices: " + << FormatAlgorithmList(algoContext, + absl::MakeSpan(algoChoices, nbChoices)); + + for (int i = 0; i < nbChoices; i++) { + const nvinfer1::IAlgorithm& alg = *algoChoices[i]; + + // Check layer-specific issues. + if (!AlgorithmPolicy(algoContext, alg)) { + LOG(WARNING) << absl::StrFormat("Rejecting Algorithm: %s ", + absl::FormatStreamed(alg)); + continue; + } + selection[num_selections++] = i; + } + return num_selections; +} + +// Called by TensorRT to report choices it made. +void TftrtAlgorithmSelector::reportAlgorithms( + const nvinfer1::IAlgorithmContext* const* algoContexts, + const nvinfer1::IAlgorithm* const* algoChoices, + int32_t nbAlgorithms) noexcept { + if (VLOG_IS_ON(1)) { + string selection_msg = "Algorithms selected:\n"; + for (int i = 0; i < nbAlgorithms; i++) { + absl::StrAppend(&selection_msg, + FormatAlgorithmList(*algoContexts[i], + absl::MakeSpan(algoChoices + i, 1))); + } + VLOG(1) << selection_msg; + } +} + +std::unique_ptr MaybeCreateAlgorithmSelector() { + auto selector = std::make_unique(); + + if (selector->IsRequired()) { + return selector; + } + + return nullptr; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h new file mode 100644 index 0000000000000000000000000000000000000000..3cf0274b0e314357be40538eb838d93923e65fd7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h @@ -0,0 +1,121 @@ +/* Copyright 2022 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_TF2TENSORRT_CONVERT_ALGORITHM_SELECTOR_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_ALGORITHM_SELECTOR_H_ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include +#include +#include + +#include "absl/types/optional.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +// Implements core algorithm selection logic in a testable manner. The policy +// implemented depends on the given TRT version. We have this class because TRT +// interfaces make it difficult to directly test an IAlgorithmSelector +// implementation. +class AlgorithmSelectorImpl { + public: + using TRTVersion = std::array; + using ImplementationID = int64_t; + using TacticID = int64_t; + + static constexpr TRTVersion CompileTimeTRTVersion() { + return TRTVersion{NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, NV_TENSORRT_PATCH, + NV_TENSORRT_BUILD}; + } + + explicit AlgorithmSelectorImpl( + const TRTVersion& version = CompileTimeTRTVersion()) + : version_(version) {} + + bool IsShuffleLayer(ImplementationID id) const; + + bool IsBannedTactic(TacticID id) const; + + // Returns true if the algorithm implementing the IShuffleLayer is acceptable. + bool AllowShuffleAlgorithm(TacticID tactic, nvinfer1::DataType input_dtype, + nvinfer1::TensorFormat input_format) const; + + bool IsTrtVersionGE(const TRTVersion& version) const; + + // Returns true if we know at compile time that the algorithm selector + // should be required. This is a conservative estimate. + bool IsAlgorithmSelectorRequired() const; + + static std::set GetBannedTRT72TuringTactics(); + + private: + TRTVersion version_; +}; + +// Implements the TRT IAlgorithmSelector interface. The method +// "selectAlgorithms" selects allowable algorithms for each layer, and +// "reportAlgorithms" summarizes the algorithms selected by TensorRT. +class TftrtAlgorithmSelector : public nvinfer1::IAlgorithmSelector { + private: + using TacticID = AlgorithmSelectorImpl::TacticID; + + // An index we should choose for all algorithms. Used for debugging. + std::optional fixed_algorithm_idx_; + + AlgorithmSelectorImpl selector_; + + public: + TftrtAlgorithmSelector(); + + // If the environment variable TF_TRT_FIXED_ALGORITHM_ID is empty, this + // function returns nullopt. Otherwise, it returns the specified number. + static std::optional GetFixedAlgorithmID(); + + // Returns true if the algorithm associated with context is acceptable. + bool AlgorithmPolicy(const nvinfer1::IAlgorithmContext& context, + const nvinfer1::IAlgorithm& alg) const; + + // This function fills the array "selection" with the indices of selected + // algorithm candidates from "algoChoices", each of which is an implementation + // for the kernel described by the given IAlgorithmContext. It should return a + // number in [0, nbChoices] indicating the number of selected indices. If 0 is + // returned, TensorRT will use its default selection mechanism. + int32_t selectAlgorithms(const nvinfer1::IAlgorithmContext& algoContext, + const nvinfer1::IAlgorithm* const* algoChoices, + int32_t nbChoices, + int32_t* selection) noexcept override; + + // Called by TensorRT to report choices it made. + void reportAlgorithms(const nvinfer1::IAlgorithmContext* const* algoContexts, + const nvinfer1::IAlgorithm* const* algoChoices, + int32_t nbAlgorithms) noexcept override; + + bool IsRequired() const { + return selector_.IsAlgorithmSelectorRequired() || + fixed_algorithm_idx_ != std::nullopt; + } +}; + +// Returns an initialized AlgorithmSelector if an algorithm selector is required +// for the current TRT version. Otherwise, returns nullptr. +std::unique_ptr MaybeCreateAlgorithmSelector(); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_ALGORITHM_SELECTOR_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..3884baaddb8f17b89d98a7559cb187b247192e33 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/algorithm_selector_test.cc @@ -0,0 +1,97 @@ +/* Copyright 2022 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h" + +#include + +#include +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +TEST(TestAlgorithmSelector, TensorRT7_1) { + // Verify that the algorithm selector for TRT 7.1 is not required. + AlgorithmSelectorImpl sel71({7, 1, 3, 4}); + ASSERT_FALSE(sel71.IsAlgorithmSelectorRequired()); +} + +TEST(TestAlgorithmSelector, TensorRT7_2) { + // Verify that the algorithm selector for TRT 7.2 is required. + AlgorithmSelectorImpl sel72({7, 2, 0, 0}); + ASSERT_TRUE(sel72.IsAlgorithmSelectorRequired()); + + // Check that the correct tactics are banned. + auto turing_tactics = AlgorithmSelectorImpl::GetBannedTRT72TuringTactics(); + + for (auto id : turing_tactics) { + EXPECT_TRUE(sel72.IsBannedTactic(id)); + } + + // Check that a bad shuffle format is banned. + EXPECT_FALSE(sel72.AllowShuffleAlgorithm(0, nvinfer1::DataType::kFLOAT, + nvinfer1::TensorFormat::kCHW32)); + + // Check that other formats are not banned. + EXPECT_TRUE(sel72.AllowShuffleAlgorithm(0, nvinfer1::DataType::kHALF, + nvinfer1::TensorFormat::kCHW32)); + EXPECT_TRUE(sel72.AllowShuffleAlgorithm(0, nvinfer1::DataType::kINT32, + nvinfer1::TensorFormat::kCHW32)); + EXPECT_TRUE(sel72.AllowShuffleAlgorithm(0, nvinfer1::DataType::kFLOAT, + nvinfer1::TensorFormat::kCHW16)); +} + +TEST(TestAlgorithmSelector, TensorRT8_0) { + // Verify that the algorithm selector for TRT 8.0 is required. + AlgorithmSelectorImpl sel80({8, 0, 1, 6}); + ASSERT_TRUE(sel80.IsAlgorithmSelectorRequired()); + + // Check that the turing 7.2 tactics are not banned. + auto turing_tactics = AlgorithmSelectorImpl::GetBannedTRT72TuringTactics(); + for (auto id : turing_tactics) { + EXPECT_FALSE(sel80.IsBannedTactic(id)); + } + + // Check that a bad shuffle format is banned. + EXPECT_FALSE(sel80.AllowShuffleAlgorithm(0, nvinfer1::DataType::kINT8, + nvinfer1::TensorFormat::kLINEAR)); + + // Check that other formats are not banned. + EXPECT_TRUE(sel80.AllowShuffleAlgorithm(0, nvinfer1::DataType::kHALF, + nvinfer1::TensorFormat::kLINEAR)); + EXPECT_TRUE(sel80.AllowShuffleAlgorithm(0, nvinfer1::DataType::kINT32, + nvinfer1::TensorFormat::kLINEAR)); + EXPECT_TRUE(sel80.AllowShuffleAlgorithm(0, nvinfer1::DataType::kFLOAT, + nvinfer1::TensorFormat::kLINEAR)); + EXPECT_TRUE(sel80.AllowShuffleAlgorithm(0, nvinfer1::DataType::kINT8, + nvinfer1::TensorFormat::kCHW16)); + EXPECT_TRUE(sel80.AllowShuffleAlgorithm(0, nvinfer1::DataType::kINT8, + nvinfer1::TensorFormat::kCHW32)); +} + +TEST(TestAlgorithmSelector, TensorRT8_2) { + // Verify that the algorithm selector for TRT 8.0 is required. + AlgorithmSelectorImpl sel({8, 2, 0, 0}); + ASSERT_FALSE(sel.IsAlgorithmSelectorRequired()); +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph.cc new file mode 100644 index 0000000000000000000000000000000000000000..5e85bc4918dadb7b133a833e38670181055798c0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph.cc @@ -0,0 +1,944 @@ +/* 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/tf2tensorrt/convert/convert_graph.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/logger_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/segment/segment.h" +#include "tensorflow/core/common_runtime/gpu/gpu_id.h" +#include "tensorflow/core/common_runtime/gpu/gpu_id_manager.h" +#include "tensorflow/core/common_runtime/gpu/gpu_process_state.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/framework/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/graph.h" +#include "tensorflow/core/grappler/clusters/virtual_cluster.h" +#include "tensorflow/core/grappler/costs/graph_properties.h" +#include "tensorflow/core/grappler/devices.h" +#include "tensorflow/core/grappler/optimizers/meta_optimizer.h" +#include "tensorflow/core/grappler/utils.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/lib/strings/numbers.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/protobuf/config.pb.h" // NOLINT +#include "tensorflow/core/protobuf/device_properties.pb.h" // NOLINT +#include "tensorflow/core/protobuf/rewriter_config.pb.h" // NOLINT +#include "tensorflow/core/util/device_name_utils.h" +#include "tensorflow/tools/graph_transforms/transform_utils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" +#include "third_party/tensorrt/NvInfer.h" +namespace tensorflow { +namespace tensorrt { +namespace convert { + +using absl::StrAppend; +using absl::StrCat; +using ::tensorflow::tensorrt::segment::ClusterProperty; +using ::tensorflow::tensorrt::segment::NodePtrCompare; +using ::tensorflow::tensorrt::segment::Segment; + +namespace { + +Status BuildNodeMap(const Graph& graph, + std::unordered_map* node_map) { + for (auto* node : graph.op_nodes()) { + if (!node_map->insert({node->name(), node}).second) { + return errors::AlreadyExists("Node name is not unique in graph: " + + node->name()); + } + } + return OkStatus(); +} + +EngineInfo::EngineType GetEngineType( + const TRTOptimizationPass::ConversionParams& params) { + return (params.is_dynamic_op || params.use_calibration) + ? EngineInfo::EngineType::TRTDynamic + : EngineInfo::EngineType::TRTStatic; +} + +// Returns true when use_implicit_batch is false or when we are building dynamic +// engine, to allow unknown size for dimensions rather than dimension 0. +bool AllowDynamicNonBatchDimension( + const TRTOptimizationPass::ConversionParams& params) { + return !params.use_implicit_batch || + GetEngineType(params) == EngineInfo::EngineType::TRTDynamic; +} + +struct EdgePtrCompare { + bool operator()(const Edge* lhs, const Edge* rhs) const { + return lhs->id() < rhs->id(); + } +}; + +// TODO(laigd): instead of deciding the device here, the converter should accept +// a device name as one of the conversion parameter so users can control on +// which device they want to run the conversion. +std::pair GetFirstValidDeviceId() { + for (int tf_device_id_value = 0; tf_device_id_value < 100; + ++tf_device_id_value) { + TfDeviceId tf_device_id(tf_device_id_value); + PlatformDeviceId platform_device_id; + Status s = + GpuIdManager::TfToPlatformDeviceId(tf_device_id, &platform_device_id); + if (s.ok()) { + VLOG(1) << "Found TF GPU " << tf_device_id.value() << " at cuda device " + << platform_device_id.value(); + return std::make_pair(tf_device_id, platform_device_id); + } + } + LOG(ERROR) << "Could not find any TF GPUs"; + return std::make_pair(TfDeviceId(-1), PlatformDeviceId(-1)); +} + +// Returns false for const nodes (we intend to drop control edges from those). +bool ShallKeepControlEdgeFrom(const Node* input_node) { + if (!input_node) { + LOG(ERROR) << "Node pointer is null, this should not happen"; + return false; + } + return input_node->type_string() != "Const"; +} + +// Function to get subsegment information structure. +Status GetEngineInfo(const Graph* g, + const grappler::GraphProperties& graph_properties, + const Segment& segment, + const std::vector& reverse_topo_order, + EngineInfo* info) { + std::vector subgraph_nodes; // Topologically sorted nodes. + std::set added_const_nodes; // Used to prevent double insertion. + + const ClusterProperty& segment_property = segment.property; + const std::set& segment_nodes = segment.nodes; + + // The device assignment accumulated from the compatible device assignments + // for the nodes in the segment. + const DeviceNameUtils::ParsedName segment_device = + segment_property.DeviceName(); + info->max_batch_size = segment_property.BatchSize().GetOptionalMaxBatchSize(); + + // Map from src_node_name+port to the unique port numbers of the TRT op, where + // the src_node_name is the name of the source node of the input/output + // edge, thus there must not be any duplicates since source nodes of + // input/output edges must be in different split of the graph. + // TODO(aaroey): consider using node id and port instead. + // TODO(aaroey): using topo order instead of reverting reverse topo order. + std::unordered_map input_to_engine_port, output_to_engine_port; + for (auto it = reverse_topo_order.rbegin(); it != reverse_topo_order.rend(); + ++it) { + const Node* node = *it; + if (segment_nodes.count(node) == 0) continue; + subgraph_nodes.push_back(node); + + const int node_id = node->id(); + const string& node_name = node->name(); + + // Create input connections. Sort edges first to make deterministic since + // in_edges is a set of pointers. + std::vector in_edges(node->in_edges().begin(), + node->in_edges().end()); + std::sort(in_edges.begin(), in_edges.end(), EdgePtrCompare()); + for (const auto edge : in_edges) { + auto input_node = edge->src(); + if (input_node->IsSource() || segment_nodes.count(input_node)) { + continue; + } + if (edge->IsControlEdge()) { + if (ShallKeepControlEdgeFrom(input_node)) { + // Non-Const control input. + info->connections.emplace_back(input_node->name(), input_node->id(), + node_name, node_id, + /*input_edge=*/true); + } + } else if (input_node->type_string() == "Const") { + // Add constant data input nodes into the segment graphdef (thus also in + // the engine). We don't care if it has other output edges going into + // other engines or TF nodes. Since we add it only to the segment + // graphdef, not the segment itself, it won't be removed from the graph. + // If it doesn't have any edges, TF will prune it out. + // + // Note that the segmenter already ensure that the constant data input + // is valid and supported by the engine. + if (!added_const_nodes.insert(input_node).second) { + // Already added before. + continue; + } + VLOG(1) << "Adding const node " << input_node->name(); + } else { + // Non-const data input. + int port = Graph::kControlSlot - 1; + // Use the source non-segment node name/port as key. + const string s = StrCat(input_node->name(), ":", edge->src_output()); + VLOG(1) << "Input edge = " << s; + if (input_to_engine_port.count(s)) { + port = input_to_engine_port.at(s); + } else { + port = input_to_engine_port.size(); + input_to_engine_port.insert({s, port}); + } + info->connections.emplace_back( + input_node->name(), input_node->id(), edge->src_output(), node_name, + node_id, edge->dst_input(), /*input_edge=*/true, port); + } + } + // Create output connections. Sort edges first to make deterministic since + // out_edges is a set of pointers. + std::vector out_edges(node->out_edges().begin(), + node->out_edges().end()); + std::sort(out_edges.begin(), out_edges.end(), EdgePtrCompare()); + for (const auto edge : out_edges) { + auto output_node = edge->dst(); + if (output_node->IsSink() || segment_nodes.count(output_node)) { + continue; + } + if (edge->IsControlEdge()) { + // Control output. + if (ShallKeepControlEdgeFrom(node)) { + info->connections.emplace_back(output_node->name(), output_node->id(), + node_name, node_id, + /*input_edge=*/false); + } + } else { + // Data output. + int port = Graph::kControlSlot - 1; + // Use the source segment node name/port as key. + const string s = StrCat(node_name, ":", edge->src_output()); + VLOG(1) << "Output edge = " << s; + if (output_to_engine_port.count(s)) { + port = output_to_engine_port.at(s); + } else { + port = output_to_engine_port.size(); + output_to_engine_port.insert({s, port}); + } + info->connections.emplace_back( + output_node->name(), output_node->id(), edge->dst_input(), + node_name, node_id, edge->src_output(), /*input_edge=*/false, port); + } + } + } // For each segment node in topological order. + + // Construct the const nodes first. + subgraph_nodes.insert(subgraph_nodes.begin(), added_const_nodes.begin(), + added_const_nodes.end()); + TF_RETURN_IF_ERROR( + ConvertSegmentToGraphDef(g, graph_properties, subgraph_nodes, info)); + VLOG(1) << "Converted TensorRT candidate segment '" << info->engine_name + << "' to a GraphDef"; + if (segment_device.has_type) { + // If the accumulated device assignment for the segment has a device type, + // the segmenter guarantees the device type is GPU. Use the device + // assignment in this case. + if (segment_device.type != "GPU") { + return errors::Internal( + "segment device is not GPU: ", + DeviceNameUtils::ParsedNameToString(segment_device)); + } + info->device = DeviceNameUtils::ParsedNameToString(segment_device); + } else { + TfDeviceId tf_device_id; + PlatformDeviceId platform_device_id; + std::tie(tf_device_id, platform_device_id) = GetFirstValidDeviceId(); + if (tf_device_id.value() >= 0) { + DeviceNameUtils::ParsedName parsed_name; + parsed_name.type = "GPU"; + parsed_name.has_type = true; + parsed_name.id = tf_device_id.value(); + parsed_name.has_id = true; + info->device = DeviceNameUtils::ParsedNameToString(parsed_name); + } else { + VLOG(1) << "No device is assigned to the segment. A device will be " + "assigned during graph execution (inference)."; + } + } + return OkStatus(); +} + +// Helper function to update edge connection from the removed node to the +// engine node. If an outside node is gone, it must have been absorbed into +// an engine node. Find the engine node. +void UpdateToEngineNode(const std::vector& infos, + const size_t my_engine_id, + const std::vector& engine_nodes, + const bool is_input_edge, const string& node_name, + Node** node, int* port) { + for (size_t t = 0; t < infos.size(); ++t) { + if (t == my_engine_id) { + continue; + } + const auto& info = infos.at(t); + for (const auto& eng_conn : info.connections) { + // If the connection being updated is an input connection, the source of + // the connection must be an output connection of another engine. And vise + // versa. + if (is_input_edge == eng_conn.is_input_edge) continue; + if (eng_conn.inside_node_name == node_name && + eng_conn.inside_port == *port) { + *node = CHECK_NOTNULL(engine_nodes[t]); + QCHECK_EQ(info.engine_name, (**node).name()) + << "Engine name mismatch: " << info.engine_name << " vs " + << (**node).name(); + *port = eng_conn.port_number; + return; + } + } + } + LOG(FATAL) << "Node " << node_name << " not found in any engine."; +} + +tensorflow::TensorShapeProto ComputeTRTNodeIOShape( + std::vector& partial_tensorshape_vect, + std::vector& shape_proto_vect, + const PartialTensorShape& conn_shape, int port_number) { + tensorflow::TensorShapeProto tmp_shape_proto; + conn_shape.AsProto(&tmp_shape_proto); + + if (partial_tensorshape_vect.size() <= port_number) { + shape_proto_vect.resize(port_number + 1); + partial_tensorshape_vect.resize(port_number + 1); + } + + return tmp_shape_proto; +} + +// Function to insert a TRT engine node into the graph. +// Create engine nodes in the following way: +// 1. Each invocation of CreateTRTNode creates an engine node for infos[pos] +// 2. When an engine node is created, add it into the graph with necessary +// re-wiring. +// 2.1. If the outside connected node is existing, connect the engine +// node to it. +// 2.2. If the outside connected node is gone, it must have been absorted +// into another engine node (which was processed before the processing +// one). Connect to the pre-existing engine node instead. +// 3. In this way, we ensure the graph is topologically sort-able after each +// invocation of CreateTRTNode(). +Status CreateTRTNode(const TRTOptimizationPass::ConversionParams& params, + const std::vector& infos, int pos, + int default_max_batch_size, Graph* graph, + std::vector* engine_nodes, + grappler::Cluster* cluster) { + const auto& info = infos.at(pos); + std::vector input_shape_protos; + std::vector output_shape_protos; + std::vector input_shapes; + std::vector output_shapes; + std::vector inputs; + std::vector input_nodes; + std::vector control_input_nodes; + std::unordered_set control_input_names; + std::vector out_types; + + VLOG(1) << "Processing " << info.engine_name; + // Collect needed info for creating the engine node in the graph + for (const auto& conn : info.connections) { + // Control edges + if (conn.is_control_edge()) { + // Skip control outputs for now. control output info are not needed for + // node creation and will be processed later. + if (!conn.is_input_edge) continue; + + // Rewrire control input if it's not found in original graph. + Node* input_node = graph->FindNodeId(conn.outside_id); + int port = Graph::kControlSlot; + if (!input_node) { + UpdateToEngineNode(infos, pos, *engine_nodes, /*is_input_edge=*/true, + conn.outside_node_name, &input_node, &port); + QCHECK_EQ(Graph::kControlSlot, port); + } + if (!control_input_names.insert(input_node->name()).second) { + continue; + } + control_input_nodes.push_back(input_node); + VLOG(1) << "Engine Control Input " << input_node->name() << " -> " + << info.engine_name; + } else { + // Data edges + if (!conn.is_input_edge) { + // Set the shapes and data types of the output edge. + tensorflow::TensorShapeProto out_shape = ComputeTRTNodeIOShape( + /*partial_tensorshape_vect=*/output_shapes, + /*shape_proto_vect=*/output_shape_protos, + /*conn_shape=*/conn.inside_shape, + /*port_number=*/conn.port_number); + + output_shape_protos.at(conn.port_number) = out_shape; + output_shapes.at(conn.port_number) = conn.inside_shape; + + if (out_types.size() <= conn.port_number) { + out_types.resize(conn.port_number + 1); + } + out_types.at(conn.port_number) = conn.connection_type; + VLOG(2) << "Collected output shape " + << output_shape_protos.at(conn.port_number).DebugString(); + } else { + // Set the shapes of the input edge. + tensorflow::TensorShapeProto in_shape = ComputeTRTNodeIOShape( + /*partial_tensorshape_vect=*/input_shapes, + /*shape_proto_vect=*/input_shape_protos, + /*conn_shape=*/conn.outside_shape, + /*port_number=*/conn.port_number); + + input_shape_protos.at(conn.port_number) = in_shape; + input_shapes.at(conn.port_number) = conn.outside_shape; + + // Shape must be fully defined (excluding batch dimension) for static + // mode. + if (params.use_implicit_batch && + info.engine_type == EngineInfo::EngineType::TRTStatic) { + for (int i = 1; i < conn.outside_shape.dims(); i++) { + if (conn.outside_shape.dim_size(i) <= 0) { + return errors::Internal( + "Not fully defined input shape when in static mode which " + "should have been excluded by the segmenter. "); + } + } + } + + // Rewrire data input if it's not found in original graph. + Node* input_node = graph->FindNodeId(conn.outside_id); + int port = conn.outside_port; + if (!input_node) { + UpdateToEngineNode(infos, pos, *engine_nodes, /*is_input_edge=*/true, + conn.outside_node_name, &input_node, &port); + } + if (std::find_if( + std::begin(inputs), std::end(inputs), + [input_node, &port](const NodeDefBuilder::NodeOut& inp) { + return inp.node == input_node->name() && inp.index == port; + }) == std::end(inputs)) { + inputs.emplace_back(input_node->name(), port, conn.connection_type); + input_nodes.push_back(CHECK_NOTNULL(input_node)); + VLOG(1) << "Engine Input " << input_node->name() << ":" << port + << " -> " << info.engine_name << ":" << inputs.size() - 1; + } + } + } + } + // We don't support segments with no inputs. Fall back to native TF here to + // avoid crash later. Constant folding should've folded the ops that make up + // these segments. + if (inputs.empty()) { + return errors::Internal( + "Segment has no inputs (possible constfold failure)"); + } + + // Build the engine and get its serialized representation. + string segment_string; + + int max_batch_size = info.max_batch_size.has_value() + ? info.max_batch_size.value() + : default_max_batch_size; + + if (info.engine_type == EngineInfo::EngineType::TRTStatic) { + TF_RETURN_IF_ERROR(CreateStaticEngine(params, info, max_batch_size, + input_shapes, nullptr, + &segment_string, cluster)); + } + + string prec_string; + TF_RETURN_IF_ERROR(TrtPrecisionModeToName(info.precision_mode, &prec_string)); + NodeDefBuilder node_builder(info.engine_name, "TRTEngineOp"); + if (!info.device.empty()) node_builder.Device(info.device); + if (VLOG_IS_ON(1)) { + string ins = StrCat(info.engine_name, " inputs= "); + for (const auto& ii : inputs) { + StrAppend(&ins, ii.node, ":", ii.index, " "); + } + VLOG(1) << ins; + } + node_builder.Input(inputs); + for (const string& c : control_input_names) { + node_builder.ControlInput(c); + } + + NodeDef trt_node; + NameAttrList function; + function.set_name(StrCat(info.engine_name, "_native_segment")); + + node_builder.Attr("input_shapes", input_shape_protos) + .Attr("output_shapes", output_shape_protos) + .Attr("static_engine", + info.engine_type == EngineInfo::EngineType::TRTStatic) + .Attr("segment_func", function) + .Attr("serialized_segment", segment_string) + .Attr("calibration_data", "") + .Attr("max_cached_engines_count", info.maximum_cached_engines) + .Attr("workspace_size_bytes", info.max_workspace_size_bytes) + .Attr("max_batch_size", max_batch_size) + .Attr("precision_mode", prec_string) + .Attr("use_calibration", info.use_calibration) + .Attr("_use_implicit_batch", params.use_implicit_batch) + .Attr("use_explicit_precision", params.use_explicit_precision) + .Attr("_allow_build_at_runtime", info.allow_build_at_runtime) + .Attr("OutT", out_types); + + if (!params.use_implicit_batch) { + node_builder.Attr("profile_strategy", + ProfileStrategyToName(params.profile_strategy)); + } + + Status status = node_builder.Finalize(&trt_node); + + if (!status.ok()) { + LOG(ERROR) << "Node construction failed with" << status; + return status; + } + VLOG(1) << "Adding TRTEngine " << info.engine_name << " to graph"; + + // Up until this point, graph is not modified. If we return !status.ok() from + // here, this segment will be skipped + // TODO(aaroey): let it return proper error status for the following logic + // instead of checking fail. + TF_ASSIGN_OR_RETURN(Node * engine_node, graph->AddNode(trt_node)); + (*engine_nodes)[pos] = engine_node; + // Add control input and input edges to the engine node. + for (const auto in : control_input_nodes) { + VLOG(1) << "Connecting control edge from " << in->name() << " to " + << engine_node->name(); + graph->AddControlEdge(in, engine_node); + } + VLOG(1) << "input_nodes size = " << input_nodes.size(); + for (int i = 0; i < input_nodes.size(); ++i) { + Node* n = CHECK_NOTNULL(input_nodes[i]); + const auto& in = inputs[i]; + VLOG(1) << "Connecting data edge from " << n->name() << ":" << in.index + << " to " << engine_node->name() << ":" << i; + graph->AddEdge(n, in.index, engine_node, i); + } + + // Updates the inputs of output edges destination nodes, and point them to the + // engine node. + for (auto& conn : info.connections) { + if (conn.is_input_edge) { + continue; + } + Node* output_node = graph->FindNodeId(conn.outside_id); + int port = conn.outside_port; + if (!output_node) { + UpdateToEngineNode(infos, pos, *engine_nodes, /*is_input_edge=*/false, + conn.outside_node_name, &output_node, &port); + } + if (conn.is_control_edge()) { + VLOG(1) << "Updating control edge from " << engine_node->name() << " to " + << output_node->name(); + QCHECK_EQ(Graph::kControlSlot, port); + graph->AddControlEdge(engine_node, output_node); + } else { + VLOG(1) << "Updating data edge from " << engine_node->name() << ":" + << conn.port_number << " to " << output_node->name() << ":" + << port; + // Use UpdateEdge() to avoid adding the same edge multiple times. + TF_CHECK_OK( + graph->UpdateEdge(engine_node, conn.port_number, output_node, port)); + } + } + return OkStatus(); +} + +int64 GetNextGraphSequenceNumber() { + static std::atomic graph_sequence_num; + return graph_sequence_num++; +} + +constexpr char kCastInputTypeAttrName[] = "SrcT"; + +// Transforms node = cast(x, fp32) where datatype(x) != fp16 to: +// castToFp16 = cast(x, fp16) +// node = cast(castToFp16, fp32) +// +Status MaybeRewriteCastToFp32(GraphDef* graph_def, NodeDef* node_def) { + if (node_def->op() != "Cast") { + return OkStatus(); + } + + DataTypeVector input_types; + DataTypeVector output_types; + TF_RETURN_IF_ERROR( + graph_transforms::GetInOutTypes(*node_def, &input_types, &output_types)); + + if (input_types.size() != 1 || output_types.size() != 1) { + return errors::Internal("Bad cast operation"); + } + + if (input_types[0] == DT_HALF || output_types[0] != DT_FLOAT) { + return OkStatus(); + } + + VLOG(2) << "Rewriting cast to FP32 " << node_def->DebugString(); + + NodeDef* castToFp16 = graph_def->add_node(); + for (auto attr_value : node_def->attr()) { + (*castToFp16->mutable_attr())[attr_value.first] = attr_value.second; + } + castToFp16->set_name(node_def->name() + "_split"); + castToFp16->set_op("Cast"); + castToFp16->set_device(node_def->device()); + castToFp16->add_input(node_def->input(0)); + (*castToFp16->mutable_attr())[kCastOutputTypeAttrName].set_type(DT_HALF); + + node_def->set_input(0, castToFp16->name() + ":0"); + (*node_def->mutable_attr())[kCastInputTypeAttrName].set_type(DT_HALF); + + VLOG(2) << castToFp16->DebugString(); + VLOG(2) << node_def->DebugString(); + + return OkStatus(); +} + +} // namespace + +Status RegisterGraphToFunctionLibrary(const GraphDef& segment_graph_def, + Graph* graph, const string& engine_name) { + Graph segment_graph(graph->flib_def()); + TF_RETURN_IF_ERROR(ConvertGraphDefToGraph(GraphConstructorOptions(), + segment_graph_def, &segment_graph)); + FunctionDefLibrary library; + auto segment_func = library.add_function(); + TF_RETURN_IF_ERROR(GraphToFunctionDef( + segment_graph, StrCat(engine_name, "_native_segment"), segment_func)); + if (VLOG_IS_ON(7)) { + VLOG(7) << engine_name << " Function_Def "; + VLOG(7) << segment_func->DebugString(); + } + VLOG(1) << "Adding funcdef " << segment_func->signature().name() + << " to graphlib"; + TF_RETURN_IF_ERROR(graph->AddFunctionLibrary(library)); + return OkStatus(); +} + +std::pair GetDeviceAndAllocator( + const grappler::Cluster* cluster, const EngineInfo& engine) { + int cuda_device_id = -1; + Allocator* dev_allocator = nullptr; + if (cluster == nullptr || cluster->GetDeviceSet() == nullptr || + engine.device.empty()) { + // If device is not set, use the first found GPU device for the conversion. + TfDeviceId tf_device_id; + PlatformDeviceId platform_device_id; + std::tie(tf_device_id, platform_device_id) = GetFirstValidDeviceId(); + cuda_device_id = platform_device_id.value(); + if (cuda_device_id >= 0) { + GPUOptions gpu_options; + // If the TF to Cuda gpu id mapping exist, the device and corresponding + // allocator must have been initialized already, so the + // GetGPUAllocator() call won't create a new allocator. + dev_allocator = GPUProcessState::singleton()->GetGPUAllocator( + gpu_options, tf_device_id, /*total_bytes=*/1, /*peer_gpu_ids=*/{}); + } + return std::make_pair(cuda_device_id, dev_allocator); + } + + // Use the device requested by the engine. + auto device_set = cluster->GetDeviceSet(); + std::vector devices; + DeviceNameUtils::ParsedName parsed_name; + if (DeviceNameUtils::ParseFullName(engine.device, &parsed_name) && + parsed_name.has_id) { + device_set->FindMatchingDevices(parsed_name, &devices); + } + if (!devices.empty()) { + if (devices.size() > 1) { + string msg = "Found multiple matching devices using name '"; + StrAppend(&msg, engine.device, "': "); + for (auto d : devices) StrAppend(&msg, d->name(), ", "); + StrAppend(&msg, ". Will get the allocator from first one."); + LOG_WARNING_WITH_PREFIX << msg; + } + AllocatorAttributes alloc_attr; + cuda_device_id = devices[0]->tensorflow_accelerator_device_info()->gpu_id; + dev_allocator = devices[0]->GetAllocator(alloc_attr); + VLOG(1) << "Using allocator " << dev_allocator->Name() + << " and cuda_device_id " << cuda_device_id; + } else { + LOG_WARNING_WITH_PREFIX << "Cluster is set but device '" << engine.device + << "' is not found in the cluster"; + } + return std::make_pair(cuda_device_id, dev_allocator); +} + +Status CreateStaticEngine(const TRTOptimizationPass::ConversionParams& params, + const EngineInfo& info, int max_batch_size, + const std::vector& input_shapes, + TrtShapeOptimizationProfile* profile, + string* segment_string, grappler::Cluster* cluster) { + std::pair device_allocator = + GetDeviceAndAllocator(cluster, info); + int cuda_device_id = 0; + std::unique_ptr trt_allocator; + if (device_allocator.first >= 0) { + cuda_device_id = device_allocator.first; + trt_allocator.reset(new TRTDeviceAllocator(device_allocator.second)); + } else { + // The value in trt_allocator is a nullptr and cudamalloc will be used. + LOG_WARNING_WITH_PREFIX << "Can't identify the cuda device. Running on " + "device 0 and use cudamalloc as an allocator"; + } + cudaSetDevice(cuda_device_id); + + auto trt_logger = GetLoggerRegistry()->LookUp(params.trt_logger_name); + const bool calibrate_int8 = + (info.precision_mode == TrtPrecisionMode::INT8 && info.use_calibration); + + // Create static engines with precision_mode fp32/fp16. + TrtUniquePtrType engine; + TF_RETURN_IF_ERROR(ConvertGraphDefToEngine( + info.segment_graph_def, nullptr, + calibrate_int8 ? TrtPrecisionMode::FP32 : info.precision_mode, + max_batch_size, info.max_workspace_size_bytes, input_shapes, trt_logger, + trt_allocator.get(), /*calibrator=*/nullptr, &engine, + info.use_calibration, params.use_implicit_batch, + /*convert_successfully=*/nullptr, profile, info.engine_name, + /*use_explicit_precision=*/params.use_explicit_precision, cluster)); + TrtUniquePtrType engine_data(engine->serialize()); + *segment_string = string(static_cast(engine_data->data()), + engine_data->size()); + return OkStatus(); +} + +Status ConvertGraph(const TRTOptimizationPass::ConversionParams& params, + grappler::GrapplerItem& grappler_item, + const std::vector& input_output_names, + grappler::Cluster* cluster, GraphDef* output) { + // Sanity checks. + TRT_ENSURE(output != nullptr) + if (params.precision_mode != TrtPrecisionMode::INT8 && + params.use_calibration) { + return errors::InvalidArgument( + "Calibration with FP32 or FP16 is not supported."); + } + + GraphDef& graph_def = grappler_item.graph; + + // When precision_mode is FP16, transform cast(x, fp32) to + // cast(cast(x, fp16), fp32). This creates cast(fp16, f32) that can be + // included in the TRTEngineOp as an TensorRT Identity layer for performance: + // . Avoid cast(fp32, fp16) in the TRT engine implementation for fp16 + // precision. + // . Changing the input to the TRTEngine from fp32 to fp16 may reduce data + // moving from the host to the GPU. + if (params.precision_mode == TrtPrecisionMode::FP16) { + for (int i = 0; i < graph_def.node_size(); i++) { + NodeDef* node_def = graph_def.mutable_node(i); + TF_RETURN_IF_ERROR(MaybeRewriteCastToFp32(&graph_def, node_def)); + } + } + + // Construct a GrapplerItem using the modified graph_def and the input + // grappler_item. + grappler::GraphProperties static_graph_properties(grappler_item); + TF_RETURN_IF_ERROR(static_graph_properties.InferStatically(true)); + + // Convert graphdef to graph. + FunctionLibraryDefinition flib(OpRegistry::Global(), graph_def.library()); + Graph graph(flib); + TF_RETURN_IF_ERROR( + ConvertGraphDefToGraph(GraphConstructorOptions(), graph_def, &graph)); + + // Segment the graph into subgraphs that can be converted to TensorRT + segment::SegmentOptions segment_options; + // TODO(ben,jie,sami): exclude output nodes (DISCUSS IT) + for (const auto& node : input_output_names) { + segment_options.exclude_node_list.insert(node); + } + segment_options.minimum_segment_size = params.minimum_segment_size; + segment_options.use_implicit_batch = params.use_implicit_batch; + if (segment_options.use_implicit_batch) + segment_options.maximum_batch_size = params.max_batch_size; + segment_options.allow_dynamic_non_batch_dim = + AllowDynamicNonBatchDimension(params); + + segment::SegmentVector initial_segments; + TrtNodeValidator validator(static_graph_properties, params.precision_mode, + params.use_calibration, params.use_implicit_batch, + params.use_explicit_precision); + TF_RETURN_IF_ERROR(segment::SegmentGraph( + /*tf_graph=*/&graph, + /*graph_properties=*/&static_graph_properties, + /*candidate_fn=*/ + std::bind(&TrtNodeValidator::IsTensorRTCandidate, &validator, + std::placeholders::_1), + // Input validation is already done by TrtNodeValidator, so we don't + // need to check the input edges. + /*input_candidate_fn=*/[](const Edge* edge) { return true; }, + /*output_candidate_fn=*/OutputEdgeValidator(), + /*options=*/segment_options, + /*segments=*/&initial_segments)); + LOG(INFO) << "Number of TensorRT candidate segments: " + << initial_segments.size(); + + // Get the EngineInfo for each segment. + std::unordered_map node_map; + TF_RETURN_IF_ERROR(BuildNodeMap(graph, &node_map)); + std::vector engine_segments; + engine_segments.reserve(initial_segments.size()); + std::vector reverse_topo_order; + GetPostOrder(graph, &reverse_topo_order); + segment::SegmentVector converted_segments; + converted_segments.reserve(initial_segments.size()); + string engine_name_prefix = + StrCat("TRTEngineOp_", + absl::StrFormat("%0*d", 3, GetNextGraphSequenceNumber()), "_"); + for (size_t t = 0; t < initial_segments.size(); t++) { + auto& curr_segment = initial_segments.at(t); + EngineInfo curr_engine; + curr_engine.engine_name = + StrCat(engine_name_prefix, absl::StrFormat("%0*d", 3, t)); + + bool int8_no_calib = (!params.use_calibration && + params.precision_mode == TrtPrecisionMode::INT8); + bool has_qdq = false; + if (int8_no_calib) { + has_qdq = absl::c_any_of(reverse_topo_order, IsQuantizeAndDequantizeOp); + } + + Status status = GetEngineInfo(&graph, static_graph_properties, curr_segment, + reverse_topo_order, &curr_engine); + if (!status.ok()) { + LOG_WARNING_WITH_PREFIX << "Failed to get engine info for segment " << t + << ": " << status; + continue; + } + + curr_engine.engine_type = GetEngineType(params); + curr_engine.use_calibration = params.use_calibration; + // Building cuda engines for INT8 without calibration and without dynamic + // range info cause TRT failure. Avoid this situation by setting the + // precision to FP16. + if (int8_no_calib && !has_qdq) { + LOG(WARNING) << "Set engine precision to FP16 due to missing QDQ OP"; + curr_engine.precision_mode = TrtPrecisionMode::FP16; + } else { + curr_engine.precision_mode = params.precision_mode; + } + curr_engine.maximum_cached_engines = params.max_cached_engines; + curr_engine.allow_build_at_runtime = params.allow_build_at_runtime; + if (!curr_engine.max_batch_size.has_value()) { + curr_engine.max_batch_size = params.max_batch_size; + } + + status = RegisterGraphToFunctionLibrary(curr_engine.segment_graph_def, + &graph, curr_engine.engine_name); + + if (!status.ok()) { + LOG_WARNING_WITH_PREFIX + << "Failed to register segment graphdef to the library " << t << ": " + << status; + continue; + } + + engine_segments.push_back(std::move(curr_engine)); + converted_segments.push_back(std::move(curr_segment)); + + if (VLOG_IS_ON(8)) { + string fname = engine_segments.back().engine_name; + StrAppend(&fname, ".pb"); + std::fstream f; + f.open(fname.c_str(), std::fstream::out | std::fstream::binary); + f << engine_segments.at(t).segment_graph_def.SerializeAsString(); + f.close(); + } + } + + // Save the cuda device since we may need to switch to another cuda device to + // build static engines. + std::optional old_cuda_device = std::nullopt; + if (!params.is_dynamic_op) { + int cuda_device_id; + cudaError_t cuda_error = cudaGetDevice(&cuda_device_id); + if (cuda_error != cudaSuccess) { + LOG_WARNING_WITH_PREFIX << "Couldn't get current device: " + << cudaGetErrorString(cuda_error); + } else { + VLOG(1) << "Current cuda device is " << cuda_device_id; + old_cuda_device = cuda_device_id; + } + } + + auto restore_cuda_device = gtl::MakeCleanup([old_cuda_device] { + if (old_cuda_device.has_value()) { + cudaSetDevice(old_cuda_device.value()); + } + }); + + std::vector engine_nodes; + engine_nodes.resize(engine_segments.size()); + for (int i = 0; i < engine_segments.size(); ++i) { + auto& engine = engine_segments.at(i); + // TODO(b/170762693): implement the heuristic to calculate + // max_workspace_size_bytes. + engine.max_workspace_size_bytes = params.max_workspace_size_bytes; + VLOG(1) << "Assigned " << engine.max_workspace_size_bytes << " bytes to " + << engine.engine_name; + auto status = + CreateTRTNode(params, engine_segments, i, params.max_batch_size, &graph, + &engine_nodes, cluster); + + string msg = StrCat("segment ", i, " consisting of ", + converted_segments.at(i).nodes.size(), " nodes by ", + engine.engine_name); + if (status.ok()) { + LOG(INFO) << "Replaced " << msg << "."; + } else { + // Graph is not modified. + LOG_WARNING_WITH_PREFIX << "Cannot replace " << msg + << " reason: " << status.message() + << " (keeping original segment)."; + } + if (VLOG_IS_ON(1)) { + msg = "Segment consists of nodes: "; + for (const Node* node : converted_segments.at(i).nodes) { + StrAppend(&msg, node->name(), ", "); + } + VLOG(1) << msg; + } + + // If status is ok, we successfully added the node to the graph and can + // remove segment ops. Otherwise graph is not modified. + if (status.ok()) { + for (const Node* node : converted_segments.at(i).nodes) { + graph.RemoveNode(const_cast(node)); + } + } + } + graph.ToGraphDef(output); + return OkStatus(); +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..a4205d86ce67a014584a317f1cce411e75977403 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph.h @@ -0,0 +1,70 @@ +/* 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_TF2TENSORRT_CONVERT_CONVERT_GRAPH_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_GRAPH_H_ + +#include + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/grappler/clusters/cluster.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +// These functions are internal implementation functions for the +// TRTOptimizationPass. + +// Performs segmentation and conversion on the given Grappler item. This method +// contains the core logic of the TRTOptimizationPass. +Status ConvertGraph(const TRTOptimizationPass::ConversionParams& params, + grappler::GrapplerItem& grappler_item, + const std::vector& input_output_names, + grappler::Cluster* cluster, GraphDef* output); + +// Helper method for the conversion, expose for testing. +std::pair GetDeviceAndAllocator( + const grappler::Cluster* cluster, const EngineInfo& engine); + +// Helper method that registers `segment_graph` as a function to the function +// library in `graph`. +Status RegisterGraphToFunctionLibrary(const GraphDef& segment_graph_def, + Graph* graph, const string& engine_name); + +// Creates and serializes an ICudaEngine. Used only in is_dynamic_op=false, +// a.k.a. static engine mode. +Status CreateStaticEngine(const TRTOptimizationPass::ConversionParams& params, + const EngineInfo& info, int max_batch_size, + const std::vector& input_shapes, + TrtShapeOptimizationProfile* profile, + string* segment_string, grappler::Cluster* cluster); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_GRAPH_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..80804a2c003f4a209f0a068619c83ca01a561d01 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_graph_test.cc @@ -0,0 +1,221 @@ +/* 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/tf2tensorrt/convert/convert_graph.h" + +#include // NOLINT + +#include +#include +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_testutils.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/grappler/clusters/cluster.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/protobuf/config.pb.h" // NOLINT +#include "tensorflow/core/public/session.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class FakeCluster : public grappler::Cluster { + public: + FakeCluster() : Cluster(0) {} + + void SetDeviceSet(const DeviceSet* device_set) { device_set_ = device_set; } + + const DeviceSet* GetDeviceSet() const override { return device_set_; } + + string type() const override { return ""; } + Status Provision() override { return OkStatus(); } + Status Initialize(const grappler::GrapplerItem& item) override { + return OkStatus(); + } + Status Run(const GraphDef& graph_def, + const std::vector>& feed, + const std::vector& fetch, RunMetadata* metadata) override { + return OkStatus(); + } + + private: + const DeviceSet* device_set_ = nullptr; +}; + +TEST(GetDeviceAndAllocatorTest, GetDeviceAndAllocator) { + TRTOptimizationPass::ConversionParams params; + EngineInfo engine_info; + { + // cluster is not set, and no gpu device is available. + auto result = GetDeviceAndAllocator(nullptr, engine_info); + EXPECT_EQ(-1, result.first); + EXPECT_EQ(nullptr, result.second); + } + + // Create a session with two (virtual) gpu device. + SessionOptions options; + ConfigProto* config = &options.config; + GPUOptions* gpu_options = config->mutable_gpu_options(); + auto virtual_devices = + gpu_options->mutable_experimental()->add_virtual_devices(); + virtual_devices->add_memory_limit_mb(200); + virtual_devices->add_memory_limit_mb(200); + std::unique_ptr session(NewSession(options)); + + { + // cluster is not set, should find and return first gpu id and + // corresponding allocator. + auto result = GetDeviceAndAllocator(nullptr, engine_info); + EXPECT_EQ(0, result.first); + EXPECT_NE(nullptr, result.second); + EXPECT_EQ("GPU_0_bfc", result.second->Name()); + } + + FakeCluster cluster; + { + // params.cluster->GetDeviceSet() returns null, should find and return first + // gpu id and corresponding allocator. + auto result = GetDeviceAndAllocator(&cluster, engine_info); + EXPECT_EQ(0, result.first); + EXPECT_NE(nullptr, result.second); + EXPECT_EQ("GPU_0_bfc", result.second->Name()); + } + + // Build the DeviceSet. + DeviceSet device_set; + const DeviceMgr* device_mgr = nullptr; + TF_ASSERT_OK(session->LocalDeviceManager(&device_mgr)); + for (auto d : device_mgr->ListDevices()) { + device_set.AddDevice(d); + } + cluster.SetDeviceSet(&device_set); + { + // engine_info.device is not set, should find and return first gpu id and + // corresponding allocator. + auto result = GetDeviceAndAllocator(&cluster, engine_info); + EXPECT_EQ(0, result.first); + EXPECT_NE(nullptr, result.second); + EXPECT_EQ("GPU_0_bfc", result.second->Name()); + } + + engine_info.device = "/GPU:1"; + { + // Set to use second device. + auto result = GetDeviceAndAllocator(&cluster, engine_info); + EXPECT_EQ(0, result.first); + EXPECT_NE(nullptr, result.second); + EXPECT_EQ("GPU_1_bfc", result.second->Name()); + } + + engine_info.device = "/GPU:3"; + { + // Set to use nonexistent device. + auto result = GetDeviceAndAllocator(&cluster, engine_info); + EXPECT_EQ(-1, result.first); + EXPECT_EQ(nullptr, result.second); + } +} + +class ConvertGraphTest : public ::testing::Test { + public: + Status RunConvertGraph(Scope s, GraphDef* output_graph_def, + int maximum_batch_size = 1000) { + // Create GraphProperties. + grappler::GrapplerItem item; + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + grappler::GraphProperties graph_properties(item); + TF_EXPECT_OK(graph_properties.InferStatically(true)); + + // Construct ConversionParams. + const std::vector input_output_names{"output"}; + TRTOptimizationPass::ConversionParams params; + params.max_batch_size = maximum_batch_size; + params.max_workspace_size_bytes = 8 << 20; + params.minimum_segment_size = 1; + params.use_calibration = false; + params.trt_logger_name = "DefaultLogger"; + return ConvertGraph(params, item, input_output_names, nullptr, + output_graph_def); + } +}; + +TEST_F(ConvertGraphTest, DirectlyConnectedEngines) { + // Create the graph. There will be two TRTEngineOps after the conversion, and + // the upstream TRTEngineOp will have two output connections from the same + // node:port inside the op to the downstream TRTEngineOp. Then, if it adds the + // downstream TRTEngineOp first, when adding the upstream op it'll need to + // update the same output connection twice. This test ensures the correctness + // of the conversion under such condition. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT, + ops::Placeholder::Shape({2, 1})); + // We purposefully choose the name of the root node of each segment, so it'll + // process the segment in the downstream first, then, when it tries to update + // the edge between the two TRTEngineOps, it'll try to add the same edge + // multiple times. + auto segment_root_1 = ops::Identity(s.WithOpName("segment_root_b"), input); + auto add1 = ops::Add(s.WithOpName("add1"), segment_root_1, segment_root_1); + // Add incompatible reshapes that change the batch dimension. + auto incompatible = + ops::Reshape(s.WithOpName("reshape1"), add1, Input({1, 2})); + incompatible = + ops::Reshape(s.WithOpName("reshape2"), incompatible, Input({2, 1})); + + auto add2 = ops::Add(s.WithOpName("add2"), incompatible, add1); + auto segment_root_2 = ops::Identity(s.WithOpName("segment_root_a"), add1); + auto add3 = ops::Add(s.WithOpName("add3"), add2, segment_root_2); + ops::Identity(s.WithOpName("output"), add3); + + GraphDef output_graph_def; + TF_EXPECT_OK(RunConvertGraph(s, &output_graph_def)); + + auto remove_graph_sequence_number = [](std::string node_name) { + const std::regex pattern("TRTEngineOp_[0-9]+_"); + return std::regex_replace(node_name, pattern, "TRTEngineOp_"); + }; + int num_trt_ops = 0; + for (const NodeDef& node : output_graph_def.node()) { + std::string node_name = node.name(); + if (node.op() != "TRTEngineOp") continue; + node_name = remove_graph_sequence_number(node_name); + if (node_name == "TRTEngineOp_001") { + EXPECT_EQ(1, node.input_size()); + EXPECT_EQ("input", node.input(0)); + ++num_trt_ops; + } else if (node_name == "TRTEngineOp_000") { + EXPECT_EQ(2, node.input_size()); + EXPECT_EQ("TRTEngineOp_001", remove_graph_sequence_number(node.input(0))); + EXPECT_EQ("reshape2", node.input(1)); + ++num_trt_ops; + } + } + EXPECT_EQ(2, num_trt_ops); +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.cc new file mode 100644 index 0000000000000000000000000000000000000000..01abe128828b187f9fb2a1c0723f96186103ef8b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.cc @@ -0,0 +1,6265 @@ +/* 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/tf2tensorrt/convert/convert_nodes.h" + +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep +#include // IWYU pragma: keep + +#include "absl/algorithm/container.h" // IWYU pragma: keep +#include "absl/container/flat_hash_set.h" // IWYU pragma: keep +#include "absl/memory/memory.h" // IWYU pragma: keep +#include "absl/strings/match.h" // IWYU pragma: keep +#include "absl/strings/str_cat.h" // IWYU pragma: keep +#include "absl/strings/str_format.h" // IWYU pragma: keep +#include "absl/strings/string_view.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/algorithm_selector.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/timing_cache.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" // IWYU pragma: keep +#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" // IWYU pragma: keep +#include "tensorflow/core/common_runtime/graph_constructor.h" // IWYU pragma: keep +#include "tensorflow/core/framework/node_def.pb.h" // IWYU pragma: keep +#include "tensorflow/core/framework/node_def_builder.h" // IWYU pragma: keep +#include "tensorflow/core/framework/tensor.pb.h" // IWYU pragma: keep +#include "tensorflow/core/framework/tensor_shape.h" // IWYU pragma: keep +#include "tensorflow/core/framework/tensor_shape.pb.h" // IWYU pragma: keep +#include "tensorflow/core/framework/tensor_util.h" // IWYU pragma: keep +#include "tensorflow/core/framework/types.h" // IWYU pragma: keep +#include "tensorflow/core/graph/algorithm.h" // IWYU pragma: keep +#include "tensorflow/core/graph/graph.h" // IWYU pragma: keep +#include "tensorflow/core/grappler/grappler_item.h" // IWYU pragma: keep +#include "tensorflow/core/grappler/op_types.h" // IWYU pragma: keep +#include "tensorflow/core/grappler/optimizers/constant_folding.h" // IWYU pragma: keep +#include "tensorflow/core/grappler/optimizers/generic_layout_optimizer.h" // IWYU pragma: keep +#include "tensorflow/core/lib/core/errors.h" // IWYU pragma: keep +#include "tensorflow/core/lib/core/status.h" // IWYU pragma: keep +#include "tensorflow/core/lib/strings/numbers.h" // IWYU pragma: keep +#include "tensorflow/core/lib/strings/str_util.h" // IWYU pragma: keep +#include "tensorflow/core/lib/strings/strcat.h" // IWYU pragma: keep +#include "tensorflow/core/platform/logging.h" // IWYU pragma: keep +#include "tensorflow/core/platform/mutex.h" // IWYU pragma: keep +#include "tensorflow/core/platform/protobuf.h" // IWYU pragma: keep +#include "tensorflow/core/platform/tensor_coding.h" // IWYU pragma: keep +#include "tensorflow/core/platform/tensor_float_32_utils.h" // IWYU pragma: keep +#include "tensorflow/core/platform/types.h" // IWYU pragma: keep +#include "tensorflow/core/profiler/lib/annotated_traceme.h" // IWYU pragma: keep +#include "tensorflow/core/profiler/lib/traceme.h" // IWYU pragma: keep +#include "tensorflow/core/public/release_version.h" // IWYU pragma: keep +#include "tensorflow/core/util/env_var.h" // IWYU pragma: keep +#include "tensorflow/core/util/strided_slice_op.h" // IWYU pragma: keep + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" +#include "third_party/tensorrt/NvInferPlugin.h" + +// Check if the types are equal. Cast to int first so that failure log message +// would work! +#define TFTRT_CHECK_EQ_TYPE(val1, val2) CHECK_EQ((int)val1, (int)val2) + +#define TFTRT_CHECK_INPUT_SIZE(size, exp_size, node_def) \ + if ((size) != (exp_size)) { \ + TFTRT_ERROR(errors::InvalidArgument, node_def.op(), " got ", (size), \ + " inputs but expected ", (exp_size)); \ + } + +// Max kernel volume copied from TRT's limits. +#define MAX_KERNEL_DIMS_PRODUCT(x) (int64_t(std::pow(100000.0F, (x) * 0.5F))) + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +using absl::StrAppend; +using absl::StrCat; + +namespace { + +#define ADD_LAYER(layer_name) \ + case nvinfer1::LayerType::k##layer_name: \ + return #layer_name; + +const char* LayerTypeToString(nvinfer1::LayerType layer_type) { + switch (layer_type) { + ADD_LAYER(CONVOLUTION) + ADD_LAYER(FULLY_CONNECTED) + ADD_LAYER(ACTIVATION) + ADD_LAYER(POOLING) + ADD_LAYER(LRN) + ADD_LAYER(SCALE) + ADD_LAYER(SOFTMAX) + ADD_LAYER(DECONVOLUTION) + ADD_LAYER(CONCATENATION) + ADD_LAYER(ELEMENTWISE) + ADD_LAYER(PLUGIN) + ADD_LAYER(UNARY) + ADD_LAYER(PADDING) + ADD_LAYER(SHUFFLE) + ADD_LAYER(REDUCE) + ADD_LAYER(TOPK) + ADD_LAYER(GATHER) +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + ADD_LAYER(GRID_SAMPLE) +#endif + ADD_LAYER(MATRIX_MULTIPLY) + ADD_LAYER(RAGGED_SOFTMAX) + ADD_LAYER(CONSTANT) + ADD_LAYER(RNN_V2) + ADD_LAYER(IDENTITY) + ADD_LAYER(PLUGIN_V2) + ADD_LAYER(SLICE) + ADD_LAYER(SHAPE) + ADD_LAYER(PARAMETRIC_RELU) + ADD_LAYER(RESIZE) + ADD_LAYER(TRIP_LIMIT) + ADD_LAYER(RECURRENCE) + ADD_LAYER(ITERATOR) + ADD_LAYER(LOOP_OUTPUT) + ADD_LAYER(SELECT) + ADD_LAYER(FILL) +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + ADD_LAYER(QUANTIZE) + ADD_LAYER(DEQUANTIZE) +#endif +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + ADD_LAYER(CONDITION) + ADD_LAYER(CONDITIONAL_INPUT) + ADD_LAYER(CONDITIONAL_OUTPUT) + ADD_LAYER(SCATTER) + ADD_LAYER(EINSUM) + ADD_LAYER(ASSERTION) +#endif +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + ADD_LAYER(ONE_HOT) + ADD_LAYER(NON_ZERO) + ADD_LAYER(NMS) +#endif +#if IS_TRT_VERSION_GE(8, 6, 0, 0) + ADD_LAYER(REVERSE_SEQUENCE) +#endif +#if !IS_TRT_VERSION_GE(8, 0, 0, 0) + // The TRT IRNNv2Layer has been deprecated in favor of the loop API. + ADD_LAYER(RNN) +#endif + default: + return "UNKNOWN_LAYER"; + } +} + +#undef ADD_LAYER + +// Sets the ILayer name in the form of +// /:. +void SetLayerNameHelper(nvinfer1::ILayer* layer, absl::string_view engine_name, + absl::string_view tf_name) { + const char* trt_name = LayerTypeToString(layer->getType()); + layer->setName( + absl::StrCat(engine_name, "/", tf_name, ":", trt_name).c_str()); +} + +// Returns a string in the form of . +std::string GetLayerNameSuffix(absl::string_view sub_op_name, + std::optional sub_op_instance) { + std::string op_suffix(sub_op_name); + if (sub_op_instance.has_value()) { + op_suffix = + absl::StrCat(op_suffix, "_", std::to_string(sub_op_instance.value())); + } + return op_suffix; +} + +} // namespace + +bool IsEngineInput(absl::string_view name) { + return absl::StartsWith(name, IONamePrefixes::kInputPHName); +} +bool IsEngineOutput(absl::string_view name) { + return absl::StartsWith(name, IONamePrefixes::kOutputPHName); +} + +void GetOutputProperties(const grappler::GraphProperties& graph_properties, + const Node* node, const int out_port, + PartialTensorShape* shape, DataType* dtype) { + if (graph_properties.HasOutputProperties(node->name())) { + auto output_params = graph_properties.GetOutputProperties(node->name()); + auto out_shape = output_params.at(out_port); + *dtype = out_shape.dtype(); + *shape = out_shape.shape(); + } else { + LOG(INFO) << "Unknown output shape at node: " << node->name(); + *dtype = node->output_type(out_port); + } +} + +void GetInputProperties(const grappler::GraphProperties& graph_properties, + const Node* node, const int in_port, + PartialTensorShape* shape, DataType* dtype) { + if (graph_properties.HasInputProperties(node->name())) { + auto input_params = graph_properties.GetInputProperties(node->name()); + auto in_shape = input_params.at(in_port); + *dtype = in_shape.dtype(); + *shape = in_shape.shape(); + } else { + *dtype = node->input_type(in_port); + } +} + +// This function checks if a tensor is compatible with TRT. +// +// We check that the shape and datatype are compatible with TensorRT. We also +// return the corresponding trt_dtype, the trt_dims and the batch_size (latter +// is only needed in implicit batch mode). +// +// The return status indicates whether the tensor is compatible. +// +// For implicit batch mode, when validation_only == false, we also check that +// all input dimensions (besides the batch dimension) are known dimensions. +Status ValidateTensorProperties(const string& producer_node_type, + const DataType dtype, + const PartialTensorShape& shape, + const bool use_implicit_batch, + bool validation_only, + nvinfer1::DataType* trt_dtype, + nvinfer1::Dims* trt_dims, int* batch_size) { + // Convert data type. + TF_RETURN_IF_ERROR(TfTypeToTrtType(dtype, trt_dtype)); + + // Convert shape. + if (shape.dims() < 0) { + return errors::InvalidArgument("Input tensor rank is unknown."); + } + // Add 1 to maximum rank for implicit batch dim. + const int max_rank = nvinfer1::Dims::MAX_DIMS + (use_implicit_batch ? 1 : 0); + if (shape.dims() > max_rank) { + return errors::OutOfRange("Input tensor rank is greater than ", max_rank); + } + if (use_implicit_batch && (producer_node_type != "Const") && + (shape.dims() < 1)) { + return errors::InvalidArgument( + "Scalar input tensor is not supported since the first dimension " + "is treated as batch dimension by TRT"); + } + StatusOr dims = DimsAdapter::Create(shape, use_implicit_batch); + TRT_ENSURE_OK(dims); + *trt_dims = dims->AsTrtDims(); + // Get batch size for tensor if it will not be included the shape. + if (use_implicit_batch) { + *batch_size = shape.dim_size(0); + } + + // Don't convert empty tensors (dim value of 0). + const int first_trt_dim = use_implicit_batch ? 1 : 0; + for (int d = first_trt_dim; d < shape.dims(); ++d) { + if (shape.dim_size(d) == 0) { + return errors::Unimplemented( + "Input tensor with shape ", shape.DebugString(), + " is an empty tensor, which is not supported by TRT"); + } + } + + if (validation_only) return OkStatus(); + + // Following checks are only used during TRT engine creation time. + if (use_implicit_batch) { + for (int d = first_trt_dim; d < shape.dims(); ++d) { + if (shape.dim_size(d) < 0) { + return errors::InvalidArgument( + "Input tensor with shape ", shape.DebugString(), + " has an unknown non-batch dimension at dim ", d); + } + } + } + return OkStatus(); +} + +Status GetTrtBroadcastShape(const TRT_TensorOrWeights& operand_l, + const TRT_TensorOrWeights& operand_r, + const bool check_feasibility, + const bool use_implicit_batch, + nvinfer1::Dims* operand_l_new_dims, + nvinfer1::Dims* operand_r_new_dims) { + // TensorRT Elementwise op supports broadcast but requires both tensor to be + // of Identical rank + // + // We consider case of: + // 1. operand_l to be a Tensor & operand_r to be a Const; + // 2. operand_l to be a Tensor & operand_r to be a Tensor; + // note: const op const (constant folding) should fallback to TensorFlow + // + // broadcast scheme: + // T: 1 3 5 (tensor would not have batch dimension) + // W: 1 1 3 1 (weight would have all explicit dimensions) + // i. fill in explicit dimensions + // -> T: -1 1 3 5 (we put a -1 for batch dimension) + // -> W: 1 1 3 1 + // ii. compare broadcast feasibility + // + // We cannot support the following since TensorRT does not allow manipulation + // on batch dimension, we cannot generate output with proper shape + // T: 3 5 1 + // W: 1 1 1 1 3 5 1 + // -> T: 1 1 1 -1 3 5 1 + // -> W: 1 1 1 1 3 5 1 + // *************************************************************************** + if (!operand_l.is_tensor() && !operand_r.is_tensor()) { + // TODO(lsugy): remove this check in dynamic shapes mode. This should work + // if both inputs are weights. + return errors::InvalidArgument( + "Broadcasting requires at least one of the operands be tensors"); + } + + constexpr int max_nb_dims = nvinfer1::Dims::MAX_DIMS + 1; + auto compute_output_dims = + [use_implicit_batch](const TRT_TensorOrWeights& input, + int broadcast_num_dims, + std::array* output_dims_array, + nvinfer1::Dims* output_dims) -> Status { + const nvinfer1::Dims input_dims = input.GetTrtDims(); + absl::c_fill(*output_dims_array, 1); + absl::c_copy( + DimsAdapter(input_dims), + output_dims_array->begin() + broadcast_num_dims - input_dims.nbDims); + if (use_implicit_batch && input.is_tensor()) { + const int true_input_dims = input_dims.nbDims + 1; + if (true_input_dims < broadcast_num_dims) { + return errors::InvalidArgument( + "Broadcasting beyond batch dimension is not supported ", + "(tensor #dims ", true_input_dims, " vs broadcast #dims ", + broadcast_num_dims, ")"); + } + // Set the batch dimension to -1, since batch size is not supposed to + // be broadcasted. + (*output_dims_array)[0] = -1; + } + // Copy to output dimensions + auto offt = use_implicit_batch ? 1 : 0; + output_dims->nbDims = broadcast_num_dims - offt; + absl::c_copy( + absl::MakeSpan(*output_dims_array).subspan(offt, broadcast_num_dims), + output_dims->d); + return OkStatus(); + }; + + // Compute the output dimensions. + const int broadcast_num_dims = + std::max(operand_l.GetTrtDims().nbDims + + (use_implicit_batch && operand_l.is_tensor()), + operand_r.GetTrtDims().nbDims + + (use_implicit_batch && operand_r.is_tensor())); + std::array output_l, output_r; + TF_RETURN_IF_ERROR(compute_output_dims(operand_l, broadcast_num_dims, + &output_l, operand_l_new_dims)); + TF_RETURN_IF_ERROR(compute_output_dims(operand_r, broadcast_num_dims, + &output_r, operand_r_new_dims)); + + // Compare broadcast feasibility + if (check_feasibility) { + for (int i = 0; i < broadcast_num_dims; ++i) { + if (!use_implicit_batch && (output_l[i] == -1 || output_r[i] == -1)) { + // If the condition is true then we are in explicit batch mode and (at + // least) one of the input dimensions are unknown. In other words we + // are in dynamic shape mode. During conversion time we only see -1 for + // the unknown shapes, therefore we cannot decide on the feasibility of + // broadcast over the unknown dimensions. Therefore we just continue for + // the next dimension. In dynamic shape mode TRT can only check the + // feasibility of the broadcast when the actual input dimensions are + // specified by SetTrtEngineInputs and the inference job is launched by + // TrtEnque. + continue; + } + if ((output_l[i] != output_r[i]) && (output_l[i] != 1) && + (output_r[i] != 1)) { + return errors::InvalidArgument("Infeasible broadcast scheme (", + "batch_dim: ", output_l[0], ", ", + DebugString(*operand_l_new_dims), " vs ", + "batch_dim: ", output_r[0], ", ", + DebugString(*operand_r_new_dims), ")"); + } + } + } + return OkStatus(); +} + +// Prepares a dynamic shape tensor for broadcast by adding leading 1 dimensions. +Status DynamicBroadcast(ITensorProxyPtr operand, + const OpConverterParams* params, + ITensorProxyPtr* output, int broadcasted_nbDims, + std::optional op_instance) { + int operand_nbDims = operand->getDimensions().nbDims; + if (broadcasted_nbDims > operand_nbDims) { + if (params->validation_only) return OkStatus(); + int n_extra_dims = broadcasted_nbDims - operand_nbDims; + VLOG(2) << "Dynamic broadcast adding " << n_extra_dims << " leading 1s"; + TF_RETURN_IF_ERROR(params->converter->DynamicReshape( + /*input=*/operand, + /*slices=*/{std::make_pair(0, operand_nbDims)}, + /*params=*/params, + /*output=*/output, + /*size_for_added_dims*/ {n_extra_dims}, + /*op_instance=*/op_instance)); + } else { + *output = operand; + } + return OkStatus(); +} + +Status BroadcastWeights(std::unique_ptr& p, + const DimsAdapter& broadcasted_dims) { + if (!p->is_weights()) return errors::Internal("Weight input expected"); + if (p->GetTrtDims().nbDims != broadcasted_dims.NumDims()) { + TRT_ShapedWeights weights(p->weights()); + TF_RETURN_IF_ERROR(weights.SetShape(broadcasted_dims)); + p = std::make_unique(weights); + } + return OkStatus(); +} + +Status ApplyBroadcast(std::unique_ptr& operand, + const DimsAdapter& broadcasted_dims, + const OpConverterParams* params, + std::optional op_instance) { + if (operand->is_weights()) { + TF_RETURN_IF_ERROR(BroadcastWeights(operand, broadcasted_dims)); + } else { + ITensorProxyPtr tensor = nullptr; + auto is_static_shuffle_compatible = [](const auto& dims) { + return absl::c_count(dims, -1) <= 1; + }; + if (is_static_shuffle_compatible(broadcasted_dims)) { + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, *operand, broadcasted_dims, + params->validation_only, &tensor, params->node_def)); + } else { + TF_RETURN_IF_ERROR(DynamicBroadcast( + /*operand=*/operand->tensor(), + /*params=*/params, + /*output=*/&tensor, + /*broadcasted_nbDims*/ broadcasted_dims.NumDims(), + /*op_instance=*/op_instance)); + } + operand = std::make_unique(tensor); + } + return OkStatus(); +} + +// Inserts leading 1 dimensions so that both operands have the same rank. +// Note: In implicit batch mode, weights' shape can include an explicit 1 batch +// dimension. The broadcasted shape might loose this leading batch dim, because +// the broadcasted shape does not include the implicit batch dim. +// TODO(tfeher): Other code blocks that use GetTrtBroadcastShape need to be +// fixed to use this routine to handle dynamic inputs. Eventually, +// GetTrtBroadcastShape should only be used by this routine. +Status BroadcastTensors(std::unique_ptr& operand_l, + std::unique_ptr& operand_r, + bool check_feasibility, + const OpConverterParams* params) { + nvinfer1::Dims broadcasted_dims_l, broadcasted_dims_r; + TF_RETURN_IF_ERROR(GetTrtBroadcastShape( + *operand_l, *operand_r, check_feasibility, params->use_implicit_batch, + &broadcasted_dims_l, &broadcasted_dims_r)); + + if (params->validation_only) return OkStatus(); + + TF_RETURN_IF_ERROR(ApplyBroadcast( + /*operand=*/operand_l, + /*broadcasted_dims=*/broadcasted_dims_l, + /*params=*/params, + /*op_instance=*/0)); + + TF_RETURN_IF_ERROR(ApplyBroadcast( + /*operand=*/operand_r, + /*broadcasted_dims=*/broadcasted_dims_r, + /*params=*/params, + /*op_instance=*/1)); + + return OkStatus(); +} + +ITensorProxyPtr Converter::CreateConstantLayer(const TRT_ShapedWeights& weights, + const nvinfer1::Dims& dims) { + nvinfer1::Weights trt_weights = weights.GetTrtWeights(); + nvinfer1::IConstantLayer* layer = network()->addConstant(dims, trt_weights); + if (!layer) return nullptr; + SetLayerName(layer, "_tftrt_constant_", + std::to_string(next_constant_layer_id_)); + next_constant_layer_id_++; + ITensorProxyPtr trt_tensor = layer->getOutput(0); + return trt_tensor; +} + +// Creates a scalar constant and fills with value. +template +Status CreateScalarConstant( + const OpConverterParams* params, T value, ITensorProxyPtr* tensor, + nvinfer1::DataType trt_type = nvinfer1::DataType::kINT32, + const nvinfer1::Dims& dims = {1, {1}}) { + StatusOr weights = + params->weight_store->GetTempWeights(trt_type, dims); + TRT_ENSURE_OK(weights); + TF_RETURN_IF_ERROR(weights->SetValues(value)); + *tensor = params->converter->CreateConstantLayer(*weights, dims); + TFTRT_RETURN_ERROR_IF_NULLPTR(*tensor, params->node_def.name()); + return OkStatus(); +} + +// Creates a constant with the same rank as dims, where each dimension has +// size = 1. +Status CreateBroadcastableScalarConstant(const OpConverterParams* params, + float value, + const nvinfer1::Dims& dims, + ITensorProxyPtr* tensor, + const char* dtype_attr_name = "T") { + nvinfer1::DataType trt_type = nvinfer1::DataType::kFLOAT; // Default to FP32. + AttrSlice attrs(params->node_def); + if (attrs.FindByString(dtype_attr_name) != nullptr) { + DataType dtype; + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, dtype_attr_name, &dtype)); + TF_RETURN_IF_ERROR(TfTypeToTrtType(dtype, &trt_type)); + } + + // In order to be broadcastable, the number of dims has to match. + nvinfer1::Dims broadcastable_dims(dims); + for (int i = 0; i < broadcastable_dims.nbDims; i++) { + broadcastable_dims.d[i] = 1; + } + return CreateScalarConstant(params, value, tensor, trt_type, + broadcastable_dims); +} + +// The function concatenates tensors on the first axis. This can be used to +// create a shape tensor from individual dimension sizes. +StatusOr ConcatenateTensors( + const OpConverterParams* params, + const std::vector input_tensors, + std::optional op_instance = std::nullopt) { + std::vector trt_input_tensors; + for (const auto& t : input_tensors) { + trt_input_tensors.push_back(t->trt_tensor()); + } + nvinfer1::IConcatenationLayer* layer = + params->converter->network()->addConcatenation( + static_cast(trt_input_tensors.data()), + input_tensors.size()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, params->node_def.op()); + params->converter->SetLayerName(layer, params->node_def.name(), + "concat_shapes", op_instance); + layer->setAxis(0); + return ITensorProxyPtr(layer->getOutput(0)); +} + +// Convert an axis from TF format to TRT format while validating. TF format +// includes the batch dimension, while TRT does not if implicit batching is used +// (i.e. for tensors). TF can also use negative indices. +Status ConvertAxis(int tf_axis, int trt_nb_dims, absl::string_view node_name, + bool use_implicit_batch, int* trt_axis) { + const int tf_nb_dims = trt_nb_dims + (use_implicit_batch ? 1 : 0); + // Check bounds. + if (tf_axis < -tf_nb_dims || tf_axis >= tf_nb_dims) { + return errors::InvalidArgument( + "Axis value of ", tf_axis, " is out of bounds, must be in range [", + -tf_nb_dims, ", ", tf_nb_dims, "), at ", node_name); + } + // Make negative axis positive. + if (tf_axis < 0) tf_axis += tf_nb_dims; + // Don't allow axis to be the batch dimension. + if (use_implicit_batch && tf_axis == 0) { + return errors::Unimplemented( + "TensorRT does not allow manipulation of the batch dimension"); + } + // Remove batch dimension if it is implicit. + *trt_axis = use_implicit_batch ? tf_axis - 1 : tf_axis; + return OkStatus(); +} + +bool AllLengthsEqual(const std::vector>& inputs) { + if (inputs.size() == 0) return true; + int length = inputs.at(0).size(); + for (int i = 1; i < inputs.size(); i++) { + if (inputs.at(i).size() != length) return false; + } + return true; +} + +bool DimsHaveSameSize(const DimsAdapter& lhs, const DimsAdapter& rhs) { + return lhs.Volume() == rhs.Volume(); +} + +// Returns whether both dimensions are fully specified and the total number of +// elements equals. +bool AreDimsStaticWithSameSize(const DimsAdapter& lhs, const DimsAdapter& rhs) { + if (!lhs.IsStatic() || !rhs.IsStatic()) return false; + return DimsHaveSameSize(lhs, rhs); +} + +bool AreDimsStaticWithDifferentSize(const DimsAdapter& lhs, + const DimsAdapter& rhs) { + if (!lhs.IsStatic() || !rhs.IsStatic()) return false; + return !DimsHaveSameSize(lhs, rhs); +} + +static std::vector> CreateSamePadding( + const nvinfer1::Dims& stride, const nvinfer1::Dims& kernel, + const std::vector& input_dims) { + std::vector> padding(input_dims.size()); + CHECK_EQ(stride.nbDims, input_dims.size()); // TODO(jie): N+C? NC+? + + for (size_t i = 0; i < input_dims.size(); ++i) { + // Formula to calculate the padding + int p = ((input_dims[i] - 1) / stride.d[i]) * stride.d[i] + kernel.d[i] - + input_dims[i]; + p = (p > 0) ? p : 0; + + // Right precedence padding, like in TensorFlow + int left = p / 2; + int right = p - left; + + VLOG(2) << "PADDING_" << i << " pre: " << left << ", post: " << right + << "paras: " << input_dims[i] << ", " << stride.d[i] << ", " + << "kernel: " << kernel.d[i]; + padding[i] = {left, right}; + } + return padding; +} + +string GetCommonNameScope(const string& op_name_a, const string& op_name_b) { + size_t last_scope_separator = 0; + const size_t min_size = std::min(op_name_a.size(), op_name_b.size()); + for (size_t i = 0; i < min_size; ++i) { + if (op_name_a[i] != op_name_b[i]) break; + if (op_name_a[i] == '/') last_scope_separator = i + 1; + } + return op_name_a.substr(0, last_scope_separator); +} + +// Verifies that shapes of the given inputs match after masking the specified +// dimension. +Status VerifyShapesMatch(absl::Span inputs, + int masked_dim, absl::string_view node_name) { + size_t num_inputs = inputs.size(); + if (num_inputs <= 1) return OkStatus(); + + const nvinfer1::Dims dims_0 = inputs.at(0).GetTrtDims(); + for (size_t i = 1; i < num_inputs; ++i) { + const nvinfer1::Dims dim_i = inputs.at(i).GetTrtDims(); + if (dim_i.nbDims != dims_0.nbDims) { + return errors::InvalidArgument( + "Received inputs with inconsistent rank, at ", node_name); + } + for (size_t j = 0; j < dims_0.nbDims; ++j) { + // Dynamic dimensions will be verified at runtime. + if (dim_i.d[j] == -1 || dims_0.d[j] == -1) continue; + if (dim_i.d[j] != dims_0.d[j] && j != masked_dim) { + return errors::InvalidArgument( + "Received inputs with inconsistent shape, at ", node_name); + } + } + } + return OkStatus(); +} + +// Perform 5 dimensional reorder of data on CPU +// This is done once at convert time and does not affect GPU inference perf +// Example: reorder NDHWC (Tensorflow) -> NCDHW (TensorRT) +template +void Reorder5(const nvinfer1::Dims& shape, const T* idata, + const nvinfer1::Dims& istrides, T* odata, + const nvinfer1::Dims& ostrides) { + for (int k = 0; k < shape.d[0]; ++k) { + for (int c = 0; c < shape.d[1]; ++c) { + for (int d = 0; d < shape.d[2]; ++d) { + for (int r = 0; r < shape.d[3]; ++r) { + for (int s = 0; s < shape.d[4]; ++s) { + odata[k * ostrides.d[0] + c * ostrides.d[1] + d * ostrides.d[2] + + r * ostrides.d[3] + s * ostrides.d[4]] = + idata[k * istrides.d[0] + c * istrides.d[1] + + d * istrides.d[2] + r * istrides.d[3] + + s * istrides.d[4]]; + } + } + } + } + } +} + +// TODO(jie): reorder4 & reorder2 should be merged? +// TODO(aaroey): fix the order of parameters. +template +void Reorder4(const nvinfer1::Dims4& shape, const T* idata, + const nvinfer1::Dims4& istrides, T* odata, + const nvinfer1::Dims4& ostrides) { + for (int n = 0; n < shape.d[0]; ++n) { + for (int c = 0; c < shape.d[1]; ++c) { + for (int h = 0; h < shape.d[2]; ++h) { + for (int w = 0; w < shape.d[3]; ++w) { + odata[n * ostrides.d[0] + c * ostrides.d[1] + h * ostrides.d[2] + + w * ostrides.d[3]] = + idata[n * istrides.d[0] + c * istrides.d[1] + h * istrides.d[2] + + w * istrides.d[3]]; + } + } + } + } +} + +template +void Reorder2(const nvinfer1::DimsHW& shape, const T* idata, + const nvinfer1::DimsHW& istrides, T* odata, + const nvinfer1::DimsHW& ostrides) { + for (int h = 0; h < shape.h(); ++h) { + for (int w = 0; w < shape.w(); ++w) { + odata[h * ostrides.h() + w * ostrides.w()] = + idata[h * istrides.h() + w * istrides.w()]; + } + } +} + +// TODO(jie): fallback to tensorflow!! +void ReorderCKtoKC(const TRT_ShapedWeights& iweights, + TRT_ShapedWeights* oweights) { + const int c = iweights.Shape().dim(0); + const int k = iweights.Shape().dim(1); + oweights->Shape().dim(0) = k; + oweights->Shape().dim(1) = c; + const nvinfer1::DimsHW istrides = {1, k}; + const nvinfer1::DimsHW ostrides = {c, 1}; + switch (iweights.TrtDType()) { + case nvinfer1::DataType::kFLOAT: { + Reorder2({k, c}, iweights.GetPointer(), istrides, + oweights->GetPointer(), ostrides); + break; + } + case nvinfer1::DataType::kHALF: { + Reorder2({k, c}, iweights.GetPointer(), istrides, + oweights->GetPointer(), ostrides); + break; + } + default: + LOG(FATAL) << "Unsupported type in reorder expected fp32 or fp16 but got " + << DebugString(iweights.TrtDType()); + } +} + +void ReorderRSCKToKCRS(const TRT_ShapedWeights& iweights, + TRT_ShapedWeights* oweights, const int num_groups) { + CHECK(iweights.TrtDType() == oweights->TrtDType()); + CHECK_EQ(iweights.size_bytes(), oweights->size_bytes()); + // K indexes over output channels, C over input channels, and R and S over the + // height and width of the convolution + const int r = iweights.Shape().dim(0); + const int s = iweights.Shape().dim(1); + // TRT requires GKcRS, while TF depthwise has RSCK where c=1, C=G + const int c = iweights.Shape().dim(2) / num_groups; + const int k = iweights.Shape().dim(3) * num_groups; + VLOG(2) << "num_groups: " << num_groups << "c" << iweights.Shape().dim(2) + << " then " << c << "k" << iweights.Shape().dim(3) << " then " << k + << "r" << iweights.Shape().dim(0) << " then " << r << "s" + << iweights.Shape().dim(1) << " then " << s; + oweights->Shape().dim(0) = k / num_groups; + oweights->Shape().dim(1) = c * num_groups; + oweights->Shape().dim(2) = r; + oweights->Shape().dim(3) = s; + const nvinfer1::Dims4 istrides = {1, k, s * k * c, c * k}; + const nvinfer1::Dims4 ostrides = {c * r * s, r * s, s, 1}; + switch (iweights.TrtDType()) { + case nvinfer1::DataType::kFLOAT: { + Reorder4({k, c, r, s}, iweights.GetPointer(), istrides, + oweights->GetPointer(), ostrides); + break; + } + case nvinfer1::DataType::kHALF: { + Reorder4({k, c, r, s}, iweights.GetPointer(), istrides, + oweights->GetPointer(), ostrides); + break; + } + + default: + LOG(FATAL) << "Unsupported type, expected fp32 or fp16 but got " + << DebugString(iweights.TrtDType()); + } +} + +// Initialize a Dims object with arbitrary dimension +nvinfer1::Dims InitDimsN(std::initializer_list list) { + nvinfer1::Dims dim; + dim.nbDims = list.size(); + std::copy(list.begin(), list.end(), dim.d); + return dim; +} + +// Reorder 3D convolution weights from TF to TRT +void ReorderDRSCKToKCDRS(const TRT_ShapedWeights& iweights, + TRT_ShapedWeights* oweights, const int num_groups) { + DCHECK(iweights.TrtDType() == oweights->TrtDType()); + CHECK_EQ(iweights.size_bytes(), oweights->size_bytes()); + // K indexes over output channels, C over input channels, and R, S, D over the + // height, width, depth + const int d = iweights.Shape().dim(0); + const int r = iweights.Shape().dim(1); + const int s = iweights.Shape().dim(2); + // TRT requires GKcRS, while TF depthwise has RSCK where c=1, C=G + const int c = iweights.Shape().dim(3) / num_groups; + const int k = iweights.Shape().dim(4) * num_groups; + + VLOG(2) << "num_groups: " << num_groups << ", c: " << iweights.Shape().dim(3) + << " becomes " << c << ", k: " << iweights.Shape().dim(4) + << " becomes " << k << ", d: " << d << ", r: " << r << ", s: " << s; + + oweights->Shape().dim(0) = iweights.Shape().dim(4); // k / num_groups; + oweights->Shape().dim(1) = iweights.Shape().dim(3); // c * num_groups; + oweights->Shape().dim(2) = d; + oweights->Shape().dim(3) = r; + oweights->Shape().dim(4) = s; + + nvinfer1::Dims shape = + InitDimsN({k, c, d, r, s}); // KCDRS shape (same as output) + + nvinfer1::Dims ostrides = + InitDimsN({c * d * r * s, d * r * s, r * s, s, + 1}); // Output = KCDRS = k*CDRS + c*DRS + d*RS + r*S + s + + nvinfer1::Dims istrides = + InitDimsN({1, k, r * s * c * k, s * c * k, + c * k}); // Input = DRSCK = k*1 + c*K + d*RSCK + r*SCK + s*CK + + switch (iweights.TrtDType()) { + case nvinfer1::DataType::kFLOAT: { + Reorder5(shape, iweights.GetPointer(), istrides, + oweights->GetPointer(), ostrides); + break; + } + case nvinfer1::DataType::kHALF: { + Reorder5(shape, iweights.GetPointer(), istrides, + oweights->GetPointer(), ostrides); + break; + } + default: + LOG(FATAL) << "Unsupported type, expected fp32 or fp16 but got " + << DebugString(iweights.TrtDType()); + } +} + +OpConverterParams::OpConverterParams( + const NodeDef& node_def, const std::vector& inputs, + std::vector* outputs, TrtWeightStore* weight_store, + TrtPrecisionMode precision_mode, bool use_calibration, + bool use_implicit_batch, bool use_explicit_precision) + : node_def(node_def), + inputs(inputs), + outputs(outputs), + validation_only(true), + weight_store(weight_store), + precision_mode(precision_mode), + use_calibration(use_calibration), + use_implicit_batch(use_implicit_batch), + use_explicit_precision(use_explicit_precision) {} + +OpConverterParams::OpConverterParams( + Converter* converter, const NodeDef& node_def, + const std::vector& inputs, + std::vector* outputs, TrtWeightStore* weight_store) + : converter(converter), + node_def(node_def), + inputs(inputs), + outputs(outputs), + validation_only(false), + weight_store(weight_store), + precision_mode(converter->precision_mode()), + use_calibration(converter->use_calibration()), + use_implicit_batch(converter->use_implicit_batch()), + use_explicit_precision(converter->UseExplicitPrecision()) {} + +TrtNodeValidator::TrtNodeValidator( + const grappler::GraphProperties& graph_properties, + TrtPrecisionMode precision_mode, bool use_calibration, + bool use_implicit_batch, bool use_explicit_precision) + : graph_properties_(graph_properties), + precision_mode_(precision_mode), + use_calibration_(use_calibration), + use_implicit_batch_(use_implicit_batch), + use_explicit_precision_(use_explicit_precision) {} + +StatusOr TrtNodeValidator::GetValidator(const std::string& op) { + return GetOpConverterRegistry()->LookUp(op); +} + +Status TrtNodeValidator::ConvertToTensorOrWeights( + const NodeDef& node_def, int output_port, + TRT_TensorOrWeights* tensor_or_weights) { + // Treat handles separately. + if (node_def.op() == "VarHandleOp" || node_def.op() == "Placeholder") { + AttrSlice attrs(node_def); + DataType dtype; + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "dtype", &dtype)); + if (dtype == DataType::DT_RESOURCE) { + // The converter doesn't use the input resource at the validation stage + // (it gets the dtype and shape from attributes). A fake resource can be + // used. + ResourceHandle fake_resource; + *tensor_or_weights = TRT_TensorOrWeights(fake_resource); + return OkStatus(); + } + } + + if (node_def.op() == "Const" || node_def.op() == "VariableV2") { + // The output of the conversion will be used as input to other nodes to + // determine whether TRT supports those nodes. If it cannot convert the + // Const, it's very likely we cannot treat it as a tensor and make it an + // input to the TRT network, since TRT removes the first dimension and + // treats it as batch size. Also, it's not likely that the converter can + // support the op, and performance may suffer even if it can, so we just + // simply return error if the conversion fails. + if (output_port != 0) { + return errors::InvalidArgument(node_def.op(), + " node should only have one output."); + } + std::vector inputs; + return ConvertConstToWeights(node_def, inputs, tensor_or_weights); + } + if (node_def.op() == "ReadVariableOp") { + // Similar treatment to Const and VariableV2, but we provide a fake + // resource input to the converter. + const std::vector inputs{ + TRT_TensorOrWeights(ResourceHandle())}; + + // Convert the variable to weights. + return ConvertConstToWeights(node_def, inputs, tensor_or_weights); + } + if (!graph_properties_.HasOutputProperties(node_def.name())) { + return errors::InvalidArgument("Shape and data type are unknown"); + } + + // Validate and convert shape and dtype. + const auto& output_params = + graph_properties_.GetOutputProperties(node_def.name()); + const auto& tensor_properties = output_params.at(output_port); + const DataType dtype = tensor_properties.dtype(); + const PartialTensorShape shape = tensor_properties.shape(); + nvinfer1::DataType trt_dtype; + nvinfer1::Dims trt_dims; + int batch_size = -1; + TF_RETURN_IF_ERROR(ValidateTensorProperties( + node_def.op(), dtype, shape, use_implicit_batch_, + /*validation_only_=*/true, &trt_dtype, &trt_dims, &batch_size)); + + // Adds a fake ITensor. This is fine since op converter operates in + // validation-only mode and it won't (and shouldn't) use the tensor to do + // any TRT network operations. + *tensor_or_weights = TRT_TensorOrWeights(trt_dtype, trt_dims, batch_size); + return OkStatus(); +} + +Status TrtNodeValidator::IsTensorRTCandidate(const Node* node) { + const string& op = node->def().op(); + // In INT8 mode, we will always apply the quantization ranges provided by + // these ops to the relevant tensors. This happens regardless of the value of + // use_calibration. + bool is_supported_op = false; + if (absl::c_find(kQuantizationOpNames, op) != kQuantizationOpNames.end()) { + is_supported_op = (precision_mode_ == TrtPrecisionMode::INT8); + } else { + is_supported_op = GetValidator(op).ok(); + } + + if (!is_supported_op) { + return errors::Unimplemented("Op type ", op, " is not supported."); + } + + // Convert input NodeDef and corresponding output ports to + // TRT_TensorOrWeights. + std::vector inputs; + std::vector input_edges; + TF_RETURN_IF_ERROR(node->input_edges(&input_edges)); + for (const Edge* edge : input_edges) { + // Go up the chain of Identity nodes. + Node* src_node = edge->src(); + while (src_node->def().op() == "Identity") { + std::vector input_edges_temp; + TF_RETURN_IF_ERROR(src_node->input_edges(&input_edges_temp)); + src_node = input_edges_temp[0]->src(); + } + const NodeDef& src_def = src_node->def(); + + TRT_TensorOrWeights tensor_or_weights; + Status status = ConvertToTensorOrWeights(src_def, edge->src_output(), + &tensor_or_weights); + if (!status.ok()) { + VLOG(2) << "Failed to convert input `" << src_def.name() << "` to a " + << "TRT_TensorOrWeights: " << status.message(); + + return errors::Internal( + "Failed to convert at least one input to a TRT_TensorOrWeights: ", + status.message()); + } + inputs.push_back(tensor_or_weights); + } + + auto validator = GetValidator(op); + TF_RETURN_IF_ERROR(validator.status()); + OpConverterParams params(node->def(), inputs, /*arg_outputs=*/nullptr, + &weight_store_, precision_mode_, use_calibration_, + use_implicit_batch_, use_explicit_precision_); + return (*validator)(¶ms); +} + +Status TrtNodeValidator::ConvertConstToWeights( + const NodeDef& const_node_def, + const std::vector& inputs, + TRT_TensorOrWeights* output) { + std::vector outputs; + OpConverterParams params(const_node_def, inputs, &outputs, &weight_store_, + precision_mode_, use_calibration_, + use_implicit_batch_, use_explicit_precision_); + auto const_val = GetValidator(const_node_def.op()); + TF_RETURN_IF_ERROR(const_val.status()); + Status status = (*const_val)(¶ms); + if (status.ok() && (output != nullptr)) { + *output = outputs[0]; + } + return status; +} + +// static +StatusOr> Converter::Create( + TrtPrecisionMode precision_mode, bool use_calibration, + nvinfer1::ILogger* trt_logger, const bool use_implicit_batch, + absl::string_view engine_name, bool use_explicit_precision, + OpKernelContext* ctx) { + std::unique_ptr converter = absl::WrapUnique(new Converter( + precision_mode, use_calibration, trt_logger, use_implicit_batch, + engine_name, use_explicit_precision, ctx)); + TF_RETURN_IF_ERROR(converter->Init(trt_logger)); + return converter; +} + +Converter::Converter(TrtPrecisionMode precision_mode, bool use_calibration, + nvinfer1::ILogger* trt_logger, + const bool use_implicit_batch, + absl::string_view engine_name, bool use_explicit_precision, + OpKernelContext* ctx) + : ctx_(ctx), + precision_mode_(precision_mode), + use_calibration_(use_calibration), + use_implicit_batch_(use_implicit_batch), + engine_name_(engine_name), + use_explicit_precision_(use_explicit_precision) { + MaybeInitializeTrtPlugins(trt_logger); +} + +Status Converter::Init(nvinfer1::ILogger* trt_logger) { + VLOG(1) << "Creating TensorRT builder"; + trt_builder_.reset(nvinfer1::createInferBuilder(*trt_logger)); + + VLOG(1) << "Creating TensorRT network"; + uint32_t flags = + use_implicit_batch_ + ? 0U + : (1U << static_cast( + nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH)); + if (use_explicit_precision_) { + flags |= + (1U << static_cast( + nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_PRECISION)); + } + trt_network_.reset(trt_builder_->createNetworkV2(flags)); + if (!trt_network_) { + return errors::Internal("Failed to create TensorRT network object"); + } + return OkStatus(); +} + +Status Converter::ConvertNode(const NodeDef& node_def) { + std::vector inputs; + std::vector outputs; + TF_RETURN_IF_ERROR(this->GetInputs(node_def, &inputs)); + + OpConverterParams params(this, node_def, inputs, &outputs, &weight_store_); + const string& op = node_def.op(); + auto op_converter = GetOpConverterRegistry()->LookUp(op); + TF_RETURN_IF_ERROR(op_converter.status()); + TF_RETURN_IF_ERROR((*op_converter)(¶ms)); + + for (size_t i = 0; i < outputs.size(); ++i) { + TRT_TensorOrWeights& output = outputs[i]; + string output_name = node_def.name(); + if (i != 0) { + StrAppend(&output_name, ":", i); + } + // We need to check the name before setting it. If the input is one of the + // engine input, setting the name here will overwrite engine input + // bindings which will cause runtime error. + // TODO(tmorris): Remove this work-around once we use TRT's IIdentityLayer + // in ConvertIdentity. + if (output.is_tensor()) { + const char* tensor_name = output.tensor()->getName(); + if (!IsEngineInput(tensor_name)) { + // TRT initializes tensor names as "(Unnamed ITensor* N)". We rename + // them to match their corresponding TensorFlow name. + // Note: ITensors that we create internally within TF-TRT which are + // not inputs or outputs of a node will not be renamed. This is a + // potential cause of confusion if an error message or warning + // mentions the unnamed tensor. + output.tensor()->setName(output_name.c_str()); + } + } + VLOG(2) << "Adding out tensor " << output_name << ": " + << output.DebugString(); + Status status = AddTensorOrWeights(output_name, output); + if (!status.ok()) { + return errors::Create(static_cast(status.code()), + StrCat("Failed to add output for node: ", + node_def.name(), ": ", status.message()), + errors::GetPayloads(status)); + } + } + return OkStatus(); +} + +Status Converter::AddInputTensor(const string& name, nvinfer1::DataType dtype, + const nvinfer1::Dims& dims, int batch_size) { + // We verify the batch size only for the input nodes, and rely on individual + // op converter to ensure the batch size of the outputs is not changed. + // TODO(laigd): we need to test this properties. + Status status; + if (use_implicit_batch_) { + status = MaybeUpdateBatchSize(batch_size); + if (!status.ok()) { + return errors::CreateWithUpdatedMessage( + status, batch_size_error(name, status.message())); + } + } + ITensorProxyPtr tensor = network()->addInput(name.c_str(), dtype, dims); + if (*tensor == nullptr) { + return errors::InvalidArgument("Failed to create Input layer tensor ", name, + " rank=", dims.nbDims); + } + status = AddTensorOrWeights(name, TRT_TensorOrWeights(tensor)); + if (!status.ok()) { + return errors::CreateWithUpdatedMessage( + status, + StrCat("Failed to add input tensor ", name, ": ", status.message())); + } + return OkStatus(); +} + +Status Converter::AddInputResource(const string& name, + const ResourceHandle& resource) { + Status status = AddTensorOrWeights(name, TRT_TensorOrWeights(resource)); + if (!status.ok()) { + return errors::CreateWithUpdatedMessage( + status, + StrCat("Failed to add input resource ", name, ": ", status.message())); + } + return OkStatus(); +} + +Status Converter::RenameAndMarkOutputTensors( + const std::vector& output_tensors) { + int output_index = 0; + for (const auto& output : output_tensors) { + TRT_TensorOrWeights tensor_or_weights; + TF_RETURN_IF_ERROR( + GetTensorOrWeights(output.source_tensor_name, &tensor_or_weights)); + if (!tensor_or_weights.is_tensor()) { + return errors::InvalidArgument("Output ", output.source_tensor_name, + " is weights not tensor"); + } + ITensorProxyPtr tensor = tensor_or_weights.tensor(); + if (*tensor == nullptr) { + return errors::NotFound("Output tensor not found: ", + output.source_tensor_name); + } + // Check if this tensor has already been marked as an input or output. + // + // ConvertIdentity can cause the same tensor to be repeated in + // output_tensors, which can cause us to overwrite the name of the output + // tensor binding. For example, if we rename OutputPH_0 to OutputPH_1 then + // we won't be able to locate OutputPH_0 during runtime. To fix this, + // duplicate the tensor using no-op shuffle. + // + // TODO(tmorris): Remove this work-around once we use TRT's IIdentityLayer + // in ConvertIdentity. + if (IsEngineInput(tensor->getName()) || IsEngineOutput(tensor->getName())) { + // Using shuffle layer for identity by not setting reshape or transpose. + nvinfer1::IShuffleLayer* layer = + network()->addShuffle(*tensor->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR( + layer, StrCat("Output Copy for ", tensor->getName())); + SetLayerName(layer, tensor->getName(), "shuffle", output_index); + tensor = layer->getOutput(0); + } + tensor->setName(output.dest_node_name.c_str()); + network()->markOutput(*tensor->trt_tensor()); + // Set type after marking as output. TRT only supports setType for engine + // outputs and inputs (type is inferred otherwise). + tensor->setType(output.trt_dtype); + output_index++; + VLOG(1) << "Marking output TRT tensor " << output.source_tensor_name + << " with data type " << DebugString(output.trt_dtype) + << ", which feeds TF node " << output.dest_node_name; + } + if (VLOG_IS_ON(2)) { + VLOG(2) << "Created TensorRT network with the following layers:"; + for (int i = 0; i < network()->getNbLayers(); i++) { + auto layer = network()->getLayer(i); + VLOG(2) << " " << layer->getName() << " (" + << "type: " << static_cast(layer->getType()) + << ", precision: " << static_cast(layer->getPrecision()) + << ")"; + } + } + return OkStatus(); +} + +// Returns the value of TF_TRT_ABORT_CUDA_ENGINE_BUILD environment variable. +// This variable can be used to abort CUDA engine construction, therefore it +// provides a way to test and debug the native segment fallback of TF-TRT. +bool AbortCudaEngineBuild() { + bool value; + Status status = ReadBoolFromEnvVar("TF_TRT_ABORT_CUDA_ENGINE_BUILD", + /*default_value=*/false, &value); + if (!status.ok()) { + LOG(ERROR) << status; + } + return value; +} + +Status Converter::BuildCudaEngine( + TrtUniquePtrType* engine, int max_batch_size, + size_t max_workspace_size_bytes, nvinfer1::IGpuAllocator* allocator, + TRTInt8Calibrator* calibrator, TrtShapeOptimizationProfile* profiles) { + tensorflow::profiler::AnnotatedTraceMe activity( + [&]() { + return tensorflow::profiler::TraceMeOpOverride("TRTEngineOp", + "BuildEngine"); + }, + tensorflow::profiler::TraceMeLevel::kInfo); + + if (AbortCudaEngineBuild()) { + return errors::Aborted( + "Engine creation aborted by TF_TRT_ABORT_CUDA_ENGINE_BUILD variable"); + } + + VLOG(1) << "Configuring TensorRT builder"; + trt_builder_->setMaxBatchSize(max_batch_size); + trt_builder_->setGpuAllocator(allocator); + + // Create a network configuration and use it to build a TRT engine. + TrtUniquePtrType builder_config( + trt_builder_->createBuilderConfig()); + builder_config->setMaxWorkspaceSize(max_workspace_size_bytes); + + // Create the algorithm selector. For TensorRT 7.x, the algorithm selector + // cannot be used when building with INT8 calibration. + std::unique_ptr trt_algorithm_selector{nullptr}; + if (!IS_TRT_VERSION_GE(8, 0, 0, 0)) { + if (!use_calibration_ || precision_mode_ != TrtPrecisionMode::INT8) { + trt_algorithm_selector = MaybeCreateAlgorithmSelector(); + } + } else { + trt_algorithm_selector = MaybeCreateAlgorithmSelector(); + } + + if (trt_algorithm_selector != nullptr) { + builder_config->setAlgorithmSelector(trt_algorithm_selector.get()); + } + +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + enum class SparseComputeMode { DISABLED, ENABLED, SIMULATED }; + + static SparseComputeMode sparse_compute_mode = []() { + SparseComputeMode _sparse_compute_mode; + int64 _sparse_mode; + /*TF_TRT_SPARSE_MODE environment variable controls if sparse compute is + enabled. It also allows to simulate the performance benefits of training a + model with sparse compute in mind. + Possible Values: + - 1 [Default]: Sparse compute is enabled if the model was trained with + sparse weights. Otherwise it has no effect. + - < 1: Sparse compute is explicitly disabled regardless on how the model was + trained. + - > 1: Sparse compute is forced. This mode is only to be used for + benchmarking or debugging purpose. This feature artificially introduces a + sparse weight pattern compatible with Sparse TensorCores introduced in + NVIDIA Ampere GPU architecture. As a side effect, it will completely corrupt + the numerical values of the computation. Therefore shall only be used to + evaluate the benefit of using sparse computation for inference.*/ + TF_CHECK_OK(tensorflow::ReadInt64FromEnvVar("TF_TRT_SPARSE_MODE", + /*default_val=*/1, + &_sparse_mode)); + + string sparse_log_msg = "[TF-TRT] Sparse compute capability: "; + if (_sparse_mode == 1) { + sparse_log_msg = StrCat(sparse_log_msg, "enabled."); + _sparse_compute_mode = SparseComputeMode::ENABLED; + } else if (_sparse_mode < 1) { + sparse_log_msg = StrCat(sparse_log_msg, "disabled."); + _sparse_compute_mode = SparseComputeMode::DISABLED; + } else { + sparse_log_msg = StrCat( + sparse_log_msg, "simulated.", + "It shall only be used for sparse computing benchmark and debug."); + _sparse_compute_mode = SparseComputeMode::SIMULATED; + } + LOG(INFO) << sparse_log_msg; + + return _sparse_compute_mode; + }(); + + if (sparse_compute_mode == SparseComputeMode::ENABLED || + sparse_compute_mode == SparseComputeMode::SIMULATED) { + builder_config->setFlag(nvinfer1::BuilderFlag::kSPARSE_WEIGHTS); + } +#endif + + if (tensorflow::tensor_float_32_execution_enabled()) { + builder_config->setFlag(nvinfer1::BuilderFlag::kTF32); + } else { + builder_config->clearFlag(nvinfer1::BuilderFlag::kTF32); + } + + if (precision_mode_ == TrtPrecisionMode::FP16) { + builder_config->setFlag(nvinfer1::BuilderFlag::kFP16); + } else if (precision_mode_ == TrtPrecisionMode::INT8) { + // FP16 is not available in Explicit Precision mode with TensorRT 7. + if (IS_TRT_VERSION_GE(8, 0, 0, 0) || !use_explicit_precision_) { + builder_config->setFlag(nvinfer1::BuilderFlag::kFP16); + } else { + LOG_WARNING_WITH_PREFIX << "With explicit precision mode, FP16 is not " + "allowed before TensorRT 8. TRT will consider " + "INT8 and FP32 tactics."; + } + builder_config->setFlag(nvinfer1::BuilderFlag::kINT8); + } + if (!use_implicit_batch_ && profiles) { + TF_RETURN_IF_ERROR(profiles->ConfigureBuilder( + trt_builder_.get(), builder_config.get(), network())); + } + if (precision_mode_ == TrtPrecisionMode::INT8) { + builder_config->setInt8Calibrator(use_calibration_ ? calibrator : nullptr); + } + + std::unique_ptr timing_cache = nullptr; + // We only use a timing cache if the algorithm selector is not used. If we + // are using TRT version >= 8.0, then we can try to deserialize an existing + // cache. + if (trt_algorithm_selector == nullptr) { +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + TimingCacheRegistry* registry = GetTimingCacheRegistry(); + + auto cache = registry->LookUp("default_cache", builder_config.get()); + if (!cache.ok()) { + LOG(WARNING) << "failed to create a timing cache: " + << cache.status().message(); + } else { + timing_cache = std::move(*cache); + builder_config->setTimingCache(*timing_cache, /*ignoreMismatch*/ false); + } +#endif // IS_TRT_VERSION_GE(8, 0, 0, 0) + } else { + // Disabling the timing cache is recommended when using the algorithm + // selector. + builder_config->setFlag(nvinfer1::BuilderFlag::kDISABLE_TIMING_CACHE); + } + + string precision_mode_str; + TF_RETURN_IF_ERROR( + TrtPrecisionModeToName(precision_mode_, &precision_mode_str)); + string trt_network_name = StrCat( + "TF:", TF_VERSION_STRING, ", ", + "TRT:", absl::StrJoin(GetLoadedTensorRTVersion(), "."), "-", + "Precision:", precision_mode_str, ", ", "Calibration:", use_calibration_, + ", ", "Max-Batch-Size:", max_batch_size, ", ", + "Max-Workspace-Size:", max_workspace_size_bytes); + +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + trt_network_name = StrCat(trt_network_name, ", Sparse Compute: "); + + switch (sparse_compute_mode) { + case SparseComputeMode::SIMULATED: + trt_network_name = StrCat(trt_network_name, "Simulated"); + break; + case SparseComputeMode::ENABLED: + trt_network_name = StrCat(trt_network_name, "Enabled"); + break; + case SparseComputeMode::DISABLED: + trt_network_name = StrCat(trt_network_name, "Disabled"); + break; + } +#endif + + VLOG(1) << "Setting TensorRT network name to " << trt_network_name; + network()->setName(trt_network_name.c_str()); + + VLOG(1) << "Building TensorRT engine"; + if (VLOG_IS_ON(2)) { + VLOG(2) << "Network inputs"; + int n_inputs = network()->getNbInputs(); + for (int i = 0; i < n_inputs; i++) { + const ITensorProxyPtr input = network()->getInput(i); + if (*input) { + VLOG(2) << " " << i << " " << input->getName(); + } else { + VLOG(2) << "Could not find input " << i; + } + } + } + engine->reset( + trt_builder_->buildEngineWithConfig(*network(), *builder_config)); + if (engine->get() == nullptr) { + return errors::Internal("Failed to build TensorRT engine"); + } + if (VLOG_IS_ON(2)) { + VLOG(2) << "TRT engine created"; + int nbBindings = (*engine)->getNbBindings(); + VLOG(2) << "Number of engine bindings: " << nbBindings; + for (int i = 0; i < nbBindings; i++) { + auto get_location_string = [&engine](int i) { + if ((*engine)->getLocation(i) == nvinfer1::TensorLocation::kDEVICE) + return " on device"; + else + return " on host"; + }; + VLOG(2) << "Binding " << i << " name: " << (*engine)->getBindingName(i) + << get_location_string(i); + } + } + + // Write back the new timing cache results to the registry. + if (timing_cache) { + GetTimingCacheRegistry()->Upsert("default_cache", timing_cache.get()); + } + + return OkStatus(); +} + +Status Converter::MaybeUpdateBatchSize(int batch_size) { + // OK iff either is unknown or they equal to each other. + if (this->batch_size_ < 0 || batch_size < 0 || + this->batch_size_ == batch_size) { + if (this->batch_size_ < 0 && batch_size >= 0) { + this->batch_size_ = batch_size; + } + return OkStatus(); + } + return errors::InvalidArgument( + "Provided batch size does not match converter batch size: ", batch_size, + " vs ", batch_size_); +} + +Status Converter::AddTensorOrWeights(const string& name, + TRT_TensorOrWeights input) { + // Set the batch size of the tensor, using batch size collected from the + // input tensors to the TRT subgraph at the beginning of the conversion. + // We rely on the individual op converter to understand the semantics of the + // TF node, and make sure it doesn't change the batch size nor introduce + // intra-element dependency inside the batch. + if (use_implicit_batch_ && input.is_tensor()) { + input.set_batch_size(batch_size_); + } + if (trt_tensors_.insert({name, std::move(input)}).second) return OkStatus(); + return errors::AlreadyExists("tensor/weights ", name, " already exist."); +} + +Status Converter::GetTensorOrWeights(const string& name, + TRT_TensorOrWeights* output) { + if (!trt_tensors_.count(name)) { + return errors::NotFound("Tensor or weights with name ", name, + " could not be found."); + } + *output = trt_tensors_.at(name); + return OkStatus(); +} + +Status Converter::TransposeTensor(ITensorProxyPtr input_tensor, + const std::vector& order_with_batch_dim, + ITensorProxyPtr* output_tensor, + const NodeDef& node_def, + absl::string_view sub_op_name) { + const auto dims = input_tensor->getDimensions(); + const int order_size = use_implicit_batch_ ? order_with_batch_dim.size() - 1 + : order_with_batch_dim.size(); + if (order_size != size_t(dims.nbDims)) { + return errors::InvalidArgument( + "Rank of perm for transpose does not match with that of the input."); + } + if (use_implicit_batch_ && order_with_batch_dim[0] != 0) { + return errors::Unimplemented( + "Transpose at batch dimension is not supported."); + } + + nvinfer1::IShuffleLayer* layer = + this->network()->addShuffle(*input_tensor->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, "TF-TRT Internal Transpose"); + SetLayerName(layer, node_def, sub_op_name); + + nvinfer1::Permutation permutation; + if (use_implicit_batch_) { + for (int32_t i = 0; i < dims.nbDims; ++i) { + permutation.order[i] = order_with_batch_dim[i + 1] - 1; + } + } else { + std::copy(order_with_batch_dim.begin(), order_with_batch_dim.end(), + permutation.order); + } + VLOG(1) << "TransposeTensor permutation: " + << DebugString(permutation, dims.nbDims); + layer->setFirstTranspose(permutation); + + nvinfer1::Dims reshape_dims; + reshape_dims.nbDims = dims.nbDims; + for (int32_t i = 0; i < reshape_dims.nbDims; ++i) { + reshape_dims.d[i] = 0; + } + layer->setReshapeDimensions(reshape_dims); + + *output_tensor = layer->getOutput(0); + return OkStatus(); +} + +Status Converter::GetWeightRange(const TRT_ShapedWeights& weights, + float* out_min, float* out_max) const { + switch (weights.TrtDType()) { + case nvinfer1::DataType::kFLOAT: { + auto inp = weights.GetPointer(); + auto result = std::minmax_element(inp, inp + weights.count()); + *out_min = *result.first; + *out_max = *result.second; + break; + } + case nvinfer1::DataType::kHALF: { + auto inp = weights.GetPointer(); + auto result = std::minmax_element(inp, inp + weights.count()); + *out_min = static_cast(*result.first); + *out_max = static_cast(*result.second); + break; + } + case nvinfer1::DataType::kINT32: { + auto inp = weights.GetPointer(); + auto result = std::minmax_element(inp, inp + weights.count()); + *out_min = static_cast(*result.first); + *out_max = static_cast(*result.second); + break; + } + default: + return errors::Unimplemented( + "Data type not supported for GetWeightRange: ", + DebugString(weights.TrtDType())); + } + return OkStatus(); +} + +// Constructs for the ILayer name as +// __ and callSetLayerNameHelper +// to set the name for the ILayer. +// +// If the operation represented by the ILayer is generated by the converter to +// support the conversion of node_def, callers need to specify a non-empty +// sub_op_name to be appended to the name of node_def to avoid layer name +// conflicts. If the operation is generated multiple times, callers also need +// to specify sub_op_instance to be appended to the name of the layers to avoid +// layer name conflicts. +void Converter::SetLayerName(nvinfer1::ILayer* layer, const NodeDef& node_def, + absl::string_view sub_op_name, + std::optional sub_op_instance, + std::optional origin_node_name) { + std::string sub_op_suffix = GetLayerNameSuffix(sub_op_name, sub_op_instance); + if (sub_op_suffix.empty()) { + SetLayerNameHelper(layer, engine_name_, node_def.name()); + } else if (origin_node_name.has_value()) { + auto layer_name = absl::StrCat(node_def.name(), "-", + absl::string_view(origin_node_name.value()), + "-", sub_op_suffix); + SetLayerNameHelper(layer, engine_name_, layer_name); + } else { + SetLayerNameHelper(layer, engine_name_, + absl::StrCat(node_def.name(), "-", sub_op_suffix)); + } +} + +// Constructs for the ILayer name as +// __ and callSetLayerNameHelper to +// set the name for the ILayer. +void Converter::SetLayerName(nvinfer1::ILayer* layer, + absl::string_view main_op_name, + absl::string_view sub_op_name, + std::optional sub_op_instance) { + std::string layer_name_suffix = + GetLayerNameSuffix(sub_op_name, sub_op_instance); + SetLayerNameHelper(layer, engine_name_, + absl::StrCat(main_op_name, "-", layer_name_suffix)); +} + +// Converts 'input' of 'node_def' into 'tensor' with shape specified by 'dims' +// (which doesn't contain the batch dimension). +// +// If validation_only is true, it doesn't do the conversion but only do some +// minimum validation for the eligibility of the conversion, and *tensor will +// be set to nullptr. +Status PrepareTensorForShape(Converter* converter, + const TRT_TensorOrWeights& input, + const DimsAdapter& dims, + const bool validation_only, + ITensorProxyPtr* tensor, const NodeDef& node_def, + std::optional op_instance, + std::optional origin_node_name) { + DimsAdapter input_dims(input.GetTrtDims()); + // The input shape may have -1s for dynamic shape. The target shape may have + // 0s representing copy over the corresponding input dimensions. It may also + // have at most one -1 representing a dimension value that needs to be + // inferred. If none of those special values present, we verify that the total + // sizes of the input and output shape are the same. + // TODO(tfeher): Verify that the total sizes of the input and output shape are + // the same in the present of 0s but no -1 in the target shape. + // If an input is a weight, it is going to become a tensor via + // CreateConstantLayer. So we can treat it as a tensor for + // AreDimsStaticWithDifferentSize(). This really only matters for 0-D tensors. + if (dims.Volume() > 0 && AreDimsStaticWithDifferentSize(input_dims, dims)) { + return errors::InvalidArgument( + "Incompatible shapes: ", input_dims.DebugString(), " vs. ", + dims.DebugString()); + } + // ConstantLayer requires static shapes (cannot infer -1). + if (input.is_weights() && !dims.IsStatic()) { + return errors::InvalidArgument("Shape is not fully defined: ", + dims.DebugString()); + } + if (validation_only) { + *tensor = nullptr; + return OkStatus(); + } + + TFTRT_RETURN_ERROR_IF_NULLPTR(converter, "converter is nullptr"); + if (input.is_tensor()) { + if (input_dims == dims) { + *tensor = input.tensor(); + } else { + nvinfer1::IShuffleLayer* layer = + converter->network()->addShuffle(*input.tensor()->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, "TF-TRT Internal Reshape"); + converter->SetLayerName(layer, node_def, "shuffle", op_instance, + origin_node_name); + layer->setReshapeDimensions(dims.AsTrtDims()); + *tensor = layer->getOutput(0); + } + } else { + *tensor = converter->CreateConstantLayer(input.weights(), dims.AsTrtDims()); + TFTRT_RETURN_ERROR_IF_NULLPTR(*tensor, "TF-TRT Internal Reshape"); + } + return OkStatus(); +} + +void Converter::ProvideQuantizationRange(ITensorProxyPtr* tensor, + float min_range, float max_range) { + float symmetric_range = std::max(std::abs(min_range), std::abs(max_range)); + if ((*tensor)->is_trt_tensor()) { + quantization_ranges_[(*tensor)->trt_tensor()] = symmetric_range; + } else if ((*tensor)->is_simple_tensor()) { + quantization_ranges_proxy_[tensor] = symmetric_range; + } +} + +void Converter::MaybeApplyQuantizationRanges() { + if (precision_mode() != TrtPrecisionMode::INT8) return; + + // Apply ranges. + for (auto pair : quantization_ranges_) { + nvinfer1::ITensor* tensor = pair.first; + const float range = pair.second; + VLOG(1) << "Setting range for: " << tensor->getName() << ": " << range; + // TODO(laigd): if 'tensor' already has a range set which doesn't match + // 'range', it should report error. + tensor->setDynamicRange(-range, range); + } + for (auto pair : quantization_ranges_proxy_) { + ITensorProxyPtr tensor = *pair.first; + const float range = pair.second; + VLOG(1) << "Setting range for: " << tensor->getName() << ": " << range; + // TODO(laigd): if 'tensor' already has a range set which doesn't match + // 'range', it should report error. + tensor->setDynamicRange(-range, range); + } +} + +Status Converter::GetInputs(const NodeDef& node_def, + std::vector* inputs) const { + 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 last = name.find_last_of(':'); + // TODO(aaroey): use TensorId + if (last != string::npos && last + 2 == name.size() && + name[last + 1] == '0') { + name.erase(last); + } + + 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 errors::InvalidArgument(msg); + } + } + return OkStatus(); +} + +// Checks that the number of inputs match, and enforces that the inputs marked +// as weights are constant. Inputs are allowed to be both weight and tensor. +Status CheckInputsWeights( + const OpConverterParams& params, + const std::vector>& expected_inputs) { + const auto& inputs = params.inputs; + const auto& node_def = params.node_def; + TFTRT_CHECK_INPUT_SIZE(inputs.size(), expected_inputs.size(), node_def); + for (int i = 0; i < inputs.size(); i++) { + if (expected_inputs[i].second == TrtInputArg::kWeight && + !inputs.at(i).is_weights()) { + return errors::Unimplemented("The input \"", expected_inputs[i].first, + "\" for ", node_def.op(), + " must be a constant"); + } + // TODO(tfeher): Remove this check and provide a method to automatically + // retrieve an input as a tensor, converting via CreateConstantLayer if it + // was originally a weight. We will want a caching mechanism to prevent many + // duplicate constants from being created. + if (expected_inputs[i].second == TrtInputArg::kTensor && + !inputs.at(i).is_tensor()) { + return errors::Unimplemented("The input \"", expected_inputs[i].first, + "\" for ", node_def.op(), + " must be a tensor"); + } + if (expected_inputs[i].second == TrtInputArg::kResource && + !inputs.at(i).is_resource()) { + return errors::Unimplemented("The input \"", expected_inputs[i].first, + "\" for ", node_def.op(), + " must be a resource handle"); + } + } + return OkStatus(); +} + +// Checks that the number of inputs match, and enforces that the inputs marked +// as true are constant weights. true means that the input must be a weight, +// while false means the input must be a tensor. +Status CheckInputsWeights( + const OpConverterParams& params, + const std::vector>& inputs_is_weight) { + std::vector> expected_inputs; + expected_inputs.reserve(inputs_is_weight.size()); + std::transform( + inputs_is_weight.begin(), inputs_is_weight.end(), + std::back_inserter(expected_inputs), [](std::pair x) { + return std::make_pair( + x.first, x.second ? TrtInputArg::kWeight : TrtInputArg::kTensor); + }); + return CheckInputsWeights(params, expected_inputs); +} + +Status GetNodeDefTfType(const NodeDef& node_def, DataType* tf_type, + const string type_attr_name_in = "") { + string type_attr_name; + if (type_attr_name_in.empty()) { + if (node_def.op() == "ReadVariableOp" || + node_def.op() == "ResourceGather") { + type_attr_name = "dtype"; + } else { + type_attr_name = "T"; + } + } else { + type_attr_name = type_attr_name_in; + } + + AttrSlice attrs(node_def); + if (attrs.FindByString(type_attr_name) == nullptr) { + return errors::InvalidArgument("Attribute with name ", type_attr_name, + " not found."); + } + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, type_attr_name, tf_type)); + return OkStatus(); +} + +Status GetInputTfType(const OpConverterParams& params, DataType* tf_type, + int pos) { + const std::vector& inputs = params.inputs; + if (inputs.size() <= pos) { + return errors::Internal("Invalid input position"); + } + + return inputs[pos].GetTfType(tf_type); +} + +Status GetOutputTfType(const OpConverterParams& params, DataType* tf_type) { + return GetNodeDefTfType(params.node_def, tf_type); +} + +Status AllowDataTypes(const OpConverterParams& params, + const std::set& allowed_types, + const char* type_attr_name = "") { + const auto& node_def = params.node_def; + DataType tf_type; + TF_RETURN_IF_ERROR(GetNodeDefTfType(node_def, &tf_type, type_attr_name)); + if (!allowed_types.count(tf_type)) { + const auto error = + convert_not_supported_dtype_msg(allowed_types, tf_type, node_def); + return errors::Unimplemented(error); + } + return OkStatus(); +} + +namespace { +// Extracts the spatial dimensions from `output_sizes` and returns them as a +// vector of size 2. +std::vector GetSpatialDimsFromOutputSizes( + const TRT_TensorOrWeights& output_sizes, const int h_index, + const int w_index) { + // We use h_index and w_index instead of 1 and 2 because we haven't + // transposed output_sizes along with the input. + const TRT_ShapedWeights& weights = output_sizes.weights(); + const int output_sizes_length = weights.count(); + auto output_sizes_values = weights.GetPointer(); + // The length of output_sizes can be 2 or 4. When the length is 4, + // output_sizes represents . + return {output_sizes_values[output_sizes_length == 4 ? h_index : 0], + output_sizes_values[output_sizes_length == 4 ? w_index : 1]}; +} +} // namespace + +Status ConvertConv2DHelper(const OpConverterParams* params, int group, + bool is_conv2d_backprop_input) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TRT_TensorOrWeights backprop_output_size; + ITensorProxyPtr tensor = nullptr; + if (is_conv2d_backprop_input) { + // In the case when Conv2dBackpropInput is used for conv2d_transpose, these + // inputs correspond to: output size, filter, and input. + // TODO(cbate): refine this check when moving to structured op converter. + if (!params->use_explicit_precision) { + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"input_sizes", true}, {"filter", true}, {"out_backprop", false}})); + } + + backprop_output_size = inputs.at(0); + tensor = inputs.at(2).tensor(); + bool has_dynamic_hw_shape{false}; + int start_idx{0}; + auto dims = tensor->getDimensions(); + if (params->use_implicit_batch) { + if (dims.nbDims != 3) { + return errors::Internal( + "In implicit batch mode, input nbDims should be 3"); + } + start_idx = 1; + } else { + if (dims.nbDims != 4) { + return errors::Internal( + "In explicit batch mode, input nbDims should be 4"); + } + start_idx = 2; + } + for (int i = start_idx; i < dims.nbDims; ++i) { + if (dims.d[i] < 0) { + has_dynamic_hw_shape = true; + } + } + if (has_dynamic_hw_shape) { + return errors::Unimplemented( + "Conv2dBackpropInput does not support input with unknown spatial " + "shape"); + } + } else { + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"input", false}, {"filter", !params->use_explicit_precision}})); + tensor = inputs.at(0).tensor(); + } + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + if (inputs.at(1).GetTrtDims().nbDims != 4) { + return errors::InvalidArgument("Conv2D expects kernel of dimension 4"); + } + + string data_format, padding_type; + std::vector tf_dilations, tf_stride; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "padding", &padding_type)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "dilations", &tf_dilations)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "strides", &tf_stride)); + + int c_index = (data_format == "NHWC") ? 3 : 1; + int h_index = (data_format == "NHWC") ? 1 : 2; + int w_index = (data_format == "NHWC") ? 2 : 3; + + if (tf_dilations.size() != 4) { + return errors::InvalidArgument( + "Convolution dilations field must specify 4 dimensions"); + } + if (tf_dilations[0] != 1 || tf_dilations[c_index] != 1) { + return errors::Unimplemented( + "Dilation rate must be 1 for batch and channel dimensions"); + } + const nvinfer1::DimsHW dilation(tf_dilations[h_index], tf_dilations[w_index]); + if (is_conv2d_backprop_input && (dilation.d[0] != 1 || dilation.d[1] != 1)) { + return errors::Unimplemented( + "Dilation with Conv2DBackpropInput (conv2d_transpose) is not" + " supported"); + } + + if (tf_stride.size() != 4) { + return errors::InvalidArgument( + "Convolution strides field must specify 4 dimensions"); + } + if (tf_stride[0] != 1 || tf_stride[c_index] != 1) { + return errors::Unimplemented( + "Stride must be 1 for batch and channel dimensions"); + } + // Channel dim must be static for DepthwiseConv2dNative since we use that + // value for num_groups at build time. + if (!params->use_implicit_batch && tensor->getDimensions().d[c_index] == -1) { + return errors::InvalidArgument("Channel dimension must be static"); + } + + if (padding_type != "SAME" && padding_type != "VALID") { + return errors::Unimplemented(padding_type + + " padding type not implemented, " + "only VALID and SAME are supported"); + } + const nvinfer1::DimsHW stride(tf_stride[h_index], tf_stride[w_index]); + if (params->validation_only) return OkStatus(); + + // Transpose to NCHW (NCHW is required for IConvLayer). + const bool need_transpose = (data_format == "NHWC"); + if (need_transpose) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + tensor, {0, 3, 1, 2}, &tensor, node_def, "to_NCHW")); + } + // Dimensions of transposed tensor. + const auto tensor_dim = tensor->getDimensions(); + const int c_dim_size = tensor_dim.d[params->use_implicit_batch ? 0 : 1]; + + // group == 0 signifies that this is a depthwise convolution, so set + // num_groups to size of input's channel dim. For a non-depthwise conv, + // num_groups will be 1. + const int num_groups = (group == 0) ? c_dim_size : group; + + // For conv, TF weights are RSCK, and TRT expects KCRS. + // For backprop, TF weights are RSKC, and TRT expects CKRS. + // Therefore, this reorder will work for both cases. + const int output_axis = is_conv2d_backprop_input ? 2 : 3; + auto weights_shape = inputs.at(1).GetTrtDims(); + const int noutput = weights_shape.d[output_axis] * num_groups; + nvinfer1::DimsHW kernel_size; + kernel_size.h() = weights_shape.d[0]; + kernel_size.w() = weights_shape.d[1]; + + TRT_ShapedWeights weights_rsck; + if (inputs.at(1).is_weights()) { + weights_rsck = inputs.at(1).weights(); + } else { + StatusOr tmp = params->weight_store->GetTempWeights( + nvinfer1::DataType::kFLOAT, weights_shape); + TRT_ENSURE_OK(tmp); + weights_rsck = std::move(tmp).value(); + } + + // In explicit precision mode, trace the input back to the constant while also + // verifying that QDQ scale layers are present. + if (!inputs.at(1).is_weights()) { + TRT_ENSURE(params->use_explicit_precision); + StatusOr builder = TRTNetworkBuilder::Create( + params->converter->network(), params->weight_store); + TRT_ENSURE_OK(builder); + auto dequant_layer = + builder->FindProducerOf(inputs.at(1).tensor()->trt_tensor()); + TRT_ENSURE_PTR_OK(dequant_layer); + + // TODO(cbate): corresponding TRT layer name check + if (!IS_TRT_VERSION_GE(8, 0, 0, 0)) { + TRT_ENSURE((*dequant_layer)->getType() == nvinfer1::LayerType::kSCALE); + } + + auto quant_layer = builder->UniqueParentOf(*dequant_layer, 0); + TRT_ENSURE_PTR_OK(quant_layer); + + // TODO(cbate): corresponding TRT layer name check + if (!IS_TRT_VERSION_GE(8, 0, 0, 0)) { + TRT_ENSURE((*quant_layer)->getType() == nvinfer1::LayerType::kSCALE); + } + + auto weights_layer = builder->UniqueParentOf(*quant_layer, 0); + TRT_ENSURE_PTR_OK(weights_layer); + TRT_ENSURE((*weights_layer)->getType() == nvinfer1::LayerType::kCONSTANT); + auto const_weights_rsck = + reinterpret_cast(*weights_layer) + ->getWeights(); + + TRT_ENSURE(weights_rsck.count() == weights_rsck.count()); + const auto* weights_ptr = + static_cast(const_weights_rsck.values); + std::copy_n(weights_ptr, const_weights_rsck.count, + weights_rsck.GetPointer()); + } + + StatusOr weights = + params->weight_store->GetTempWeights(weights_rsck); + TRT_ENSURE_OK(weights); + StatusOr biases = params->weight_store->GetTempWeights( + nvinfer1::DataType::kFLOAT, nvinfer1::Dims{1, {noutput}}); + TRT_ENSURE_OK(biases); + std::fill_n(biases->GetPointer(), noutput, 0.0f); + ReorderRSCKToKCRS(weights_rsck, &*weights, num_groups); + + // Add convolution. + nvinfer1::ILayer* conv_layer = nullptr; + if (is_conv2d_backprop_input) { + nvinfer1::IDeconvolutionLayer* layer = + params->converter->network()->addDeconvolution( + *tensor->trt_tensor(), noutput, kernel_size, + weights->GetTrtWeights(), biases->GetTrtWeights()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + layer->setStride(stride); + // VALID padding is the default TRT behavior. + if (padding_type == "SAME") { + // SAME_UPPER means that post padding is preferred. + layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + layer->setNbGroups(num_groups); + conv_layer = layer; + } else { + const nvinfer1::Weights empty_weights{nvinfer1::DataType::kFLOAT, nullptr, + 0}; + nvinfer1::IConvolutionLayer* layer = + params->converter->network()->addConvolution( + *tensor->trt_tensor(), noutput, kernel_size, + params->use_explicit_precision ? empty_weights + : weights->GetTrtWeights(), + empty_weights); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + layer->setStride(stride); + if (padding_type == "SAME") { + layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + layer->setNbGroups(num_groups); + layer->setDilation(dilation); + conv_layer = layer; + } + + // After creating the conv layer, if we are in explicit precision mode and the + // weights input is a tensor, then we need to override the weights input by + // calling setInput() on the layer. + if (params->use_explicit_precision) { + TRT_ENSURE(inputs.at(1).is_tensor()); + + nvinfer1::IShuffleLayer* layer = params->converter->network()->addShuffle( + *inputs.at(1).tensor()->trt_tensor()); + layer->setFirstTranspose({3, 2, 0, 1}); + layer->setReshapeDimensions({4, {0, 0, 0, 0}}); + conv_layer->setInput(1, *layer->getOutput(0)); + } + + params->converter->SetLayerName(conv_layer, node_def, "conv"); + ITensorProxyPtr output_tensor = conv_layer->getOutput(0); + // Add an extra padding for Deconv because TRT doesn't accept the + // argument output_shape and thus the TRT output shape could be wrong + // in case of strides>1. + if (is_conv2d_backprop_input) { + std::vector output_spatial_dims = + GetSpatialDimsFromOutputSizes(backprop_output_size, h_index, w_index); + const int output_height = output_spatial_dims[0]; + const int output_width = output_spatial_dims[1]; + nvinfer1::Dims trt_output_shape = output_tensor->getDimensions(); + // What determines the padding size is the difference between the given + // input_sizes (tf_output_shape) and TRT computed size. + int out_h_idx = params->use_implicit_batch ? 1 : 2; + int out_w_idx = params->use_implicit_batch ? 2 : 3; + const int height_diff = output_height - trt_output_shape.d[out_h_idx]; + const int width_diff = output_width - trt_output_shape.d[out_w_idx]; + if ((height_diff < 0) || (width_diff < 0)) { + return errors::InvalidArgument( + "input_sizes argument of Conv2DBackprop (i.e. output_shape argument " + "of conv2d_transpose) ", + "is too small for the given out_backprop argument of Conv2DBackprop " + "(i.e. input argument of conv2d_transpose). Expect: ", + "(", output_height, ", ", output_width, ") >= ", "(", + trt_output_shape.d[out_h_idx], ", ", trt_output_shape.d[out_w_idx], + ")"); + } + // Only add a padding layer if padding sizes are larger than 0 + if ((height_diff > 0) || (width_diff > 0)) { + nvinfer1::DimsHW pre_padding(0, 0); + nvinfer1::DimsHW post_padding(height_diff, width_diff); + nvinfer1::IPaddingLayer* padding_layer = + params->converter->network()->addPadding(*output_tensor->trt_tensor(), + pre_padding, post_padding); + output_tensor = padding_layer->getOutput(0); + params->converter->SetLayerName(padding_layer, node_def, "pad"); + } + } + // Restore transpose. + if (need_transpose) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output_tensor, {0, 2, 3, 1}, &output_tensor, node_def, "to_NHWC")); + } + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +bool AllowInefficientTranspose() { + static bool result = [] { + bool value; + Status status = + ReadBoolFromEnvVar("TF_DEBUG_TRT_ALLOW_INEFFICIENT_TRANSPOSE", + /*default_value=*/false, &value); + if (!status.ok()) { + LOG(ERROR) << status; + } + return value; + }(); + + return result; +} + +Status ConvertTranspose(const OpConverterParams* params) { + const auto& inputs = params->inputs; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"x", false}, {"perm", true}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + // Get the permutation from weights. + TRT_ShapedWeights weights = inputs.at(1).weights(); + const int* weights_ptr = weights.GetPointer(); + std::vector perm(weights_ptr, weights_ptr + weights.count()); + + // Verify the permutation. + ITensorProxyPtr input_tensor = inputs.at(0).tensor(); + const int perm_size = + params->use_implicit_batch ? perm.size() - 1 : perm.size(); + if (perm_size != size_t(input_tensor->getDimensions().nbDims)) { + return errors::InvalidArgument( + "Rank of perm for transpose does not match with that of the input."); + } + if (params->use_implicit_batch && perm[0] != 0) { + return errors::Unimplemented( + "Transpose at batch dimension is not supported."); + } + + if (!IS_TRT_VERSION_GE(7, 1, 3, 4)) { + // TensorRT versions before 7.1.3.4 is slow transposing large tensors. + // So check tensor size, and don't convert if it is too large. + constexpr int64_t kMaxEfficientTranspose = 2500000; + int64_t tensor_size = DimsAdapter(input_tensor->getDimensions()).Volume(); + if (!AllowInefficientTranspose() && tensor_size > kMaxEfficientTranspose) { + return errors::Unimplemented(StrCat("Transpose too large:", tensor_size)); + } + } + + if (params->validation_only) return OkStatus(); + + // Start conversion. + ITensorProxyPtr output_tensor = nullptr; + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + input_tensor, perm, &output_tensor, params->node_def)); + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertShape(const OpConverterParams* params) { + const auto& inputs = params->inputs; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"input", TrtInputArg::kBoth}})); + if (params->use_implicit_batch) { + return errors::Unimplemented( + "Shape is only supported for explicit batch mode."); + } + DimsAdapter input_dims(inputs.at(0).GetTrtDims()); + if (params->validation_only) return OkStatus(); + + StatusOr builder = TRTNetworkBuilder::Create( + params->converter->network(), params->weight_store); + TRT_ENSURE_OK(builder); + if (input_dims.IsStatic()) { + // Create a const node with the value of the shape. + StatusOr const_layer = + builder->ConstantShape(input_dims); + TRT_ENSURE_PTR_OK(const_layer); + params->outputs->push_back( + TRT_TensorOrWeights((*const_layer)->getOutput(0))); + return OkStatus(); + } + StatusOr shape_layer = + builder->Shape(inputs.at(0).tensor()->trt_tensor()); + TRT_ENSURE_PTR_OK(shape_layer); + params->converter->SetLayerName(*shape_layer, params->node_def, "shape"); + params->outputs->push_back(TRT_TensorOrWeights((*shape_layer)->getOutput(0))); + return OkStatus(); +} + +Status ExpectShapeTensor(const TRT_TensorOrWeights& tensor) { + if (tensor.tensor()->getType() != nvinfer1::DataType::kINT32) { + return errors::InvalidArgument("Expected a shape tensor with INT32 type"); + } + if (tensor.GetTrtDims().nbDims > 1) { + return errors::InvalidArgument("Expected a 0D or 1D shape tensor"); + } + return OkStatus(); +} + +// Converts Reshape op if the input has dynamic (unknown) dims. +Status ConvertDynamicReshape(const OpConverterParams* params) { + if (params->use_implicit_batch) { + return errors::InvalidArgument( + "The input \"shape\" for Reshape must be a constant in implicit batch" + " mode."); + } + if (!IS_TRT_VERSION_GE(7, 1, 3, 0)) { + // While officially TRT supports shape value input , there are problems with + // shape input handling that cause networks converted with + // ConvertDynamicReshape fail. Here we conservatively switch off the + // converter before TRT 7.1.3. + return errors::InvalidArgument( + "Non constant shape input tensor for Reshape requires minimum TRT " + "7.1.3"); + } + const auto& inputs = params->inputs; + const TRT_TensorOrWeights& input_tensor = inputs.at(0); + + // If the input is a tensor it must be a shape tensor. + TF_RETURN_IF_ERROR(ExpectShapeTensor(inputs.at(1))); + if (inputs.at(1).tensor()->getDimensions().nbDims == 0) { + // Dynamic reshape requires a 1D shape tensor. + return errors::Unimplemented( + "Reshape with dynamic input requires 1D input tensor"); + } + if (params->validation_only) return OkStatus(); + nvinfer1::IShuffleLayer* layer = params->converter->network()->addShuffle( + *input_tensor.tensor()->trt_tensor()); + VLOG(2) << "ConvertReshape setInput (1) " + << DebugString(inputs.at(1).tensor()->getDimensions()); + layer->setInput(1, *inputs.at(1).tensor()->trt_tensor()); + params->outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0))); + return OkStatus(); +} + +// Converts Reshape in explicit batch mode if the input has static (known) dims. +Status ConvertStaticReshapeForExplicitBatchMode( + const OpConverterParams* params, DimsAdapter output_dims, + ITensorProxyPtr* output_tensor) { + return PrepareTensorForShape(params->converter, params->inputs.at(0), + output_dims, params->validation_only, + output_tensor, params->node_def); +} + +// Converts Reshape in implicit batch mode. The input has static (known) dims. +Status ConvertStaticReshapeForImplicitBatchMode( + const OpConverterParams* params, DimsAdapter output_dims, + ITensorProxyPtr* output_tensor) { + const auto& inputs = params->inputs; + const TRT_TensorOrWeights& input_tensor = inputs.at(0); + const int input_batch_dim = input_tensor.batch_size(); + const int64_t output_batch_dim = output_dims.dim(0); + + DimsAdapter input_nonbatch_dims(input_tensor.GetTrtDims()); + DimsAdapter output_nonbatch_dims(output_dims); + TF_RETURN_IF_ERROR(output_nonbatch_dims.RemoveBatchDimension()); + + VLOG(1) << "input_batch_dim=" << input_batch_dim + << ", input_nonbatch_dims=" << input_nonbatch_dims.DebugString() + << "\nresult_batch_dim=" << output_batch_dim + << ", result_nonbatch_dims=" << output_nonbatch_dims.DebugString(); + + // Check whether input_batch_dim and output_batch_dim will have the same + // static value. + bool reshape_may_change_batch_dim = false; + if (input_batch_dim != -1 && output_batch_dim != -1) { + reshape_may_change_batch_dim = (input_batch_dim != output_batch_dim); + } else { + reshape_may_change_batch_dim = + !AreDimsStaticWithSameSize(input_nonbatch_dims, output_nonbatch_dims); + } + if (reshape_may_change_batch_dim) { + return errors::Unimplemented("Reshape on batch dimension is not supported"); + } + // Perform the conversion. + return PrepareTensorForShape(params->converter, input_tensor, + output_nonbatch_dims, params->validation_only, + output_tensor, params->node_def); +} + +Status ConvertReshape(const OpConverterParams* params) { + const auto& inputs = params->inputs; + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"tensor", TrtInputArg::kTensor}, {"shape", TrtInputArg::kBoth}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + if (inputs.at(1).is_tensor()) { + return ConvertDynamicReshape(params); + } + + // TODO(bixia): we can't use inputs.at(1).weights().ToVector() for two + // reasons: (1) When weights.count()==0, TRT_ShapedWeights::tensor_ dtype is + // not properly set to INT32. (2) I tried a fix for the first problem, I got + // shared pointer related error in convert_nodes_test. We should fix the + // problems and switch to use inputs.at(1).weights().ToVector(), a type + // safe method to access the content of the tensor. + TRT_ShapedWeights weights = inputs.at(1).weights(); + if (weights.count() == 0 && params->use_implicit_batch) { + return errors::Unimplemented("Reshape to shape=[] is not supported"); + } + + DimsAdapter output_shape_dims( + absl::MakeSpan(weights.GetPointer(), weights.count())); + ITensorProxyPtr output_tensor = nullptr; + + if (!params->use_implicit_batch) { + TF_RETURN_IF_ERROR(ConvertStaticReshapeForExplicitBatchMode( + params, output_shape_dims, &output_tensor)); + } else { + TF_RETURN_IF_ERROR(ConvertStaticReshapeForImplicitBatchMode( + params, output_shape_dims, &output_tensor)); + } + if (params->validation_only) return OkStatus(); + + // Record the conversion result. + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertExpandDims(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"input", false}, {"axis", true}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + // Get input shape as vector. + const TRT_TensorOrWeights& input_tensor = inputs.at(0); + const nvinfer1::Dims dims = input_tensor.GetTrtDims(); + std::vector input_dims(dims.d, dims.d + dims.nbDims); + // Get axis to expand on. + auto axis = inputs.at(1).weights().GetSpan(); + if (axis.size() != 1) { + return errors::InvalidArgument("ExpandDims axis must be a scalar"); + } + // Use rank = nbDims + 1 for ConvertAxis's bounds checking to account for + // ExpandDim's ability to add an axis at end of the shape. + int trt_axis; + TF_RETURN_IF_ERROR(ConvertAxis(axis[0], dims.nbDims + 1, node_def.name(), + params->use_implicit_batch, &trt_axis)); + if (params->validation_only) return OkStatus(); + ITensorProxyPtr output_tensor = nullptr; + + if (!params->use_implicit_batch && !HasStaticShape(input_dims)) { + TF_RETURN_IF_ERROR(params->converter->DynamicExpandDims( + /*input=*/input_tensor.tensor(), + /*dims=*/dims, + /*axis=*/trt_axis, + /*params=*/params, + /*output=*/&output_tensor)); + } else { + // ExpandDims: Insert new dim of size 1. + input_dims.insert(input_dims.begin() + trt_axis, 1); + // Reshape tensor. + DimsAdapter dims(input_dims); + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, input_tensor, dims, + /*validation_only=*/false, &output_tensor, params->node_def)); + } + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status Converter::DynamicReshape(ITensorProxyPtr input, + std::vector> slices, + const OpConverterParams* params, + ITensorProxyPtr* output, + std::vector size_for_added_dims, + std::optional op_instance) { + *output = nullptr; + // DynamicReshape relies on INetworkDefinition::addShape + if (params->validation_only) { + return errors::Internal( + "DynamicReshape should not be used during validation"); + } + ITensorProxyPtr shape = + network()->addShape(*input->trt_tensor())->getOutput(0); + // Build new shape = shape[:trt_axis] + [1] + shape[trt_axis:] + std::vector concat_inputs; + int max_num_slices = std::max(slices.size(), size_for_added_dims.size()); + int op_instance_value = op_instance.has_value() ? op_instance.value() : 0; + + for (int i = 0; i < max_num_slices; i++) { + ITensorProxyPtr tensor; + // maybe_add_a_dimension(i); + if (i < size_for_added_dims.size() && size_for_added_dims[i] >= 0) { + nvinfer1::Dims dims{1, {1}}; + if (size_for_added_dims[i] > 0) { + dims.d[0] = size_for_added_dims[i]; + } + TF_RETURN_IF_ERROR( + CreateScalarConstant(params, std::min(size_for_added_dims[i], 1), + &tensor, nvinfer1::DataType::kINT32, dims)); + concat_inputs.push_back(tensor); + } + if (i < slices.size()) { + nvinfer1::ISliceLayer* slice_layer = network()->addSlice( + *shape->trt_tensor(), {1, {slices[i].first}}, + {1, {slices[i].second - slices[i].first}}, {1, {1}}); + concat_inputs.push_back(slice_layer->getOutput(0)); + string slice_name = StrCat("slice_", op_instance_value); + SetLayerName(slice_layer, params->node_def, slice_name, + /*op_instance=*/i); + } + } + std::vector trt_concat_inputs; + for (const auto& t : concat_inputs) { + trt_concat_inputs.push_back(t->trt_tensor()); + } + nvinfer1::IConcatenationLayer* concat_layer = network()->addConcatenation( + static_cast(trt_concat_inputs.data()), + concat_inputs.size()); + SetLayerName(concat_layer, params->node_def, "concat", op_instance); + concat_layer->setAxis(0); + ITensorProxyPtr new_shape = concat_layer->getOutput(0); + // Reshape input using new shape + nvinfer1::IShuffleLayer* shuffle = + network()->addShuffle(*input->trt_tensor()); + SetLayerName(shuffle, params->node_def, "shuffle", op_instance); + shuffle->setInput(1, *new_shape->trt_tensor()); + *output = shuffle->getOutput(0); + return OkStatus(); +} + +Status Converter::DynamicExpandDims(ITensorProxyPtr input, + const nvinfer1::Dims& dims, int axis, + const OpConverterParams* params, + ITensorProxyPtr* output, + std::optional op_instance) { + if (params->validation_only) { + *output = nullptr; + return errors::Internal( + "DynamicExpandDims should not be used during validation"); + } + std::vector> slices; + std::vector extra_dims; + if (axis != 0) { + slices.push_back(std::pair{0, axis}); + extra_dims.push_back(-1); + } + extra_dims.push_back(1); + if (axis != dims.nbDims) { + slices.push_back(std::pair{axis, dims.nbDims}); + } + return DynamicReshape( + /*input=*/input, + /*slices=*/slices, + /*params=*/params, + /*output=*/output, + /*size_for_added_dims=*/extra_dims, + /*op_instance=*/op_instance); +} + +Status Converter::SqueezeTensor(ITensorProxyPtr input, + std::vector* input_dims, + const OpConverterParams* params, + ITensorProxyPtr* output, + std::optional op_instance) { + // If the remaining dimensions of a squeeze operation have dynamic sizes, we + // need to use TRT ops to build the result shape for the squeeze operation. + // This is because IShuffleLayer::setReshapeDimensions treats -1 as a special + // value. + if (!params->use_implicit_batch && !HasStaticShape(*input_dims)) { + std::vector> slices; + for (int i = 0; i < input_dims->size(); i++) { + if (input_dims->at(i) != 0) { + slices.push_back(std::pair(i, i + 1)); + } + } + return DynamicReshape( + /*input=*/input, + /*slices=*/slices, + /*params=*/params, + /*output=*/output, + /*size_for_added_dims=*/{}, + /*op_instance=*/op_instance); + } + // Remove all dims which are equal to 0. + input_dims->erase(std::remove(input_dims->begin(), input_dims->end(), 0), + input_dims->end()); + // Reshape tensor. + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, TRT_TensorOrWeights(input), DimsAdapter(*input_dims), + /*validation_only=*/false, output, params->node_def, op_instance)); + return OkStatus(); +} + +Status ConvertSqueeze(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"input", false}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + // Get input shape. + const TRT_TensorOrWeights& input_tensor = inputs.at(0); + const nvinfer1::Dims dims = input_tensor.GetTrtDims(); + std::vector input_dims(dims.d, dims.d + dims.nbDims); + std::vector squeeze_dims; + TF_RETURN_IF_ERROR( + GetNodeAttr(AttrSlice(node_def), "squeeze_dims", &squeeze_dims)); + if (squeeze_dims.empty()) { + if (params->use_implicit_batch || !HasStaticShape(dims)) { + return errors::Unimplemented( + "Squeeze is not implemented for empty squeeze_dims"); + } else { + // explicit batch mode with static input shape we squeeze all singleton + // dimensions + for (int& dim : input_dims) { + if (dim == 1) { + // Mark it for removal by setting it to 0 + dim = 0; + } + } + } + } else { + std::vector trt_axes; + trt_axes.reserve(squeeze_dims.size()); + for (int tf_axis : squeeze_dims) { + // If the axis is valid, then convert it to TRT axis, otherwise abort + // conversion. + int trt_axis; + TF_RETURN_IF_ERROR(ConvertAxis(tf_axis, dims.nbDims, node_def.name(), + params->use_implicit_batch, &trt_axis)); + // Make sure target dimension is size 1 or unknown size (-1) + if (input_dims[trt_axis] != -1 && input_dims[trt_axis] != 1) { + return errors::InvalidArgument( + "Dimension ", tf_axis, " with size ", input_dims[trt_axis], + " cannot be squeezed because it must be size 1"); + } + trt_axes.push_back(trt_axis); + } + // Mark axes to remove by setting them to 0. + for (int axis : trt_axes) { + input_dims[axis] = 0; + } + } + if (params->validation_only) return OkStatus(); + + ITensorProxyPtr output_tensor = nullptr; + TF_RETURN_IF_ERROR(params->converter->SqueezeTensor( + /*input=*/input_tensor.tensor(), + /*input_dims=*/&input_dims, + /*params=*/params, + /*output=*/&output_tensor)); + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertSlice(const OpConverterParams* params) { + const auto& inputs = params->inputs; + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, {{"input", false}, {"begin", true}, {"size", true}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + + const TRT_ShapedWeights& begin_weights = inputs.at(1).weights(); + const TRT_ShapedWeights& size_weights = inputs.at(2).weights(); + + // Check that "begin" is not negative. + if (absl::c_any_of(begin_weights.GetSpan(), + [](const int32 val) { return val < 0; })) { + return errors::InvalidArgument("\"begin\" in Slice is out of range"); + } + + // Check that "size" is not less than -1. + if (absl::c_any_of(size_weights.GetSpan(), + [](const int32 val) { return val < -1; })) { + return errors::InvalidArgument("\"size\" in Slice is out of range"); + } + + // Get the input dims and add batch dimension so that indexes line up + // properly. + PartialTensorShape input_shape; + TF_RETURN_IF_ERROR( + DimsAdapter(inputs.at(0).GetTrtDims()) + .PartialTensorShape( + &input_shape, params->use_implicit_batch + ? std::optional(inputs.at(0).batch_size()) + : std::nullopt)); + + if (static_cast(input_shape.dims()) != + begin_weights.GetTensor().NumElements() || + static_cast(input_shape.dims()) != + size_weights.GetTensor().NumElements()) { + return errors::InvalidArgument( + "Length of begin and size arguments must equal rank of input for " + "Slice"); + } + + // Check that batch dimension is unmodified. + if (params->use_implicit_batch) { + auto begin_v = begin_weights.GetSpan(); + auto size_v = size_weights.GetSpan(); + + // The batch dimension is modified if begin doesn't start from 0 or slice + // size on d0 is not equal to input size on d0. Slice size -1 means slices + // to the end of the dimension. + if (begin_v[0] != 0 || + (size_v[0] != -1 && size_v[0] != input_shape.dim_size(0))) { + return errors::Unimplemented( + "TensorRT does not allow modifications to the batch dimension in " + "implicit batch mode"); + } + } + + PartialTensorShape processing_shape; + PartialTensorShape final_shape; + bool is_identity; + bool is_simple_slice; + bool slice_dim0; + absl::InlinedVector begin; + absl::InlinedVector end; + absl::InlinedVector strides; + StridedSliceShapeSpec strided_slice_spec; + std::bitset<32> begin_mask(0); + std::bitset<32> end_mask(0); + std::bitset<32> ellipsis_mask(0); + std::bitset<32> new_axis_mask(0); + std::bitset<32> shrink_axis_mask(0); + Tensor strides_tensor = tensor::DeepCopy(begin_weights.GetTensor()); + Tensor end_tensor = tensor::DeepCopy(size_weights.GetTensor()); + Tensor size_tensor = tensor::DeepCopy(size_weights.GetTensor()); + + // Use the content in begin_weights and size_tensor to setup begin_mask, + // end_mask, end_tensor, strides_tensor, and end_tensor. + auto strides_vec = strides_tensor.flat(); + auto end_vec = end_tensor.flat(); + auto size_vec = size_tensor.flat(); + auto begin_vec = begin_weights.GetTensor().flat(); + + for (int i = 0; i < input_shape.dims(); i++) { + strides_vec(i) = 1; + begin_mask[i] = false; + if (size_vec(i) == -1) { + end_mask[i] = true; + end_vec(i) = 0; + size_vec(i) = 0; + } else { + end_mask[i] = false; + end_vec(i) = begin_vec(i) + size_vec(i); + if (end_vec(i) > input_shape.dim_size(i) && input_shape.dim_size(i) > 0) { + return errors::InvalidArgument("\"begin\" + \"size\" for dimension ", i, + " in Slice is out of range"); + } + } + } + + auto bitset_to_int32 = [](const std::bitset<32>& bs) { + return static_cast(bs.to_ulong()); + }; + + TF_RETURN_IF_ERROR(ValidateStridedSliceOp( + &begin_weights.GetTensor(), &end_tensor, strides_tensor, input_shape, + bitset_to_int32(begin_mask), bitset_to_int32(end_mask), + bitset_to_int32(ellipsis_mask), bitset_to_int32(new_axis_mask), + bitset_to_int32(shrink_axis_mask), &processing_shape, &final_shape, + &is_identity, &is_simple_slice, &slice_dim0, &begin, &end, &strides, + &strided_slice_spec)); + + VLOG(2) << "ConvertSlice: " << "\n input_shape: " << input_shape + << "\n processing_shape: " << processing_shape + << "\n final_shape: " << final_shape + << "\n begin: " << DebugString(begin) + << "\n stride: " << DebugString(strides) + << "\n end: " << DebugString(end) + << "\n is identity: " << is_identity + << "\n is simple_slice: " << is_simple_slice + << "\n slice dim0: " << slice_dim0 + << " StridedSliceShapeSpec:" << "\n begin_dense_mask: " + << std::bitset<32>(strided_slice_spec.begin_dense_mask) + << "\n end_dense_mask: " + << std::bitset<32>(strided_slice_spec.end_dense_mask) + << "\n shrink_dense_mask: " + << std::bitset<32>(strided_slice_spec.shrink_axis_dense_mask); + + return ConvertStridedSliceHelper(params, inputs.at(0), input_shape, begin, + strides, end, std::nullopt, std::nullopt, + strided_slice_spec); +} + +Status ConvertStridedSlice(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"input", false}, {"begin", true}, {"end", true}, {"strides", true}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + + int32 begin_mask, end_mask, ellipsis_mask, shrink_axis_mask, new_axis_mask; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "begin_mask", &begin_mask)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "end_mask", &end_mask)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "ellipsis_mask", &ellipsis_mask)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "shrink_axis_mask", &shrink_axis_mask)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "new_axis_mask", &new_axis_mask)); + + // New_axis_mask is not supported. TODO(tfeher): Support this by expanddims. + if (new_axis_mask != 0) { + return errors::Unimplemented( + "new_axis_mask is not supported for StridedSlice"); + } + + // Shrinking axis on batch dimension is not allowed in implicit batch mode. + if (params->use_implicit_batch && shrink_axis_mask & 1) { + return errors::Unimplemented( + "TensorRT does not allow modifications to the batch dimension"); + } + + // Convert TensorRT dimensions to TensorFlow shape. Implicit batch is added to + // the TensorFlow shape, to be consistent with the weights and masks and to + // support the use of TensorFlow slice op validator. + PartialTensorShape input_shape; + TF_RETURN_IF_ERROR( + DimsAdapter(inputs.at(0).GetTrtDims()) + .PartialTensorShape( + &input_shape, params->use_implicit_batch + ? std::optional(inputs.at(0).batch_size()) + : std::nullopt)); + + const TRT_ShapedWeights& begin_weights = inputs.at(1).weights(); + const TRT_ShapedWeights& end_weights = inputs.at(2).weights(); + const TRT_ShapedWeights& stride_weights = inputs.at(3).weights(); + if (!AllLengthsEqual({begin_weights.ToVector(), + end_weights.ToVector(), + stride_weights.ToVector()})) { + return errors::InvalidArgument( + "Length of begin, end, and stride must be equal"); + } + + PartialTensorShape processing_shape; + PartialTensorShape final_shape; + bool is_identity; + bool is_simple_slice; + bool slice_dim0; + absl::InlinedVector begin; + absl::InlinedVector end; + absl::InlinedVector strides; + StridedSliceShapeSpec strided_slice_spec; + + TF_RETURN_IF_ERROR(ValidateStridedSliceOp( + &begin_weights.GetTensor(), &end_weights.GetTensor(), + stride_weights.GetTensor(), input_shape, begin_mask, end_mask, + ellipsis_mask, new_axis_mask, shrink_axis_mask, &processing_shape, + &final_shape, &is_identity, &is_simple_slice, &slice_dim0, &begin, &end, + &strides, &strided_slice_spec)); + + if (!params->validation_only) { + VLOG(2) << "After ValidateStridedSliceOp:" << "\n input_shape: " + << input_shape << "\n processing_shape: " << processing_shape + << "\n final_shape: " << final_shape + << "\n begin: " << DebugString(begin) + << "\n stride: " << DebugString(strides) + << "\n end: " << DebugString(end) + << " is identity: " << is_identity + << "\n is simple_slice: " << is_simple_slice + << "\n slice dim0: " << slice_dim0 + << " StridedSliceShapeSpec:" << "\n begin_dense_mask: " + << std::bitset<32>(strided_slice_spec.begin_dense_mask) + << "\n end_dense_mask: " + << std::bitset<32>(strided_slice_spec.end_dense_mask) + << "\n shrink_dense_mask: " + << std::bitset<32>(strided_slice_spec.shrink_axis_dense_mask); + } + + // If the first dimension of the ellepsis_mask is set, and fewer dimensions + // are specified than the number of input dimensions, then the batch dimension + // is not modified Otherwise we must check whether the batch dimension is + // modified. + if (params->use_implicit_batch && + !((ellipsis_mask & 1) && + begin_weights.Shape().NumDims() < input_shape.dims())) { + // Check that batch dimension is unmodified. We need to use the expanded + // begin/end/strides array since the original array may be incorrect when + // (ellipsis_mask&1)==1. + const bool begin_is_modified = !(begin_mask & 1) && (begin[0] != 0); + const bool stride_is_modified = (strides[0] != 1); + // If the batch size is -1 and the end mask is not set, we can only know if + // the batch dimension is unmodified when the batch size is defined. When + // the batch size is undefined, we don't convert to be safe. + const bool batch_size_is_defined = (input_shape.dim_size(0) > 0); + const bool end_is_modified = + !(end_mask & 1) && + (!batch_size_is_defined || (end[0] != input_shape.dim_size(0))); + if (begin_is_modified || stride_is_modified || end_is_modified) { + return errors::Unimplemented( + "TensorRT does not allow modifications to the batch dimension"); + } + } + + // shrink_axis_mask requires a reshape after the slice. + std::optional final_shape_dims = std::nullopt; + if (shrink_axis_mask) { + final_shape_dims.emplace(); + auto dims_adap = + DimsAdapter::Create(final_shape, params->use_implicit_batch); + TRT_ENSURE_OK(dims_adap); + *final_shape_dims = dims_adap->AsTrtDims(); + } + + return ConvertStridedSliceHelper(params, inputs.at(0), input_shape, begin, + strides, end, final_shape_dims, 0, + strided_slice_spec); +} + +Status ConvertConv2D(const OpConverterParams* params) { + return ConvertConv2DHelper(params, 1, /*is_conv2d_backprop_input=*/false); +} + +Status ConvertConv2DDepthwise(const OpConverterParams* params) { + return ConvertConv2DHelper(params, 0, /*is_conv2d_backprop_input=*/false); +} + +Status ConvertConv2DBackpropInput(const OpConverterParams* params) { + return ConvertConv2DHelper(params, 1, /*is_conv2d_backprop_input=*/true); +} + +Status ConvertConv3DHelper(const OpConverterParams* params, int group, + bool is_conv3d_backprop_input = false) { + const int kNumDims = 5; + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TRT_TensorOrWeights backprop_output_size; + ITensorProxyPtr tensor = nullptr; + if (is_conv3d_backprop_input) { + // In the case when Conv3dBackpropInput is used for conv3d_transpose, these + // inputs correspond to: output size, filter, and input. + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"input_sizes", true}, {"filter", true}, {"out_backprop", false}})); + backprop_output_size = inputs.at(0); + tensor = inputs.at(2).tensor(); + } else { + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"input", false}, {"filter", true}})); + tensor = inputs.at(0).tensor(); + } + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + const TRT_ShapedWeights weights_drsck = inputs.at(1).weights(); + if (weights_drsck.Shape().NumDims() != kNumDims) { + return errors::InvalidArgument("Conv3D expects kernel of dimension 5"); + } + + string data_format, padding_type; + std::vector tf_dilations, tf_stride; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "padding", &padding_type)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "dilations", &tf_dilations)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "strides", &tf_stride)); + + const bool is_ndhwc = (data_format == "NDHWC"); // Or NCDHW 01234 - > 02341 + const int d_index = is_ndhwc ? 1 : 2; + const int h_index = is_ndhwc ? 2 : 3; + const int w_index = is_ndhwc ? 3 : 4; + const int c_index = is_ndhwc ? 4 : 1; + if (tf_dilations.size() != kNumDims) { + return errors::InvalidArgument( + "Convolution dilations field must specify 5 dimensions"); + } + if (tf_dilations[0] != 1 || tf_dilations[c_index] != 1) { + return errors::Unimplemented( + "Dilation rate must be 1 for batch and channel dimensions"); + } + + const nvinfer1::Dims3 dilation_dhw( + tf_dilations[d_index], tf_dilations[h_index], tf_dilations[w_index]); + if (is_conv3d_backprop_input && + (dilation_dhw.d[0] != 1 || dilation_dhw.d[1] != 1 || + dilation_dhw.d[2] != 1)) { + return errors::Unimplemented( + "Dilation with Conv3DBackpropInputV2 (conv3d_transpose) is not " + "supported"); + } + + if (tf_stride.size() != kNumDims) { + return errors::InvalidArgument( + "Convolution strides field must specify 5 dimensions"); + } + if (tf_stride[0] != 1 || tf_stride[c_index] != 1) { + return errors::Unimplemented( + "Stride must be 1 for batch and channel dimensions"); + } + + const nvinfer1::Dims3 stride_dhw(tf_stride[d_index], tf_stride[h_index], + tf_stride[w_index]); + const auto tensor_dim = tensor->getDimensions(); + + // Asymmetric padding on Deconv not supported for now + if (is_conv3d_backprop_input && padding_type == "SAME") { + StatusOr weights = + params->weight_store->GetTempWeights(weights_drsck); + TRT_ENSURE_OK(weights); + nvinfer1::Dims3 effective_kernel_size( + weights->Shape().dim(0) + + (weights->Shape().dim(0) - 1) * (dilation_dhw.d[0] - 1), // D + weights->Shape().dim(1) + + (weights->Shape().dim(1) - 1) * (dilation_dhw.d[1] - 1), // R + weights->Shape().dim(2) + + (weights->Shape().dim(2) - 1) * (dilation_dhw.d[2] - 1) // S + ); + + const auto output_size_weights = + backprop_output_size.weights().GetPointer(); + const std::vector input_dims = {output_size_weights[d_index], + output_size_weights[h_index], + output_size_weights[w_index]}; + + const std::vector> padding = + CreateSamePadding(stride_dhw, effective_kernel_size, input_dims); + + if (padding[0].first != padding[0].second || + padding[1].first != padding[1].second || + padding[2].first != padding[2].second) { + return errors::Unimplemented( + "Asymmetric padding with Conv3DBackpropInputV2 (conv3d_transpose) is " + "not supported"); + } + } + + // Channel dim must be static for Conv3D since we use that value for + // num_groups at build time. + // TODO: Allow conversion if kImplicitBatchModeCompatible||kOptimal is used. + int implicit_batch_offset = params->use_implicit_batch ? -1 : 0; + if (tensor->getDimensions().d[c_index + implicit_batch_offset] == -1) { + return errors::InvalidArgument("Channel dimension must be static"); + } + + // Finished validation checks + if (params->validation_only) return OkStatus(); + + // Transpose to NCDHW (NCDHW is required for IConvLayer). + const bool need_transpose = is_ndhwc; + if (need_transpose) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + tensor, {0, 4, 1, 2, 3}, &tensor, node_def, "to_NCDHW")); + } + + // group == 0 signifies that this is a depthwise convolution, so set + // num_groups to size of input's channel dim. For a non-depthwise conv, + // num_groups will be 1. + const int num_groups = (group == 0) ? tensor_dim.d[0] : group; + + // For conv, TF weights are DRSCK, and TRT expects KCDRS. + // For backprop, TF weights are DRSKC, and TRT expects KCDRS. + // Therefore, this reorder will work for both cases. + StatusOr weights = + params->weight_store->GetTempWeights(weights_drsck); + TRT_ENSURE_OK(weights); + ReorderDRSCKToKCDRS(weights_drsck, &*weights, num_groups); + TRT_ShapedWeights biases(weights->TrtDType()); + const int output_axis = is_conv3d_backprop_input ? 1 : 0; + const int noutput = weights->Shape().dim(output_axis) * num_groups; + nvinfer1::Dims3 kernel_size_drs(weights->Shape().dim(2), // D + weights->Shape().dim(3), // R + weights->Shape().dim(4) // S + ); + + // Add convolution. + nvinfer1::ILayer* conv_layer = nullptr; + if (is_conv3d_backprop_input) { + nvinfer1::IDeconvolutionLayer* layer = + params->converter->network()->addDeconvolutionNd( + *tensor->trt_tensor(), noutput, kernel_size_drs, + weights->GetTrtWeights(), biases.GetTrtWeights()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + layer->setStrideNd(stride_dhw); // change to nd set stride + + if (padding_type == "SAME") { + VLOG(2) << "Using SAME padding"; + // SAME_UPPER means that post padding is preferred. + layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + + layer->setNbGroups(num_groups); + conv_layer = layer; + } else { + nvinfer1::IConvolutionLayer* layer = + params->converter->network()->addConvolutionNd( + *tensor->trt_tensor(), noutput, kernel_size_drs, + weights->GetTrtWeights(), biases.GetTrtWeights()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + layer->setStrideNd(stride_dhw); + + if (padding_type == "SAME") { + VLOG(2) << "Using SAME padding"; + layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + + layer->setNbGroups(num_groups); + layer->setDilationNd(dilation_dhw); + conv_layer = layer; + } + params->converter->SetLayerName(conv_layer, node_def, "conv"); + ITensorProxyPtr output_tensor = conv_layer->getOutput(0); + + // Restore transpose. + if (need_transpose) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output_tensor, {0, 2, 3, 4, 1}, &output_tensor, node_def, "to_NDHWC")); + } + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertConv3D(const OpConverterParams* params) { + return ConvertConv3DHelper(params, 1, /*is_conv3d_backprop_input=*/false); +} + +Status ConvertConv3DBackpropInputV2(const OpConverterParams* params) { + return ConvertConv3DHelper(params, 1, /*is_conv3d_backprop_input=*/true); +} + +Status ConvertPool3D(const OpConverterParams* params) { + const int kNumDims = 5; + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"input", false}})); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + nvinfer1::PoolingType type; + if (node_def.op() == "MaxPool3D") { + type = nvinfer1::PoolingType::kMAX; + } else if (node_def.op() == "AvgPool3D") { + type = nvinfer1::PoolingType::kAVERAGE; + } else { + return errors::Unimplemented("Unsupported pooling type: ", node_def.op()); + } + + string data_format, padding_type; + std::vector tf_stride, tf_kernel; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "padding", &padding_type)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "strides", &tf_stride)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "ksize", &tf_kernel)); + + if ((padding_type != "SAME") && (padding_type != "VALID")) { + return errors::Unimplemented("Unsupported padding type: ", padding_type); + } + + const bool is_ndhwc = (data_format == "NDHWC"); + const int c_index = is_ndhwc ? 4 : 1; + const int d_index = is_ndhwc ? 1 : 2; + const int h_index = is_ndhwc ? 2 : 3; + const int w_index = is_ndhwc ? 3 : 4; + + if (tf_stride.size() != kNumDims) { + return errors::InvalidArgument( + "Pooling strides field must specify 5 dimensions"); + } + if (tf_stride[0] != 1 || tf_stride[c_index] != 1) { + return errors::Unimplemented( + "stride must be 1 for batch and channel dimensions"); + } + + if (tf_kernel.size() != kNumDims) { + return errors::InvalidArgument( + "Pooling ksize field must specify 5 dimensions"); + } + if (tf_kernel[0] != 1 || tf_kernel[c_index] != 1) { + return errors::Unimplemented( + "ksize must be 1 for batch and channel dimensions"); + } + + const nvinfer1::Dims3 stride(tf_stride[d_index], tf_stride[h_index], + tf_stride[w_index]); + const nvinfer1::Dims3 ksize(tf_kernel[d_index], tf_kernel[h_index], + tf_kernel[w_index]); + + if (!(ksize.nbDims >= 3 && + (ksize.d[0] >= 1 && ksize.d[1] >= 1 && ksize.d[2] >= 1) && + (ksize.d[0] * ksize.d[1] * ksize.d[2] < MAX_KERNEL_DIMS_PRODUCT(3)))) { + return errors::InvalidArgument("Window dimensions are not within bounds"); + } + if (params->validation_only) return OkStatus(); + + ITensorProxyPtr tensor = inputs.at(0).tensor(); + if (data_format == "NDHWC") { + // NDHWC => NCDHW + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + tensor, {0, 4, 1, 2, 3}, &tensor, node_def, "to_NCDHW")); + } + + nvinfer1::IPoolingLayer* layer = params->converter->network()->addPoolingNd( + *tensor->trt_tensor(), type, ksize); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + + layer->setStrideNd(stride); + // VALID padding is the default TRT behavior. + if (padding_type == "SAME") { + // SAME_UPPER means that post padding is preferred. + layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + params->converter->SetLayerName(layer, node_def, "pooling"); + + ITensorProxyPtr output_tensor = layer->getOutput(0); + if (data_format == "NDHWC") { + // NCDHW => NDHWC + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output_tensor, {0, 2, 3, 4, 1}, &output_tensor, node_def, "to_NDHWC")); + } + + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertFusedConv2DBiasActivation(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"input", false}, + {"filter", true}, + {"bias", true}, + {"side_input", true}, + {"conv_input_scale", true}, + {"side_input_scale", true}})); + ITensorProxyPtr tensor = inputs.at(0).tensor(); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + TRT_ShapedWeights weights = inputs.at(1).weights(); + if (weights.Shape().NumDims() != 4) { + return errors::InvalidArgument( + "FusedConv2DBiasActivation expects kernel of dimension 4"); + } + + string data_format, filter_format, activation_mode, padding_type; + std::vector tf_dilations, tf_stride; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "filter_format", &filter_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "activation_mode", &activation_mode)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "padding", &padding_type)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "dilations", &tf_dilations)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "strides", &tf_stride)); + + if (data_format != "NHWC" && data_format != "NCHW") { + return errors::InvalidArgument("Unsupported data_format:", data_format); + } + int c_index = (data_format == "NHWC") ? 3 : 1; + int h_index = (data_format == "NHWC") ? 1 : 2; + int w_index = (data_format == "NHWC") ? 2 : 3; + + if (tf_dilations.size() != 4) { + return errors::InvalidArgument( + "Convolution dilations field must specify 4 dimensions"); + } + if (tf_dilations[0] != 1 || tf_dilations[c_index] != 1) { + return errors::Unimplemented( + "Dilation rate must be 1 for batch and channel dimensions"); + } + const nvinfer1::DimsHW dilation(tf_dilations[h_index], tf_dilations[w_index]); + + if (tf_stride.size() != 4) { + return errors::InvalidArgument( + "Convolution strides field must specify 4 dimensions"); + } + if (tf_stride[0] != 1 || tf_stride[c_index] != 1) { + return errors::Unimplemented( + "Stride must be 1 for batch and channel dimensions"); + } + const nvinfer1::DimsHW stride(tf_stride[h_index], tf_stride[w_index]); + auto op_pair = ActivationTypeMap()->find(activation_mode); + if (op_pair == ActivationTypeMap()->end() && activation_mode != "None") { + return errors::Unimplemented("Activation mode not supported: ", + activation_mode); + } + + if (filter_format != "HWIO" && filter_format != "OIHW") { + return errors::InvalidArgument("Unsupported filter_format:", filter_format); + } + // Check that there's no side_input or conv_input_scale. + TRT_ShapedWeights side_input = inputs.at(3).weights(); + if (side_input.count() != 0) { + return errors::InvalidArgument( + "FusedConv2DBiasActivation doesn't yet support side_input"); + } + TRT_ShapedWeights conv_input_scale = inputs.at(4).weights(); + if (conv_input_scale.count() != 1 || + conv_input_scale.TrtDType() != nvinfer1::DataType::kFLOAT || + conv_input_scale.GetSpan()[0] != 1.0) { + return errors::InvalidArgument( + "FusedConv2DBiasActivation doesn't yet support conv_input_scale"); + } + if (params->validation_only) return OkStatus(); + + // Transpose to NCHW (NCHW is required for IConvLayer). + const bool need_transpose = (data_format == "NHWC"); + if (need_transpose) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + tensor, {0, 3, 1, 2}, &tensor, node_def, "to_NCHW")); + } + + nvinfer1::DimsHW kernel_size; + if (filter_format == "OIHW") { + kernel_size.h() = weights.Shape().dim(2); + kernel_size.w() = weights.Shape().dim(3); + } else { + // HWIO. + DCHECK_EQ(filter_format, "HWIO"); + kernel_size.h() = weights.Shape().dim(0); + kernel_size.w() = weights.Shape().dim(1); + } + + // Add convolution. + TRT_ShapedWeights biases = inputs.at(2).weights(); + nvinfer1::IConvolutionLayer* conv_layer = nullptr; + if (filter_format == "OIHW") { + // Weights are already in the right order. + conv_layer = params->converter->network()->addConvolution( + *tensor->trt_tensor(), weights.Shape().dim(0), kernel_size, + weights.GetTrtWeights(), biases.GetTrtWeights()); + } else { + // For conv, TF weights are RSCK, and TRT expects KCRS. + TRT_ENSURE(filter_format == "HWIO"); + StatusOr weights_kcrs = + params->weight_store->GetTempWeights(weights); + TRT_ENSURE_OK(weights_kcrs); + ReorderRSCKToKCRS(weights, &*weights_kcrs, 1); + conv_layer = params->converter->network()->addConvolution( + *tensor->trt_tensor(), weights.Shape().dim(3), kernel_size, + weights_kcrs->GetTrtWeights(), biases.GetTrtWeights()); + } + TFTRT_RETURN_ERROR_IF_NULLPTR(conv_layer, node_def.name()); + conv_layer->setStride(stride); + if (padding_type == "SAME") { + conv_layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + params->converter->SetLayerName(conv_layer, node_def, "conv"); + conv_layer->setNbGroups(1); + conv_layer->setDilation(dilation); + ITensorProxyPtr output_tensor = conv_layer->getOutput(0); + + // Add activation if there is one. + if (op_pair != ActivationTypeMap()->end()) { + nvinfer1::IActivationLayer* activation_layer = + params->converter->network()->addActivation( + *output_tensor->trt_tensor(), op_pair->second); + TFTRT_RETURN_ERROR_IF_NULLPTR(activation_layer, node_def.name()); + params->converter->SetLayerName(activation_layer, node_def, "activation"); + output_tensor = activation_layer->getOutput(0); + } + // Restore transpose. + if (need_transpose) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output_tensor, {0, 2, 3, 1}, &output_tensor, node_def, "to_NHWC")); + } + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertPool(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"input", false}})); + std::set allowed_types{DataType::DT_FLOAT, DataType::DT_HALF, + DataType::DT_INT8}; + TF_RETURN_IF_ERROR(AllowDataTypes(*params, allowed_types)); + nvinfer1::PoolingType type; + if (node_def.op() == "MaxPool") { + type = nvinfer1::PoolingType::kMAX; + } else if (node_def.op() == "AvgPool") { + type = nvinfer1::PoolingType::kAVERAGE; + } else { + return errors::Unimplemented("Unsupported pooling type: ", node_def.op()); + } + + string data_format, padding_type; + std::vector tf_stride, tf_kernel; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "padding", &padding_type)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "strides", &tf_stride)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "ksize", &tf_kernel)); + + if ((padding_type != "SAME") && (padding_type != "VALID")) { + return errors::Unimplemented("Unsupported padding type: ", padding_type); + } + + ITensorProxyPtr tensor = inputs.at(0).tensor(); + int h_index = 2; + int w_index = 3; + if (data_format == "NHWC") { + h_index = 1; + w_index = 2; + } + + const nvinfer1::DimsHW stride(tf_stride[h_index], tf_stride[w_index]); + const nvinfer1::DimsHW ksize(tf_kernel[h_index], tf_kernel[w_index]); + + if (!((ksize.h() >= 1 && ksize.w() >= 1) && + (ksize.h() * ksize.w() < MAX_KERNEL_DIMS_PRODUCT(2)))) { + return errors::InvalidArgument("Window dimensions are not within bounds"); + } + + if (params->validation_only) return OkStatus(); + + if (data_format == "NHWC") { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + tensor, {0, 3, 1, 2}, &tensor, node_def, "to_NCHW")); + } + + nvinfer1::IPoolingLayer* layer = params->converter->network()->addPooling( + *tensor->trt_tensor(), type, ksize); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + + layer->setStride(stride); + // VALID padding is the default TRT behavior. + if (padding_type == "SAME") { + // SAME_UPPER means that post padding is preferred. + layer->setPaddingMode(nvinfer1::PaddingMode::kSAME_UPPER); + } + params->converter->SetLayerName(layer, node_def, "pooling"); + ITensorProxyPtr output_tensor = layer->getOutput(0); + + if (data_format == "NHWC") { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output_tensor, {0, 2, 3, 1}, &output_tensor, node_def, "to_NHWC")); + } + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertClipByValue(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + // TODO(tmorris): We can also allow the case where min and max are tensors by + // using elementwise min and max layers. + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"t", false}, {"clip_value_min", true}, {"clip_value_max", true}})); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + if (params->validation_only) return OkStatus(); + + DataType dtype; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node_def), "T", &dtype)); + + float clip_value_min = 0.0f; + float clip_value_max = 0.0f; + // TODO(tmorris): Add a templated helper function to get scalar weights of + // InType casted to OutType. + if (dtype == DataType::DT_FLOAT) { + clip_value_min = inputs.at(1).weights().GetSpan()[0]; + clip_value_max = inputs.at(2).weights().GetSpan()[0]; + } else if (dtype == DataType::DT_HALF) { + clip_value_min = + static_cast(inputs.at(1).weights().GetSpan()[0]); + clip_value_max = + static_cast(inputs.at(2).weights().GetSpan()[0]); + } + + nvinfer1::IActivationLayer* layer = + params->converter->network()->addActivation( + *inputs.at(0).tensor()->trt_tensor(), + nvinfer1::ActivationType::kCLIP); + layer->setAlpha(clip_value_min); + layer->setBeta(clip_value_max); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def, "activation"); + params->outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0))); + return OkStatus(); +} + +Status ConvertBiasAdd(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TFTRT_CHECK_INPUT_SIZE(inputs.size(), 2, node_def); + + if (inputs[0].is_weights() && inputs[1].is_weights()) { + // TODO(lsugy): don't assume that if all inputs are weights, grappler + // should fold them, because variables are weights. + return errors::InvalidArgument( + "All inputs are weights, but Grappler is expected to fold them."); + } + + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + string data_format; + TF_RETURN_IF_ERROR( + GetNodeAttr(AttrSlice(node_def), "data_format", &data_format)); + + nvinfer1::Dims input_shape = inputs.at(0).GetTrtDims(); + nvinfer1::Dims bias_shape = inputs.at(1).GetTrtDims(); + // The bias input arg is a 1-D tensor with length C. If the input is NCHW, + // then we need to unsqueeze the bias such that its shape is [1, C, 1, 1]. + if (data_format == "NCHW") { + if (params->use_implicit_batch) { + // The batch dim is not included in implicit batch mode, so the shape of + // the bias tensor is [C, 1, 1]. + bias_shape.nbDims = input_shape.nbDims; + std::fill(bias_shape.d + 1, bias_shape.d + bias_shape.nbDims, 1); + } else { + // In explicit batch mode we create a tensor with shape [1, C, 1, 1]. + std::vector bias_shape_vec(bias_shape.d, + bias_shape.d + bias_shape.nbDims); + // Insert 1 before for batch dim + bias_shape_vec.insert(bias_shape_vec.begin(), 1); + // Trail with 1s to match input_shape size + bias_shape_vec.insert(bias_shape_vec.end(), + input_shape.nbDims - bias_shape_vec.size(), 1); + DimsAdapter(bias_shape_vec).TrtDims(&bias_shape); + } + } else { + // Next, broadcast the bias across the input. + TF_RETURN_IF_ERROR(GetTrtBroadcastShape(inputs.at(0), inputs.at(1), + /*check_feasibility=*/true, + params->use_implicit_batch, + &input_shape, &bias_shape)); + } + + // Convert input to a TRT tensor + ITensorProxyPtr input_tensor{nullptr}; + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, inputs.at(0), DimsAdapter(input_shape), + params->validation_only, &input_tensor, node_def, + /*op_instance=*/0)); + + // Finally, reshape bias. Since the bias is usually a constant, this will + // normally happen at conversion-time. + ITensorProxyPtr bias_tensor{nullptr}; + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, inputs.at(1), DimsAdapter(bias_shape), + params->validation_only, &bias_tensor, node_def, + /*op_instance=*/1)); + VLOG(2) << "Bias shape adjusted to " << DebugString(bias_shape); + + if (params->validation_only) return OkStatus(); + + nvinfer1::IElementWiseLayer* layer = + params->converter->network()->addElementWise( + *input_tensor->trt_tensor(), *bias_tensor->trt_tensor(), + nvinfer1::ElementWiseOperation::kSUM); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def, "sum"); + ITensorProxyPtr output_tensor = layer->getOutput(0); + + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +template +inline bool IsIntegerInInt32Bounds(const Input& inp) { + static_assert(std::is_integral::value, + "This function is only implemented for integral types."); + // If Input is always within the range of int32, return true. + if (sizeof(Input) < sizeof(int32) || std::is_same::value) { + return true; + } + // Otherwise, we need to check the value of the input. If the input is + // unsigned, we only check the upper bound. + if (!std::numeric_limits::is_signed) { + return inp <= static_cast(std::numeric_limits::max()); + } + // We can safely cast lowest() here since we now know that Input is signed and + // sizeof(Input) >= sizeof(int32) + return (inp >= static_cast(std::numeric_limits::lowest()) && + inp <= static_cast(std::numeric_limits::max())); +} + +template +Status CopyToTrtInt32Array(const Tensor& tensor, int32* dst) { + typedef typename EnumToDataType::Type CType; + const CType* src = tensor.flat().data(); + for (int i = 0; i < tensor.NumElements(); ++i) { + // This becomes a no-op if CType is within bounds of int32 + if (!IsIntegerInInt32Bounds(src[i])) { + return errors::InvalidArgument("Value at index ", i, + " is outside the range of int32"); + } + dst[i] = static_cast(src[i]); + } + return OkStatus(); +} + +Status TfTensorToTrtWeights(const Tensor& tensor, TrtWeightStore* weight_store, + TRT_ShapedWeights* weights) { + const DataType dtype = tensor.dtype(); + + // We always convert the integer constants to INT32. + // + // TODO(aaroey): FP16 will remain in half format and is not converted to + // FP32, but the converter currently uses all float weights as FP32. Fix + // this. + DataType converted_dtype = DataTypeIsInteger(dtype) ? DT_INT32 : dtype; + + // Verify that the dtype is supported by TensorRT. Otherwise, return an error. + nvinfer1::DataType trt_dtype; + TF_RETURN_IF_ERROR(TfTypeToTrtType(converted_dtype, &trt_dtype)); + + if (tensor.NumElements() == 0) { + // Return empty weights. + *weights = TRT_ShapedWeights(trt_dtype); + return OkStatus(); + } + + StatusOr weight_dims = DimsAdapter::Create(tensor.shape()); + TRT_ENSURE_OK(weight_dims); + + auto tmp = weight_store->GetTempWeights(trt_dtype, weight_dims->AsTrtDims()); + TRT_ENSURE_OK(tmp); + *weights = std::move(tmp).value(); + + // Copy the tensor directly if the tensor does not require cast to the + // supported type. + if (converted_dtype == dtype) { + std::copy_n(tensor.tensor_data().data(), tensor.TotalBytes(), + weights->GetPointer()); + return OkStatus(); + } + + Status status = OkStatus(); + // Copy tensor elements after casting them to the converted DataType. + int32* dst = weights->GetPointer(); + switch (dtype) { + case DT_INT8: + status = CopyToTrtInt32Array(tensor, dst); + break; + case DT_UINT8: + status = CopyToTrtInt32Array(tensor, dst); + break; + case DT_INT16: + status = CopyToTrtInt32Array(tensor, dst); + break; + case DT_UINT16: + status = CopyToTrtInt32Array(tensor, dst); + break; + case DT_UINT32: + status = CopyToTrtInt32Array(tensor, dst); + break; + case DT_INT64: + status = CopyToTrtInt32Array(tensor, dst); + break; + case DT_UINT64: + status = CopyToTrtInt32Array(tensor, dst); + break; + default: + return errors::Internal("Unexpected DataType: ", DataTypeString(dtype)); + } + return status; +} + +// Convert a Const NodeDef to TRT_ShapedWeights. This is a special converter, it +// always ignores the params->validation_only parameter but adds the converted +// weights to params->outputs. We did this since TrtNodeValidator needs the +// weights as input to other nodes, and use it to determine whether those nodes +// are supported by TRT. +Status ConvertConst(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + if (!inputs.empty()) { + return errors::InvalidArgument( + "Constant node is expected to have empty input list"); + } + + // Create shaped weights as output + const auto& tensor_proto = node_def.attr().at("value").tensor(); + Tensor tensor; + if (!tensor.FromProto(tensor_proto)) { + return errors::Internal("Cannot parse weight tensor proto: ", + node_def.name()); + } + + DataType dtype; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node_def), "dtype", &dtype)); + + if (dtype != tensor.dtype()) { + return errors::InvalidArgument("DataType mismatch between attr (", + DataTypeString(dtype), ") and tensor (", + DataTypeString(tensor.dtype()), ")"); + } + + TRT_ShapedWeights weights; + TF_RETURN_IF_ERROR( + TfTensorToTrtWeights(tensor, params->weight_store, &weights)); + + if (params->outputs != nullptr) { + params->outputs->push_back(TRT_TensorOrWeights(weights)); + } + return OkStatus(); +} + +Status ConvertIdentity(const OpConverterParams* params) { + // TODO(tmorris): TRT's Identity layer does not get optimized away as of TRT + // 5.0, however once we know that it does it would be nice to use that + // instead. + if (params->validation_only) return OkStatus(); + + for (int i = 0; i < params->inputs.size(); i++) { + params->outputs->push_back(params->inputs.at(i)); + } + return OkStatus(); +} + +// This converter is a debug-only feature designed to allow graph segmentation +// experiments. Its use is being controlled by +// `TF_TRT_OP_FAKELIST=OpName1,OpName2,...`. +// See `op_converter_registry.cc` for further details. +// +// This converter is designed as followed: +// - always succeed at graph segmentation time. +// - always fail at TRT Engine build time. +Status ConvertFake(const OpConverterParams* params) { + if (params->validation_only) return OkStatus(); + + return errors::Unimplemented( + "This converter is not valid after graph " + "segmentation. Building an engine using this " + "converter will trigger a native segment " + "fallback."); +} + +Status ConvertSquare(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"x", false}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + if (params->validation_only) return OkStatus(); + + // Constant 2 with same rank as input + ITensorProxyPtr const2_tensor = nullptr; + TF_RETURN_IF_ERROR(CreateBroadcastableScalarConstant( + params, 2.0f, inputs.at(0).GetTrtDims(), &const2_tensor)); + + // ElementWise Pow Operation + nvinfer1::IElementWiseLayer* layer = + params->converter->network()->addElementWise( + *inputs.at(0).tensor()->trt_tensor(), *const2_tensor->trt_tensor(), + nvinfer1::ElementWiseOperation::kPOW); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + ITensorProxyPtr output_tensor = layer->getOutput(0); + + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertReduce(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"input", false}, {"axis", true}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + + ITensorProxyPtr tensor = inputs.at(0).tensor(); + auto tf_axes_list = inputs.at(1).weights().GetSpan(); + + DataType idx_dtype{DataType::DT_INT32}; + bool keep_dims{false}; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "Tidx", &idx_dtype)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "keep_dims", &keep_dims)); + + // Only expect to handle INT32 as attributes for now + if (idx_dtype != DataType::DT_INT32) { + return errors::Unimplemented("Tidx supports only DT_INT32"); + } + + int axes = 0; + if (tf_axes_list.size() == 0) { + return errors::InvalidArgument( + "TRT cannot support reduce on all (batch) dimensions"); + } + for (int i = 0; i < tf_axes_list.size(); i++) { + int trt_axis; + TF_RETURN_IF_ERROR( + ConvertAxis(tf_axes_list[i], tensor->getDimensions().nbDims, + node_def.name(), params->use_implicit_batch, &trt_axis)); + axes |= (1 << trt_axis); + } + + nvinfer1::ReduceOperation reduce_operation; + if (node_def.op() == "Sum") { + reduce_operation = nvinfer1::ReduceOperation::kSUM; + } else if (node_def.op() == "Prod") { + reduce_operation = nvinfer1::ReduceOperation::kPROD; + } else if (node_def.op() == "Max") { + reduce_operation = nvinfer1::ReduceOperation::kMAX; + } else if (node_def.op() == "Min") { + reduce_operation = nvinfer1::ReduceOperation::kMIN; + } else if (node_def.op() == "Mean") { + reduce_operation = nvinfer1::ReduceOperation::kAVG; + } else { + return errors::Unimplemented("Op not supported ", node_def.op()); + } + if (params->validation_only) return OkStatus(); + + nvinfer1::ILayer* layer = params->converter->network()->addReduce( + *tensor->trt_tensor(), reduce_operation, axes, keep_dims); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + + params->outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0))); + return OkStatus(); +} + +// TensorRT does not support the Pack op natively. Therefore, Pack op is +// converted by first expanding input tensors by adding a new dimension of size +// one at the specified axis and then concatenating the tensors at the same +// axis. +Status ConvertPack(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + + int num_inputs{0}; + int64_t tf_axis{0}; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "N", &num_inputs)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "axis", &tf_axis)); + + if (num_inputs != inputs.size()) { + return errors::InvalidArgument( + "Number of inputs for Pack is inconsistent with N attribute"); + } + + // In implicit batch mode we do not allow weight input. An input tensor with + // dims NCHW is represented with dims CHW during conversion time, and N is + // defined only during runtime. A weight is represented with dims NCHW. We + // cannot be sure that the runtime N will agree with the conversion time N, + // therefore we do not convert the pack op if it has both tensor and weight + // inputs. This restriction does not apply in explicit batch mode, in that + // case the input tensors are also represented with full dims that include the + // batch size. + TrtInputArg expected_arg = + params->use_implicit_batch ? TrtInputArg::kTensor : TrtInputArg::kBoth; + + std::vector> inputs_is_weight; + inputs_is_weight.reserve(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + inputs_is_weight.push_back({StrCat("values_", i), expected_arg}); + } + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, inputs_is_weight)); + + std::set allowed_types{DataType::DT_FLOAT, DataType::DT_HALF, + DataType::DT_INT32}; + TF_RETURN_IF_ERROR(AllowDataTypes(*params, allowed_types)); + if (num_inputs > 1) { + // Verify that inputs are compatible for concatenation after the expansion. + TF_RETURN_IF_ERROR( + VerifyShapesMatch(inputs, /*masked_dim=*/-1, node_def.name())); + } + + // Find the dimension of the inputs. In general inputs can have dynamic shape, + // in that case we have to use DynamicExpandDims to calculate the expanded + // dimensions. To avoid that, we try to find a weight input which is + // guaranteed to have known static shape. + int idx = 0; + for (int i = 1; i < inputs.size(); i++) { + if (HasStaticShape(inputs.at(i).GetTrtDims())) { + idx = i; + } + } + DimsAdapter dims(inputs.at(idx).GetTrtDims()); + // Convert axis from the TensorFlow format to TensorRT format. + int trt_axis{0}; + TF_RETURN_IF_ERROR(ConvertAxis(tf_axis, dims.NumDims() + 1, node_def.name(), + params->use_implicit_batch, &trt_axis)); + + // Compute expanded dimensions and then reshape input tensors. + std::vector tensor_dims(dims.begin(), dims.end()); + tensor_dims.insert(tensor_dims.begin() + trt_axis, 1); + std::vector expanded_tensors; + + int input_index = 0; + for (const TRT_TensorOrWeights& input : inputs) { + ITensorProxyPtr expanded_tensor = nullptr; + if (input.is_tensor() && !params->use_implicit_batch && + !HasStaticShape(dims)) { + if (!params->validation_only) { + TF_RETURN_IF_ERROR(params->converter->DynamicExpandDims( + /*input=*/input.tensor(), + /*dims=*/dims.AsTrtDims(), + /*axis=*/trt_axis, + /*params=*/params, + /*output=*/&expanded_tensor, + /*op_instance=*/input_index)); + } + } else { + TF_RETURN_IF_ERROR(PrepareTensorForShape( + /*converter=*/params->converter, + /*input=*/input, + /*dims=*/DimsAdapter(tensor_dims), + /*validation_only=*/params->validation_only, + /*tensor=*/&expanded_tensor, + /*node_def=*/node_def, + /*op_instance=*/input_index)); + } + if (!params->validation_only) { + expanded_tensors.push_back(expanded_tensor); + } + input_index++; + } + if (params->validation_only) return OkStatus(); + + // If there is only one tensor in the input, return the expanded tensor. + if (num_inputs == 1) { + params->outputs->push_back(TRT_TensorOrWeights(expanded_tensors[0])); + return OkStatus(); + } + + // Otherwise, concatenate expanded tensors. + std::vector trt_expanded_tensors; + for (const auto& t : expanded_tensors) { + trt_expanded_tensors.push_back(t->trt_tensor()); + } + nvinfer1::IConcatenationLayer* layer = + params->converter->network()->addConcatenation( + static_cast(trt_expanded_tensors.data()), + expanded_tensors.size()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def, "concat"); + // Note that trt_axis stays the same even after expanding tensors at the axis. + layer->setAxis(trt_axis); + params->outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0))); + return OkStatus(); +} + +Status ConvertPad(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"tensor", false}, {"paddings", true}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT8})); + + // Implement tensor binaryOp weight [channel wise] for now; + ITensorProxyPtr tensor = inputs.at(0).tensor(); + const auto dims = tensor->getDimensions(); + // Restore implicit batch dimension + const int nb_dims = + params->use_implicit_batch ? dims.nbDims + 1 : dims.nbDims; + + // TODO(tfeher): Support nb_dims < 4 by inserting extra dimensions to the + // original input. + if (nb_dims < 4) { + return errors::InvalidArgument("Convertpad requires at least 4D input"); + } + TRT_ShapedWeights pads = inputs.at(1).weights(); + + // TODO(jie): handle data type conversion for TRT? + DataType padding_dtype{DataType::DT_INT32}; + TF_RETURN_IF_ERROR( + GetNodeAttr(AttrSlice(node_def), "Tpaddings", &padding_dtype)); + + if (pads.Shape().dim(0) != nb_dims || pads.Shape().dim(1) != 2) { + return errors::InvalidArgument("Paddings must be a weight with shape ", + "[n, 2], where n is the rank of input ", + "tensor"); + } + + // Only expect to handle INT32 as attributes for now + if (padding_dtype != DataType::DT_INT32) { + return errors::Unimplemented("Tpaddings supports only DT_INT32"); + } + auto pad_data = pads.GetPointer(); + + std::vector tf_pad_index; + for (int i = 0; i < nb_dims; i++) { + if (pad_data[2 * i] != 0 || pad_data[2 * i + 1] != 0) { + tf_pad_index.push_back(i); + } + } + + // No padding at all, we should exit + if (tf_pad_index.empty()) { + params->outputs->push_back(inputs.at(0)); + return OkStatus(); + } + + // TRT pad layer can only support padding on up to 2 dimensions (TRT-2579). + // TODO(tfeher): Use multiple TRT pad layers to support padding on more than 2 + // dimensions. + if (tf_pad_index.size() > 2) { + return errors::InvalidArgument( + "Padding layer does not support padding on > 2"); + } + + // Padding on batch dimension is not supported + if (params->use_implicit_batch && tf_pad_index[0] == 0) { + return errors::InvalidArgument( + "Padding layer does not support padding on batch dimension"); + } + + if (params->validation_only) return OkStatus(); + + // TRT can only do the padding at the last two dimensions. We transpose the + // input tensor if needed. + bool transposed_pad = false; + std::vector transpose_idx(nb_dims); + std::iota(transpose_idx.begin(), transpose_idx.end(), 0); + + // trt_pad_index denotes the actual idx where the padding is performed by TRT. + std::vector trt_pad_index{nb_dims - 2, nb_dims - 1}; + + // How many zeros are padded at the last two dimensions. + nvinfer1::DimsHW pre_padding(0, 0); + nvinfer1::DimsHW post_padding(0, 0); + + // Dimension to set in the pre_padding and post_padding array. + std::vector trt_pre_post_padding_index{0, 1}; + + // Two special cases where we can avoid permutations. + if (tf_pad_index.size() == 1 && tf_pad_index[0] == nb_dims - 1) { + // Only one dimension needs to be padded. We store its index at + // trt_pad_index[0]. We ignore trt_pad_index[1]. + trt_pad_index[0] = nb_dims - 1; + trt_pre_post_padding_index[0] = 1; + } + if (tf_pad_index.size() == 2 && tf_pad_index[1] == nb_dims - 2) { + // tf_pad_index only has two values that are in ascending order. If + // tf_pad_index[1] is nb_dims-2, then swapping the two values in + // trt_pad_index here makes it possible to only swap one pair of dimensions + // (swap tf_pad_index[0] with nb_dims-1) in the input tensor. Otherwise, we + // would have to swap two pairs of dimensions in the input tensor: + // (tf_pad_index[0] with nb_dims-2) and (tf_pad_index[1], with nb_dims-1). + // Here is an example for a 4D input tensor: + // tf_pad_index = [1, 2] + // trt_pad_index = [3, 2] + // transpose_idx = [0, 3, 2, 1] + std::swap(trt_pad_index[0], trt_pad_index[1]); + std::swap(trt_pre_post_padding_index[0], trt_pre_post_padding_index[1]); + } + + for (int i = 0; i < tf_pad_index.size(); i++) { + const int tf_index = tf_pad_index[i]; + const int trt_index = trt_pad_index[i]; + const int k = trt_pre_post_padding_index[i]; + pre_padding.d[k] = pad_data[tf_index * 2]; + post_padding.d[k] = pad_data[tf_index * 2 + 1]; + if (tf_index != trt_index) { + transposed_pad = true; + std::swap(transpose_idx[tf_index], transpose_idx[trt_index]); + } + } + + if (transposed_pad) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + tensor, transpose_idx, &tensor, node_def, "to_pad")); + } + + nvinfer1::IPaddingLayer* layer = params->converter->network()->addPadding( + *tensor->trt_tensor(), pre_padding, post_padding); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + ITensorProxyPtr output_tensor = layer->getOutput(0); + + if (transposed_pad) { + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output_tensor, transpose_idx, &output_tensor, node_def, "from_pad")); + } + + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertSplitHelper(const OpConverterParams* params, + const TRT_TensorOrWeights& input, int tf_axis, + int num_splits, bool squeeze_after) { + const auto& node_def = params->node_def; + const nvinfer1::Dims dims = input.GetTrtDims(); + // Convert axis. + int trt_axis; + TF_RETURN_IF_ERROR(ConvertAxis(tf_axis, dims.nbDims, node_def.name(), + params->use_implicit_batch, &trt_axis)); + + if (dims.d[trt_axis] < 0) { + return errors::InvalidArgument("Dimension ", tf_axis, + " must have statically defined dimensions"); + } + + // Dimension must equal num_splits for Unstack (when squeeze_after is true) + if (squeeze_after && dims.d[trt_axis] != num_splits) { + return errors::InvalidArgument( + "Dimension ", tf_axis, " has size ", dims.d[trt_axis], + " which is not equal to num of ", num_splits); + } + // Dimension must be evenly divisible by num_splits. + if (dims.d[trt_axis] % num_splits != 0) { + return errors::InvalidArgument("Dimension ", tf_axis, " of size ", + dims.d[trt_axis], + " is not evenly divisible by ", num_splits); + } + + // Create parameters for StridedSliceHelper. + // Slice will begin on zero for all dims, except the one being split which + // will change. + std::vector begin(dims.nbDims, 0); + std::vector input_dims(dims.d, dims.d + dims.nbDims); + + // Determine size of split. Slice will get the full length of all dims, except + // the one being split. Undefined dims (-1) will translate to a size of -1 + // which will tell StridedSlice to take full length of that dim. + std::vector size(dims.d, dims.d + dims.nbDims); + const int split_size_on_axis = dims.d[trt_axis] / num_splits; + size[trt_axis] = split_size_on_axis; + // Stride will always be 1 + std::vector stride(dims.nbDims, 1); + // Add dummy batch dimension + if (params->use_implicit_batch) { + begin.insert(begin.begin(), 0); + size.insert(size.begin(), 1); + stride.insert(stride.begin(), 1); + input_dims.insert(input_dims.begin(), std::max(-1, input.batch_size())); + } + PartialTensorShape input_shape(input_dims); + + // Create final shape for Unpack/Unstack, where split axis is squeezed. + std::optional final_shape_for_unpack = std::nullopt; + + // We can't use final_shape_for_unpack_ptr when input dimensions are not + // fully defined. + const bool is_dynamic_shape = !HasStaticShape(dims); + if (squeeze_after && !is_dynamic_shape) { + std::vector size_after_squeeze(size); + const int tf_axis = trt_axis + (params->use_implicit_batch ? 1 : 0); + size_after_squeeze.erase(size_after_squeeze.begin() + tf_axis); + DimsAdapter adap(size_after_squeeze); + if (params->use_implicit_batch) + TF_RETURN_IF_ERROR(adap.RemoveBatchDimension()); + final_shape_for_unpack = adap.AsTrtDims(); + } + + // Slice the input. ConvertStridedSliceHelper will push the outputs onto + // params->outputs. + for (int i = 0; i < num_splits; ++i) { + const int tf_axis = trt_axis + (params->use_implicit_batch ? 1 : 0); + begin[tf_axis] = i * split_size_on_axis; + + // Stride is 1 for all dims. + absl::InlinedVector stride_v(begin.size(), 1); + absl::InlinedVector begin_v; + absl::InlinedVector end_v; + for (int i = 0; i < begin.size(); i++) { + end_v.push_back(begin[i] + size[i]); + begin_v.push_back(begin[i]); + } + + TF_RETURN_IF_ERROR(ConvertStridedSliceHelper( + params, input, input_shape, begin_v, stride_v, end_v, + final_shape_for_unpack, + /*op_instance=*/i, /*strided_slice_spec=*/std::nullopt)); + } + if (params->validation_only) return OkStatus(); + + // Squeeze for dynamic shapes + if (squeeze_after && is_dynamic_shape) { + for (int i = 0; i < params->outputs->size(); i++) { + ITensorProxyPtr output_tensor = nullptr; + std::vector in_dims(dims.d, dims.d + dims.nbDims); + input_dims[trt_axis] = 0; + TF_RETURN_IF_ERROR(params->converter->SqueezeTensor( + /*input=*/params->outputs->at(i).tensor(), + /*input_dims=*/&in_dims, + /*params=*/params, + /*output=*/&output_tensor, + /*op_instance=*/i)); + (*params->outputs)[i] = TRT_TensorOrWeights(output_tensor); + } + } + return OkStatus(); +} + +Status ConvertSplit(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"axis", true}, {"value", false}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + int tf_axis = inputs.at(0).weights().GetSpan()[0]; + + int num_split; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node_def), "num_split", &num_split)); + + return ConvertSplitHelper(params, inputs.at(1), tf_axis, num_split, false); +} + +Status ConvertUnpack(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"value", false}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + // Input must be rank 1 or higher, since we can't unpack on axis 0. + if (inputs.at(0).GetTrtDims().nbDims == 0) { + return errors::Unimplemented( + "Input \"value\" for Unpack must be rank 2 or greater"); + } + + int tf_axis = 0, num = 0; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "axis", &tf_axis)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "num", &num)); + + return ConvertSplitHelper(params, inputs.at(0), tf_axis, num, true); +} + +Status ConvertCast(const OpConverterParams* params) { + auto unsupport_cast_error = [&](string msg) { + return errors::Unimplemented("Cast op is not supported - ", msg); + }; + + if (isExperimentalFeatureActivated("reject_all_fp_cast_ops")) { + LOG(WARNING) << "`TF_TRT_EXPERIMENTAL_FEATURES=reject_all_fp_cast_ops`is " + << "meant as a workaround. If the Cast converter leads to any " + << "performance or accuracy regression, please open an issue " + << "on GitHub."; + return unsupport_cast_error( + "TF_TRT_EXPERIMENTAL_FEATURES=reject_all_fp_cast_ops has been defined"); + } + + std::set allowed_types{DataType::DT_FLOAT, DataType::DT_HALF}; + + DataType input_type; + TF_RETURN_IF_ERROR(GetInputTfType(*params, &input_type, 0)); + + if (allowed_types.find(input_type) == allowed_types.end()) { + return unsupport_cast_error( + StrCat("Allowed input dtypes: [", DataTypeString(DataType::DT_FLOAT), + ", ", DataTypeString(DataType::DT_HALF), + "]. Received: ", DataTypeString(input_type))); + } + + DataType output_type; + TF_RETURN_IF_ERROR(GetNodeDefTfType(params->node_def, &output_type, + kCastOutputTypeAttrName)); + + if (allowed_types.find(output_type) == allowed_types.end()) { + return unsupport_cast_error( + StrCat("Allowed output dtypes: [", DataTypeString(DataType::DT_FLOAT), + ", ", DataTypeString(DataType::DT_HALF), + "]. Received: ", DataTypeString(output_type))); + } + + return ConvertIdentity(params); +} + +Status ConvertConcat(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + + int num_inputs{0}; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node_def), "N", &num_inputs)); + + if (num_inputs != static_cast(inputs.size()) - 1) { + return errors::InvalidArgument( + "Number of inputs for ConcatV2 is inconsistent with N attributes."); + } + // Validate inputs. + std::vector> inputs_kinds; + TrtInputArg expected_input = + params->use_implicit_batch ? TrtInputArg::kTensor : TrtInputArg::kBoth; + + inputs_kinds.reserve(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + inputs_kinds.push_back({StrCat("values_", i), expected_input}); + } + inputs_kinds.push_back({"axis", TrtInputArg::kWeight}); + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, inputs_kinds)); + + std::set allowed_types{DataType::DT_FLOAT, DataType::DT_HALF, + DataType::DT_INT32}; + + TF_RETURN_IF_ERROR(AllowDataTypes(*params, allowed_types)); + const auto axis = inputs.at(num_inputs).weights().GetSpan(); + if (axis.size() != 1) { + return errors::InvalidArgument("Axis for ConcatV2 must be a scalar"); + } + int trt_axis = 0; + const auto dim = inputs.at(0).GetTrtDims(); + TF_RETURN_IF_ERROR(ConvertAxis(axis[0], dim.nbDims, node_def.name(), + params->use_implicit_batch, &trt_axis)); + // Check that dimensions match on non-concatenate axis. + TF_RETURN_IF_ERROR(VerifyShapesMatch( + absl::Span(inputs).first(num_inputs), trt_axis, + node_def.name())); + if (params->validation_only) return OkStatus(); + + // Gather inputs as tensors + std::vector input_tensors; + input_tensors.reserve(num_inputs); + + for (int i = 0; i < num_inputs; i++) { + if (inputs.at(i).is_tensor()) { + input_tensors.push_back(inputs.at(i).tensor()); + } else { + input_tensors.push_back(params->converter->CreateConstantLayer( + inputs.at(i).weights(), inputs.at(i).GetTrtDims())); + } + } + std::vector trt_input_tensors; + for (const auto& t : input_tensors) { + trt_input_tensors.push_back(t->trt_tensor()); + } + nvinfer1::IConcatenationLayer* layer = + params->converter->network()->addConcatenation( + static_cast(trt_input_tensors.data()), + input_tensors.size()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + layer->setAxis(trt_axis); + params->outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0))); + return OkStatus(); +} + +Status ConvertFusedBatchNorm(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"x", false}, + {"scale", true}, + {"offset", true}, + {"mean", true}, + {"variance", true}})); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + float epsilon{0.1f}; + string data_format; + bool is_training{false}; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "epsilon", &epsilon)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "is_training", &is_training)); + + if (is_training) { + // Trying to use batchnorm in training mode is a very common problem. + // Because the error message will only be printed in VLOG(1) by the + // segmenter, we issue a special warning so that users will actually see it. + LOG_WARNING_WITH_PREFIX + << node_def.op() << " only supports is_training=false. If you " + << "are using Keras, please call " + << "keras.backend.set_learning_phase(0) before constructing " + << "your model. At " << node_def.name(); + return errors::Unimplemented(node_def.op(), + " only supports is_training=false"); + } + ITensorProxyPtr tensor = inputs.at(0).tensor(); + if (!params->use_implicit_batch) { + // This check is to make sure that channel dimension is known during + // conversion. + // + // We check this only in explicit batch mode and reject an op with unknown + // channel dimension during segmentation. In implicit batch mode we have + // known shapes during conversion even though the shapes may not be known + // during segmentation (see the actual argument for input_shapes when + // ConvertGraphDefToEngine is called from TRTEngineOp::BuildEngine). + int channel_dim = (data_format == "NCHW" ? 1 : 3); + if (tensor->getDimensions().d[channel_dim] == -1) { + return errors::InvalidArgument("Channel dimension must be static"); + } + } + // Check parameter types + auto parameter_type = inputs.at(1).weights().TrtDType(); + if ((parameter_type != nvinfer1::DataType::kFLOAT) && + (parameter_type != nvinfer1::DataType::kHALF)) { + return errors::Unimplemented( + "Only float32 or float16 weight data type is supported,", " got ", + DebugString(parameter_type)); + } + for (int i = 1; i < 5; i++) { + if (inputs.at(i).weights().TrtDType() != parameter_type) { + return errors::Unimplemented( + "Inconsistent parameter type for batchnorm is not supported"); + } + } + + TRT_ShapedWeights dummy_power_weights(parameter_type); + size_t nweight = 0; + for (int i = 1; i < 5; i++) { + nweight = std::max(nweight, inputs.at(i).weights().count()); + } + const TRT_ShapedWeights* ptr_shape_weights = nullptr; + for (int i = 1; i < 5; i++) { + if (inputs.at(i).weights().count() == nweight) { + ptr_shape_weights = &(inputs.at(i).weights()); + } else if (inputs.at(i).weights().count() != 1) { + return errors::InvalidArgument("Inconsistent batchnorm parameter count"); + } + } + if (params->validation_only) return OkStatus(); + + // We could technically have two weights with different shape. + // that requires two addScale op, arguably less performant + StatusOr combined_scale_weights = + params->weight_store->GetTempWeights(*ptr_shape_weights); + TRT_ENSURE_OK(combined_scale_weights); + StatusOr combined_offset_weights = + params->weight_store->GetTempWeights(*ptr_shape_weights); + TRT_ENSURE_OK(combined_offset_weights); + + const Eigen::half* cast_vals_array[4]; + const float* vals_array[4]; + for (int j = 0; j < 4; j++) { + cast_vals_array[j] = inputs.at(j + 1).weights().GetPointer(); + vals_array[j] = inputs.at(j + 1).weights().GetPointer(); + } + Eigen::half* cast_combined_scale_vals = + combined_scale_weights->GetPointer(); + Eigen::half* cast_combined_offset_vals = + combined_offset_weights->GetPointer(); + float* combined_scale_vals = combined_scale_weights->GetPointer(); + float* combined_offset_vals = combined_offset_weights->GetPointer(); + + for (size_t i = 0; i < nweight; ++i) { + float batchnorm_data[4]; + for (int j = 0; j < 4; j++) { + if (inputs.at(j + 1).weights().count() != 1) { + if (parameter_type == nvinfer1::DataType::kFLOAT) { + batchnorm_data[j] = vals_array[j][i]; + } else if (parameter_type == nvinfer1::DataType::kHALF) { + batchnorm_data[j] = static_cast(cast_vals_array[j][i]); + } + } else { + if (parameter_type == nvinfer1::DataType::kFLOAT) { + batchnorm_data[j] = vals_array[j][0]; + } else if (parameter_type == nvinfer1::DataType::kHALF) { + batchnorm_data[j] = static_cast(cast_vals_array[j][0]); + } + } + } + float scale = batchnorm_data[0]; + float offset = batchnorm_data[1]; + float mean = batchnorm_data[2]; + float variance = batchnorm_data[3]; + float combined_scale_val = scale / sqrtf(variance + epsilon); + float combined_offset_val = offset - mean * combined_scale_val; + if (parameter_type == nvinfer1::DataType::kFLOAT) { + combined_scale_vals[i] = combined_scale_val; + combined_offset_vals[i] = combined_offset_val; + } else if (parameter_type == nvinfer1::DataType::kHALF) { + cast_combined_scale_vals[i] = Eigen::half(combined_scale_val); + cast_combined_offset_vals[i] = Eigen::half(combined_offset_val); + } + } + + ITensorProxyPtr output_tensor; + + if (data_format == "NCHW") { + // IScaleLayer CHANNEL mode requires NCHW format. + nvinfer1::ScaleMode mode = nvinfer1::ScaleMode::kCHANNEL; + nvinfer1::IScaleLayer* layer = params->converter->network()->addScale( + *tensor->trt_tensor(), mode, combined_offset_weights->GetTrtWeights(), + combined_scale_weights->GetTrtWeights(), + nvinfer1::Weights{nvinfer1::DataType::kFLOAT, nullptr, 0}); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + output_tensor = layer->getOutput(0); + } + if (data_format == "NHWC") { + // nweight is the number of channels. TensorRT IElementWiseLayer supports + // implicit broadcasting for dimensions of size 1. + nvinfer1::Dims dims = tensor->getDimensions(); + for (int i = 0; i < dims.nbDims - 1; i++) { + dims.d[i] = 1; + } + dims.d[dims.nbDims - 1] = nweight; + StatusOr builder = TRTNetworkBuilder::Create( + params->converter->network(), params->weight_store); + TRT_ENSURE_OK(builder); + auto scale_constant_layer = builder->WeightsToConstant( + combined_scale_weights->GetTrtWeights(), dims); + ITensorProxyPtr scale_constant = (*scale_constant_layer)->getOutput(0); + auto scale_layer = + builder->Mul(tensor->trt_tensor(), scale_constant->trt_tensor()); + auto offset_constant_layer = builder->WeightsToConstant( + combined_offset_weights->GetTrtWeights(), dims); + ITensorProxyPtr offset_constant = (*offset_constant_layer)->getOutput(0); + auto offset_layer = builder->Add((*scale_layer)->getOutput(0), + offset_constant->trt_tensor()); + output_tensor = (*offset_layer)->getOutput(0); + } + + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +Status ConvertGather(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + // TODO(tmorris): Use CheckInputsWeights by changing bool to enum with an + // option for an input to be either tensor or weight. + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"params", TrtInputArg::kBoth}, + {"indices", TrtInputArg::kBoth}, + {"axis", TrtInputArg::kWeight}})); + + const auto& params_input = inputs.at(0); + const auto& indices_input = inputs.at(1); + const auto& axis_input = inputs.at(2); + + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32}, + /*dtype_attr_name=*/"Tparams")); + TF_RETURN_IF_ERROR(AllowDataTypes(*params, {DataType::DT_INT32}, + /*dtype_attr_name=*/"Tindices")); + + absl::Span axis = axis_input.weights().GetSpan(); + if (axis.size() != 1) { + return errors::InvalidArgument("Axis for GatherV2 must be a scalar"); + } + + int trt_axis = 0; + TF_RETURN_IF_ERROR(ConvertAxis( + axis[0], params_input.GetTrtDims().nbDims, node_def.name(), + params->use_implicit_batch && params_input.is_tensor(), &trt_axis)); + if (params->use_implicit_batch && params_input.is_weights() && + trt_axis != 0) { + return errors::Unimplemented( + "The input axis must be zero when params is a weight."); + } + if (params->use_implicit_batch && + (params_input.is_tensor() == indices_input.is_tensor()) && + (indices_input.batch_size() != 1 || params_input.batch_size() != 1)) { + return errors::Unimplemented( + "Params and indices must have a batch size of 1 when params and indices" + " are both tensors or both constants."); + } + + auto get_rank = [params](const auto& input) { + return input.GetTrtDims().nbDims + + (params->use_implicit_batch && input.is_tensor() ? 1 : 0); + }; + // Both input are tensors, and the TF gather result will have rank: + // (params.nbDims + 1) + (indices.nbDims + 1) - 1, + // where "+ 1" adds the batch dim. If params is a weight, the TRT rank matches + // the TF rank so we don't have to add + 1. + const int params_tf_rank = get_rank(params_input); + const int indices_tf_rank = get_rank(indices_input); + const int tf_gather_output_rank = params_tf_rank + indices_tf_rank - 1; + if (tf_gather_output_rank > + nvinfer1::Dims::MAX_DIMS + (params->use_implicit_batch ? 1 : 0)) { + return errors::InvalidArgument( + "Result of gather has dimension greater than ", + nvinfer1::Dims::MAX_DIMS + 1); + } + + int32 batch_dims; + TF_RETURN_IF_ERROR(GetNodeAttr(node_def, "batch_dims", &batch_dims)); + if (params->use_implicit_batch && batch_dims) { + return errors::InvalidArgument( + "batch_dims must be zero in implicit batch mode"); + } + if (!params->use_implicit_batch && batch_dims > 1) { + return errors::InvalidArgument( + "batch_dims cannot exceed 1 in dynamic shape mode"); + } + + if (params->validation_only) return OkStatus(); + + // Convert input or indices to tensor if it is a constant. + auto populate_tensor = [params](const auto& input) -> ITensorProxyPtr { + ITensorProxyPtr result_tensor = nullptr; + + if (input.is_weights()) { + result_tensor = params->converter->CreateConstantLayer( + input.weights(), input.GetTrtDims()); + } else { + result_tensor = input.tensor(); + } + + return result_tensor; + }; + + ITensorProxyPtr params_tensor = populate_tensor(params_input); + ITensorProxyPtr indices_tensor = populate_tensor(indices_input); + + // Note on how IGatherLayer works: if both the data and indices tensors have + // a batch size dimension of size N, it performs: + // for batchid in xrange(N): + // output[batchid, a0, ..., an, i, ..., j, b0, ..., bn] = ( + // data[batchid, a0, ..., an, indices[batchid, i, ..., j] b0, ..., bn]) + nvinfer1::IGatherLayer* layer = params->converter->network()->addGather( + *params_tensor->trt_tensor(), *indices_tensor->trt_tensor(), trt_axis); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + layer->setNbElementWiseDims(batch_dims); + + ITensorProxyPtr output_tensor = layer->getOutput(0); + nvinfer1::Dims trt_gather_output_dims = output_tensor->getDimensions(); + + if (params->use_implicit_batch) { + // Note for the "- 2": one is for the output batch dim encapsulated by + // TF-TRT, and the other is for the output dimension that is squeezed by + // IGatherLayer because of the implicit batch dim in the indices (see the + // above note). + const int expected_trt_output_rank = tf_gather_output_rank - + (params_input.is_tensor() ? 1 : 0) - + (indices_input.is_tensor() ? 1 : 0); + + if (trt_gather_output_dims.nbDims != expected_trt_output_rank) { + return errors::Internal( + "Get unexpected output dimensions of IGatherLayer. Expect nbDims: ", + expected_trt_output_rank, + ", actual nbDims: ", trt_gather_output_dims.nbDims); + } + } + // Reshape the output so after adding the implicit batch dim it'll match the + // output shape of TF GatherV2. + if (params->use_implicit_batch && params_input.is_tensor() && + indices_input.is_tensor()) { + for (int i = trt_gather_output_dims.nbDims; i > trt_axis; --i) { + trt_gather_output_dims.d[i] = trt_gather_output_dims.d[i - 1]; + } + trt_gather_output_dims.d[trt_axis] = 1; + ++trt_gather_output_dims.nbDims; + + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, TRT_TensorOrWeights(output_tensor), + trt_gather_output_dims, + /*validation_only=*/false, &output_tensor, node_def)); + } + + // When input and indices are both constants, for the supported cases, reshape + // output so that after removing the implicit batch dim it will match the + // output shape of TF GatherV2 op. + if (params->use_implicit_batch && params_input.is_weights() && + indices_input.is_weights()) { + for (int i = trt_axis; i < trt_gather_output_dims.nbDims - 1; ++i) { + trt_gather_output_dims.d[i] = trt_gather_output_dims.d[i + 1]; + } + + // Squeeze the implicit batch dimension out. Note: this works only + // when batch size for both inputs and indices are 1. + --trt_gather_output_dims.nbDims; + + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, TRT_TensorOrWeights(output_tensor), + trt_gather_output_dims, + /*validation_only=*/false, &output_tensor, node_def)); + } + + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); +} + +// Converts the input matrix multiplication node to a fully connected (FC) layer +// if possible, as the FC layer has more tactics and INT implementations. +// Returns the output ITensor* if the node is converted or nullptr if conversion +// is not possible. An error status indicates internal problems during +// conversion. +StatusOr ConvertFullyConnectedImpl( + const OpConverterParams* params, TRT_TensorOrWeights input_a, + TRT_TensorOrWeights input_b, bool transpose_a, bool transpose_b) { + if (!(!transpose_a && input_a.is_tensor() && input_b.is_weights())) { + VLOG(2) << "Not FC compatible, A must be non transposed tensor, and B " + "must be constant."; + return ITensorProxyPtr(nullptr); + } + + if (!params->use_implicit_batch && input_b.GetTrtDims().nbDims > 2 && + input_b.GetTrtDims().d[0] != 1) { + // Implicit broadcasting, if needed, has already been considered to + // transform the inputs and ensure the two operands have the same rank here. + // If the inputs have rank >= 3, then d[0] is the explicit batch dimension. + // The weight (input_b) must have batch size 1 in implicit batch mode. + VLOG(2) << "Not FC compatible, if B has an explicit batch dimension, then " + "it must be 1."; + return ITensorProxyPtr(nullptr); + } + + nvinfer1::Dims input_dim = input_a.GetTrtDims(); + if (input_dim.d[input_dim.nbDims - 1] == -1) { + VLOG(2) << "Not FC compatible, last dim of A must be static."; + return ITensorProxyPtr(nullptr); + } + + if (input_dim.nbDims + 2 > nvinfer1::Dims::MAX_DIMS) { + VLOG(2) << "Not FC compatible, cannot expand A's shape."; + return ITensorProxyPtr(nullptr); + } + + // Add two trailing 1's because FC layer combines the last three dims. + ITensorProxyPtr tensor_a = nullptr; + + // Initialize the elements of reshap_dim to 0. A value 0 in + // reshape_dim(i) will preserve the i-th dimension value from the shape of + // input_a. Add two trailing dimensions of size 1. + auto reshape_dim = DimsAdapter(input_dim.nbDims, + DimsAdapter::StorageType(input_dim.nbDims, 0)) + .Append(1) + .Append(1); + + const NodeDef& node_def = params->node_def; + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, input_a, reshape_dim, + /*validation_only=*/false, &tensor_a, node_def, /*op_instance=*/0, + /*origin_node_name=*/"FULLY_CONNECTED")); + + VLOG(2) << "New shape of A " << DebugString(tensor_a->getDimensions()); + + TRT_ShapedWeights weights_b = input_b.weights(); + TRT_ShapedWeights weights_2D(weights_b); + if (weights_b.Shape().NumDims() > 2) { + // Combine first nbDims-1 dims into a single dim, e.g. for a 4D tensor we + // transform [N, H, W, C] -> [N*H*W, C]. This is only valid if all batch + // dimensions are 1. + if (std::any_of(weights_b.Shape().begin(), + weights_b.Shape().begin() + weights_b.Shape().NumDims() - 2, + [](int d) { return d != 1; })) { + VLOG(2) << "Not FC compatible, B has a batch dim larger than 1"; + return ITensorProxyPtr(nullptr); + } + int k = weights_b.Shape().dim(weights_b.Shape().NumDims() - 1); + nvinfer1::Dims dims{2, {static_cast(weights_b.count() / k), k}}; + TF_RETURN_IF_ERROR(weights_2D.SetShape(dims)); + } + + // FC layer will transpose weights, so we need to pre-transpose. + TRT_ShapedWeights weights(weights_2D.TrtDType()); + if (!transpose_b) { + auto tmp = params->weight_store->GetTempWeights(weights_2D); + TRT_ENSURE_OK(tmp); + weights = std::move(tmp).value(); + ReorderCKtoKC(weights_2D, &weights); + } else { + weights = weights_2D; + } + TRT_ShapedWeights biases(weights.TrtDType()); + int k = weights.Shape().dim(weights.Shape().NumDims() - 1); + const int noutput = weights.count() / k; + VLOG(2) << "Using fully connected layer with k=" << k + << ", n_output=" << noutput + << " weights shape: " << weights.Shape().DebugString() + << " to convert " << node_def.op(); + nvinfer1::IFullyConnectedLayer* layer = + params->converter->network()->addFullyConnected( + *tensor_a->trt_tensor(), noutput, weights.GetTrtWeights(), + biases.GetTrtWeights()); + + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + ITensorProxyPtr output_tensor = layer->getOutput(0); + + // A fully connected layer produces output with two trailing singleton + // dimensions. We remove these. + auto output_dim = output_tensor->getDimensions(); + output_dim.nbDims -= 2; + // A zero in output_dim indicates copying the corresponding input dimension + // value during reshape. + std::fill(output_dim.d, output_dim.d + output_dim.nbDims, 0); + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, TRT_TensorOrWeights(output_tensor), output_dim, + /*validation_only=*/false, &output_tensor, node_def, + /*op_instance=*/1, /*origin_node_name=*/"FULLY_CONNECTED")); + return output_tensor; +} + +StatusOr ConvertMatMulImpl(const OpConverterParams* params, + TRT_TensorOrWeights input_a, + TRT_TensorOrWeights input_b, + bool transpose_a, + bool transpose_b) { + if (params->use_implicit_batch) { + // In implicit batch mode we are very limited when can we multiply 2D + // matrices. If input_A is a 2D tensor, then nbDims==1 (implicit batch dim + // not counted). If A is not transposed and B is weight, then we can convert + // this treating A as a batch of vectors. This is the only possibility + // to implement MatMul with 2D input in implicit batch mode. + if ((input_a.GetTrtDims().nbDims < 2 && + (transpose_a || !input_b.is_weights())) || + (input_b.GetTrtDims().nbDims < 2)) { + return errors::InvalidArgument( + "MatMul with 2D tensors requires explicit batch mode, or that tensor" + " A is not transposed and B is a constant tensor."); + } + } + + if (params->validation_only) return ITensorProxyPtr(nullptr); + + StatusOr result = ConvertFullyConnectedImpl( + params, input_a, input_b, transpose_a, transpose_b); + TF_RETURN_IF_ERROR(result.status()); + ITensorProxyPtr output = result.value(); + if (*output) { + // FC conversion was successful, we can return. + return output; + } + const auto convert_to_itensor = + [¶ms](TRT_TensorOrWeights operand) -> ITensorProxyPtr { + if (operand.is_tensor()) { + return operand.tensor(); + } else { + return params->converter->CreateConstantLayer(operand.weights(), + operand.GetTrtDims()); + } + }; + + ITensorProxyPtr tensor_a = convert_to_itensor(input_a); + ITensorProxyPtr tensor_b = convert_to_itensor(input_b); + + const auto get_matrix_op = [](ITensorProxyPtr in, + bool transpose) -> nvinfer1::MatrixOperation { + return (transpose) ? nvinfer1::MatrixOperation::kTRANSPOSE + : nvinfer1::MatrixOperation::kNONE; + }; + nvinfer1::MatrixOperation op_a, op_b; + // Note: In implicit batch mode kTRANSPOSE and kNONE are only valid if the + // matrix has at least 2 non-batch dimension. In implicit batch mode, if a has + // 1 dim (excluding batch dim), then we can only use kVECTOR, which will treat + // matrix A as a batch of vectors. + op_a = (tensor_a->getDimensions().nbDims < 2) + ? nvinfer1::MatrixOperation::kVECTOR + : get_matrix_op(tensor_a, transpose_a); + // In implicit batch mode, if B has only 1 dims (excluding batch dim) then we + // already reject the case and don't convert. One could consider using the + // kVECTOR flag to express C = MatMul(A, B.T) if A is weight, but the result + // will not have the correct shape: in TRT's implicit batch implementation, + // the result is a batch of vectors D_ji = A_ik * B_jk, where j is the batch + // dimension. In contrast, the TF MatMul op produces C = D.T, and we cannot + // transpose over the batch dimension (implicit batch mode). + op_b = get_matrix_op(tensor_b, transpose_b); + + nvinfer1::IMatrixMultiplyLayer* layer = + params->converter->network()->addMatrixMultiply( + *tensor_a->trt_tensor(), op_a, *tensor_b->trt_tensor(), op_b); + + const auto& node_def = params->node_def; + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + return ITensorProxyPtr(layer->getOutput(0)); +} + +Status ConvertMatMulHelper(const OpConverterParams* params, + TRT_TensorOrWeights input_a, + TRT_TensorOrWeights input_b, bool transpose_a, + bool transpose_b) { + StatusOr result = + ConvertMatMulImpl(params, input_a, input_b, transpose_a, transpose_b); + TF_RETURN_IF_ERROR(result.status()); + if (!params->validation_only) { + params->outputs->push_back(TRT_TensorOrWeights(result.value())); + } + return OkStatus(); +} + +// inputs are both two dimensional (ops::MatMul) +Status ConvertMatMul(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TFTRT_CHECK_INPUT_SIZE(inputs.size(), 2, node_def); + + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + bool transpose_a = false, transpose_b = false; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "transpose_a", &transpose_a)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "transpose_b", &transpose_b)); + + return ConvertMatMulHelper(params, inputs.at(0), inputs.at(1), transpose_a, + transpose_b); +} + +Status ConvertBatchMatMul(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TFTRT_CHECK_INPUT_SIZE(inputs.size(), 2, node_def); + + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, {{"x", TrtInputArg::kBoth}, {"y", TrtInputArg::kBoth}})); + // TODO(tfeher): Consider adding INT8 type because FC layer can support it. + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + if (inputs.at(0).is_weights() && inputs.at(1).is_weights()) { + // TODO(lsugy): don't assume that if all inputs are weights, grappler + // should fold them, because variables are weights. + return errors::InvalidArgument( + "All inputs are weights, but Grappler is expected to fold them."); + } + + bool transpose_a = false, transpose_b = false; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "adj_x", &transpose_a)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "adj_y", &transpose_b)); + + // In case input_l is weight, check whether input_l has implicit batch mode + // compatible batch dim. + const auto check_weight_is_not_batched = + [](const TRT_TensorOrWeights& input_l, + const TRT_TensorOrWeights& input_r) { + // There is no way to batch constants in TRT using implicit batch mode. + // Example: + // Tensor with TF Dims: 12 5 3 -> TRT Dims: 5 3 + // Weight with TF Dims: 12 3 6 -> TRT Dims: 12 3 6 + // It is not possible to treat the weight input as a batched [3, 6] + // tensor. Batched weight tensors must have batch dim = 1 (after the + // broadcast). + if (input_l.is_weights() && + input_l.GetTrtDims().nbDims > input_r.GetTrtDims().nbDims && + input_l.GetTrtDims().d[0] != 1) { + return errors::Unimplemented( + "TensorRT does not support batched constants in implicit batch " + "mode."); + } + return OkStatus(); + }; + if (params->use_implicit_batch) { + TF_RETURN_IF_ERROR(check_weight_is_not_batched(inputs.at(0), inputs.at(1))); + TF_RETURN_IF_ERROR(check_weight_is_not_batched(inputs.at(1), inputs.at(0))); + } + + // Broadcast inputs. We don't check feasibility since the dimensions in a + // MatMul don't need to match. For example, consider a valid set of inputs + // which would produce an output of shape [N, T, K]: + // input 0: [N, T, C] + // input 1: [1, C, K] + // Since C != K and T != C, check feasiblity would fail. + auto input_l = std::make_unique(inputs.at(0)); + auto input_r = std::make_unique(inputs.at(1)); + TF_RETURN_IF_ERROR(BroadcastTensors(input_l, input_r, + /*check_feasibility=*/false, params)); + + if (params->validation_only) return OkStatus(); + + return ConvertMatMulHelper(params, *input_l, *input_r, transpose_a, + transpose_b); +} + +Status ConvertArgMinMax(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"input", false}, {"dimension", true}})); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + DataType output_dtype{DataType::DT_INT32}; + TF_RETURN_IF_ERROR( + GetNodeAttr(AttrSlice(node_def), "output_type", &output_dtype)); + + if (output_dtype != DataType::DT_INT32) { + return errors::Unimplemented("Output type ", DataTypeString(output_dtype), + " is not supported"); + } + int tf_axis = inputs.at(1).weights().GetSpan()[0]; + int trt_axis; + nvinfer1::Dims dims = inputs.at(0).GetTrtDims(); + TF_RETURN_IF_ERROR(ConvertAxis(tf_axis, dims.nbDims, node_def.name(), + params->use_implicit_batch, &trt_axis)); + nvinfer1::TopKOperation topk_op; + if (node_def.op() == "ArgMin") { + topk_op = nvinfer1::TopKOperation::kMIN; + } else if (node_def.op() == "ArgMax") { + topk_op = nvinfer1::TopKOperation::kMAX; + } else { + return errors::InvalidArgument("Unsupported ArgMin/Max operation"); + } + +#if !IS_TRT_VERSION_GE(7, 0, 0, 11) + const nvinfer1::Dims trt_dims = params->inputs.at(0).GetTrtDims(); + if (trt_dims.nbDims >= 4) { + string trt_dim_str = DebugString(trt_dims); + + return errors::Unimplemented(node_def.op(), "op is not able to support", + " tensors with 4+ dimensions (excluding batch", + " size). Received: ", trt_dim_str); + } +#endif + + if (params->validation_only) return OkStatus(); + + // Use TopK with k = 1. Only indices output is needed (output 1). + const uint32_t reduce_axes = 1 << trt_axis; + nvinfer1::ITopKLayer* layer = params->converter->network()->addTopK( + *inputs.at(0).tensor()->trt_tensor(), topk_op, 1, reduce_axes); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def, "topk"); + ITensorProxyPtr output_indices_tensor = layer->getOutput(1); + + // Squeeze on axis. + std::vector input_dims(dims.d, dims.d + dims.nbDims); + input_dims[trt_axis] = 0; + ITensorProxyPtr output_tensor = nullptr; + TF_RETURN_IF_ERROR(params->converter->SqueezeTensor( + /*input=*/output_indices_tensor, + /*input_dims=*/&input_dims, + /*params=*/params, + /*output=*/&output_tensor)); + params->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + + return OkStatus(); +} + +Status ConvertTopK(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + CheckInputsWeights(*params, {{"input", false}, {"k", true}})); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + bool sorted{false}; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node_def), "sorted", &sorted)); + + if (!sorted) { + // TensorRT only supports sorted output. Although TensorFlow API + // doesn't specify the order of output elements in case sorted=false, + // but it's safer to not convert because the output of TensorRT might + // be different with TensorFlow which can cause confusion. + return errors::InvalidArgument("Only sorted=True is supported"); + } + + ITensorProxyPtr tensor = inputs.at(0).tensor(); + const int num_dims = tensor->getDimensions().nbDims; + if (num_dims == 0) { + return errors::InvalidArgument( + "TensorRT TopK cannot apply on batch dimension"); + } + + TRT_ShapedWeights k_w = inputs.at(1).weights(); + if (k_w.count() != 1) { + return errors::InvalidArgument("k value of TopK should be a scalar"); + } + // Note that ITopKLayer always have sorted outputs, so we don't need to handle + // the 'sorted' attribute of the node. + if (params->validation_only) return OkStatus(); + + const nvinfer1::TopKOperation op = nvinfer1::TopKOperation::kMAX; + const int k = *(k_w.GetPointer()); + const uint32_t reduce_axes = 1 << (num_dims - 1); + nvinfer1::ITopKLayer* layer = params->converter->network()->addTopK( + *tensor->trt_tensor(), op, k, reduce_axes); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + + ITensorProxyPtr output_value_tensor = layer->getOutput(0); + ITensorProxyPtr output_indices_tensor = layer->getOutput(1); + params->outputs->push_back(TRT_TensorOrWeights(output_value_tensor)); + params->outputs->push_back(TRT_TensorOrWeights(output_indices_tensor)); + return OkStatus(); +} + +StatusOr> +CalcDepthSpaceDynamicShape(const OpConverterParams* params, int block_size, + string data_format) { + // Instead we use a shape layer and shape arithmetic to calculate the reshape + // dimensions. + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + + const int channels_axis = data_format == "NCHW" ? 1 : 3; + const int h_axis = data_format == "NCHW" ? 2 : 1; + const int w_axis = data_format == "NCHW" ? 3 : 2; + + // Get shapes. + ITensorProxyPtr shape = params->converter->network() + ->addShape(*inputs.at(0).tensor()->trt_tensor()) + ->getOutput(0); + ITensorProxyPtr batch_size = + params->converter->network() + ->addSlice(*shape->trt_tensor(), {1, {0}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + ITensorProxyPtr num_channels = + params->converter->network() + ->addSlice(*shape->trt_tensor(), {1, {channels_axis}}, {1, {1}}, + {1, {1}}) + ->getOutput(0); + ITensorProxyPtr h = + params->converter->network() + ->addSlice(*shape->trt_tensor(), {1, {h_axis}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + ITensorProxyPtr w = + params->converter->network() + ->addSlice(*shape->trt_tensor(), {1, {w_axis}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + ITensorProxyPtr r; + TF_RETURN_IF_ERROR(CreateScalarConstant(params, block_size, &r)); + ITensorProxyPtr r_squared; + TF_RETURN_IF_ERROR( + CreateScalarConstant(params, block_size * block_size, &r_squared)); + // Get shuffle parameters. + std::vector first_shuffle_tensors(6, nullptr); + std::vector second_shuffle_tensors(4, nullptr); + if (node_def.op() == "DepthToSpace") { + // First Reshape [N, C, H, W] - > [N, r, r, C/(r*r), H, W]. + first_shuffle_tensors[0] = batch_size; + first_shuffle_tensors[1] = r; + first_shuffle_tensors[2] = r; + first_shuffle_tensors[3] = + params->converter->network() + ->addElementWise(*num_channels->trt_tensor(), + *r_squared->trt_tensor(), + nvinfer1::ElementWiseOperation::kDIV) + ->getOutput(0); + first_shuffle_tensors[4] = h; + first_shuffle_tensors[5] = w; + // Second Reshape [N, C/(r*r), H, r, W, r] -> [N, C/(r*r), H * r, W * r]. + second_shuffle_tensors[0] = batch_size; + second_shuffle_tensors[1] = + params->converter->network() + ->addElementWise(*num_channels->trt_tensor(), + *r_squared->trt_tensor(), + nvinfer1::ElementWiseOperation::kDIV) + ->getOutput(0); + second_shuffle_tensors[2] = + params->converter->network() + ->addElementWise(*h->trt_tensor(), *r->trt_tensor(), + nvinfer1::ElementWiseOperation::kPROD) + ->getOutput(0); + second_shuffle_tensors[3] = + params->converter->network() + ->addElementWise(*w->trt_tensor(), *r->trt_tensor(), + nvinfer1::ElementWiseOperation::kPROD) + ->getOutput(0); + } else if (node_def.op() == "SpaceToDepth") { + // First Reshape [N, C, H, W] -> [N, C, H/r, r, W/r, r]. + first_shuffle_tensors[0] = batch_size; + first_shuffle_tensors[1] = num_channels; + first_shuffle_tensors[2] = + params->converter->network() + ->addElementWise(*h->trt_tensor(), *r->trt_tensor(), + nvinfer1::ElementWiseOperation::kDIV) + ->getOutput(0); + first_shuffle_tensors[3] = r; + first_shuffle_tensors[4] = + params->converter->network() + ->addElementWise(*w->trt_tensor(), *r->trt_tensor(), + nvinfer1::ElementWiseOperation::kDIV) + ->getOutput(0); + first_shuffle_tensors[5] = r; + + // Second Reshape [N, r, r, C, H/r, W/r] -> [N, C*r*r, H/r, W/r]. + second_shuffle_tensors[0] = batch_size; + second_shuffle_tensors[1] = + params->converter->network() + ->addElementWise(*num_channels->trt_tensor(), + *r_squared->trt_tensor(), + nvinfer1::ElementWiseOperation::kPROD) + ->getOutput(0); + second_shuffle_tensors[2] = + params->converter->network() + ->addElementWise(*h->trt_tensor(), *r->trt_tensor(), + nvinfer1::ElementWiseOperation::kDIV) + ->getOutput(0); + second_shuffle_tensors[3] = + params->converter->network() + ->addElementWise(*w->trt_tensor(), *r->trt_tensor(), + nvinfer1::ElementWiseOperation::kDIV) + ->getOutput(0); + } + + StatusOr result = + ConcatenateTensors(params, first_shuffle_tensors, 0); + TF_RETURN_IF_ERROR(result.status()); + ITensorProxyPtr first_shuffle_shape = result.value(); + + result = ConcatenateTensors(params, second_shuffle_tensors, 1); + TF_RETURN_IF_ERROR(result.status()); + ITensorProxyPtr second_shuffle_shape = result.value(); + + return std::make_pair(first_shuffle_shape, second_shuffle_shape); +} + +Status ConvertDepthSpaceShuffle(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"input", false}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + + string data_format; + int block_size; + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "data_format", &data_format)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "block_size", &block_size)); + + if (block_size < 2) { + return errors::InvalidArgument("Block size must be 2 or greater"); + } + + if (data_format != "NCHW" && data_format != "NHWC") { + return errors::Unimplemented("Data format ", data_format, + " is not supported"); + } + int idx_offset = params->use_implicit_batch ? 0 : 1; + nvinfer1::Dims dims = inputs.at(0).GetTrtDims(); + const int required_rank = 3 + idx_offset; + if (dims.nbDims != required_rank) { + return errors::InvalidArgument("The input to ", node_def.op(), + " must be rank 4"); + } + const int num_channels = + data_format == "NCHW" ? dims.d[0 + idx_offset] : dims.d[2 + idx_offset]; + const int h = + data_format == "NCHW" ? dims.d[1 + idx_offset] : dims.d[0 + idx_offset]; + const int w = + data_format == "NCHW" ? dims.d[2 + idx_offset] : dims.d[1 + idx_offset]; + // Get shuffle parameters. + nvinfer1::Dims first_shuffle_shape; + nvinfer1::Permutation transpose_perm; + nvinfer1::Dims second_shuffle_shape; + + // We define all the shuffle and transpose dimensions assuming implicit batch + // mode. Afterwards we will update them to explicit batch mode if needed. + // Additionally, an NCHW layout is assumed, and this assumption is corrected + // afterwards with an initial transpose op. TODO(tfeher): Get rid of the + // layout_transpose ops by defining shuffle shape specifically for NCHW and + // NHCW. + if (node_def.op() == "DepthToSpace") { + if (num_channels != -1 && num_channels % (block_size * block_size) != 0) { + return errors::InvalidArgument( + "Number of channels must be divisible by block_size*block_size"); + } + // First Reshape [C, H, W] - > [r, r, C/(r*r), H, W] + first_shuffle_shape = { + /*nbDims=*/5, + /*d=*/{block_size, block_size, num_channels / (block_size * block_size), + h, w}}; + // Transpose [r, r, C/(r*r), H, W] -> [C/(r*r), H, r, W, r] + transpose_perm = {2, 3, 0, 4, 1}; + // Second Reshape [C/(r*r), H, r, W, r] -> [C/(r*r), H * r, W * r] + second_shuffle_shape = + nvinfer1::Dims3(num_channels / (block_size * block_size), + h * block_size, w * block_size); + } else { + if (node_def.op() != "SpaceToDepth") + return errors::InvalidArgument("Incorrect op type ", node_def.op()); + if ((h != -1 && h % block_size != 0) || (w != -1 && w % block_size != 0)) { + return errors::InvalidArgument( + "Width and height must be divisible by block_size"); + } + // First Reshape [C, H, W] -> [C, H/r, r, W/r, r] + first_shuffle_shape = {/*nbDims=*/5, + /*d=*/{num_channels, h / block_size, block_size, + w / block_size, block_size}}; + // Transpose [C, H/r, r, W/r, r] -> [r, r, C, H/r, W/r] + transpose_perm = {2, 4, 0, 1, 3}; + // Second Reshape [r, r, C, H/r, W/r] -> [C*r*r, H/r, W/r] + second_shuffle_shape = nvinfer1::Dims3( + num_channels * block_size * block_size, h / block_size, w / block_size); + } + if (params->validation_only) return OkStatus(); + + nvinfer1::IShuffleLayer* first_shuffle = + params->converter->network()->addShuffle( + *inputs.at(0).tensor()->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR(first_shuffle, node_def.name()); + params->converter->SetLayerName(first_shuffle, node_def, "shuffle", + /*op_instance=*/0); + + ITensorProxyPtr second_shuffle_shape_tensor; + + if (HasStaticShape(inputs.at(0).GetTrtDims())) { + // Adjust a reshape constructed at implicit batch mode for explicit batch + // mode. In particular, we need to insert the batch dimension size to the + // beginning of all the dimension sizes. Example: reshape {20,10,30} for + // implicit batch mode becomes reshape {N,20,10,30} for explicit batch mode. + auto adjust_reshape = [](int N, nvinfer1::Dims dims, + bool use_implicit_batch) { + if (use_implicit_batch) return dims; + for (int i = dims.nbDims; i > 0; i--) { + dims.d[i] = dims.d[i - 1]; + } + dims.d[0] = N; + dims.nbDims++; + return dims; + }; + + first_shuffle_shape = adjust_reshape(dims.d[0], first_shuffle_shape, + params->use_implicit_batch); + second_shuffle_shape = adjust_reshape(dims.d[0], second_shuffle_shape, + params->use_implicit_batch); + + first_shuffle->setReshapeDimensions(first_shuffle_shape); + } else { + StatusOr> result = + CalcDepthSpaceDynamicShape(params, block_size, data_format); + TF_RETURN_IF_ERROR(result.status()); + first_shuffle->setInput(1, *result.value().first->trt_tensor()); + second_shuffle_shape_tensor = result.value().second; + } + + // Adjust a transpose constructed assuming implicit batch mode for explicit + // batch mode. In particular, we need to add the batch dimension to d0 and + // add 1 to all the dimension id in the transpose. Example: permutation + // for implicit batch mode becomes permutation {0,3,2,1} for explicit batch + // mode. + auto adjust_perm = [](int n, nvinfer1::Permutation perm, + bool use_implicit_batch) { + if (use_implicit_batch) return perm; + for (int i = n; i > 0; i--) { + perm.order[i] = perm.order[i - 1] + 1; + } + perm.order[0] = 0; + return perm; + }; + transpose_perm = adjust_perm(5, transpose_perm, params->use_implicit_batch); + + if (data_format == "NHWC") { + nvinfer1::Permutation layout_transpose = + adjust_perm(3, {2, 0, 1}, params->use_implicit_batch); + first_shuffle->setFirstTranspose(layout_transpose); + } + first_shuffle->setSecondTranspose(transpose_perm); + + nvinfer1::IShuffleLayer* second_shuffle = + params->converter->network()->addShuffle(*first_shuffle->getOutput(0)); + TFTRT_RETURN_ERROR_IF_NULLPTR(second_shuffle, node_def.name()); + params->converter->SetLayerName(second_shuffle, node_def, "shuffle", + /*op_instance=*/1); + + if (HasStaticShape(inputs.at(0).GetTrtDims())) { + second_shuffle->setReshapeDimensions(second_shuffle_shape); + } else { + second_shuffle->setInput(1, *second_shuffle_shape_tensor->trt_tensor()); + } + if (data_format == "NHWC") { + nvinfer1::Permutation layout_transpose = + adjust_perm(3, {1, 2, 0}, params->use_implicit_batch); + second_shuffle->setSecondTranspose(layout_transpose); + } + + params->outputs->push_back(TRT_TensorOrWeights(second_shuffle->getOutput(0))); + return OkStatus(); +} + +Status ConvertSquaredDifference(const OpConverterParams* params) { + TF_RETURN_IF_ERROR(CheckInputsWeights(*params, {{"x", false}, {"y", false}})); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + // Broadcast inputs. + nvinfer1::Dims broadcasted_dims_l, broadcasted_dims_r; + TF_RETURN_IF_ERROR(GetTrtBroadcastShape( + inputs.at(0), inputs.at(1), /*check_feasibility=*/true, + params->use_implicit_batch, &broadcasted_dims_l, &broadcasted_dims_r)); + ITensorProxyPtr tensor_l = nullptr; + ITensorProxyPtr tensor_r = nullptr; + TF_RETURN_IF_ERROR( + PrepareTensorForShape(params->converter, inputs.at(0), broadcasted_dims_l, + params->validation_only, &tensor_l, node_def)); + TF_RETURN_IF_ERROR( + PrepareTensorForShape(params->converter, inputs.at(1), broadcasted_dims_r, + params->validation_only, &tensor_r, node_def)); + if (params->validation_only) return OkStatus(); + + // Subtract x - y. + nvinfer1::IElementWiseLayer* sub = + params->converter->network()->addElementWise( + *tensor_l->trt_tensor(), *tensor_r->trt_tensor(), + nvinfer1::ElementWiseOperation::kSUB); + TFTRT_RETURN_ERROR_IF_NULLPTR(sub, node_def.name()); + params->converter->SetLayerName(sub, node_def, "sub"); + + // Multiply (x - y) * (x - y). + nvinfer1::IElementWiseLayer* mul = + params->converter->network()->addElementWise( + *sub->getOutput(0), *sub->getOutput(0), + nvinfer1::ElementWiseOperation::kPROD); + TFTRT_RETURN_ERROR_IF_NULLPTR(mul, node_def.name()); + params->converter->SetLayerName(mul, node_def, "mul"); + + params->outputs->push_back(TRT_TensorOrWeights(mul->getOutput(0))); + return OkStatus(); +} + +#if IS_TRT_VERSION_GE(7, 1, 3, 0) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) +Status ConvertCombinedNMS(const OpConverterParams* params) { + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, {{"boxes", TrtInputArg::kTensor}, + {"scores", TrtInputArg::kTensor}, + {"max_output_size_per_class", TrtInputArg::kWeight}, + {"max_total_size", TrtInputArg::kWeight}, + {"iou_threshold", TrtInputArg::kWeight}, + {"score_threshold", TrtInputArg::kWeight}})); + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + const auto& node_name = node_def.name(); + + const ITensorProxyPtr boxes_tensor = inputs.at(0).tensor(); + const ITensorProxyPtr scores_tensor = inputs.at(1).tensor(); + const auto boxes_dims = boxes_tensor->getDimensions(); + const auto scores_dims = scores_tensor->getDimensions(); + +#if IS_TRT_VERSION_GE(8, 2, 1, 6) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) + const auto flag = true; + const auto* plugin_name = "NMS TRT Plugin "; + const auto* pluginName = "EfficientNMS_TFTRT_TRT"; +#else // IS_TRT_VERSION_GE(7, 1, 3, 0) + const auto flag = false; + const auto* plugin_name = "TensorRT BatchedNMS Plugin "; + const auto* pluginName = "BatchedNMS_TRT"; + + auto AllowNmsTopkOverride = []() { + static bool result = [] { + bool value; + const Status status = ReadBoolFromEnvVar("TF_TRT_ALLOW_NMS_TOPK_OVERRIDE", + /*default_value=*/false, &value); + if (!status.ok()) { + LOG(ERROR) << status; + } + return value; + }(); + return result; + }; +#endif + + if (params->use_implicit_batch == flag) { + if (flag) { + return errors::Unimplemented( + convert_not_supported_implicit(node_def.op(), node_name)); + } else { + if (!HasStaticShape(boxes_dims) || !HasStaticShape(scores_dims)) { + return errors::Unimplemented(plugin_name, + "requires input with static shape"); + } + } + } + + const auto& output_size_per_class = inputs.at(2).weights(); + const auto& total_size = inputs.at(3).weights(); + const auto& iou_threshold = inputs.at(4).weights(); + const auto& score_threshold = inputs.at(5).weights(); + + const int offset = params->use_implicit_batch ? 0 : 1; + if (boxes_dims.nbDims != 3 + offset) { + return errors::InvalidArgument( + plugin_name, "input boxes must be 4-D including batch, at ", node_name); + } + + AttrSlice attrs(node_def); + bool clip_boxes = false, pad_per_class = false; + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "clip_boxes", &clip_boxes)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "pad_per_class", &pad_per_class)); + + const int class_idx = 1 + offset; + const int num_classes = scores_dims.d[class_idx]; + const bool box_check = + boxes_dims.d[class_idx] == 1 || boxes_dims.d[class_idx] == num_classes; + if (!box_check) { + return errors::InvalidArgument( + plugin_name, + "third dimension of boxes must be either 1" + "or match the num_classes dimension of scores, at ", + node_name); + } + + if (output_size_per_class.count() != 1) { + return errors::InvalidArgument( + plugin_name, "max_output_size_per_class must be scalar, at ", + node_name); + } + + const int max_size_per_class = *(output_size_per_class.GetPointer()); + if (max_size_per_class <= 0) { + return errors::InvalidArgument( + plugin_name, "max_output_size_per_class should be > 0, at ", node_name); + } + + if (total_size.count() != 1) { + return errors::InvalidArgument( + plugin_name, "max_total_size must be scalar, at ", node_name); + } + + int max_total_size = *(total_size.GetPointer()); + if (max_total_size <= 0) { + return errors::InvalidArgument( + plugin_name, "max_total_size should be > 0, at ", node_name); + } + + if (iou_threshold.count() != 1) { + return errors::InvalidArgument( + plugin_name, "iou_threshold must be scalar, at ", node_name); + } + + const auto iou_thresh = *(iou_threshold.GetPointer()); + if (iou_thresh < 0.0 || iou_thresh > 1.0) { + return errors::InvalidArgument( + plugin_name, "iou_threshold must be in [0, 1], at", node_name); + } + + if (score_threshold.count() != 1) { + return errors::InvalidArgument( + plugin_name, "score_threshold must be scalar, at ", node_name); + } + +#if !IS_TRT_VERSION_GE(8, 2, 1, 6) && !defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) + // TRT op is_normalized=False treats input coordinates as pixels and + // calculates width/height as (max - min + 1). + // + // TF op CombinedNonMaxSuppression doesn't care about the normalization and + // calculates width/height as (max-min). + // + // We set is_normalized = true to be consistent with TF IOU calculaton. + const bool is_normalized = true; + const int backgrnd_id = -1; + const bool share_location = (boxes_dims.d[class_idx] == 1); + int keep_top_k = + pad_per_class ? std::min(max_size_per_class * num_classes, max_total_size) + : max_total_size; + + // According to the batchedNMS plugin description we need to set top_k so that + // keep_top_k <= top_k + // https://github.com/NVIDIA/TensorRT/tree/master/plugin/batchedNMSPlugin + // Before the NMS step, TRT selects top_k candidate from each class and + // discards the rest. The NMS step is performed only among the top_k + // candidates. To be strictly compatible with the TF op, we need that top_k is + // greater equal to num_boxes. + const int num_boxes = boxes_dims.d[offset]; + int top_k = std::max(num_boxes, keep_top_k); + // TRT has a limitation: top_k <=4096. + if (top_k > 4096) { + if (AllowNmsTopkOverride()) { + top_k = 4096; + keep_top_k = std::min(top_k, keep_top_k); + } else { + return errors::InvalidArgument( + "TRT NMS plugin allow top_k<=4096, where top_k = max(num_boxes, " + "max_total_size). You can override this by setting " + "TF_TRT_ALLOW_NMS_TOPK_OVERRIDE=1 environment variable, but this can " + "result in a loss of accuracy."); + } + } +#endif + + if (params->validation_only) return OkStatus(); + + // Create plugin. + float score_thresh = *(score_threshold.GetPointer()); + nvinfer1::PluginField fields[] = { +#if IS_TRT_VERSION_GE(8, 2, 1, 6) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) + {"max_output_size_per_class", &max_size_per_class, + nvinfer1::PluginFieldType::kINT32, 1}, + {"max_total_size", &max_total_size, nvinfer1::PluginFieldType::kINT32, 1}, + {"iou_threshold", &iou_thresh, nvinfer1::PluginFieldType::kFLOAT32, 1}, + {"score_threshold", &score_thresh, nvinfer1::PluginFieldType::kFLOAT32, + 1}, + {"pad_per_class", &pad_per_class, nvinfer1::PluginFieldType::kINT32, 1}, + {"clip_boxes", &clip_boxes, nvinfer1::PluginFieldType::kINT32, 1}, +#else // IS_TRT_VERSION_GE(7, 1, 3, 0) + {"shareLocation", &share_location, nvinfer1::PluginFieldType::kINT32, 1}, + {"backgroundLabelId", &backgrnd_id, nvinfer1::PluginFieldType::kINT32, 1}, + {"numClasses", &num_classes, nvinfer1::PluginFieldType::kINT32, 1}, + {"topK", &top_k, nvinfer1::PluginFieldType::kINT32, 1}, + {"keepTopK", &keep_top_k, nvinfer1::PluginFieldType::kINT32, 1}, + {"scoreThreshold", &score_thresh, nvinfer1::PluginFieldType::kFLOAT32, 1}, + {"iouThreshold", &iou_thresh, nvinfer1::PluginFieldType::kFLOAT32, 1}, + {"isNormalized", &is_normalized, nvinfer1::PluginFieldType::kINT32, 1}, + {"clipBoxes", &clip_boxes, nvinfer1::PluginFieldType::kINT32, 1}, +#endif + }; + + nvinfer1::PluginFieldCollection fc{sizeof(fields) / sizeof(fields[0]), + fields}; + + // Get plugin creator. + auto creator = getPluginRegistry()->getPluginCreator(pluginName, "1", ""); + TFTRT_RETURN_ERROR_IF_NULLPTR(creator, node_name); + + TrtUniquePtrType plugin( + creator->createPlugin(node_name.c_str(), &fc)); + TFTRT_RETURN_ERROR_IF_NULLPTR(plugin, node_name); + + // Set plugin inputs. + std::vector trt_plugin_inputs; + trt_plugin_inputs.push_back(boxes_tensor->trt_tensor()); + trt_plugin_inputs.push_back(scores_tensor->trt_tensor()); + + // Add plugin to network. + nvinfer1::IPluginV2Layer* layer = params->converter->network()->addPluginV2( + &trt_plugin_inputs[0], static_cast(trt_plugin_inputs.size()), + *plugin); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_name); + params->converter->SetLayerName(layer, node_def, "plugin"); + + // Set plugin outputs. + const ITensorProxyPtr output_detection_boxes = layer->getOutput(1); + const ITensorProxyPtr output_detection_scores = layer->getOutput(2); + ITensorProxyPtr output_num_detections = layer->getOutput(0); + ITensorProxyPtr output_detection_classes = layer->getOutput(3); + +#if IS_TRT_VERSION_GE(8, 2, 1, 6) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) + // Cast the classes output from int32 to float32. + nvinfer1::IIdentityLayer* layer_detection_classes = + params->converter->network()->addIdentity( + *output_detection_classes->trt_tensor()); + layer_detection_classes->setOutputType(0, nvinfer1::DataType::kFLOAT); + output_detection_classes = layer_detection_classes->getOutput(0); + + // The plugin produces a [N, 1] tensor for the num output, squeeze it to [N] + std::vector input_dims{output_num_detections->getDimensions().d[0], 0}; + TF_RETURN_IF_ERROR(params->converter->SqueezeTensor( + /*input=*/output_num_detections, + /*input_dims=*/&input_dims, + /*params=*/params, + /*output=*/&output_num_detections)); +#endif + + // Final outputs. + params->outputs->push_back(TRT_TensorOrWeights(output_detection_boxes)); + params->outputs->push_back(TRT_TensorOrWeights(output_detection_scores)); + params->outputs->push_back(TRT_TensorOrWeights(output_detection_classes)); + params->outputs->push_back(TRT_TensorOrWeights(output_num_detections)); + return OkStatus(); +} +#endif + +Status ConvertResize(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR(CheckInputsWeights( + *params, + {{"input", TrtInputArg::kTensor}, {"size", TrtInputArg::kBoth}})); + TF_RETURN_IF_ERROR(AllowDataTypes( + *params, {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32})); + + // Get input tensor. + ITensorProxyPtr inputs_tensor = inputs.at(0).tensor(); + TFTRT_RETURN_ERROR_IF_NULLPTR(inputs_tensor, params->node_def.name()); + + // Check output size. It must contain two values i.e. [H_out, W_out] + const bool const_output_size = inputs.at(1).is_weights(); + if (const_output_size) { + // Output size is given as a constant. + if (inputs.at(1).weights().count() != 2) { + return errors::Unimplemented("Resize requires 2D values for the size"); + } + } else { + // Output size is given as a tensor, possibly as the result of shape + // calculation ops in the graph. + if (params->use_implicit_batch) { + return errors::Unimplemented( + "Resize requires constant size in implicit batch mode"); + } + TF_RETURN_IF_ERROR(ExpectShapeTensor(inputs.at(1))); + if (inputs.at(1).tensor()->getDimensions().d[0] != 2) { + return errors::Unimplemented("Resize requires 2D values for the size"); + } + } + + // Verify and consume node attributes. + bool align_corners; + TF_RETURN_IF_ERROR( + GetNodeAttr(AttrSlice(node_def), "align_corners", &align_corners)); + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + // Verify resize mode. Initialize resize mode if supported. + nvinfer1::ResizeMode resize_mode; + if (node_def.op() == "ResizeBilinear") { +#if IS_TRT_VERSION_GE(7, 1, 0, 0) + if (!align_corners) { + return errors::InvalidArgument( + "Cannot Convert Bilinear Resize when align_corners=False"); + } +#endif + resize_mode = nvinfer1::ResizeMode::kLINEAR; + } else if (node_def.op() == "ResizeNearestNeighbor") { + resize_mode = nvinfer1::ResizeMode::kNEAREST; + } else { + return errors::Unimplemented(node_def.op(), " is not yet implemented"); + } + + // return after validation if only validation is requested. + if (params->validation_only) return OkStatus(); + + // Transpose tensor from NHWC to NCHW format. + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + inputs_tensor, {0, 3, 1, 2}, &inputs_tensor, node_def, "to_NCHW")); + + // Calculate the output shape as static dimensions or a shape tensor: + // Given input shape [N, C, H, W] and output size [H_out, W_out], + // output shape equals [N, C, H_out, W_out]. + nvinfer1::Dims output_shape_dims; + ITensorProxyPtr output_shape_tensor; + const bool static_output_shape = + HasStaticShape(inputs_tensor->getDimensions()) && const_output_size; + if (static_output_shape) { + // If the output shape can be fully determined at build time, calculate it + // as a set of dimensions. + output_shape_dims.nbDims = inputs_tensor->getDimensions().nbDims; + for (int i = 0; i < output_shape_dims.nbDims; ++i) { + output_shape_dims.d[i] = inputs_tensor->getDimensions().d[i]; + } + const int* weights_ptr = inputs.at(1).weights().GetPointer(); + output_shape_dims.d[output_shape_dims.nbDims - 2] = weights_ptr[0]; + output_shape_dims.d[output_shape_dims.nbDims - 1] = weights_ptr[1]; + } else { + // Otherwise, build the output shape as a shape tensor that will be computed + // at run time. + // The batch size and num of channels will be copied from the input shape. + ITensorProxyPtr shape = params->converter->network() + ->addShape(*inputs_tensor->trt_tensor()) + ->getOutput(0); + ITensorProxyPtr batch_size = + params->converter->network() + ->addSlice(*shape->trt_tensor(), {1, {0}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + ITensorProxyPtr num_channels = + params->converter->network() + ->addSlice(*shape->trt_tensor(), {1, {1}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + + // The height and width will be obtained from the requested output size. + ITensorProxyPtr height, width; + if (const_output_size) { + // If the output size is constant, the height and width dimensions can be + // created as constants from the size values. + const int* weights_ptr = inputs.at(1).weights().GetPointer(); + TF_RETURN_IF_ERROR(CreateScalarConstant(params, weights_ptr[0], &height)); + TF_RETURN_IF_ERROR(CreateScalarConstant(params, weights_ptr[1], &width)); + } else { + // Otherwise, the size is a tensor which can be sliced, and each element + // used directly as the output height and width dimensions. + ITensorProxyPtr size = inputs.at(1).tensor(); + height = params->converter->network() + ->addSlice(*size->trt_tensor(), {1, {0}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + width = params->converter->network() + ->addSlice(*size->trt_tensor(), {1, {1}}, {1, {1}}, {1, {1}}) + ->getOutput(0); + } + + StatusOr result = ConcatenateTensors( + params, {batch_size, num_channels, height, width}, 0); + TF_RETURN_IF_ERROR(result.status()); + output_shape_tensor = result.value(); + } + + // Add resize layer. + nvinfer1::IResizeLayer* layer = + params->converter->network()->addResize(*inputs_tensor->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def); + + // Set layer parameters. + layer->setResizeMode(resize_mode); + layer->setAlignCorners(align_corners); + + // Set output shape. + if (static_output_shape) { + // If the shapes are fully known at build time, pass the static output shape + // to the resize layer as expected output dimensions. + layer->setOutputDimensions(output_shape_dims); + } else { + // Otherwise, pass the output shape tensor to the resize layer as an input. + layer->setInput(1, *output_shape_tensor->trt_tensor()); + } + + // Get output tensor. Transpose it from NCHW to NHWC. + ITensorProxyPtr output = layer->getOutput(0); + + TF_RETURN_IF_ERROR(params->converter->TransposeTensor( + output, {0, 2, 3, 1}, &output, node_def, "to_NHWC")); + params->outputs->push_back(TRT_TensorOrWeights(output)); + // Success + return OkStatus(); +} // ConvertResize + +Status ConvertAddN(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + TF_RETURN_IF_ERROR( + AllowDataTypes(*params, {DataType::DT_FLOAT, DataType::DT_HALF})); + + int num_inputs; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(node_def), "N", &num_inputs)); + + if (num_inputs < 2) { + return errors::InvalidArgument("AddN requires at least two inputs"); + } + + TFTRT_CHECK_INPUT_SIZE(inputs.size(), num_inputs, node_def); + + for (const auto& input : inputs) { + if (!input.is_tensor() && input.weights().Shape().dim(0) != 1) { + return errors::InvalidArgument( + "Weights input to AddN is required to have batch dimension 1."); + } + } + if (params->validation_only) return OkStatus(); + + // AddN doesn't support broadcast. + std::vector tensor_inputs; + tensor_inputs.reserve(inputs.size()); + for (const auto& input : inputs) { + if (input.is_tensor()) { + tensor_inputs.push_back(input.tensor()); + } else { + auto dims = input.weights().Shape(); + if (params->use_implicit_batch) { + TF_RETURN_IF_ERROR(dims.RemoveBatchDimension()); + } + tensor_inputs.push_back(params->converter->CreateConstantLayer( + input.weights(), dims.AsTrtDims())); + } + } + ITensorProxyPtr lhs = tensor_inputs[0]; + for (int i = 1; i < num_inputs; ++i) { + ITensorProxyPtr rhs = tensor_inputs[i]; + nvinfer1::ILayer* layer = params->converter->network()->addElementWise( + *lhs->trt_tensor(), *rhs->trt_tensor(), + nvinfer1::ElementWiseOperation::kSUM); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params->converter->SetLayerName(layer, node_def, std::to_string(i)); + lhs = layer->getOutput(0); + } + params->outputs->push_back(TRT_TensorOrWeights(lhs)); + return OkStatus(); +} + +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertBiasAdd, "BiasAdd"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertClipByValue, "ClipByValue"); +#if IS_TRT_VERSION_GE(7, 1, 3, 0) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertCombinedNMS, + "CombinedNonMaxSuppression"); +#endif +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertAddN, "AddN"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertCast, "Cast"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConcat, "ConcatV2"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConst, "Const"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConv2D, "Conv2D"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConv2DBackpropInput, + "Conv2DBackpropInput"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertDepthSpaceShuffle, "DepthToSpace"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConv2DDepthwise, + "DepthwiseConv2dNative"); + +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertExpandDims, "ExpandDims"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertFusedConv2DBiasActivation, + "FusedConv2DBiasActivation"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertGather, "GatherV2"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertMatMul, "MatMul"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertPack, "Pack"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertPad, "Pad"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertReshape, "Reshape"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConv3D, "Conv3D"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertConv3DBackpropInputV2, + "Conv3DBackpropInputV2"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertResize, "ResizeBilinear"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertResize, "ResizeNearestNeighbor"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertPool3D, "AvgPool3D"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertPool3D, "MaxPool3D"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertShape, "Shape"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertSlice, "Slice"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertDepthSpaceShuffle, "SpaceToDepth"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertSplit, "Split"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertSquare, "Square"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertSquaredDifference, + "SquaredDifference"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertSqueeze, "Squeeze"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertStridedSlice, "StridedSlice"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertTopK, "TopKV2"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertTranspose, "Transpose"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertUnpack, "Unpack"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertPool, {"MaxPool", "AvgPool"}); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertFusedBatchNorm, + {"FusedBatchNorm", "FusedBatchNormV2", + "FusedBatchNormV3"}); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertReduce, + {"Sum", "Prod", "Max", "Min", "Mean"}); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertArgMinMax, {"ArgMin", "ArgMax"}); +// The following are no-ops during inference and will not be mapped to any +// TRT layer. +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertIdentity, + {"Identity", "IdentityN", "Snapshot", + "StopGradient", "_CopyFromHostToGpu"}); +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertBatchMatMul, + {"BatchMatMul", "BatchMatMulV2"}); +// Debug converter only accessible via `TF_TRT_OP_FAKELIST=OpName1,OpName2,...` +REGISTER_DEFAULT_TRT_OP_CONVERTER(ConvertFake, "FakeOp"); + +static Status SetDeviceInfoInNodes(GraphDef* graph_def, const string& device) { + for (auto& node : *(graph_def->mutable_node())) { + *node.mutable_device() = device; + } + return OkStatus(); +} + +Status ConvertGraphDefToEngine( + const GraphDef& gdef, OpKernelContext* ctx, TrtPrecisionMode precision_mode, + int max_batch_size, size_t max_workspace_size_bytes, + const std::vector& input_shapes, + nvinfer1::ILogger* trt_logger, nvinfer1::IGpuAllocator* allocator, + TRTInt8Calibrator* calibrator, + TrtUniquePtrType* engine, bool use_calibration, + const bool use_implicit_batch, bool* convert_successfully, + TrtShapeOptimizationProfile* profiles, absl::string_view engine_name, + bool use_explicit_precision, tensorflow::grappler::Cluster* cluster, + const string& device) { + engine->reset(); + if (convert_successfully) *convert_successfully = false; + + // Creating converter, TensorRT builder and network + auto statusor = Converter::Create(precision_mode, use_calibration, trt_logger, + use_implicit_batch, engine_name, + use_explicit_precision, ctx); + + TF_RETURN_IF_ERROR(statusor.status()); + std::unique_ptr converter = std::move(statusor.value()); + + GraphDef graph = gdef; + if (cluster != nullptr) { + bool apply_layout_optim; + Status status = + ReadBoolFromEnvVar("TF_TRT_ENABLE_LAYOUT_OPTIMIZER", + /*default_value=*/true, &apply_layout_optim); + if (!status.ok()) { + LOG(ERROR) << status; + } + if (apply_layout_optim) { + tensorflow::grappler::GrapplerItem grappler_item; + grappler_item.graph = gdef; + + // Add device information to each node in the graphdef for successful + // execution of the layout optimizer + TF_RETURN_IF_ERROR(SetDeviceInfoInNodes(&grappler_item.graph, device)); + + // TensorRT API requires the input for convolution to be in NCHW. + tensorflow::grappler::GenericLayoutOptimizer layout_optimizer("NCHW"); + TF_RETURN_IF_ERROR( + layout_optimizer.Optimize(cluster, grappler_item, &graph)); + + grappler_item.graph = graph; + + tensorflow::grappler::ConstantFolding const_optimizer( + nullptr, + /*disable_compressed_tensor_optimization=*/false, + /*fold_quantization_emulation=*/false); + TF_RETURN_IF_ERROR( + const_optimizer.Optimize(cluster, grappler_item, &graph)); + + // The optimizers may break the topological order + // so we need these steps to restore it + Graph g(OpRegistry::Global()); + TF_RETURN_IF_ERROR( + ConvertGraphDefToGraph(GraphConstructorOptions(), graph, &g)); + g.ToGraphDef(&graph); + } + } + VLOG(1) << "Starting to convert TensorFlow ops to TensorRT layers"; + std::vector output_tensors; + int num_layers = converter->network()->getNbLayers(); + absl::flat_hash_set layer_names; + // Graph nodes are already topologically sorted during construction + for (const auto& node_def : graph.node()) { + const string& node_name = node_def.name(); + VLOG(2) << "Converting node " << node_name << ", op=" << node_def.op(); + if (IsEngineInput(node_name)) { + int32 slot_number = -1; + string type_key; + if (node_def.op() == "Placeholder") { + if (!strings::safe_strto32( // non-absl ok + node_name.c_str() + strlen(IONamePrefixes::kInputPHName), + &slot_number)) { + return errors::InvalidArgument("Failed to parse slot number from ", + node_name); + } + type_key = "dtype"; + } else if (tensorflow::grappler::IsArg(node_def)) { + // Maybe remove the dependence on grappler and re-implement IsArg, + // which is pretty simple (but could change if new Arg nodes are added) + slot_number = node_def.attr().at("index").i(); + type_key = "T"; + } else { + return errors::InvalidArgument( + "Node ", node_name, + " with is neither Placeholder nor Arg, instead ", node_def.op()); + } + DataType tf_dtype = node_def.attr().at(type_key).type(); + if (tf_dtype == DT_RESOURCE) { + VLOG(2) << "Adding engine input resource " << node_name; + if (ctx == nullptr) { + return errors::InvalidArgument( + "Variable resource type conversion requires a valid ctx"); + } + + if (ctx->input(slot_number).NumElements() == 0) { + return errors::InvalidArgument("Resource input ", node_name, + " is empty."); + } + TF_RETURN_IF_ERROR(converter->AddInputResource( + node_name, ctx->input(slot_number).flat()(0))); + } else { + nvinfer1::DataType trt_dtype; + nvinfer1::Dims trt_dims; + int batch_size = -1; + const auto shape = input_shapes.at(slot_number); + const auto status = ValidateTensorProperties( + node_def.op(), node_def.attr().at(type_key).type(), shape, + use_implicit_batch, /*validation_only=*/false, &trt_dtype, + &trt_dims, &batch_size); + if (!status.ok()) { + const string error_message = + StrCat("Validation failed for ", node_name, " and input slot ", + slot_number, ": ", status.message()); + LOG_WARNING_WITH_PREFIX << error_message; + return errors::CreateWithUpdatedMessage(status, error_message); + } + VLOG(2) << "Adding engine input tensor " << node_name << " with shape " + << DebugString(trt_dims); + // TODO(laigd): the conversion should always happen at runtime where all + // the shapes are known, and we can provide a mode to generate the + // engines offline, by calling sess.run() and cache/serialize the + // engines. + TF_RETURN_IF_ERROR(converter->AddInputTensor(node_name, trt_dtype, + trt_dims, batch_size)); + } + } else if (IsEngineOutput(node_name)) { + int32 slot_number = -1; + if (node_def.op() == "Identity") { + if (!strings::safe_strto32( // non-absl ok + node_name.c_str() + strlen(IONamePrefixes::kOutputPHName), + &slot_number)) { + return errors::InvalidArgument("Failed to parse slot number from ", + node_name); + } + } else if (tensorflow::grappler::IsRetval(node_def)) { + slot_number = node_def.attr().at("index").i(); + } else { + return errors::InvalidArgument( + "Node with name ", node_name, + " starting with IONamePrefixes::kOutputPHName is " + "neither Identity nor Retval, instead ", + node_def.op()); + } + // Get output type that TensorFlow expects + string out_type_key; + if (node_def.op() == "ReadVariableOp" || + node_def.op() == "ResourceGather") { + out_type_key = "dtype"; + } else { + out_type_key = "T"; + } + DataType tf_dtype; + TF_RETURN_IF_ERROR( + GetNodeAttr(AttrSlice(node_def), out_type_key, &tf_dtype)); + nvinfer1::DataType trt_dtype; + TF_RETURN_IF_ERROR(TfTypeToTrtType(tf_dtype, &trt_dtype)); + if (output_tensors.size() <= slot_number) { + output_tensors.resize(slot_number + 1); + } + output_tensors.at(slot_number) = {node_def.input(0), node_name, + trt_dtype}; + } else { + TF_RETURN_IF_ERROR(converter->ConvertNode(node_def)); + } + + // To support TF-TRT profiling, we ensure each ILayer has a non-empty name. + // BuildCudaEngine returns an error if there is any ILayer name collision. + // We want to report the error here before BuildCudaEngine in a more + // meaningful way. + int new_num_layers = converter->network()->getNbLayers(); + for (int i = num_layers; i < new_num_layers; i++) { + auto layer = converter->network()->getLayer(i); + if (layer->getName() == nullptr || + !layer_names.insert(layer->getName()).second) { + std::string error_message = absl::StrCat( + "Converting node ", node_name, ", op=", node_def.op(), + layer->getName() ? " creates a layer with name collision" + : " creates a layer without a name"); + LOG_WARNING_WITH_PREFIX << error_message; + return errors::Internal(error_message); + } + } + num_layers = new_num_layers; + } + TF_RETURN_IF_ERROR(converter->RenameAndMarkOutputTensors(output_tensors)); + if (convert_successfully) *convert_successfully = true; + + // Apply user provided quantization ranges to tensors + if (!use_explicit_precision) { + converter->MaybeApplyQuantizationRanges(); + } + + // Build the engine. + TF_RETURN_IF_ERROR(converter->BuildCudaEngine( + engine, max_batch_size, max_workspace_size_bytes, allocator, calibrator, + profiles)); + + VLOG(1) << "Finished conversion"; + return OkStatus(); +} + +Status ConvertSegmentToGraphDef( + const Graph* graph, const grappler::GraphProperties& graph_properties, + const std::vector& subgraph_nodes, // In topological order + EngineInfo* engine_info) { + tensorflow::profiler::TraceMe activity( + "ConvertSegmentToGraphDef", tensorflow::profiler::TraceMeLevel::kInfo); + std::vector* connections = &engine_info->connections; + GraphDef* segment_def = &engine_info->segment_graph_def; + std::set marker_nodes; + // Update connection shapes/data types and add corresponding input/output + // nodes in the segment graphdef. + for (size_t i = 0; i < connections->size(); ++i) { + tensorflow::profiler::TraceMe activity( + [&] { + return StrCat("Constructing TRTEngine IO: ", i + 1, "/", + connections->size()); + }, + tensorflow::profiler::TraceMeLevel::kInfo); + auto& connection = connections->at(i); + if (connection.is_control_edge()) continue; + auto outside_node = graph->FindNodeId(connection.outside_id); + if (!outside_node) { + // This should never happen, unless the original graph is problematic. + return errors::NotFound("Cannot find node with id ", + connection.outside_id, " in the graph."); + } + // Updates the shape and data types of input/output connections. + DataType dtype; + PartialTensorShape partial_shape; + if (connection.is_input_edge) { + GetOutputProperties(graph_properties, + graph->FindNodeId(connection.outside_id), + connection.outside_port, &partial_shape, &dtype); + connection.outside_shape = partial_shape; + } else { + GetInputProperties(graph_properties, + graph->FindNodeId(connection.outside_id), + connection.outside_port, &partial_shape, &dtype); + connection.inside_shape = partial_shape; + } + connection.connection_type = dtype; + + // Add dummy input/output nodes to the segment graphdef. + if (connection.is_input_edge) { + const string node_name = + StrCat(IONamePrefixes::kInputPHName, connection.port_number); + if (marker_nodes.count(node_name)) { + VLOG(1) << "Reusing input " << node_name << " for the edge " + << connection.outside_node_name << ":" + << connection.outside_port << " -> " + << connection.inside_node_name << ":" << connection.inside_port; + continue; + } + marker_nodes.insert(node_name); + auto seg_node = segment_def->add_node(); + NodeDefBuilder builder(node_name, "_Arg"); + auto status = builder.Attr("shape", partial_shape) + .Attr("T", dtype) + .Attr("index", connection.port_number) + .Finalize(seg_node); + VLOG(1) << "Constructing input " << node_name << " for the edge " + << connection.outside_node_name << ":" << connection.outside_port + << " -> " << connection.inside_node_name << ":" + << connection.inside_port; + } else { + const string node_name = + StrCat(IONamePrefixes::kOutputPHName, connection.port_number); + if (marker_nodes.count(node_name)) { + VLOG(1) << "Reusing output " << node_name << " for the edge " + << connection.inside_node_name << ":" << connection.inside_port + << " -> " << connection.outside_node_name << ":" + << connection.outside_port; + continue; + } + marker_nodes.insert(node_name); + auto seg_node = segment_def->add_node(); + NodeDefBuilder builder(node_name, "_Retval"); + auto status = + builder.Attr("T", dtype) + .Attr("index", connection.port_number) + .Input(connection.inside_node_name, connection.inside_port, dtype) + .Finalize(seg_node); + VLOG(1) << "Constructing output " << node_name << " for the edge " + << connection.inside_node_name << ":" << connection.inside_port + << " -> " << connection.outside_node_name << ":" + << connection.outside_port; + } + } // for each connection. + + std::unordered_map old_to_new_id_map; + // Copy internal nodes to new graphdef + string local_scope = subgraph_nodes.front()->name(); + int i = 0; + for (const Node* node : subgraph_nodes) { + tensorflow::profiler::TraceMe activity( + [&] { + return StrCat("Copy Node to Subgraph: ", ++i, "/", + subgraph_nodes.size()); + }, + tensorflow::profiler::TraceMeLevel::kInfo); + local_scope = GetCommonNameScope(local_scope, node->name()); + old_to_new_id_map[node->id()] = segment_def->node_size(); + auto snode = segment_def->add_node(); + *snode = node->def(); + VLOG(2) << "Copying " << snode->name() << " to subgraph"; + } + // Update the inputs of the new input nodes to point to placeholder nodes. + for (int i = 0; i < connections->size(); ++i) { + tensorflow::profiler::TraceMe activity( + [&] { + return StrCat("Updating Subgraph Input: ", i + 1, "/", + connections->size()); + }, + tensorflow::profiler::TraceMeLevel::kInfo); + + auto& connection = connections->at(i); + if (connection.is_control_edge() || !connection.is_input_edge) continue; + auto snode = + segment_def->mutable_node(old_to_new_id_map[connection.inside_id]); + const string arg_name = + StrCat(IONamePrefixes::kInputPHName, connection.port_number); + VLOG(1) << "Updating " << snode->name() << ":" << connection.inside_port + << " from " << snode->input(connection.inside_port) << " to " + << arg_name; + snode->set_input(connection.inside_port, arg_name); + } + + std::set subgraph_node_names; + { + tensorflow::profiler::TraceMe activity( + "Constructing subgraph_node_names set: ", + tensorflow::profiler::TraceMeLevel::kInfo); + + for (const Node* node : subgraph_nodes) { + subgraph_node_names.insert(node->name()); + } + } + + // Remove control inputs that are not inside the segment. + for (int i = 0; i < segment_def->node_size(); ++i) { + tensorflow::profiler::TraceMe activity( + [&] { + return StrCat("Removing outside to subgraph control inputs: ", i + 1, + "/", segment_def->node_size()); + }, + tensorflow::profiler::TraceMeLevel::kInfo); + auto snode = segment_def->mutable_node(i); + const int input_size = snode->input_size(); + int input_idx = 0; + int actual_input_idx = 0; + while (input_idx < input_size) { + TensorId input = ParseTensorName(snode->input(input_idx)); + if (!subgraph_node_names.count( + string(input.first.data(), input.first.size())) && + !IsEngineInput(input.first)) { + if (input.second == Graph::kControlSlot) { + VLOG(1) << "... removing control inputs " << input.first + << " from subgraph."; + ++input_idx; + continue; + } + /// TODO(lsugy): throw error when it's not a resource input. + } + if (actual_input_idx != input_idx) { + snode->set_input(actual_input_idx, snode->input(input_idx)); + } + ++input_idx; + ++actual_input_idx; + } + for (int remove = input_size - actual_input_idx; remove > 0; --remove) { + snode->mutable_input()->RemoveLast(); + } + } + return OkStatus(); +} + +bool OutputEdgeValidator::operator()(const Edge* out_edge) const { + if (out_edge->IsControlEdge()) return true; + if (out_edge->src()->type_string() == "Const") { + VLOG(1) << "--> Need to remove output node " << out_edge->src()->name() + << " which is a Const."; + return false; + } + return true; +} + +ITensorProxyPtr TRT_TensorOrWeights::as_tensor( + const OpConverterParams* params) { + if (is_tensor()) { + return tensor(); + } else { + return params->converter->CreateConstantLayer(weights(), GetTrtDims()); + } +} + +std::string unexpected_type_error_msg(nvinfer1::DataType type_being_checked, + nvinfer1::DataType type_expected, + const NodeDef& node_def, int idx) { + return "The '" + node_def.input(idx) + "' parameter of " + node_def.op() + + " operation in " + node_def.name() + " is expected to be of type " + + DebugString(type_expected) + " type, got " + + DebugString(type_being_checked) + "."; +} + +string batch_size_error(absl::string_view name, absl::string_view comment) { + return StrCat("Batch size doesn't match for tensor '", name, "' : ", comment); +} + +Status check_type(nvinfer1::DataType type_being_checked, + nvinfer1::DataType type_expected, const NodeDef& node_def, + int idx) { + if (type_being_checked == type_expected) return OkStatus(); + + return errors::InvalidArgument(unexpected_type_error_msg( + type_being_checked, type_expected, node_def, idx)); +} + +std::string convert_not_supported_implicit(const std::string& pOpName, + const std::string& pNodeName, + const char* pOpType) { + const auto oper = pOpType ? absl::StrCat(pOpType, " ") : string(""); + return absl::StrCat("Convertion for ", oper, "op: '", pOpName, + "' is not supported in implicit batch mode, at ", + pNodeName); +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h new file mode 100644 index 0000000000000000000000000000000000000000..a8a056c7a6a4765ecedd72a92509f65b894f08a3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h @@ -0,0 +1,593 @@ +/* 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_TF2TENSORRT_CONVERT_CONVERT_NODES_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_NODES_H_ + +#include +#include +#include +#include +#include + +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/weights.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/grappler/costs/graph_properties.h" +#include "tensorflow/core/lib/core/status.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +namespace convert { +using ::tsl::StatusOr; + +struct EngineConnection { + // Constructs a non-control edge. + EngineConnection(const string& outside, int out_id, int out_port, + const string& inside, int in_id, int in_port, + bool input_edge, int port) + : outside_node_name(outside), + outside_id(out_id), + outside_port(out_port), + inside_node_name(inside), + inside_id(in_id), + inside_port(in_port), + is_input_edge(input_edge), + port_number(port) {} + + // Constructs a control edge. + EngineConnection(const string& outside, int out_id, const string& inside, + int in_id, bool input_edge) + : outside_node_name(outside), + outside_id(out_id), + outside_port(Graph::kControlSlot), + inside_node_name(inside), + inside_id(in_id), + inside_port(Graph::kControlSlot), + is_input_edge(input_edge), + port_number(Graph::kControlSlot) {} + + bool is_control_edge() const { return port_number == Graph::kControlSlot; } + + const string outside_node_name; + const int outside_id; + const int outside_port; + PartialTensorShape outside_shape; // Only set for input edge. + + const string inside_node_name; + const int inside_id; + const int inside_port; + PartialTensorShape inside_shape; // Only set for output edge. + + DataType connection_type; + const bool is_input_edge; + + // The port number of the TRT node connected with this edge. + const int port_number; +}; + +struct EngineInfo { + EngineInfo() + : engine_type(EngineType::TRTStatic), + max_workspace_size_bytes(0), + max_batch_size(std::nullopt), + maximum_cached_engines(0), + precision_mode(TrtPrecisionMode::FP32), + use_calibration(true), + + allow_build_at_runtime(true), + use_explicit_precision(false) {} + + string engine_name; + string device; + GraphDef segment_graph_def; + + // Non-control input connections inside this vector are sorted in a way such + // that, the segment nodes connecting to them are topological sorted. + // In addition, for non-control connections, there must be no duplicates. + std::vector connections; + + enum class EngineType { TRTStatic = 0, TRTDynamic = 1 }; + EngineType engine_type; + int64 max_workspace_size_bytes; + std::optional max_batch_size; + int maximum_cached_engines; + TrtPrecisionMode precision_mode; + bool use_calibration; + bool allow_build_at_runtime; + bool use_explicit_precision; +}; + +// Constructs a graphdef from the segment in the given graph and stores it to +// the engine_info. Adds _Arg nodes for input edges (InputPH_*) and _Retval +// nodes for output edges (OutputPH_*). Maintains the topological order of the +// non-input/output nodes in the graphdef. This function needs to be called +// before TensorRT layers are created because it prepares the original graph +// for TensorRT conversion. +// +// - subgraph_node_names: the node names of the subgraph. +// - subgraph_node_ids: the node ids of the subgraph, must be sorted in +// topological order. +// - engine_info: a data structure that records the information about the +// engine containing the subgraph. +// +// TODO(aaroey): add tests to validate these properties. +Status ConvertSegmentToGraphDef( + const Graph* graph, const grappler::GraphProperties& graph_properties, + const std::vector& subgraph_nodes, EngineInfo* engine_info); + +// Converts given subgraph to a TRT engine saved in 'engine'. Returns ok iff +// 'builder' successfully build the engine. If the result is not ok, 'engine' +// will be set to nullptr +// Once returned, 'builder' is not needed any more and can be safely destroyed. +// +// - convert_successfully: indicates whether the conversion to TensorRT network +// is successful. This is different than successfully building the engine: +// building can still fail afterwards. +// Note: When 'cluster' is not null, it contains the graph to be converted. +// We may perform additional optimizations to the graph before converting +// the graph. +Status ConvertGraphDefToEngine( + const GraphDef& gdef, OpKernelContext* ctx, TrtPrecisionMode precision_mode, + int max_batch_size, size_t max_workspace_size_bytes, + const std::vector& input_shapes, + nvinfer1::ILogger* logger, nvinfer1::IGpuAllocator* allocator, + TRTInt8Calibrator* calibrator, + TrtUniquePtrType* engine, bool use_calibration, + const bool use_implicit_batch, bool* convert_successfully, + TrtShapeOptimizationProfile* profiles, absl::string_view engine_name, + bool use_explicit_precision, + tensorflow::grappler::Cluster* cluster = nullptr, + const string& device = ""); + +// Helper class for the segmenter to determine whether an output edge from the +// TRT segment is valid. +class OutputEdgeValidator { + public: + // Return true if the specified edge is eligible to be an output edge of the + // TRT segment. + bool operator()(const Edge* out_edge) const; +}; + +// Class to verify if specific TF node is supported by TRT. +class TrtNodeValidator { + public: + // 'graph_properties' is the GraphProperties of the graph whose nodes will be + // checked by IsTensorRTCandidate() later. It is used to get the shape and + // data type information of a tensor for validation purpose. + TrtNodeValidator(const grappler::GraphProperties& graph_properties, + TrtPrecisionMode precision_mode, bool use_calibration, + bool use_implicit_batch, bool use_explicit_precision); + + // Returns OK iff 'node' is a TF-TRT conversion candidate, which will be added + // to TRT subgraph and later converted into TRT engine. + Status IsTensorRTCandidate(const Node* node); + + static const std::set* quantize_ops; + + // Returns validator by op type. If no validator is registered for + // specific op, it means no validation is needed and ValidateNode() will + // return OK. + StatusOr GetValidator(const std::string& op); + + private: + // Convert a Const node to a TRT_TensorOrWeights. + Status ConvertConstToWeights(const NodeDef& const_node_def, + const std::vector& inputs, + TRT_TensorOrWeights* output); + + // Convert a VariableV2 node to a TRT_TensorOrWeights. + Status ConvertVariableToWeights( + const NodeDef& const_node_def, + const std::vector& inputs, + TRT_TensorOrWeights* output); + + // Convert the output tensor at 'output_port' of 'node_def' to a + // TRT_TensorOrWeights which will be later used as an input to other nodes and + // passed to ValidateNode() below. + Status ConvertToTensorOrWeights(const NodeDef& node_def, int output_port, + TRT_TensorOrWeights* tensor_or_weights); + + // Store the weights added during validation. Some validations (e.g. + // validation for Const node) may produce weights. + TrtWeightStore weight_store_; + + // GraphProperties of the graph whose nodes are to be validated by + // IsTensorRTCandidate(). + const grappler::GraphProperties& graph_properties_; + + // Quantization ops are only converted when using quantized precisions. + const TrtPrecisionMode precision_mode_; + + const bool use_calibration_; + + const bool use_implicit_batch_; + + const bool use_explicit_precision_; + + friend class ValidatorTest; + friend class OpConverterTest; +}; + +// Class to convert TF nodes to TRT network. +class Converter { + public: + // Used for Converter::RenameAndMarkOutputTensors() + struct EngineOutputInfo { + // The TRT tensor name which produces the output. + string source_tensor_name; + // The TensorFlow node name which is receiving the output from the TRT + // engine. This should always be the Identity node created in + // ConvertSegmentToGraphDef. + string dest_node_name; + // Output type. TensorRT requires this to be explicitly set for engine + // outputs. + nvinfer1::DataType trt_dtype; + }; + + static StatusOr> Create( + TrtPrecisionMode precision_mode, bool use_calibration, + nvinfer1::ILogger* trt_logger, const bool use_implicit_batch, + absl::string_view engine_name, bool use_explicit_precision = false, + OpKernelContext* ctx = nullptr); + + ////////////////////////////////////////////////////////////////////////////// + // Methods used by the TRT engine builder to build a TRT network from a TF + // function/subgraph. + + // Convert the node to TRT network. + Status ConvertNode(const NodeDef& node_def); + + // Add input tensor to the TRT network with given 'name', 'dtype', 'dims' and + // 'batch_size'. + Status AddInputTensor(const string& name, nvinfer1::DataType dtype, + const nvinfer1::Dims& dims, int batch_size); + + // Store the ResourceHandle as a TRT_TensorOrWeights object. This can be + // later used as input to other nodes. + Status AddInputResource(const string& name, const ResourceHandle& resource); + + // Mark the tensors with names specified by source_tensor_name as output of + // the TRT network, and set their names in the TRT network as dest_node_name. + Status RenameAndMarkOutputTensors( + const std::vector& output_tensors); + + // Build a TRT engine using the created network. + Status BuildCudaEngine(TrtUniquePtrType* engine, + int max_batch_size, size_t max_workspace_size_bytes, + nvinfer1::IGpuAllocator* allocator, + TRTInt8Calibrator* calibrator, + TrtShapeOptimizationProfile* profiles); + + ////////////////////////////////////////////////////////////////////////////// + // Methods used by op converters to convert individual TF node and add layers + // to the TRT network. + + // Op converters (e.g. ConvertReshape) need to access the TRT network in order + // to add TRT layers. + nvinfer1::INetworkDefinition* network() { return trt_network_.get(); } + + // What precision are we targeting? + TrtPrecisionMode precision_mode() const { return precision_mode_; } + + // Variable converters need the context to read variable values. + OpKernelContext* context() { return ctx_; } + + // Calibration will be or was previously performed on this network? + bool use_calibration() const { return use_calibration_; } + + // Whether implicit batch mode is enabled + bool use_implicit_batch() const { return use_implicit_batch_; } + + // This function should be called when we know the quantization range of a + // tensor from a quantize/dequantize node. + void ProvideQuantizationRange(ITensorProxyPtr* tensor, float min_range, + float max_range); + + // Should be called when full TRT network has been constructed and before + // building the engine. + void MaybeApplyQuantizationRanges(); + + // Below are helper methods for op converters to add different layers to the + // TRT network. + + // Transpose 'input_tensor' with given permutation 'order_with_batch_dim' to + // 'output_tensor'. The permutation 'order_with_batch_dim' contains the batch + // dimension which should always be 0. If this is for adding a transpose layer + // to support the conversion of 'node_def', callers need to provide a + // non-empty 'sub_op_name' appended to the name of 'node_def' to avoid layer + // name conflicts. + Status TransposeTensor(ITensorProxyPtr input_tensor, + const std::vector& order_with_batch_dim, + ITensorProxyPtr* output_tensor, + const NodeDef& node_def, + absl::string_view sub_op_name = ""); + + // Reshapes a dynamic shape tensor by removing or adding dimensions of size 1, + // and/or permuting the dimensions. The new shape is derived from the shape of + // the input tensor according to the slices and size_for_added_dims arguments. + // + // If there would be at most one unknown dimension, we could set the new shape + // using IShuffleLayer::setReshapeDimensions, which treats -1 as a special + // value (the same way as TF). In general, we can have more than one unknown + // dimensions, and we have to manipulate the shape tensors during runtime to + // define the new shape. This helper function defines the necessary shape + // inference layers and calls reshape using the calculated new shape. + // + // Example: + // + // Assume that we want to reshape a tensor from shape {A,B,C,D} to {C,D,A,B} + // (no transpose, just change the shape). In dynamic shape mode, the A,B,C,D + // values are not necessarily known at conversion time, they can be all -1. We + // can only define the new shape at runtime, when the actual shape is already + // known. To define the new shape: + // - We use an IShapeLayer to retrieve a shape tensor with the {A,B,C,D} + // values. + // - Create two slices {C,D} and {A,B} of the shape tensor. + // - Concatenate these slices {C,D,A,B}, + // - Set the {C,D,A,B} shape tensor as an input shape tensor for + // IShuffleLayer. + // + // This can be achieved by calling DynamicReshape(input, {{2,4},{0,2}}, + // params). + // + // Before each slice we can insert new dims if the corresponding + // size_for_added_dims element is not negative. The size_for_added_dims array + // can have more than slices.size() elements, in order to insert a dimension + // after the last slice. For example, to add two leading 1 dimensions, and + // three trailing 1 dimensions, call DynamicReshape(input, {{0,nbDims}}, + // {2, 3}). + // + // Parameters: + // input - input tensor + // slices - [start, end) pairs of slices + // params - conversion parameters + // output - reshaped tensor + // size_for_added_dims - size of dimension inserted right before slice[i]. We + // only insert a new dim if size_for_added_dims[i] >= 0. + Status DynamicReshape(ITensorProxyPtr input, + std::vector> slices, + const OpConverterParams* params, + ITensorProxyPtr* output, + std::vector size_for_added_dims = {}, + std::optional op_instance = std::nullopt); + + // Inserts a singleton dimension at axis for a dynamic shape tensor. + Status DynamicExpandDims(ITensorProxyPtr input, const nvinfer1::Dims& dims, + int axis, const OpConverterParams* params, + ITensorProxyPtr* output, + std::optional op_instance = std::nullopt); + + // Helper function to add a squeeze op to the network. + // + // The input_dims argument stores the TRT dimensions of the input tensor, + // where the dimensions to be squeezed are replaced by 0. + Status SqueezeTensor(ITensorProxyPtr input, std::vector* input_dims, + const OpConverterParams* params, ITensorProxyPtr* output, + std::optional op_instance = std::nullopt); + + // Creates an IConstantLayer using 'weights' whose dimensions are specified by + // 'dims', and returns the output ITensor. + ITensorProxyPtr CreateConstantLayer(const TRT_ShapedWeights& weights, + const nvinfer1::Dims& dims); + + // Gets the min and max value in a TRT_ShapedWeights + Status GetWeightRange(const TRT_ShapedWeights& weights, float* out_min, + float* out_max) const; + + // Constructs a name and passed it to the TensorRT layer to support xprof. + void SetLayerName(nvinfer1::ILayer* layer, const NodeDef& node_def, + absl::string_view sub_op_name = "", + std::optional sub_op_instance = std::nullopt, + std::optional origin_node_name = std::nullopt); + + void SetLayerName(nvinfer1::ILayer* layer, absl::string_view main_op_name, + absl::string_view sub_op_name, + std::optional sub_op_instance = std::nullopt); + + std::unordered_map& TensorsMap() { + return trt_tensors_; + } + + bool UseExplicitPrecision() const { return use_explicit_precision_; } + + private: + Converter(TrtPrecisionMode precision_mode, bool use_calibration, + nvinfer1::ILogger* trt_logger, const bool use_implicit_batch, + absl::string_view engine_name, bool use_explicit_precision, + OpKernelContext* ctx); + + Status Init(nvinfer1::ILogger* trt_logger); + + // Verify the provided batch_size is consistent with batch_size_ and update it + // if necessary. + Status MaybeUpdateBatchSize(int batch_size); + + // Add the provided tensor/weights to the map trt_tensors_. + Status AddTensorOrWeights(const string& name, TRT_TensorOrWeights input); + + // Get the tensor/weights from trt_tensors_ by 'name'. + Status GetTensorOrWeights(const string& name, TRT_TensorOrWeights* output); + + // Get the inputs of 'node_def' from trt_tensors_. + Status GetInputs(const NodeDef& node_def, + std::vector* inputs) const; + + // Tensors/weights added during construction of trt_network_. + std::unordered_map trt_tensors_; + + // The TRT builder used to create the network and build the engine. Not owned. + TrtUniquePtrType trt_builder_; + + // The TRT network being built. + TrtUniquePtrType trt_network_; + + // Store the weights added during construction of trt_network_. + TrtWeightStore weight_store_; + + // Store the context. + OpKernelContext* ctx_; + + // During conversion, this table is populated with quantization ranges per + // tensor. MaybeApplyQuantizationRanges() will use this table to set the TRT + // quantization ranges. Since TRT only supports symmetric ranges, we will + // store the range as a single float = max(abs(min_range), abs(max_range)). + // Range refers to the floating point values, e.g. min_range = 0.0f, max_range + // = 6.0f for Relu6. + std::unordered_map quantization_ranges_proxy_; + std::unordered_map quantization_ranges_; + + const TrtPrecisionMode precision_mode_; + + const bool use_calibration_; + + // If this is false, all dimensions including the batch dimension are + // set explicitly. + const bool use_implicit_batch_; + + // Batch size of inputs to trt_network_ added by AddInputTensor(). During + // network construction it will update this, use it to verify the batch + // size of all inputs are compatible, and make sure individual TF node is + // acceptable by TRT. + int batch_size_ = -1; + + // Assign a ID to each constant layer we create, so that we can assign a + // unique name to the layer. + int next_constant_layer_id_ = 0; + + // The name of the TRTEngineOp node. + absl::string_view engine_name_; + + // Indicates whether to use explicit precision in TensorRT (Q/DQ support). + bool use_explicit_precision_; + + friend class ConverterTest; + friend class OpConverterTest; +}; + +// Converts a TensorFlow tensor to TRT shaped weights. +Status TfTensorToTrtWeights(const Tensor& tensor, TrtWeightStore* weight_store, + TRT_ShapedWeights* weights); + +// Converts 'input' of 'node_def' into 'tensor' with shape specified by 'dims' +// (which doesn't contain the batch dimension). +// +// If validation_only is true, it doesn't do the conversion but only do some +// minimum validation for the eligibility of the conversion, and *tensor will +// be set to nullptr. +// If validation_only is false converter must not be nullptr. +Status PrepareTensorForShape( + Converter* converter, const TRT_TensorOrWeights& input, + const DimsAdapter& dims, const bool validation_only, + ITensorProxyPtr* tensor, const NodeDef& node_def, + std::optional op_instance = std::nullopt, + std::optional origin_node_name = std::nullopt); + +// Return OK if the broadcast scheme is supported and compute the shapes after +// broadcasting. check_feasibility can be set to false in cases where dimensions +// do not need to match exactly (as in the case of BatchMatMulV2). +Status GetTrtBroadcastShape(const TRT_TensorOrWeights& operand_l, + const TRT_TensorOrWeights& operand_r, + const bool check_feasibility, + const bool use_implicit_batch, + nvinfer1::Dims* operand_l_new_dims, + nvinfer1::Dims* operand_r_new_dims); + +template +using OperationMap = std::unordered_map; + +// Map from Tensorflow operation names to TensorRT unary operations. +using UnaryOperationMapType = OperationMap; +const UnaryOperationMapType* UnaryOperationMap(); + +// Map from Tensorflow boolean operation names to TensorRT unary operations. +const UnaryOperationMapType* UnaryBooleanOperationMap(); + +// Map of all supported ActivationTypes. +using ActivationTypeMapType = OperationMap; +const ActivationTypeMapType* ActivationTypeMap(); + +// Map from Tensorflow binary operation names to TensorRT binary operations +// types. +using BinaryOperationMapType = OperationMap; +const BinaryOperationMapType* BinaryOperationMap(); + +// Map from Tensorflow boolean binary operation names to TensorRT binary +// operations types. +const BinaryOperationMapType* BinaryBooleanOperationMap(); + +template +absl::InlinedVector GetOperationNames(const T& set) { + absl::InlinedVector result; + absl::c_transform(set, std::back_inserter(result), + [](const auto x) { return x.first; }); + return result; +} + +// Adds a matrix multiplication operation to the TensorRT graph. The "params" +// pointer is only used to access the TRT network builder. The inputs and +// parameters for the op are fully specified by input_[a|b] and transpose_[a|b]. +StatusOr ConvertMatMulImpl(const OpConverterParams* params, + TRT_TensorOrWeights input_a, + TRT_TensorOrWeights input_b, + bool transpose_a, bool transpose_b); + +Status ApplyBroadcast(std::unique_ptr& operand, + const DimsAdapter& broadcasted_dims, + const OpConverterParams* params, + std::optional op_instance); + +std::string convert_range_error_msg(float start, float limit, float delta); +std::string convert_range_expected_msg(const NodeDef& node_def); +std::string bool_weight_error_msg(const NodeDef& node_def); +std::string unexpected_type_error_msg(nvinfer1::DataType type_being_checked, + nvinfer1::DataType type_expected, + const NodeDef& node_def, int idx = 0); +std::string then_else_dtypes_error_msg(nvinfer1::DataType type_then, + nvinfer1::DataType type_else, + const NodeDef& node_def); +std::string input_shapes_error_msg(const nvinfer1::Dims& shape1, + const nvinfer1::Dims& shape2, + const NodeDef& node, + bool then_vs_else = false); +std::string batch_size_error(absl::string_view name, absl::string_view comment); + +inline bool find_name(const string& name, const std::vector names) { + return std::find(names.begin(), names.end(), name) != names.end(); +} + +Status check_type(nvinfer1::DataType type_being_checked, + nvinfer1::DataType type_expected, const NodeDef& node_def, + int idx = 0); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_CONVERT_NODES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b23a10d05b7ace0829db0d08f92f6eb12122c066 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/convert_nodes_test.cc @@ -0,0 +1,9951 @@ +/* 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/tf2tensorrt/convert/convert_nodes.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/time/civil_time.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include +#include "absl/algorithm/container.h" +#include "absl/base/call_once.h" +#include "absl/container/inlined_vector.h" +#include "absl/strings/match.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "Eigen/Core" // from @eigen_archive +#include "third_party/gpus/cuda/include/cuda.h" +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/nn_ops_internal.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/compiler/tf2tensorrt/common/datavec.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_testutils.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/gpu/gpu_managed_allocator.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_factory.h" +#include "tensorflow/core/framework/node_def.pb.h" // NOLINT +#include "tensorflow/core/framework/resource_var.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor.pb.h" // NOLINT +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/grappler/costs/graph_properties.h" +#include "tensorflow/core/kernels/variable_ops.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/status_matchers.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/threadpool.h" +#include "tensorflow/core/protobuf/config.pb.h" // NOLINT +#include "tensorflow/core/public/session.h" +#include "tensorflow/core/public/version.h" +#include "tensorflow/core/util/tensor_slice_reader_cache.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +// TensorRT modes for testing. We define the following three modes: +// 1. Implicit batch mode: The tensors have static (known) input shape and the +// the batch dimension (first dim) is removed from the TRT tensor shape. In +// a loose notation: trt_shape = tf_shape[1:]. +// 2. Explicit batch mode: static (known) input shape, but the batch dimension +// is part of the trt tensor shape. (trt_shape = tf_shape) +// 3. Dynamic shape mode allows unknown input shapes, and requires explicit +// batch size definition (trt_shape = tf_shape). +// +// Note that the Converter only distinguishes between two modes: +// - use_implicit_batch == true, this corresponds to kImplicitBatch, +// - use_implicit_batch == false which includes both kExplicitBatch and +// kDynamicShape. +// +// For the converter, the distinction between explicit batch or dynamic shape +// mode follows from the input tensors of the network: dynamic shape input +// implies dynamic shape mode, while static shape input tensors imply explicit +// batch mode. We want to test all these modes, therefore we define the +// TrtTestMode with the following three options. +enum class TrtTestMode { + kImplicitBatch = 0, + kExplicitBatch = 1, + kDynamicShape = 2 +}; + +string DebugString(const TrtTestMode mode) { + switch (mode) { + case TrtTestMode::kImplicitBatch: + return "kImplicitBatch"; + case TrtTestMode::kExplicitBatch: + return "kExplicitBatch"; + case TrtTestMode::kDynamicShape: + return "kDynamicShape"; + default: + return "Invalid TrtTestMode"; + } +} + +namespace convert { + +using absl::StrCat; +using ::testing::ElementsAre; +using ::testing::ElementsAreArray; +using ::testing::HasSubstr; +using ::testing::Matcher; +using ::testing::PrintToString; + +using ::tensorflow::testing::IsOk; +using ::tensorflow::testing::StatusIs; + +constexpr std::array ValidTrtModes = { + TrtTestMode::kImplicitBatch, TrtTestMode::kExplicitBatch, + TrtTestMode::kDynamicShape}; + +bool TrtShapedWeightsEquals(const TRT_ShapedWeights& lhs, + const TRT_ShapedWeights& rhs) { + return lhs.Shape() == rhs.Shape() && lhs.TrtDType() == rhs.TrtDType() && + lhs.GetPointer() == rhs.GetPointer(); +} + +template +void ValidateWeights(const TRT_ShapedWeights& weights, + const std::vector& expected_dims, + const std::vector& expected_value) { + EXPECT_EQ(weights.Shape(), DimsAdapter(expected_dims)); + ASSERT_EQ(expected_value.size(), weights.count()) << weights.DebugString(); + const T* actual_values = weights.GetPointer(); + for (int i = 0; i < expected_value.size(); ++i) { + EXPECT_EQ(expected_value[i], actual_values[i]); + } +} + +TEST(TRT_ShapedWeights_Test, Basic) { + // Test constructor with no arguments. + { + TRT_ShapedWeights weights; + TRT_ShapedWeights copy(weights); + for (auto ptr : {&weights, ©}) { + nvinfer1::Weights trt_weights = ptr->GetTrtWeights(); + EXPECT_EQ(nvinfer1::DataType::kFLOAT, trt_weights.type); + EXPECT_EQ(nullptr, trt_weights.values); + EXPECT_EQ(0, trt_weights.count); + + EXPECT_EQ(nullptr, ptr->GetPointer()); + EXPECT_EQ(0, ptr->count()); + EXPECT_EQ(0, ptr->size_bytes()); + } + } + // Test constructor with DataType argument. + { + TRT_ShapedWeights weights(nvinfer1::DataType::kFLOAT); + TRT_ShapedWeights copy(weights); + for (auto ptr : {&weights, ©}) { + nvinfer1::Weights trt_weights = ptr->GetTrtWeights(); + EXPECT_EQ(nvinfer1::DataType::kFLOAT, trt_weights.type); + EXPECT_EQ(nullptr, trt_weights.values); + EXPECT_EQ(0, trt_weights.count); + + EXPECT_EQ(nullptr, ptr->GetPointer()); + EXPECT_EQ(0, ptr->count()); + EXPECT_EQ(0, ptr->size_bytes()); + } + } + // Test constructor with DataType and nvinfer1::Dims arguments. + { + TrtWeightStore store; + TRT_ShapedWeights weights = + store.GetTempWeights(nvinfer1::DataType::kFLOAT, CreateDims({2, 5})) + .value(); + TRT_ShapedWeights copy(weights); + for (auto ptr : {&weights, ©}) { + nvinfer1::Weights trt_weights = ptr->GetTrtWeights(); + EXPECT_EQ(nvinfer1::DataType::kFLOAT, trt_weights.type); + EXPECT_NE(nullptr, trt_weights.values); + EXPECT_EQ(10, trt_weights.count); + + EXPECT_EQ(trt_weights.values, ptr->GetPointer()); + EXPECT_EQ(10, ptr->count()); + EXPECT_EQ(40, ptr->size_bytes()); + } + // Test that it doesn't copy the underlying buffer. + EXPECT_EQ(weights.GetPointer(), copy.GetPointer()); + } +} + +TEST(TRT_TensorOrWeights_Test, Basic) { + // Test constructor with no arguments. + { + TRT_TensorOrWeights tw; + TRT_TensorOrWeights copy(tw); + TRT_TensorOrWeights assigned; + assigned = tw; + for (auto ptr : {&tw, ©, &assigned}) { + EXPECT_EQ(false, ptr->is_tensor()); + EXPECT_EQ(false, ptr->is_weights()); + EXPECT_EQ(-1, ptr->batch_size()); + } + } + + // Test constructor with ITensor and batch size argument. + { + nvinfer1::Dims dims; + dims.nbDims = 1; + dims.d[0] = 1; + ITensorProxyPtr itensor(dims); + TRT_TensorOrWeights tw(itensor); + TRT_TensorOrWeights tw1(itensor, /*batch_size=*/1); + + for (auto original_ptr : {&tw, &tw1}) { + TRT_TensorOrWeights copy(*original_ptr); + TRT_TensorOrWeights assigned; + assigned = *original_ptr; + + for (auto ptr : {original_ptr, ©, &assigned}) { + ASSERT_TRUE(ptr->is_tensor()); + EXPECT_EQ(false, ptr->is_weights()); + if (original_ptr == &tw) { + EXPECT_EQ(-1, ptr->batch_size()); + } else { + EXPECT_EQ(1, ptr->batch_size()); + } + EXPECT_EQ(itensor->simple_tensor(), ptr->tensor()->simple_tensor()); + EXPECT_THAT(ptr->GetTrtDims(), DimsAreArray({1})); + } + } + } + // Test constructor which creates and owns an ITensor. + { + nvinfer1::Dims dims; + dims.nbDims = 1; + dims.d[0] = 1; + TRT_TensorOrWeights tw(nvinfer1::DataType::kFLOAT, dims, /*batch_size=*/1); + TRT_TensorOrWeights copy(tw); + TRT_TensorOrWeights assigned; + assigned = tw; + + for (auto ptr : {&tw, ©, &assigned}) { + ASSERT_TRUE(ptr->is_tensor()); + EXPECT_EQ(false, ptr->is_weights()); + EXPECT_EQ(1, ptr->batch_size()); + EXPECT_NE(nullptr, ptr->tensor()->simple_tensor()); + EXPECT_THAT(ptr->GetTrtDims(), DimsAreArray({1})); + } + } + // Test constructor with TRT_ShapedWeights argument. + { + TRT_ShapedWeights weights; + TRT_TensorOrWeights tw(weights); + TRT_TensorOrWeights copy(tw); + TRT_TensorOrWeights assigned; + assigned = tw; + for (auto ptr : {&tw, ©, &assigned}) { + EXPECT_EQ(false, ptr->is_tensor()); + EXPECT_EQ(true, ptr->is_weights()); + EXPECT_TRUE(TrtShapedWeightsEquals(weights, ptr->weights())); + std::vector empty_dims; + EXPECT_THAT(ptr->GetTrtDims(), DimsAreArray(empty_dims)); + } + } +} + +class ValidatorTest : public ::testing::Test { + public: + ValidatorTest() {} + Status ConvertToTensorOrWeights(const Scope& scope, const Node* node, + int output_port, + TRT_TensorOrWeights* tensor_or_weights) { + grappler::GrapplerItem item; + TF_EXPECT_OK(scope.ToGraphDef(&item.graph)); + grappler::GraphProperties graph_properties(item); + TF_EXPECT_OK(graph_properties.InferStatically(true)); + + TrtNodeValidator validator(graph_properties, TrtPrecisionMode::FP32, + /*use_calibration=*/false, + /*use_implicit_batch=*/true, + /*use_explicit_precision=*/false); + return validator.ConvertToTensorOrWeights(node->def(), output_port, + tensor_or_weights); + } +}; + +TEST_F(ValidatorTest, ConvertToTensorOrWeights) { + // Convert Const. + { + Scope s = Scope::NewRootScope(); + auto node = + ops::Const(s.WithOpName("my_const"), {1.0f, 2.0f}, TensorShape({2})); + TRT_TensorOrWeights output; + EXPECT_THAT(ConvertToTensorOrWeights(s, node.op().node(), + /*output_port=*/0, &output), + IsOk()); + ValidateWeights(output.weights(), {2}, {1.0, 2.0}); + } + + // Helper method to run ConvertToTensorOrWeights() with predefined parameters. + auto convert_to_tensor_or_weights = [this](const std::vector& dims, + TRT_TensorOrWeights* output) { + Scope s = Scope::NewRootScope(); + const auto attrs = ops::Placeholder::Shape(PartialTensorShape{dims}); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT, attrs); + auto add = ops::Add(s.WithOpName("add"), feed, feed); + return this->ConvertToTensorOrWeights(s, add.operation.node(), + /*output_port=*/0, output); + }; + // Convert non-Const with #dims > nvinfer1::Dims::MAX_DIMS+1. + { + TRT_TensorOrWeights output; + EXPECT_THAT( + convert_to_tensor_or_weights( + std::vector(nvinfer1::Dims::MAX_DIMS + 2, 1), &output), + StatusIs(absl::StatusCode::kOutOfRange, + HasSubstr("Input tensor rank is greater than 9"))); + } + // Convert non-Const with #dims < 1. + { + TRT_TensorOrWeights output; + EXPECT_THAT(convert_to_tensor_or_weights({}, &output), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Scalar input tensor is not supported since " + "the first dimension " + "is treated as batch dimension by TRT"))); + } + // Convert non-Const. We test the case where the non-batch dimension is + // unknown as well, to make sure the validator allows that. + for (const int32 non_batch_dim : {-1, 2}) { + const int32 batch_size = 12; + TRT_TensorOrWeights output; + EXPECT_THAT( + convert_to_tensor_or_weights({batch_size, non_batch_dim}, &output), + IsOk()); + ASSERT_TRUE(output.is_tensor()); + EXPECT_EQ(batch_size, output.batch_size()); + EXPECT_NE(nullptr, output.tensor()->simple_tensor()); + EXPECT_THAT(output.GetTrtDims(), DimsAreArray({non_batch_dim})); + } +} + +TEST_F(ValidatorTest, IsTensorRTCandidate_Basics) { + Scope s = Scope::NewRootScope(); + auto input = + ops::Const(s.WithOpName("const"), {1.0f, 2.0f}, TensorShape({2})); + auto add = ops::Add(s.WithOpName("add"), input, input); + const Node* add_node = add.operation.node(); + + grappler::GrapplerItem item; + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + grappler::GraphProperties graph_properties(item); + TF_EXPECT_OK(graph_properties.InferStatically(true)); + TrtNodeValidator validator(graph_properties, TrtPrecisionMode::FP32, + /*use_calibration=*/false, + /*use_implicit_batch=*/true, + /*use_explicit_precision=*/false); + + // Override the Add converter. + bool start_conversion = false; + bool should_fail = false; + auto op_converter = [&start_conversion, &should_fail]( + const OpConverterParams* params) -> Status { + if (should_fail) return errors::InvalidArgument(""); + if (!params->validation_only) start_conversion = true; + return OkStatus(); + }; + + // Validator not registered. + auto original_op_converter = GetOpConverterRegistry()->LookUp("Add"); + ASSERT_TRUE(original_op_converter.ok()); + GetOpConverterRegistry()->Clear("Add"); + EXPECT_THAT(validator.IsTensorRTCandidate(add_node), + StatusIs(absl::StatusCode::kUnimplemented, + HasSubstr("Op type Add is not supported."))); + GetOpConverterRegistry()->Register("Add", kDefaultConverterPriority + 1, + op_converter); + TF_EXPECT_OK(validator.IsTensorRTCandidate(add_node)); + EXPECT_EQ(false, start_conversion); + + // Let the converter return error. + should_fail = true; + EXPECT_THAT(validator.IsTensorRTCandidate(add_node), + StatusIs(absl::StatusCode::kInvalidArgument)); + GetOpConverterRegistry()->Clear("Add"); + GetOpConverterRegistry()->Register("Add", kDefaultConverterPriority, + *original_op_converter); +} + +TEST(TrtNodeValidator, IsTensorRTCandidate) { + // Create a graph containing both TRT-compatible and TRT-incompatible nodes + // and use it to test TrtNodeValidator::IsTensorRTCandidate(). + const std::vector input_shape_array{2, 2}; + TensorShape input_shape; + TF_EXPECT_OK(TensorShapeUtils::MakeShape(input_shape_array, &input_shape)); + + Scope s = Scope::NewRootScope(); + ops::Placeholder::Attrs feed_attrs; + TF_EXPECT_OK( + TensorShapeUtils::MakeShape(input_shape_array, &feed_attrs.shape_)); + + // Compatible input. + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT, feed_attrs); + auto const_1 = ops::Const(s.WithOpName("const_1"), 1.0f, input_shape); + + // Compatible MatMul. + auto matmul = ops::MatMul(s.WithOpName("matmul"), feed, const_1); + + // Incompatible MatMul. + ops::MatMul::Attrs matmul_attrs; + matmul_attrs.transpose_a_ = true; + auto incompatible_matmul = ops::MatMul(s.WithOpName("incompatible_matmul"), + feed, const_1, matmul_attrs); + + // Unsupported op. + auto unsupported_op = ops::Erfc(s.WithOpName("sin"), feed); + + // Incompatible input. + auto incompatible_feed = ops::Placeholder(s.WithOpName("feed"), DT_DOUBLE); + auto const_2 = ops::Const(s.WithOpName("const_2"), 1.0, input_shape); + // Compatible op with incompatible input. + auto matmul_with_incompatible_input = + ops::MatMul(s.WithOpName("matmul_with_incompatible_input"), + incompatible_feed, const_2); + + // Quantize ops. + auto quantize_attrs = ops::FakeQuantWithMinMaxArgs::Min(-6.0f).Max(6.0f); + auto quantize = ops::FakeQuantWithMinMaxArgs(s.WithOpName("quantize"), feed, + quantize_attrs); + + // Get GrapplerItem and GraphProperties. + grappler::GrapplerItem item; + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + Tensor feed_tensor(DT_FLOAT, input_shape); + item.feed.push_back(std::make_pair("feed", feed_tensor)); + grappler::GraphProperties graph_properties(item); + TF_EXPECT_OK(graph_properties.InferStatically(true)); + + for (const TrtPrecisionMode precision_mode : + {TrtPrecisionMode::FP32, TrtPrecisionMode::INT8}) { + TrtNodeValidator validator(graph_properties, precision_mode, + /*use_calibration=*/false, + /*use_implicit_batch=*/true, + /*use_explicit_precision=*/false); + TF_EXPECT_OK(validator.IsTensorRTCandidate(matmul.operation.node())); + EXPECT_THAT( + validator.IsTensorRTCandidate(incompatible_matmul.operation.node()), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("MatMul with 2D tensors requires explicit batch " + "mode, or that tensor A " + "is not transposed and B is a constant tensor."))); + EXPECT_THAT(validator.IsTensorRTCandidate(unsupported_op.operation.node()), + StatusIs(absl::StatusCode::kUnimplemented, + HasSubstr("Op type Erfc is not supported"))); + EXPECT_THAT(validator.IsTensorRTCandidate( + matmul_with_incompatible_input.operation.node()), + StatusIs(absl::StatusCode::kInternal, + HasSubstr("Failed to convert at least one input to a " + "TRT_TensorOrWeights:"))); + if (precision_mode == TrtPrecisionMode::INT8) { + TF_EXPECT_OK(validator.IsTensorRTCandidate(quantize.operation.node())); + } else { + EXPECT_THAT( + validator.IsTensorRTCandidate(quantize.operation.node()), + StatusIs( + absl::StatusCode::kUnimplemented, + HasSubstr("Op type FakeQuantWithMinMaxArgs is not supported"))); + } + } +} + +class ConverterTest : public ::testing::Test { + public: + ConverterTest() { Reset(); } + + void Reset() { + GetOpConverterRegistry()->Clear("MyOp"); + GetOpConverterRegistry()->Clear("DummyOp"); + converter_ = + std::move(Converter::Create(TrtPrecisionMode::FP32, + /*use_calibration=*/false, &logger_, + /*use_implicit_batch=*/true, + /*engine_name=*/"TRTEngineOp_000_000", + /*use_explicit_precision=*/false) + .value()); + weight_store_ = &converter_->weight_store_; + } + + // TODO(cbate): These should be removed or changed to public per black-box + // testing principle. + // Below we expose private methods of Converter for testing. + Status MaybeUpdateBatchSize(int batch_size) { + return converter_->MaybeUpdateBatchSize(batch_size); + } + + Status AddTensorOrWeights(const string& name, TRT_TensorOrWeights input) { + return converter_->AddTensorOrWeights(name, input); + } + + Status GetTensorOrWeights(const string& name, TRT_TensorOrWeights* output) { + return converter_->GetTensorOrWeights(name, output); + } + + Status GetInputs(const NodeDef& node_def, + std::vector* inputs) const { + return converter_->GetInputs(node_def, inputs); + } + + Status GetWeightRange(const TRT_ShapedWeights& weights, float* out_min, + float* out_max) const { + return converter_->GetWeightRange(weights, out_min, out_max); + } + + int batch_size() const { return converter_->batch_size_; } + + std::unordered_map& quantization_ranges_proxy() { + return converter_->quantization_ranges_proxy_; + } + + std::unordered_map& quantization_ranges() { + return converter_->quantization_ranges_; + } + + private: + Logger& logger_ = *Logger::GetLogger(); + + protected: + std::unique_ptr converter_; + TrtWeightStore* weight_store_; +}; + +TEST_F(ConverterTest, ConvertNode) { + ITensorProxyPtr output_tensors[2]; + auto op_converter = + [&output_tensors](const OpConverterParams* params) -> Status { + nvinfer1::Dims dims = params->inputs[0].tensor()->getDimensions(); + for (int i = 0; i < 2; ++i) { + dims.d[0] += 1; + output_tensors[i]->setDimensions(dims); + params->outputs->push_back(TRT_TensorOrWeights(output_tensors[i])); + } + return OkStatus(); + }; + NodeDef node_def = MakeNodeDef("my_op", "MyOp", {"my_input"}); + + TF_ASSERT_OK(converter_->AddInputTensor( + "my_input", nvinfer1::DataType::kFLOAT, CreateDims({123}), 1)); + + // Converter not registered. + EXPECT_THAT(converter_->ConvertNode(node_def), + StatusIs(absl::StatusCode::kNotFound, + HasSubstr("No converter for op MyOp"))); + + // Register the converter and retry. + GetOpConverterRegistry()->Register("MyOp", kDefaultConverterPriority, + op_converter); + TF_ASSERT_OK(converter_->ConvertNode(node_def)); + + TRT_TensorOrWeights actual_output_1; + TF_EXPECT_OK(GetTensorOrWeights("my_op", &actual_output_1)); + EXPECT_EQ(output_tensors[0]->simple_tensor(), + actual_output_1.tensor()->simple_tensor()); + EXPECT_EQ(124, actual_output_1.tensor()->getDimensions().d[0]); + + TRT_TensorOrWeights actual_output_2; + TF_EXPECT_OK(GetTensorOrWeights("my_op:1", &actual_output_2)); + EXPECT_EQ(output_tensors[1]->simple_tensor(), + actual_output_2.tensor()->simple_tensor()); + EXPECT_EQ(125, actual_output_2.tensor()->getDimensions().d[0]); + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, AddAndGetInputs) { + NodeDef node_def; + node_def.add_input("^control_input"); + node_def.add_input("input"); + node_def.add_input("input:0"); + node_def.add_input("input:1"); + node_def.add_input("weird_input:2:3:4:0"); + + TF_EXPECT_OK(converter_->AddInputTensor("input", nvinfer1::DataType::kFLOAT, + CreateDims({1}), 1)); + TF_EXPECT_OK(converter_->AddInputTensor("input:1", nvinfer1::DataType::kINT32, + CreateDims({2, 3}), 1)); + TF_EXPECT_OK(converter_->AddInputTensor( + "weird_input:2:3:4", nvinfer1::DataType::kHALF, CreateDims({5, 3}), 1)); + + std::vector inputs; + TF_EXPECT_OK(GetInputs(node_def, &inputs)); + + EXPECT_EQ(4, inputs.size()); + EXPECT_EQ(inputs[0].tensor()->trt_tensor(), inputs[1].tensor()->trt_tensor()); + + EXPECT_EQ(nvinfer1::DataType::kFLOAT, inputs[0].tensor()->getType()); + EXPECT_EQ(nvinfer1::DataType::kINT32, inputs[2].tensor()->getType()); + EXPECT_EQ(nvinfer1::DataType::kHALF, inputs[3].tensor()->getType()); + EXPECT_THAT(inputs[0].tensor()->getDimensions(), DimsAreArray({1})); + EXPECT_THAT(inputs[2].tensor()->getDimensions(), DimsAreArray({2, 3})); + EXPECT_THAT(inputs[3].tensor()->getDimensions(), DimsAreArray({5, 3})); + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, RenameAndMarkOutputTensors) { + // Test that the tensor are actually named and marked as output after + // Converter::RenameAndMarkOutputTensors() is called. + + // Register a custom converter which shuffles the input. We use it to build a + // TRT network whose output will be later marked. + std::vector output_tensors; + auto op_converter = + [&output_tensors](const OpConverterParams* params) -> Status { + nvinfer1::Permutation perm; + perm.order[0] = 1; + perm.order[1] = 0; + for (int i = 0; i < 2; ++i) { + ITensorProxyPtr input_tensor = params->inputs[0].tensor(); + nvinfer1::IShuffleLayer* layer = + params->converter->network()->addShuffle(*input_tensor->trt_tensor()); + layer->setFirstTranspose(perm); + ITensorProxyPtr output_tensor = layer->getOutput(0); + params->outputs->emplace_back(output_tensor); + output_tensors.push_back(output_tensor); + } + TRT_ShapedWeights output_weights(nvinfer1::DataType::kFLOAT); + params->outputs->emplace_back(output_weights); + return OkStatus(); + }; + GetOpConverterRegistry()->Register("MyOp", kDefaultConverterPriority, + op_converter); + + // Run the conversion. + NodeDef node_def = MakeNodeDef("my_op", "MyOp", {"my_input"}); + TF_EXPECT_OK(converter_->AddInputTensor( + "my_input", nvinfer1::DataType::kFLOAT, CreateDims({1, 2}), 1)); + TF_EXPECT_OK(converter_->ConvertNode(node_def)); + + // Mark a weight as output, should fail. + EXPECT_THAT( + converter_->RenameAndMarkOutputTensors({{"my_op:2", "my_output"}}), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Output my_op:2 is weights not tensor"))); + + // Mark tensors as output, should pass. + TF_EXPECT_OK(converter_->RenameAndMarkOutputTensors( + {{"my_op", "my_output"}, {"my_op:1", "my_output_1"}})); + EXPECT_EQ(2, output_tensors.size()); + for (auto output_tensor : output_tensors) { + EXPECT_THAT(output_tensor->getDimensions(), DimsAreArray({2, 1})); + } + EXPECT_EQ("my_output", string(output_tensors[0]->getName())); + EXPECT_EQ("my_output_1", string(output_tensors[1]->getName())); + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, TransposeTensor) { + ITensorProxyPtr input_tensor = converter_->network()->addInput( + "", nvinfer1::DataType::kFLOAT, CreateDims({2, 3, 5})); + ITensorProxyPtr output_tensor = nullptr; + NodeDef dummy_node_def = MakeNodeDef("dummy_op", "DummyOp", {}); + // Rank doesn't match. + EXPECT_THAT(converter_->TransposeTensor(input_tensor, {0, 1}, &output_tensor, + dummy_node_def, "sub1"), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr("Rank of perm for transpose does not match " + "with that of the input"))); + + // Transpose at batch dimension. + EXPECT_THAT( + converter_->TransposeTensor(input_tensor, {1, 0, 2, 3}, &output_tensor, + dummy_node_def, "sub2"), + StatusIs(absl::StatusCode::kUnimplemented, + HasSubstr("Transpose at batch dimension is not supported."))); + + // OK. + TF_EXPECT_OK(converter_->TransposeTensor( + input_tensor, {0, 3, 1, 2}, &output_tensor, dummy_node_def, "sub3")); + EXPECT_THAT(output_tensor->getDimensions(), DimsAreArray({5, 2, 3})); + EXPECT_THAT( + converter_->network(), + LayerNamesAreArray({"TRTEngineOp_000_000/dummy_op-sub3:SHUFFLE"})); +} + +void TestPrepareTensorForShape( + const std::vector& input_dims, const std::vector& reshape_dims, + const std::vector& expected_tensor_dims, bool input_is_tensor, + Converter* converter, TrtWeightStore* weight_store, + absl::StatusCode expected_code = absl::StatusCode::kOk, + const char* expected_error_msg_substr = nullptr) { + TRT_TensorOrWeights input; + if (input_is_tensor) { + input = TRT_TensorOrWeights(converter->network()->addInput( + "", nvinfer1::DataType::kFLOAT, CreateDims(input_dims))); + } else { + input = TRT_TensorOrWeights( + weight_store + ->GetTempWeights(nvinfer1::DataType::kFLOAT, CreateDims(input_dims)) + .value()); + } + ITensorProxyPtr output_tensor = nullptr; + + NodeDef dummy_node_def = MakeNodeDef("dummy_op", "DummyOp", {}); + for (bool validation_only : {false, true}) { + const Status status = + PrepareTensorForShape(converter, input, DimsAdapter(reshape_dims), + validation_only, &output_tensor, dummy_node_def); + if (expected_code == absl::StatusCode::kOk) { + TF_EXPECT_OK(status); + if (validation_only) { + EXPECT_EQ(nullptr, *output_tensor); + } else { + EXPECT_THAT(output_tensor->getDimensions(), + DimsAreArray(expected_tensor_dims)); + } + } else { + EXPECT_THAT(status, StatusIs(expected_code, + HasSubstr(expected_error_msg_substr))); + } + } +} + +TEST_F(ConverterTest, PrepareTensorForShape) { + for (bool input_is_tensor : {true, false}) { + // Shape size doesn't match. + Reset(); + TestPrepareTensorForShape({2, 3, 5}, {2, 3, 6}, {}, input_is_tensor, + converter_.get(), weight_store_, + absl::StatusCode::kInvalidArgument, + "Incompatible shapes"); + + // Regular shape. + Reset(); + TestPrepareTensorForShape({2, 3, 5}, {10, 3}, {10, 3}, input_is_tensor, + converter_.get(), weight_store_); + + // Reshape to zero rank. + Reset(); + TestPrepareTensorForShape({1, 1}, {}, {}, input_is_tensor, converter_.get(), + weight_store_); + } + + // Tensor input with zero rank. + Reset(); + TestPrepareTensorForShape({}, {1, 1}, {1, 1}, /*input_is_tensor=*/true, + converter_.get(), weight_store_); + + // TODO(aaroey): we should check the case where uninferred dimensions are + // not an exact divisor of input dim ensions, e.g. for dims {-1, 7}. + + // Infer tensor shape, ok. + Reset(); + TestPrepareTensorForShape({2, 3, 5}, {-1, 2}, {15, 2}, + /*input_is_tensor=*/true, converter_.get(), + weight_store_); + + // Infer weight shape, should fail. + Reset(); + TestPrepareTensorForShape({2, 3, 5}, {-1, 2}, {15, 2}, + /*input_is_tensor=*/false, converter_.get(), + weight_store_, absl::StatusCode::kInvalidArgument, + "Shape is not fully defined"); + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, MaybeUpdateBatchSize) { + EXPECT_EQ(-1, batch_size()); + + TF_EXPECT_OK(MaybeUpdateBatchSize(-1)); + EXPECT_EQ(-1, batch_size()); + + TF_EXPECT_OK(MaybeUpdateBatchSize(123)); + EXPECT_EQ(123, batch_size()); + + TF_EXPECT_OK(MaybeUpdateBatchSize(123)); + EXPECT_EQ(123, batch_size()); + + TF_EXPECT_OK(MaybeUpdateBatchSize(-1)); + EXPECT_EQ(123, batch_size()); + + EXPECT_THAT( + MaybeUpdateBatchSize(124), + StatusIs(absl::StatusCode::kInvalidArgument, + HasSubstr( + "Provided batch size does not match converter batch size"))); +} + +TEST_F(ConverterTest, AddAndGetTensorOrWeights) { + // Add a tensor. + ITensorProxyPtr simple_tensor; + TRT_TensorOrWeights tensor(simple_tensor); + EXPECT_EQ(-1, tensor.batch_size()); + TF_EXPECT_OK(MaybeUpdateBatchSize(123)); + TF_EXPECT_OK(AddTensorOrWeights("my_tensor", tensor)); + + // Get the added tensor. + TRT_TensorOrWeights added_tensor; + TF_EXPECT_OK(GetTensorOrWeights("my_tensor", &added_tensor)); + EXPECT_EQ(123, added_tensor.batch_size()); + + // Add the same tensor again. + EXPECT_THAT(AddTensorOrWeights("my_tensor", tensor), + StatusIs(absl::StatusCode::kAlreadyExists, + HasSubstr("tensor/weights my_tensor already exist"))); +} + +template +void TestGetWeightRange(ConverterTest* test, TrtWeightStore* weight_store) { + nvinfer1::DataType trt_type; + TF_ASSERT_OK(TfTypeToTrtType(DataTypeToEnum::v(), &trt_type)); + TRT_ShapedWeights weights = + weight_store->GetTempWeights(trt_type, CreateDims({2, 3})).value(); + const std::vector values = {T(3), T(1), T(2), T(6), T(5), T(4)}; + absl::c_copy(values, weights.GetPointer()); + float out_min = 0.0f; + float out_max = 0.0f; + TF_EXPECT_OK(test->GetWeightRange(weights, &out_min, &out_max)); + EXPECT_EQ(1.0f, out_min); + EXPECT_EQ(6.0f, out_max); +} + +TEST_F(ConverterTest, GetWeightRange) { + TestGetWeightRange(this, weight_store_); + TestGetWeightRange(this, weight_store_); + TestGetWeightRange(this, weight_store_); +} + +TEST_F(ConverterTest, ProvideQuantizationRange) { + ITensorProxyPtr simple_tensor; + // Asymmetric range + converter_->ProvideQuantizationRange(&simple_tensor, 0.0f, 6.0f); + EXPECT_EQ(6.0f, quantization_ranges_proxy()[&simple_tensor]); + converter_->ProvideQuantizationRange(&simple_tensor, 1.0f, 6.0f); + EXPECT_EQ(6.0f, quantization_ranges_proxy()[&simple_tensor]); + converter_->ProvideQuantizationRange(&simple_tensor, -8.0f, 6.0f); + EXPECT_EQ(8.0f, quantization_ranges_proxy()[&simple_tensor]); + converter_->ProvideQuantizationRange(&simple_tensor, -8.123f, -6.123f); + EXPECT_EQ(8.123f, quantization_ranges_proxy()[&simple_tensor]); + // Symmetric range + converter_->ProvideQuantizationRange(&simple_tensor, -6.123f, 6.123f); + EXPECT_EQ(6.123f, quantization_ranges_proxy()[&simple_tensor]); + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, MaybeApplyQuantizationRanges) { + ITensorProxyPtr input; + ITensorProxyPtr not_infer; + Logger& logger = *Logger::GetLogger(); + auto int8_converter = Converter::Create(TrtPrecisionMode::INT8, + /*use_calibration=*/true, &logger, + /*use_implicit_batch=*/true, + /*engine_name=*/"") + .value(); + int8_converter->ProvideQuantizationRange(&input, -5.0f, 5.0f); + int8_converter->ProvideQuantizationRange(¬_infer, -100.0f, 100.0f); + + int8_converter->MaybeApplyQuantizationRanges(); + EXPECT_EQ(input->getDynamicRangeMax(), 5.0f); + EXPECT_EQ(not_infer->getDynamicRangeMax(), 100.0f); + + EXPECT_THAT(int8_converter->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, GetTrtBroadcastShape) { + const bool kIsTensor = true; + const bool kIsNotTensor = false; + auto symmetric_test = [this](const std::vector& operand_1_shape, + const std::vector& operand_2_shape, + const bool operand_1_is_tensor, + const bool operand_2_is_tensor, + const std::vector& expected_operand_1_shape, + const std::vector& expected_operand_2_shape, + absl::StatusCode expected_code = + absl::StatusCode::kOk, + const char* expected_error_msg_substr = "", + const int operand_1_batch_size = -1, + const int operand_2_batch_size = -1) { + auto create_tensor_or_weights = [](const std::vector& shape, + bool is_tensor, int batch_size = -1) { + if (is_tensor) { + return TRT_TensorOrWeights(nvinfer1::DataType::kFLOAT, + CreateDims(shape), batch_size); + } + TRT_ShapedWeights weights; + weights.Shape() = CreateDims(shape); + return TRT_TensorOrWeights(weights); + }; + + nvinfer1::Dims operand_1_new_dims, operand_2_new_dims; + TRT_TensorOrWeights operand_1 = create_tensor_or_weights( + operand_1_shape, operand_1_is_tensor, operand_1_batch_size); + TRT_TensorOrWeights operand_2 = create_tensor_or_weights( + operand_2_shape, operand_2_is_tensor, operand_2_batch_size); + + // operand_1 broadcast operand_2 + EXPECT_THAT( + GetTrtBroadcastShape(operand_1, operand_2, /*check_feasibility=*/true, + /*use_implicit_batch=*/true, &operand_1_new_dims, + &operand_2_new_dims), + StatusIs(expected_code, HasSubstr(expected_error_msg_substr))); + if (expected_code == absl::StatusCode::kOk) { + EXPECT_THAT(operand_1_new_dims, DimsAreArray(expected_operand_1_shape)); + EXPECT_THAT(operand_2_new_dims, DimsAreArray(expected_operand_2_shape)); + } + // operand_2 broadcast operand_1 + EXPECT_THAT( + GetTrtBroadcastShape(operand_2, operand_1, /*check_feasibility=*/true, + /*use_implicit_batch=*/true, &operand_2_new_dims, + &operand_1_new_dims), + StatusIs(expected_code, HasSubstr(expected_error_msg_substr))); + if (expected_code == absl::StatusCode::kOk) { + EXPECT_THAT(operand_1_new_dims, DimsAreArray(expected_operand_1_shape)); + EXPECT_THAT(operand_2_new_dims, DimsAreArray(expected_operand_2_shape)); + } + }; + + // Both inputs are weights. + symmetric_test( + {1}, {1}, kIsNotTensor, kIsNotTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Broadcasting requires at least one of the operands be tensors"); + + // One tensor and one weights. + symmetric_test({1, 1, 1}, {2}, kIsTensor, kIsNotTensor, {1, 1, 1}, {1, 1, 2}); + symmetric_test({1, 1, 2}, {2}, kIsTensor, kIsNotTensor, {1, 1, 2}, {1, 1, 2}); + symmetric_test({1, 3, 2}, {1}, kIsTensor, kIsNotTensor, {1, 3, 2}, {1, 1, 1}); + symmetric_test({1, 1, 1}, {2, 3}, kIsTensor, kIsNotTensor, {1, 1, 1}, + {1, 2, 3}); + symmetric_test({1, 1, 1}, {2, 3, 4}, kIsTensor, kIsNotTensor, {1, 1, 1}, + {2, 3, 4}); + symmetric_test({1, 1, 1}, {1, 2, 3, 4}, kIsTensor, kIsNotTensor, {1, 1, 1}, + {2, 3, 4}); + symmetric_test({1, 3, 4}, {1, 2, 1, 4}, kIsTensor, kIsNotTensor, {1, 3, 4}, + {2, 1, 4}); + symmetric_test({1, 1, 1}, {2, 1, 1, 1}, kIsTensor, kIsNotTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Infeasible broadcast scheme"); + symmetric_test({1, 1, 1}, {2, 1, 1, 1}, kIsTensor, kIsNotTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Infeasible broadcast scheme", + /*operand_1_batch_size=*/2); + symmetric_test({1, 1, 1}, {1, 1, 1, 1, 1}, kIsTensor, kIsNotTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims 4 vs broadcast #dims 5)"); + symmetric_test({3}, {1, 1, 3}, kIsTensor, kIsNotTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims 2 vs broadcast #dims 3)", + /*operand_1_batch_size=*/2); + + // Both inputs are tensors. + symmetric_test({1, 1, 1}, {1, 1}, kIsTensor, kIsTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims 3 vs broadcast #dims 4)"); + symmetric_test({1, 3}, {3}, kIsTensor, kIsTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims 2 vs broadcast #dims 3)"); + symmetric_test({1, 3, 4}, {2, 1, 4}, kIsTensor, kIsTensor, {1, 3, 4}, + {2, 1, 4}); + symmetric_test({1, 1, 1}, {1, 1, 1, 1}, kIsTensor, kIsTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims 4 vs broadcast #dims 5)"); + symmetric_test({2, 3}, {7, 5}, kIsTensor, kIsTensor, {}, {}, + absl::StatusCode::kInvalidArgument, + "Infeasible broadcast scheme"); + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +TEST_F(ConverterTest, CreateConstantLayer) { + for (auto dtype : {nvinfer1::DataType::kFLOAT, nvinfer1::DataType::kINT32}) { + TRT_ShapedWeights weights = + weight_store_->GetTempWeights(dtype, CreateDims({2, 3, 5})).value(); + ITensorProxyPtr tensor = + converter_->CreateConstantLayer(weights, CreateDims({3, 10})); + ASSERT_NE(nullptr, tensor->trt_tensor()); + EXPECT_EQ(dtype, tensor->getType()) + << "Expected " << DebugString(dtype) << " vs. actual " + << DebugString(tensor->getType()); + EXPECT_THAT(tensor->getDimensions(), DimsAreArray({3, 10})); + } + + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); +} + +class ConvertGraphDefToEngineTest : public ::testing::Test { + public: + Status RunConvertGraphDefToEngine(Scope* s) { + GraphDef gdef; + TF_EXPECT_OK(s->ToGraphDef(&gdef)); + std::vector input_shapes; + int batch_size = -1; + for (const NodeDef& node : gdef.node()) { + absl::string_view node_name(node.name()); + if (absl::ConsumePrefix(&node_name, IONamePrefixes::kInputPHName)) { + int port = -1; + EXPECT_TRUE(absl::SimpleAtoi(node_name, &port)) << node.name(); + if (input_shapes.size() < port + 1) input_shapes.resize(port + 1); + input_shapes[port] = + PartialTensorShape(node.attr().at("shape").shape()); + if (batch_size == -1) { + batch_size = input_shapes[port].dim_size(0); + } else { + EXPECT_EQ(batch_size, input_shapes[port].dim_size(0)); + } + } + } + // TODO(laigd): execute the engine and get outputs. + return ConvertGraphDefToEngine( + gdef, /*ctx=*/nullptr, TrtPrecisionMode::FP32, /*max_batch_size=*/1, + /*max_workspace_size_bytes=*/64 << 20, input_shapes, &logger_, + /*allocator=*/nullptr, /*calibrator=*/nullptr, &engine_, + /*use_calibration=*/false, /*use_implicit_batch=*/true, + /*convert_successfully=*/nullptr, /*profiles=*/nullptr, + "TRTEngineOp_000_000", /*use_explicit_precision=*/false); + } + + protected: + TrtUniquePtrType engine_; + + private: + Logger& logger_ = *Logger::GetLogger(); +}; + +TEST_F(ConvertGraphDefToEngineTest, IdentityGraph) { + Scope s = Scope::NewRootScope(); + auto input = + ops::Placeholder(s.WithOpName(StrCat(IONamePrefixes::kInputPHName, 0)), + DT_FLOAT, ops::Placeholder::Shape({1, 1})); + auto output = ops::Identity(s.WithOpName("identity1"), input); + output = ops::Identity(s.WithOpName("identity2"), output); + output = ops::Identity(s.WithOpName(StrCat(IONamePrefixes::kOutputPHName, 0)), + output); + // If the converter marks the input tensor as output tensor, the conversion + // below will fail with: + // > TensorRTOutputPH_0 cannot be both input and output + // > Network must have at least one output + TF_EXPECT_OK(RunConvertGraphDefToEngine(&s)); +} + +// Returns a vector of shapes from a vector of input tensors. This can be used +// to create optimization profiles. +Status GetShapeFromDataVec(DataVec input_data, + std::vector* shape_vec) { + shape_vec->reserve(input_data.size()); + std::transform(input_data.begin(), input_data.end(), + std::back_inserter(*shape_vec), + [](InputOutputData x) { return x.tensor.shape(); }); + return OkStatus(); +} + +template +inline absl::Span GetSpanForData(const InputOutputData& data) { + const auto& tensor_map = data.tensor.flat(); + return absl::Span(tensor_map.data(), tensor_map.size()); +} + +std::vector GetDataAsFloat(InputOutputData& data) { + const auto dType = data.tensor.dtype(); + if (dType == DT_FLOAT) { + auto span = GetSpanForData(data); + return std::vector(span.begin(), span.end()); + } + if (dType == DT_HALF) { + return CastVector(GetSpanForData(data)); + } + if (dType == DT_INT32) { + return CastVector(GetSpanForData(data)); + } +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + if (dType == DT_BOOL) { + return CastVector(GetSpanForData(data)); + } +#endif + LOG(FATAL) << "DataType not supported for testing " << DataTypeString(dType); + return {}; +} + +// Class to test various op converters, using both a TrtNodeValidator and +// Converter. +class OpConverterTest : public ::testing::Test { + public: + OpConverterTest() + : tensor_buffer_allocator_(new GpuManagedAllocator()), + scope_(Scope::NewRootScope()) { + QCHECK_EQ(0, cudaStreamCreate(&stream_)); + Reset(); + } + + ~OpConverterTest() noexcept override { + QCHECK_EQ(0, cudaStreamDestroy(stream_)); + } + + Status GetTensorOrWeights(const string& name, TRT_TensorOrWeights* output) { + return converter_->GetTensorOrWeights(name, output); + } + + void Reset(TrtPrecisionMode precision_mode_to_test = TrtPrecisionMode::FP32, + TrtTestMode trt_mode = TrtTestMode::kImplicitBatch, + OpKernelContext* ctx = nullptr) { + // Destroy existing TRT objects in a proper order. + converter_.reset(nullptr); + engine_.reset(nullptr); + + // Re-create them in proper order. + converter_ = + std::move(Converter::Create(precision_mode_to_test, + /*use_calibration=*/false, &logger_, + /*use_implicit_batch=*/trt_mode == + TrtTestMode::kImplicitBatch, + /*engine_name=*/"", + /*use_explicit_precision=*/false, ctx) + .value()); + + // Reset other related artifacts. + scope_ = Scope::NewRootScope(); + } + + // Constructs a flat tensor with 'vals' in Unified Memory. + template + Tensor AsTensor(gtl::ArraySlice vals) { // non-absl ok + Tensor ret(tensor_buffer_allocator_.get(), DataTypeToEnum::value, + {static_cast(vals.size())}); + std::copy_n(vals.data(), vals.size(), ret.flat().data()); + return ret; + } + + // Constructs a tensor of "shape" with values "vals" in Unified Memory. + template + Tensor AsTensor(gtl::ArraySlice vals, // non-absl ok + const TensorShape& shape) { + Tensor ret(tensor_buffer_allocator_.get(), DataTypeToEnum::value, + {static_cast(vals.size())}); + CHECK(ret.CopyFrom(AsTensor(vals), shape)); + return ret; + } + + template + void transformTensor(const std::vector& vals, Tensor& ret) { + std::transform(vals.begin(), vals.end(), ret.flat().data(), + [](const T in_val) -> S { return static_cast(in_val); }); + } + + template + void transformWeights(const std::vector& vals, + TRT_ShapedWeights& weights) { + std::transform(vals.begin(), vals.end(), weights.GetPointer(), + [](const T in_val) -> S { return static_cast(in_val); }); + } + + // Constructs a tensor with given values (vals). The tensor type is defined by + // the tf_type argument, its shape is given by input_dims. The tensor is + // constructed using the allocator of OpConverterTest in Unified Memory. + template + Tensor AsTensor(const std::vector& vals, + const std::vector& input_dims, DataType tf_type) { + Tensor ret(tensor_buffer_allocator_.get(), tf_type, + {static_cast(vals.size())}); + if (tf_type == DT_FLOAT) { + transformTensor(vals, ret); + } else if (tf_type == DT_HALF) { + transformTensor(vals, ret); + } else if (tf_type == DT_INT32) { + transformTensor(vals, ret); +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + } else if (tf_type == DT_BOOL) { + transformTensor(vals, ret); +#endif + } else { + LOG(FATAL) << "Cannot create tensor with type " + << DataTypeString(tf_type); + } + TensorShape shape; + TF_EXPECT_OK(TensorShapeUtils::MakeShape(input_dims, &shape)); + CHECK(ret.CopyFrom(ret, shape)); + return ret; + } + + template + Tensor AsTensor(const std::vector& vals, + const std::vector& input_dims, DataType tf_type) { + const auto& conv_vals = CastVector(vals); + return AsTensor(conv_vals, input_dims, tf_type); + } + + // Constructs a flat tensor in Unified Memory. + template + Tensor ConstructTensor(int data_size, const T& value = T()) { + std::vector values(data_size, value); + return AsTensor(values); + } + + // Constructs a flat tensor in Unified Memory. + template + Tensor ConstructTensor(int data_size, const T& value, DataType tf_type) { + std::vector values(data_size, value); + return AsTensor(values, {data_size}, tf_type); + } + + void CheckDataTypeMatches(const DataVec& datas) { + if (VLOG_IS_ON(2)) { + int nbBindings = engine_->getNbBindings(); + VLOG(2) << "Number of engine bindings: " << nbBindings; + for (int i = 0; i < nbBindings; i++) { + VLOG(2) << "Binding " << i << " name: " << engine_->getBindingName(i); + } + } + for (const auto& data : datas) { + VLOG(2) << "Checking if data type matches for tensor " << data.name; + const int input_index = engine_->getBindingIndex(data.name.c_str()); + ASSERT_NE(-1, input_index); + const nvinfer1::DataType trt_dtype = + engine_->getBindingDataType(input_index); + DataType tf_type; + TF_ASSERT_OK(TrtTypeToTfType(trt_dtype, &tf_type)); + ASSERT_EQ(data.tensor.dtype(), tf_type) + << DataTypeString(data.tensor.dtype()) << " vs. " + << DataTypeString(tf_type); + } + } + + Status BuildAndRun(const DataVec& input_data, DataVec* output_data, + const int batch_size = 1) { + // Mark the output tensor as TRT engine output. + std::vector output_info; + for (const auto& data : *output_data) { + nvinfer1::DataType trt_type; + TF_RETURN_IF_ERROR(TfTypeToTrtType(data.tensor.dtype(), &trt_type)); + output_info.push_back({data.name, data.name, trt_type}); + } + TF_RETURN_IF_ERROR(converter_->RenameAndMarkOutputTensors(output_info)); + + // Build the TRT engine. + if (engine_.get() != nullptr) { + return errors::Internal("Engine already exists"); + } + TrtShapeOptimizationProfile profiles; + if (!converter_->use_implicit_batch()) { + std::vector input_mask(input_data.size()); + for (int i = 0; i < input_data.size(); i++) { + input_mask[i] = (input_data[i].tensor.dtype() != DataType::DT_RESOURCE); + } + profiles.SetInputMask(input_mask); + profiles.SetShapeTensorMask(converter_->network()); + TF_RETURN_IF_ERROR(profiles.CollectShapeValues(input_data)); + // Create a single optimization profile for explicit batch mode + std::vector input_shapes; + TF_RETURN_IF_ERROR(GetShapeFromDataVec(input_data, &input_shapes)); + profiles.AddShape(input_shapes); + std::vector input_partial_shapes; + TF_RETURN_IF_ERROR( + GetNetworkInputShapes(converter_->network(), &input_partial_shapes)); + profiles.InitProfiles(input_partial_shapes, ProfileStrategy::kRange); + } + TF_RETURN_IF_ERROR( + converter_->BuildCudaEngine(&engine_, + /*max_batch_size=*/batch_size, + /*max_workspace_size_bytes=*/1 << 26, + /*allocator=*/nullptr, + /*calibrator=*/nullptr, + /*profiles=*/&profiles)); + CHECK_NOTNULL(engine_.get()); + CheckDataTypeMatches(input_data); + CheckDataTypeMatches(*output_data); + + const int num_bindings = input_data.size() + output_data->size(); + std::vector buffers(num_bindings); + + if (engine_->getNbBindings() != num_bindings) { + return errors::Internal("Number of bindings do not match"); + } + // Since we have only 1 optimization profile (which is enabled by default) + // it is fine to create execution context directly, instead of calling + // profiles.CreateExecutionContexts() + TrtUniquePtrType execution_context( + engine_->createExecutionContext()); + + // Prepare input bindings. + TF_RETURN_IF_ERROR( + SetTrtEngineInputs(engine_.get(), execution_context.get(), 0, buffers, + converter_->use_implicit_batch(), batch_size, + profiles, nullptr, &input_data)); + // Prepare output bindings. + TF_RETURN_IF_ERROR(SetTrtEngineOutputs( + engine_.get(), execution_context.get(), 0, buffers, + converter_->use_implicit_batch(), batch_size, nullptr, output_data)); + // Execute the TRT engine. + TF_RETURN_IF_ERROR(TrtEnqueue(execution_context.get(), buffers, stream_, + converter_->use_implicit_batch(), + batch_size)); + cudaStreamSynchronize(stream_); + return OkStatus(); + } + + // Adds ITensor for both validation and conversion, assuming explicit batch + // dimension is included in dims (ie for an NCHW tensor dims = {N, C, H, W}). + void AddTestTensorWithTFDims( + const string& name, const std::vector& dims, + nvinfer1::DataType trt_type = nvinfer1::DataType::kFLOAT, + Status add_input_status = OkStatus()) { + DataType tf_type; + TF_ASSERT_OK(TrtTypeToTfType(trt_type, &tf_type)); + ops::Placeholder::Attrs attrs; + TF_EXPECT_OK(TensorShapeUtils::MakeShape(dims, &attrs.shape_)); + + auto input = ops::Placeholder(scope_.WithOpName(name), tf_type, attrs); + node_inputs_[name] = input.output; + + // Add a real ITensor for conversion conditionally. + + auto dims_adap = + DimsAdapter::Create(attrs.shape_, converter_->use_implicit_batch()); + if (converter_->use_implicit_batch() && !dims_adap.ok()) { + ASSERT_EQ(add_input_status, dims_adap.status()); + return; + } else { + TF_EXPECT_OK(dims_adap.status()); + } + if (!converter_->use_implicit_batch() || dims_adap->IsStatic()) { + int batch_size = dims.size() > 0 ? dims[0] : 0; + Status status = converter_->AddInputTensor( + name, trt_type, dims_adap->AsTrtDims(), batch_size); + ASSERT_EQ(add_input_status, status); + } + } + + Status AddTensorOrWeights(const string& name, TRT_TensorOrWeights input) { + return converter_->AddTensorOrWeights(name, input); + } + + // Adds ITensor for both validation and conversion. The difference compared to + // AddTestTensorWithTFDims is in the meaning of the dims parameter. To define + // a tensor with NCHW shape, here we set dims = {C,H,W} and batch_size = N. + // TODO(tfeher) remove this function once all test are updated to use the + // other version of AddTestTensor (defined by + // ParameterizedOpConverterTestBase). + void AddTestTensor( + const string& name, const std::vector& dims, int batch_size = 1, + nvinfer1::DataType trt_dtype = nvinfer1::DataType::kFLOAT) { + DimsAdapter adap(dims); + std::vector dims_vec; + TF_CHECK_OK(adap.Prepend(batch_size).Vector(&dims_vec)); + AddTestTensorWithTFDims(name, dims_vec, trt_dtype); + if (adap.IsStatic()) { + ASSERT_EQ(batch_size, converter_->batch_size_); + } + } + + // Adds weights for both validation and conversion. The type of the weight is + // determined by tf_type. The initial value vector (values) can have any + // type (T) that can be statically casted to tf_type. + template + void AddTestWeights(const string& name, const std::vector& dims, + const std::vector& values_inp, DataType tf_type, + bool fix_values = true) { + const DimsAdapter dims_adap(dims); + const int64_t num_elements = dims_adap.Volume(); + + std::vector values(values_inp); + if (num_elements != values.size()) { + if (fix_values) { + AdjustVectorByDims(values, num_elements, name, "AddTestWeights"); + } else { + FAIL() << "Unable to create test weights: " + << (num_elements > values.size() ? "not enough" : "to many") + << " values specified: " << values.size() << " vs. " + << num_elements << " defined by dims"; + } + } + // Add weights for validation. + Tensor t = AsTensor(values, dims, tf_type); + node_inputs_[name] = ops::Const(scope_.WithOpName(name), t); + + // Add weights for conversion. + nvinfer1::DataType dtype; + TF_ASSERT_OK(TfTypeToTrtType(tf_type, &dtype)); + QCHECK_EQ(num_elements, values.size()) + << num_elements << " vs " << values.size(); + TRT_ShapedWeights weights(dtype); + if (num_elements) { + weights = + converter_->weight_store_.GetTempWeights(dtype, dims_adap.AsTrtDims()) + .value(); + + if (tf_type == DT_FLOAT) { + transformWeights(values, weights); + } else if (tf_type == DT_HALF) { + transformWeights(values, weights); + } else if (tf_type == DT_INT32) { + transformWeights(values, weights); +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + } else if (tf_type == DT_BOOL) { + transformWeights(values, weights); +#endif + } else { + LOG(FATAL) << "Cannot create tensor with type " + << DataTypeString(tf_type); + } + } + TF_EXPECT_OK( + converter_->AddTensorOrWeights(name, TRT_TensorOrWeights{weights})); + } + + // Adds test weight without specifying tf_type arg. In this case the initial + // value type (T) will determine the type of the weights. + template + void AddTestWeights(const string& name, const std::vector& dims, + const std::vector& value, bool fix_values = true) { + AddTestWeights(name, dims, value, DataTypeToEnum::value, fix_values); + } + + // Test validation in validation-only mode. + Status RunValidation(const Node* node) { + grappler::GrapplerItem item; + TF_EXPECT_OK(scope_.ToGraphDef(&item.graph)); + grappler::GraphProperties graph_properties(item); + TF_EXPECT_OK(graph_properties.InferStatically(true)); + + TrtNodeValidator validator( + graph_properties, converter_->precision_mode(), + /*use_calibration=*/false, + /*use_implicit_batch=*/converter_->use_implicit_batch(), + /*use_explicit_precision=*/false); + return validator.IsTensorRTCandidate(node); + } + + void RunConversion(const Node* node, + absl::StatusCode expected_code = absl::StatusCode::kOk, + absl::string_view expected_msg_substr = "") { + EXPECT_THAT(converter_->ConvertNode(node->def()), + StatusIs(expected_code, HasSubstr(expected_msg_substr))); + if (expected_code == absl::StatusCode::kOk) { + EXPECT_THAT(converter_->network(), LayerNamesNonEmpty()); + } + } + + // Helper method to run both validation and conversion, when the expected + // output are same. + void RunValidationAndConversion( + const NodeDef& node_def, + absl::StatusCode expected_code = absl::StatusCode::kOk, + absl::string_view expected_msg_substr = "", + bool should_run_conversion = true) { + // Add the node to the graph. + // TODO(laigd): we should accept a function that adds the node using + // `scope_`, so individual test case can reuse the scope object and we don't + // need to add the edges here by ourselves. + Graph* graph = scope_.graph(); + Status status; + Node* node = graph->AddNode(std::move(node_def), &status); + TF_EXPECT_OK(status); + for (int i = 0; i < node_def.input().size(); ++i) { + const string& input_name = node_def.input(i); + const auto& itr = node_inputs_.find(input_name); + QCHECK(itr != node_inputs_.end()); + const Output& input = itr->second; + graph->AddEdge(input.node(), input.index(), node, i); + } + + status = RunValidation(node); + if (should_run_conversion && status.ok()) { + RunConversion(node, expected_code, expected_msg_substr); + } else { + EXPECT_THAT(status, + StatusIs(expected_code, HasSubstr(expected_msg_substr))); + } + } + + // Helper method to run both validation and conversion, and check the output + // shapes. + void RunValidationAndConversion( + const NodeDef& node_def, const Status& status, + const std::string& output_name, + const std::vector>& exp_out_dims) { + RunValidationAndConversion(node_def, + static_cast(status.code()), + status.message(), true); + + if (status.ok()) { + // TODO(tfeher): Enable this check in explicit_batch_mode. + // In dynamic shape mode the output dims cannot be tested here. In that + // case we need to wait for the concrate input shapes to be defined (by + // setBindingDimensions before enqueue) before we can check the output + // dims. + if (converter_->use_implicit_batch()) { + for (int i = 0; i < exp_out_dims.size(); i++) { + TRT_TensorOrWeights output; + string name = i == 0 ? output_name : StrCat(output_name, ":", i); + TF_EXPECT_OK(GetTensorOrWeights(name.c_str(), &output)); + ASSERT_TRUE(output.is_tensor()); + if (!exp_out_dims[i].empty()) { + // Removing batch dim. + auto out_dims = std::vector(exp_out_dims[i].begin() + 1, + exp_out_dims[i].end()); + VLOG(2) << "Testing output shape for tensor " << name; + EXPECT_THAT(output.tensor()->getDimensions(), + DimsAreArray(out_dims)); + } + } + } + } + } + + // Expose quantization_ranges_ for tests + std::unordered_map& quantization_ranges_proxy() { + return converter_->quantization_ranges_proxy_; + } + + // Expose quantization_ranges_ for tests + std::unordered_map& quantization_ranges() { + return converter_->quantization_ranges_; + } + + protected: + template + void AdjustVectorByDims(std::vector& values, size_t num_elements, + const string& name, const char* callingFunc) { + const auto old_size = values.size(); + if (num_elements > old_size) { + // Expending vector with 0's. + const std::vector zeros(num_elements - old_size, 0); + values.reserve(num_elements); + values.insert(values.end(), zeros.begin(), zeros.end()); + VLOG(2) << "In function " << callingFunc << " the vector '" << name + << "' was extended by " << num_elements - old_size << " zeros"; + } else { + // Removing unnecessary elements. + values.resize(num_elements); + VLOG(2) << "Only first " << num_elements << " out of " << old_size + << " elements of the vector '" << name + << "' will be used in function" << callingFunc; + } + } + + public: + std::unique_ptr converter_; + + protected: + Logger& logger_ = *Logger::GetLogger(); + + private: + TrtUniquePtrType engine_; + cudaStream_t stream_; + std::unique_ptr tensor_buffer_allocator_; + + public: + // The scope that contains the graph being converted. Because + // tensor_buffer_allocator_ provides the storage for tensor contents that are + // represented as attributes for graph nodes within scope_, + // tensor_buffer_allocator_ needs to be available when destructing scope_. + // Therefore, scope_ comes after tensor_buffer_allocator_ in the class member + // field list. + Scope scope_; + + protected: + std::unordered_map node_inputs_; +}; + +// Extends the OpConverterTest for variable converters which require a properly +// setup context. +class VariableOpConverterTest : public OpConverterTest { + public: + void Reset(TrtPrecisionMode precision_mode_to_test = TrtPrecisionMode::FP32, + TrtTestMode trt_mode = TrtTestMode::kImplicitBatch) { + OpConverterTest::Reset(precision_mode_to_test, trt_mode, context_.get()); + } + + void CreateContext(const NodeDef& node_def, OpKernel** kernel, + OpKernelContext** context) { + std::unique_ptr device_( + DeviceFactory::NewDevice("GPU", {}, "/job:a/replica:0/task:0")); + Device* device_ptr = device_.get(); + + device_mgr_ = std::make_unique(std::move(device_)); + + managed_allocator_ = std::make_unique(); + Allocator* allocator = managed_allocator_.get(); + step_container_ = + std::make_unique(0, [](const string&) {}); + slice_reader_cache_wrapper_ = + std::make_unique(); + + flib_def_ = std::make_unique( + OpRegistry::Global(), FunctionDefLibrary()); + + thread_pool_ = + std::make_unique(Env::Default(), "default", + /*num_threads=*/1); + pflr_ = std::make_unique( + device_mgr_.get(), Env::Default(), /*config=*/nullptr, + TF_GRAPH_DEF_VERSION, flib_def_.get(), OptimizerOptions(), + thread_pool_.get()); + + FunctionLibraryRuntime* flib = pflr_->GetFLR(device_ptr->name()); + ResourceMgr* resource_mgr = device_ptr->resource_manager(); + + TF_CHECK_OK(NodeProperties::CreateFromNodeDef( + node_def, OpRegistry::Global(), &props_)); + + OpKernel* kernel_ptr = nullptr; + TF_CHECK_OK(CreateOpKernel(DEVICE_GPU, device_ptr, allocator, flib, + resource_mgr, props_, TF_GRAPH_DEF_VERSION, + &kernel_ptr)); + op_kernel_ = std::unique_ptr(kernel_ptr); + + auto* dev_info = device_ptr->tensorflow_accelerator_device_info(); + CHECK_NOTNULL(dev_info); + DeviceContext* device_context = dev_info->default_context; + + // Note: this setup is not exhaustive. + params_.device = device_ptr; + params_.op_kernel = op_kernel_.get(); + params_.resource_manager = resource_mgr; + params_.frame_iter = FrameAndIter(0, 0); + params_.inputs = inputs_; + params_.step_container = step_container_.get(); + params_.function_library = flib; + params_.slice_reader_cache = slice_reader_cache_wrapper_.get(); + params_.op_device_context = device_context; + + context_ = std::make_unique(¶ms_); + + // Outputs. + *kernel = op_kernel_.get(); + *context = context_.get(); + } + + // Adds resource for resource variable op converters. + void AddTestResource(const string& name, const ResourceHandle& resource) { + // Add resource for validation. + node_inputs_[name] = + ops::Placeholder(scope_.WithOpName("my_handle"), DT_RESOURCE); + + // Add resource for conversion. + TF_EXPECT_OK(AddTensorOrWeights(name, TRT_TensorOrWeights{resource})); + } + + private: + // The following pointers manage the kernel context. + std::unique_ptr device_mgr_; + std::unique_ptr managed_allocator_; + std::unique_ptr step_container_; + std::unique_ptr + slice_reader_cache_wrapper_; + std::unique_ptr flib_def_; + std::unique_ptr thread_pool_; + std::unique_ptr pflr_; + OpKernelContext::Params params_; + std::unique_ptr op_kernel_; + std::unique_ptr context_; + std::shared_ptr props_; + absl::InlinedVector inputs_; +}; + +// General test parameters to be used with ops that take a single input tensor. +struct TestParamBase { + // Concrete input dimensions for the test (including the batch dim) + std::vector input_dims; + + // Dimensions to define an input with PartialTensorShape. This can be used to + // define networks with dynamic input shape. It can be left empty, in that + // case AddTestTensor sets partial shapes that are appropriate to TrtTestMode. + std::vector partial_input_dims; + + // Concrete (static) output dimensions, including batch size as first dim + std::vector expected_output_dims; + + // Parameter vector, has converter specific meaning. + std::vector param; + + // Expected status of conversion (with concrete error message) + Status status; + + // Expected status of BuildAndRun + Status runtime_status; +}; + +std::ostream& operator<<(std::ostream& os, const TestParamBase& p) { + os << "input_dims" << PrintToString(p.input_dims); + if (!p.partial_input_dims.empty()) { + os << ", partial_input_dims" << PrintToString(p.partial_input_dims); + } + if (!p.expected_output_dims.empty()) { + os << ", exp_out_dims" << PrintToString(p.expected_output_dims); + } + if (!p.param.empty()) { + os << ", param" << PrintToString(p.param); + } + os << ", " << p.status; + return os; +} + +// Printing vector with the numbers of type T which defines tensor or shape. +template +const std::string get_debug_string_for_vector(const std::vector& vector, + absl::string_view pComment, + absl::string_view name, + absl::string_view type = "") { + const std::string t1 = absl::StrCat(pComment, " '", name, "': Dims(nbDims="); + const std::string t2 = absl::StrJoin(vector, ","); + const std::string t3 = type != "" ? absl::StrCat(") of type ", type) : ")"; + std::stringstream stream; + stream << t1 << vector.size() << ", d=" << t2 << t3; + return stream.str(); +} + +// Parameterized version of OpConverterTest. We have the following parameters: +// 1. TrtTestMode: implicit batch, explicit batch, dynamic shape modes +// 2. DataType of the input TF tensors: DT_FLOAT, DT_HALF, DT_INT32 +// 3. TrtPrecisionMode argument for the Converter: FP32, FP16, INT8 +// We will introduce subclasses that will be instantiated using different +// combinations of the DataType and TrtPrecisionMode parameters. +class ParameterizedOpConverterTestBase + : public OpConverterTest, + public ::testing::WithParamInterface< + std::tuple> { + public: + ParameterizedOpConverterTestBase() + : trt_mode_(std::get<0>(GetParam())), + tf_type_(std::get<1>(GetParam())), + converter_precision_(std::get<2>(GetParam())) { + LOG(INFO) << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; + LOG(INFO) << "tf_type_: " << DebugString(tf_type_); + LOG(INFO) << "trt_mode_: " << DebugString(trt_mode_); + LOG(INFO) << "converter_precision_: " << DebugString(converter_precision_); + LOG(INFO) << "%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%"; + } + + void Reset() { + OpConverterTest::Reset(converter_precision_, trt_mode_); + input_data_.clear(); + } + + void Reset(TrtPrecisionMode precision) { + OpConverterTest::Reset(precision, trt_mode_); + input_data_.clear(); + } + + // Getters of protected attributes + DataType get_tf_type() { return tf_type_; } + TrtTestMode get_trt_mode() { return trt_mode_; } + TrtPrecisionMode get_converter_precision() { return converter_precision_; } + + // Adds an input ITensor for TRT network. Also creates the corresponding TF + // tensor, and stores it in the list of inputs (input_data_). + // + // The TF tensor is always created with concrete static input shape given by + // dims. The ITensor can have static or dynamic shape based on the trt_mode + // attribute. The ITensor shape is set automatically according to the trt_mode + // parameter, unless the user overrides it with an explicit + // partial_input_shape_dims argument. + // + // Parameters: + // - name of the input node + // - dims actual dimensions of the tensor that we will use during the test + // (including explicit batch dim) + // - values initial values for the TF tensor + // - dtype data type of the tensor + // - partial_input_shape dimensions which can include unknown shapes. This can + // be empty, in that case the partial_input_shape will be set automatically + // depending on the trt_mode argument. (This argument also includes explicit + // batch dim). + // - add_input_status adding ITensor to the network can fail in implicit batch + // mode if the batch size is inconsistent. Using the add_input_status arg we + // can test such errors. + // + template + void AddTestTensor(const string& name, const std::vector& dims, + DataType tf_type, const std::vector& values_inp, + const std::vector& partial_input_shape_dims = {}, + Status add_input_status = OkStatus(), + bool fix_values = true) { + std::vector values(values_inp); + VLOG(2) << "**** AddTestTensor for " << name + << " ***** dims empty() = " << dims.empty() + << " tf_type = " << DebugString(tf_type); + if (!dims.empty()) { + const auto num_elements = std::accumulate( + std::begin(dims), std::end(dims), 1, std::multiplies()); + if (!values.empty() && num_elements != values.size()) { + if (fix_values) { + AdjustVectorByDims(values, num_elements, name, "AddTestTensor"); + } else { + // Note: for conversion only tests, it is valid to have empty values, + // otherwise the number of elements should match. + LOG(WARNING) << "Expected Test Tensor Shape: " << DebugString(dims) + << ", Received Input Tensor: " << DebugString(values); + } + } + } + + std::vector partial_shape; + if (!partial_input_shape_dims.empty()) { + partial_shape = partial_input_shape_dims; + } else { + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // In dynamic shape mode we make all dims unknown. + partial_shape = std::vector(dims.size(), -1); + } else { + // Use static (known) input shapes. + partial_shape = dims; + } + if (VLOG_IS_ON(2)) { + VLOG(2) << get_debug_string_for_vector(partial_shape, + "Using partial_shape for", name); + } + } + nvinfer1::DataType trt_type; + TF_ASSERT_OK(TfTypeToTrtType(tf_type, &trt_type)); + AddTestTensorWithTFDims(name, partial_shape, trt_type, add_input_status); + if (!values.empty()) { + if (VLOG_IS_ON(2)) { + VLOG(2) << get_debug_string_for_vector(values, "Adding test tensor for", + name, DataTypeString(tf_type)); + } + InputOutputData data{name, AsTensor(values, dims, tf_type)}; + VLOG(2) << "Added tensor: " << data.name << " with dtype " + << DataTypeString(data.tensor.dtype()); + input_data_.push_back(data); + } + } + + // Adds test tensor (same as above) but with the default tf_type defined by + // the test params. + template + void AddTestTensor(const string& name, const std::vector& dims, + const std::vector& values = {}, + const std::vector& partial_input_shape_dims = {}) { + AddTestTensor(name, dims, tf_type_, values, partial_input_shape_dims); + } + + // Builds and runs the converted network. Checks output tensor shape. Tests + // output values using a matcher. The network can have multiple input and + // output tensors. The inputs are defined by the input_data_ member variable. + void BuildAndRun(const string& name, + const std::vector>& expected_output_dims, + const Status& expected_runtime_status, + const std::vector>>& matcher, + const std::vector& out_tf_types = {}) { + TensorShape shape; + const int n_output = expected_output_dims.size(); + ASSERT_EQ(n_output, matcher.size()); + DataVec output_data; + for (int i = 0; i < n_output; i++) { + TF_EXPECT_OK( + TensorShapeUtils::MakeShape(expected_output_dims[i], &shape)); + string out_name = (i == 0) ? name : StrCat(name, ":", i); + DataType out_tf_type = + out_tf_types.size() > i ? out_tf_types[i] : tf_type_; + InputOutputData data{ + out_name, ConstructTensor(shape.num_elements(), 0, out_tf_type)}; + output_data.push_back(data); + } + const int batch_size = + input_data_.empty() || + TensorShapeUtils::IsScalar(input_data_[0].tensor.shape()) + ? 1 + : input_data_[0].tensor.shape().dim_size(0); + Status stat = + OpConverterTest::BuildAndRun(input_data_, &output_data, batch_size); + ASSERT_EQ(expected_runtime_status.ok(), stat.ok()) + << "expected status: " << expected_runtime_status + << ", actual status: " << stat; + if (expected_runtime_status.ok() && stat.ok()) { + for (int i = 0; i < n_output; i++) { + // Check the shape of the actual output tensors + TF_EXPECT_OK( + TensorShapeUtils::MakeShape(expected_output_dims[i], &shape)); + EXPECT_TRUE(output_data[i].tensor.shape() == shape) + << "Expected shape: " << shape.DebugString() << ", actual shape: " + << output_data[i].tensor.shape().DebugString(); + EXPECT_THAT(GetDataAsFloat(output_data[i]), matcher[i]); + } + } + } + + // Runs validation and conversion. If conversion is successful then builds + // the TRT network, executes it and checks the output. Handles multiple output + // tensors. + void TestOpConverterMultiOut( + const NodeDef& node_def, + const std::vector>& expected_output_dims, + const Status& expected_conversion_status, + const Status& expected_runtime_status, + const std::vector>>& matcher, + const std::vector& out_tf_type = {}) { + const auto& name = node_def.name(); + RunValidationAndConversion(node_def, expected_conversion_status, name, + expected_output_dims); + if (expected_conversion_status.ok()) { + BuildAndRun(name, expected_output_dims, expected_runtime_status, matcher, + out_tf_type); + } + } + + // Runs validation and conversion. If conversion is successful then builds + // the TRT network, executes it and checks the output. + void TestOpConverter(const NodeDef& node_def, + const std::vector& expected_output_dims, + const Status& expected_conversion_status, + const Status& expected_runtime_status, + const Matcher>& matcher, + const std::vector& out_tf_types = {}) { + TestOpConverterMultiOut( + node_def, std::vector>({expected_output_dims}), + expected_conversion_status, expected_runtime_status, + std::vector>>({matcher}), out_tf_types); + } + + protected: + const TrtTestMode trt_mode_; + const DataType tf_type_; + const TrtPrecisionMode converter_precision_; + DataVec input_data_; +}; + +template +class OpConverter_UnaryTest : public ParameterizedOpConverterTestBase { + public: + template + void RunTests( + const string& testName, const OperationMap& map, + std::map, T (*)(T)>>& op_map, + const std::vector input_values, const std::string input_name = "input", + float max_abs_error = 0.0001, bool nan_sensitive = true) { + // Prepare test parameters. + auto p = TestParamBase{ + {1, 1, 2, 3}, // input dims + {}, // input partial dims + {1, 1, 2, 3}, // expected output dims + }; + + // Get list of ops to test. + std::vector ops_to_test; + for (auto& pair : map) { + ops_to_test.push_back(pair.first); + } + + for (const string& op_name : ops_to_test) { + SCOPED_TRACE(op_name); + if (!op_map.count(op_name)) { + FAIL() << testName << " op test map does not contain op " << op_name; + } + + const DataType tf_type = get_tf_type(); + const NodeDef& node = op_map[op_name].first(tf_type); + runExpectedToFailTest(node, input_name, input_values, op_name); + + Status conv_status = OkStatus(); + if (trt_mode_ == TrtTestMode::kImplicitBatch && + (op_name == "Sign" || op_name == "Round" || + op_name == "LogicalNot")) { + const auto& err = + convert_not_supported_implicit(op_name, node.name(), "Unary"); + conv_status = errors::Unimplemented(err); + } + + Reset(); + const DataType input_tf_type = op_name == "Cast" ? DT_HALF : tf_type; + const DataType output_tf_type = op_name == "Cast" ? DT_FLOAT : tf_type; + + AddTestTensor("input", p.input_dims, input_tf_type, input_values); + + std::vector output; + std::transform(input_values.begin(), input_values.end(), + std::back_inserter(output), op_map[op_name].second); + + TestOpConverter(node, p.expected_output_dims, conv_status, OkStatus(), + ArrayFloatNear(output, max_abs_error, nan_sensitive), + {output_tf_type}); + } + } + void runExpectedToFailTest(const NodeDef& node_def, + const std::string& input_name, + const std::vector& input_values, + const std::string& op_name) { + // Input is weights, should fail. + Reset(); + std::string error = + "The input \"" + input_name + "\" for " + op_name + " must be a tensor"; + AddTestWeights("input", {1, 2, 3}, input_values, get_tf_type()); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + error); + + // Input has 0 dimensions, should fail. + Reset(); + std::vector dims{}; + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + dims = {1}; + } + error = "At least 1 dimension is required for UNARY operation '" + op_name + + "'"; + AddTestTensor("input", dims); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + error); + } +}; + +template +class OpConverter_BinaryTest : public ParameterizedOpConverterTestBase { + public: + template + void RunTests( + const OperationMap& map, + std::map, std::vector>>& + op_test_info, + const std::vector>& data) { + const std::vector bool_types{DT_BOOL}, default_types{}; + std::vector logical_ops{"Greater", "Less", "Equal"}; + std::vector combined_ops{"GreaterEqual", "LessEqual"}; + const DataType tf_type = get_tf_type(); + AttrValue dtype; + dtype.set_type(tf_type); + std::map nodes; + for (const auto op_name : combined_ops) { + nodes[op_name] = MakeNodeDef("my_binary", op_name, {"input1", "input2"}, + {{"T", dtype}}); + } + + for (auto& iter : map) { + const string& op_name = iter.first; + if (!op_test_info.count(op_name)) { + FAIL() << "Binary op test map does not contain op " << op_name; + } + const auto comb_op = find_name(op_name, combined_ops); + const auto& node_def = + comb_op ? nodes[op_name] : op_test_info[op_name].first(tf_type); + + for (const bool operand_1_is_tensor : {true, false}) { + for (const bool operand_2_is_tensor : {true, false}) { + SCOPED_TRACE(StrCat(op_name, "_", operand_1_is_tensor ? "T" : "W", + operand_2_is_tensor ? "T" : "W")); + Reset(); + if (!operand_1_is_tensor && !operand_2_is_tensor) { + // In that case the only test which should be launched is in + // runExpectedToFailTest + runExpectedToFailTest(op_name, node_def); + continue; + } + + const bool logical_op = comb_op || find_name(op_name, logical_ops); + auto conv_status = OkStatus(); + if (tf_type == DT_BOOL || logical_op) { + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + conv_status = + errors::Unimplemented(convert_not_supported_implicit( + op_name, node_def.name(), "Binary")); + } else if (!logical_op && + (!operand_1_is_tensor || !operand_2_is_tensor)) { + conv_status = errors::InvalidArgument( + "Both inputs of '", op_name, "' are expected to be tensors"); + } + } + + if (operand_1_is_tensor) { + AddTestTensor("input1", {2, 1, 2}, data[0]); + } else { + AddTestWeights("input1", {1, 2}, data[1], tf_type); + } + if (operand_2_is_tensor) { + AddTestTensor("input2", {2, 2, 1}, data[2]); + } else { + AddTestWeights("input2", {2, 1}, data[3], tf_type); + } + + TestOpConverter(node_def, {2, 2, 2}, conv_status, OkStatus(), + ElementsAreArray(op_test_info[op_name].second), + logical_op ? bool_types : default_types); + } + } + } + } + + void runExpectedToFailTest(const std::string& op_name, const NodeDef& node) { + AddTestWeights("input1", {1}, {1}, tf_type_); + AddTestWeights("input2", {1}, {1}, tf_type_); + const string error = + "Constant folding is falled back to TensorFlow, " + "binary op '" + + op_name + "' received both input as constant"; + RunValidationAndConversion(node, absl::StatusCode::kUnimplemented, error); + } +}; + +// Op converter test in FP32 mode. While for debugging purposes it might make +// sense to run over all possible combinations, normally a subset of them +// would be sufficient: +// - All valid options to TrtTestMode (implicit, explicit, dynamic shape) +// - DataType: is the TF data type of the input tensors. This usually only +// influences the data type added by Converter::AddInputTensor. We test the +// valid combinations of input data types in AddAndGetInputs, therefore +// for most of the OpConverterTest its is sufficient to test for DT_FLOAT. +// - TrtPrecisionMode: valid options are FP32, FP16 and INT8. This influences +// how TRT handles the precision inside the TRT network, but should not matter +// for the TF -> TRT conversion. Therefore it should be sufficient to test +// for FP32. +typedef ParameterizedOpConverterTestBase OpConverter_FP32_Test; +// Base class for tests that need to be tested for both FP32 and FP16. +typedef ParameterizedOpConverterTestBase OpConverter_FP32_FP16_Test; +// Base class for Binary tests that need to be tested +typedef OpConverter_BinaryTest OpConverter_FP32_FP16_BinaryTest; +typedef OpConverter_BinaryTest OpConverter_BOOL_BinaryTest; +// Base class for tests that need to be tested for FP32, FP16, and INT32 +typedef ParameterizedOpConverterTestBase OpConverter_FP32_FP16_INT32_Test; +// Base class for tests that need to be tested for INT32 +typedef ParameterizedOpConverterTestBase OpConverter_INT32_Test; +// Base class for Unary tests that need to be tested +typedef OpConverter_UnaryTest OpConverter_FP32_UnaryTest; +typedef OpConverter_UnaryTest OpConverter_BOOL_Test; + +// Instantiate parameter combinations to OpConverter__Test +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_FP32_Test, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_FLOAT), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_FP32_FP16_Test, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_FLOAT, DT_HALF), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_FP32_FP16_INT32_Test, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_FLOAT, DT_HALF, DT_INT32), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_INT32_Test, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_INT32), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_FP32_UnaryTest, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_FLOAT), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_BOOL_Test, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_BOOL), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_FP32_FP16_BinaryTest, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_FLOAT, DT_HALF), + ::testing::Values(TrtPrecisionMode::FP32))); + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_BOOL_BinaryTest, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_BOOL), + ::testing::Values(TrtPrecisionMode::FP32))); + +template +void CopyTensorElements(const Tensor& tensor, protobuf::RepeatedField* out) { + out->Clear(); + if (tensor.NumElements() == 0) return; + + // TensorProto does not need to have all the elements present and can truncate + // trailing elements with the same value for compressed representation. Such + // elements are derived based on the tensor shape. + const auto flat = tensor.flat(); + int64 last_index = 0; + for (int64 i = 0; i < tensor.NumElements(); ++i) { + if (flat(i) != flat(last_index)) { + last_index = i; + } + } + + int num_out_elements = last_index + 1; + out->Reserve(num_out_elements); + out->AddNAlreadyReserved(num_out_elements); + const T* src = flat.data(); + T* dst = out->mutable_data(); + std::copy(src, src + num_out_elements, dst); +} + +template +void TestConvertVariableV2(VariableOpConverterTest* test) { + struct TestParam { + string container; + string shared_name; + std::vector dims; + float epsilon; + Status conversion_status; + }; + + std::vector test_param = { + {"", "var0", {}, 0.001, OkStatus()}, + {"", "var0", {64}, 0.001, OkStatus()}, + {"", "var0", {8, 16}, 0.001, OkStatus()}, + {"box", "var", {8, 16}, 0.001, OkStatus()}}; + for (auto p : test_param) { + // Create node definition. + NodeDef node_def; + std::vector dims_64(p.dims.begin(), p.dims.end()); + TensorShape shape = TensorShape(absl::Span(dims_64)); + TF_CHECK_OK(NodeDefBuilder("my_var", "VariableV2") + .Attr("dtype", dtype) + .Attr("shape", shape) + .Attr("container", p.container) + .Attr("shared_name", p.shared_name) + .Finalize(&node_def)); + + OpKernel* kernel; + OpKernelContext* context; + test->CreateContext(node_def, &kernel, &context); + + test->Reset(TrtPrecisionMode::FP32, TrtTestMode::kDynamicShape); + + // Set the value of the variable according to p.dims. + int var_size = std::accumulate(p.dims.begin(), p.dims.end(), 1, + std::multiplies()); + std::vector expected_value; + expected_value.reserve(var_size); + for (int i = 0; i < var_size; i++) { + expected_value.push_back((CType)i); + } + + // To set the variable, we get the tensor by executing the VariableV2 op + // rather than creating the resource directly in the manager, because: + // 1) LegacyVar defined in `variable_ops.cc` is not accessible. + // 2) Tensor::set_shape is private, VariableOp is a friend class. + kernel->Compute(context); + Tensor* tensor_ptr = context->mutable_output(0); + CHECK_NOTNULL(tensor_ptr); + // We allocate the tensor in the temporary memory. Note that creating a + // tensor in this scope and sharing the underlying storage by copy would + // lead to double destruction. + AllocatorAttributes attr; + attr.set_gpu_compatible(true); + attr.set_nic_compatible(true); + OP_REQUIRES_OK(context, + context->allocate_temp(dtype, shape, tensor_ptr, attr)); + // The tensor is allocated on GPU. We copy the values from the CPU. + auto tensor_flat = tensor_ptr->flat(); + CHECK_NOTNULL(tensor_flat.data()); + auto ret = cudaMemcpy(tensor_flat.data(), expected_value.data(), + expected_value.size() * sizeof(CType), + cudaMemcpyHostToDevice); + CHECK_EQ(ret, 0); + + test->RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(test->GetTensorOrWeights("my_var", &output)); + EXPECT_THAT(output.weights(), + ShapedWeightsHasDimsAndValues(p.dims, expected_value)); + } +} + +TEST_F(VariableOpConverterTest, ConvertVariableV2) { + TestConvertVariableV2(this); + TestConvertVariableV2(this); +} + +template +void TestConvertReadVariableOp(VariableOpConverterTest* test) { + struct TestParam { + string container; + string name; + std::vector dims; + float epsilon; + Status conversion_status; + }; + + std::vector test_param = { + {"", "var0", {}, 0.001, OkStatus()}, + {"", "var0", {64}, 0.001, OkStatus()}, + {"", "var0", {8, 16}, 0.001, OkStatus()}, + {"box", "var", {8, 16}, 0.001, OkStatus()}}; + for (auto p : test_param) { + // Create node definition. + NodeDefBuilder::NodeOut rvo_input = + NodeDefBuilder::NodeOut("my_handle", 0, DT_RESOURCE); + NodeDef node_def; + std::vector dims_64(p.dims.begin(), p.dims.end()); + TensorShape shape = + TensorShape(gtl::ArraySlice(dims_64)); // non-absl ok + TF_CHECK_OK(NodeDefBuilder("my_var", "ReadVariableOp") + .Attr("dtype", dtype) + .Attr("_shape", shape) + .Input(rvo_input) + .Finalize(&node_def)); + + OpKernel* kernel; + OpKernelContext* context; + test->CreateContext(node_def, &kernel, &context); + + test->Reset(TrtPrecisionMode::FP32, TrtTestMode::kDynamicShape); + + // Set the value of the variable according to p.dims. + int var_size = std::accumulate(p.dims.begin(), p.dims.end(), 1, + std::multiplies()); + std::vector expected_value; + expected_value.reserve(var_size); + for (int i = 0; i < var_size; i++) { + // Set expected_value[i] = (cast)i. + expected_value.push_back((CType)i); + } + + // Create a resource handle. + DtypeAndPartialTensorShape dtype_and_shape; + dtype_and_shape.dtype = dtype; + TF_CHECK_OK(PartialTensorShape::BuildPartialTensorShape( + gtl::ArraySlice(dims_64), // non-absl ok + &dtype_and_shape.shape)); + ResourceHandle handle = MakeResourceHandle( + context, p.container, p.name, + std::vector{dtype_and_shape}); + + // Create input resource with the handle. + test->AddTestResource("my_handle", handle); + + // Create a resource with this handle. + Var* resource = new Var(dtype); + TF_EXPECT_OK(CreateResource(context, handle, resource)); + + // Setup the tensor of the variable. + // We allocate the tensor in the temporary memory. Note that creating a + // tensor in this scope and sharing the underlying storage by copy would + // lead to double destruction. + AllocatorAttributes attr_value; + attr_value.set_gpu_compatible(true); + attr_value.set_nic_compatible(true); + TF_EXPECT_OK( + context->allocate_temp(dtype, shape, resource->tensor(), attr_value)); + // The tensor is allocated on GPU. We copy the values from the CPU. + auto tensor_flat = resource->tensor()->flat(); + CHECK(tensor_flat.data()); + auto ret = cudaMemcpy(tensor_flat.data(), expected_value.data(), + expected_value.size() * sizeof(CType), + cudaMemcpyHostToDevice); + CHECK_EQ(ret, 0); + + test->RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(test->GetTensorOrWeights("my_var", &output)); + EXPECT_THAT(output.weights(), + ShapedWeightsHasDimsAndValues(p.dims, expected_value)); + } +} + +TEST_F(VariableOpConverterTest, ConvertReadVariableOp) { + TestConvertReadVariableOp(this); + TestConvertReadVariableOp(this); +} + +template +void TestConvertConst(OpConverterTest* test) { + NodeDef node_def; + node_def.set_name("my_const"); + node_def.set_op("Const"); + + auto reset_and_test = [&node_def, test]( + const Tensor& tensor, const bool as_tensor_content, + const std::vector& expected_dims, + const std::vector& expected_value) { + test->Reset(); + + TensorProto* tensor_attr = + (*node_def.mutable_attr())["value"].mutable_tensor(); + tensor_attr->Clear(); + + if (as_tensor_content) { + tensor.AsProtoTensorContent(tensor_attr); + } else { + tensor.shape().AsProto(tensor_attr->mutable_tensor_shape()); + tensor_attr->set_dtype(tensor.dtype()); + + if (tensor.dtype() == DT_FLOAT) { + CopyTensorElements(tensor, tensor_attr->mutable_float_val()); + } else if (tensor.dtype() == DT_INT32) { + CopyTensorElements(tensor, tensor_attr->mutable_int_val()); + } else { + tensor.AsProtoField(tensor_attr); + } + } + test->RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(test->GetTensorOrWeights("my_const", &output)); + EXPECT_THAT(output.weights(), ShapedWeightsHasDimsAndValues( + expected_dims, expected_value)); + }; + + auto& attr = *node_def.mutable_attr(); + attr["dtype"].set_type(dtype); + { + // By default empty tensor will pick DT_FLOAT as data type and we fix it + // here. + Tensor t(dtype); // Empty tensor. + reset_and_test(t, false, {}, {}); + } + { + Tensor t = test::AsScalar(12); + std::vector expected_dims{1}; + // Scalars are represented as rank 0 tensors. + expected_dims.clear(); + reset_and_test(t, false, expected_dims, {12}); + reset_and_test(t, true, expected_dims, {12}); + } + { + Tensor t = test->AsTensor({1, 2}); + reset_and_test(t, false, {2}, {1, 2}); + reset_and_test(t, true, {2}, {1, 2}); + } + { + Tensor t = + test->AsTensor({1, 2, 3, 4, 5, 6}, TensorShape({2, 3})); + reset_and_test(t, false, {2, 3}, {1, 2, 3, 4, 5, 6}); + reset_and_test(t, true, {2, 3}, {1, 2, 3, 4, 5, 6}); + } + { + // Set all tensor elements to the same value. Such tensors are encoded + // using a single element list in tensor proto. + Tensor t = + test->AsTensor({1, 1, 1, 1, 1, 1}, TensorShape({2, 3})); + reset_and_test(t, false, {2, 3}, {1, 1, 1, 1, 1, 1}); + reset_and_test(t, true, {2, 3}, {1, 1, 1, 1, 1, 1}); + } + { + // Set trailing tensor elements to the same value. Such tensors are + // encoded by truncating all equal elements except the first one. + Tensor t = + test->AsTensor({2, 2, 1, 1, 1, 1}, TensorShape({2, 3})); + reset_and_test(t, false, {2, 3}, {2, 2, 1, 1, 1, 1}); + reset_and_test(t, true, {2, 3}, {2, 2, 1, 1, 1, 1}); + } +} + +TEST_F(OpConverterTest, ConvertConst) { + { + Reset(); + NodeDef node_def = MakeConstNodeDef("my_const", {}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Unsupported tensorflow data type double"); + } + { + Reset(); + Tensor tensor = + AsTensor({1, std::numeric_limits::max(), 1, 1, 1, + std::numeric_limits::lowest()}, + TensorShape({2, 3})); + NodeDef node_def; + node_def.set_name("my_const"); + node_def.set_op("Const"); + (*node_def.mutable_attr())["dtype"].set_type(DT_INT64); + TensorProto* tensor_attr = + (*node_def.mutable_attr())["value"].mutable_tensor(); + tensor_attr->Clear(); + tensor.AsProtoTensorContent(tensor_attr); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "outside the range of int32"); + } + + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); + TestConvertConst(this); +} + +template +NodeDef CreateFusedBatchNormOp(DataType tf_type, std::string data_format, + bool is_training, float epsilon) { + Scope s = Scope::NewRootScope(); + auto x = ops::Placeholder(s.WithOpName("x"), tf_type); + auto scale = ops::Placeholder(s.WithOpName("scale"), tf_type); + auto offset = ops::Placeholder(s.WithOpName("offset"), tf_type); + auto mean = ops::Placeholder(s.WithOpName("mean"), tf_type); + auto variance = ops::Placeholder(s.WithOpName("variance"), tf_type); + typename T::Attrs attrs; + attrs.data_format_ = data_format; + attrs.is_training_ = is_training; + if (epsilon > 0) { + attrs.epsilon_ = epsilon; + } else { + EXPECT_GE(epsilon, 0); + } + return T(s.WithOpName("my_batchnorm"), x, scale, offset, mean, variance, + attrs) + .operation.node() + ->def(); +} + +TEST_P(OpConverter_FP32_Test, ConvertFusedBatchNorm) { + using OpFunc = std::function; + std::vector get_node_def_vec{ + CreateFusedBatchNormOp, + CreateFusedBatchNormOp, + CreateFusedBatchNormOp}; + + struct TestParam { + std::string data_format; + int tensor_input_idx; // Index of an input that will be provided as tensor. + bool is_training; + float epsilon; + Status conversion_status; + bool keep_channel_unknown; + }; + + struct NodeInput { + std::string name; + std::vector dims; + std::vector val; + }; + std::vector node_input_nchw{ + {"x", {2, 3, 2, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}}, + {"scale", {3}, {7, 8, 9}}, + {"offset", {3}, {10, 20, 30}}, + {"mean", {3}, {1, 2, 3}}, + {"variance", {3}, {4, 5, 6}}}; + + std::vector node_input_nhwc{ + {"x", {2, 2, 1, 3}, {1, 3, 5, 2, 4, 6, 7, 9, 11, 8, 10, 12}}, + {"scale", {3}, {7, 8, 9}}, + {"offset", {3}, {10, 20, 30}}, + {"mean", {3}, {1, 2, 3}}, + {"variance", {3}, {4, 5, 6}}}; + + std::vector expected_output_nchw{ + 10.0, 13.495633, 23.574135, 27.148273, 37.342354, 41.013527, + 30.9738, 34.469433, 45.018955, 48.59309, 59.369415, 63.04059}; + + std::vector expected_output_nhwc{ + 10.0, 23.574135, 37.342354, 13.495633, 27.148273, 41.013527, + 30.9738, 45.018955, 59.369415, 34.469433, 48.59309, 63.04059}; + + for (auto get_node_def : get_node_def_vec) { + NodeDef tmp_node_def = get_node_def(tf_type_, "NCHW", true, 0); + std::string op_name = tmp_node_def.op(); + std::vector test_param{ + {"NCHW", 0, true, 0, + errors::Unimplemented( + StrCat(op_name, " only supports is_training=false"))}, + {"NCHW", 1, false, 0, + errors::Unimplemented(StrCat("The input \"scale\" for ", op_name, + " must be a constant"))}, + {"NCHW", 2, false, 0, + errors::Unimplemented(StrCat("The input \"offset\" for ", op_name, + " must be a constant"))}, + {"NCHW", 3, false, 0, + errors::Unimplemented(StrCat("The input \"mean\" for ", op_name, + " must be a constant"))}, + {"NCHW", 4, false, 0, + errors::Unimplemented(StrCat("The input \"variance\" for ", op_name, + " must be a constant"))}, + {"NCHW", 0, false, 0.01}, + {"NHWC", 0, false, 0.01}}; + if (trt_mode_ == TrtTestMode::kDynamicShape) { + test_param.push_back( + {"NCHW", 0, false, 0.01, + errors::InvalidArgument("Channel dimension must be static"), true}); + test_param.push_back( + {"NHWC", 0, false, 0.01, + errors::InvalidArgument("Channel dimension must be static"), true}); + } + for (auto p : test_param) { + Reset(); + NodeDef node_def = + get_node_def(tf_type_, p.data_format, p.is_training, p.epsilon); + std::vector node_input = + p.data_format == "NCHW" ? node_input_nchw : node_input_nhwc; + std::vector expected_output = + p.data_format == "NCHW" ? expected_output_nchw : expected_output_nhwc; + for (int i = 0; i < node_input.size(); i++) { + if (i == 0 || i == p.tensor_input_idx) { + // The first input (x) is always added as a tensor, and it has shape + // NCHW/NHWC. The other inputs are per channel values (1D, size C). + // + // In implicit batch mode, it is not possible to add any of the 1D + // inputs as a tensor: the first dim is always treated as batch dim in + // implicit batch mode, and that has to agree for all tensors. We have + // two input tensors with shapes NCHW and C and in general N != C. + // The converter already picked up N from the fist input, and reports + // an error when we try to add any other tensors with not matching + // first dim. + // + // This restriction does not apply in explicit batch mode: the tensors + // can have different first dim. The converter still expects that only + // the first arg is a tensor. TODO(tfeher) Check if one can relax this + // restriction. + Status expected_status = + (i != 0 && trt_mode_ == TrtTestMode::kImplicitBatch) + ? errors::InvalidArgument( + batch_size_error(node_input[i].name, + "Provided batch size does not match " + "converter batch size: 3 vs 2")) + : OkStatus(); + std::vector partial_input_shape; + if (i == 0 && trt_mode_ == TrtTestMode::kDynamicShape && + !p.keep_channel_unknown) { + // keep channel dim static (known) + partial_input_shape.resize(4, -1); + int channel_dim = (p.data_format == "NCHW" ? 1 : 3); + partial_input_shape[channel_dim] = node_input[i].dims[channel_dim]; + } + AddTestTensor(node_input[i].name, node_input[i].dims, tf_type_, + node_input[i].val, partial_input_shape, + expected_status); + + } else { + AddTestWeights(node_input[i].name, node_input[i].dims, + node_input[i].val, tf_type_); + } + } + TestOpConverter(node_def, node_input[0].dims, p.conversion_status, + OkStatus(), ArrayFloatNear(expected_output)); + } + } +} + +TEST_P(OpConverter_FP32_Test, ConvertTranspose) { + // Get the NodeDef for Transpose. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto weights = ops::Placeholder(s.WithOpName("weights"), DT_INT32); + auto transpose = ops::Transpose(s.WithOpName("my_transpose"), input, weights); + const NodeDef& node_def = transpose.operation.node()->def(); + + std::vector test_params = { + // For the first test we leave param empty. This signals to use a + // input as weight which will be invalid + TestParamBase{{3, 1, 2, 1}, + {}, + {}, + {}, + Status(absl::StatusCode::kUnimplemented, + "The input \"perm\" for Transpose must be a " + "constant")}, + TestParamBase{{1, 1, 2, 3}, + {}, + {}, + {0, 1, 2}, + Status(absl::StatusCode::kInvalidArgument, + "Rank of perm for transpose does not match with " + "that of the input.")}, + // Transpose batch dim + TestParamBase{ + {1, 1, 2, 3}, + {}, + {3, 2, 1, 1}, + {3, 2, 1, 0}, + (trt_mode_ == TrtTestMode::kImplicitBatch) + ? Status(absl::StatusCode::kUnimplemented, + "Transpose at batch dimension is not supported") + : OkStatus()}, + TestParamBase{{1, 1, 2, 3}, {}, {1, 3, 1, 2}, {0, 3, 1, 2}}, + }; + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // Dynamic shape tests where some shapes are known + test_params.push_back(TestParamBase{ + {1, 1, 2, 3}, {-1, 1, 2, -1}, {1, 3, 1, 2}, {0, 3, 1, 2}}); + } + std::vector expected_values{1, 4, 2, 5, 3, 6}; + for (auto p : test_params) { + SCOPED_TRACE(p); + Reset(); + AddTestTensor("input", p.input_dims, {1, 2, 3, 4, 5, 6}, + p.partial_input_dims); + if (p.param.empty()) { + AddTestTensor("weights", {3}); + } else { + AddTestWeights("weights", {static_cast(p.param.size())}, + p.param); + } + TestOpConverter(node_def, p.expected_output_dims, p.status, + p.runtime_status, ElementsAreArray(expected_values)); + } +} + +TEST_P(OpConverter_FP32_Test, ConvertTile) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto weights = ops::Placeholder(s.WithOpName("weights"), DT_INT32); + auto tile = ops::Tile(s.WithOpName("my_tile"), input, weights); + const NodeDef& node_def = tile.operation.node()->def(); + + struct TileParam { + std::vector input_dims; + std::vector multiplier; + std::vector tensor; + // Concrete (static) output dimensions, including batch size as first dim. + std::vector expected_output_dims; + std::vector expected_results; + int test_ID; + // Expected status of conversion (with concrete error message). + Status status; + }; + + std::vector test_params = { + // Tests to be rejected by ConvertTile::Validate() for any trt_mode_. + TileParam{{1, 2, 3}, // input_dims + {1, -2, 1}, // multiplier + {}, // tensor + {}, // expected_output_dims + {}, // expected_results + 1, // test_ID + Status(absl::StatusCode::kInvalidArgument, + "All replications of the Tile operation in " + "'my_tile' should be positive, got (1, -2, 1).")}, + TileParam{{1, 2, 3}, // input_dims + {1, 2, 1, 3}, // multiplier + {0, 1, 2, 3, 4, 5}, // tensor + {}, // expected_output_dims + {}, // expected_results + 2, // test_ID + Status(absl::StatusCode::kInvalidArgument, + "The length of the replication vector (4) of the " + "Tile operation in 'my_tile' is expected to be equal " + "to the rank of the input vector (3).")}, + // Tests passed ConvertTile::Validate() for at least some trt_mode_. + TileParam{{1, 2}, // input_dims + {1, 3}, // multiplier + {2, 3}, // tensor + {1, 6}, // expected_output_dims + {2, 3, 2, 3, 2, 3}}, // out values + TileParam{{1, 2, 3}, // input_dims + {1, 2, 1}, // multiplier + {0, 1, 2, 3, 4, 5}, // tensor + {1, 4, 3}, // output dims + {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5}}, // expected_results + TileParam{{1, 2, 3}, // input_dims + {1, 1, 2}, // multiplier + {0, 1, 2, 3, 4, 5}, // tensor + {1, 2, 6}, // expected_output_dims + {0, 1, 2, 0, 1, 2, 3, 4, 5, 3, 4, 5}}, // expected_results + TileParam{{1, 2, 3}, // input_dims + {1, 2, 2}, // multiplier + {0, 1, 2, 3, 4, 5}, // tensor + {1, 4, 6}, // expected_output_dims + {0, 1, 2, 0, 1, 2, 3, 4, 5, 3, 4, 5, + 0, 1, 2, 0, 1, 2, 3, 4, 5, 3, 4, 5}}, // expected_results + // Tests with non trivial batch size multiplier. + TileParam{{1, 2}, // input_dims + {2, 3}, // multiplier + {2, 3}, // tensor + {2, 6}, // expected_output_dims + {2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3}}, // out values + TileParam{{1, 2, 3}, // input_dims + {2, 2, 1}, // multiplier + {0, 1, 2, 3, 4, 5}, // tensor + {2, 4, 3}, // output dims + {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, + 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5}}, // expected_results + }; + + for (bool multiplier_is_tensor : {true, false}) { + for (bool input_is_tensor : {true, false}) { + for (auto p : test_params) { + std::vector num_mults = {static_cast(p.multiplier.size())}; + std::vector partial_input_dims = {}; + if (multiplier_is_tensor) { + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + p.status = + Status(absl::StatusCode::kInvalidArgument, + "Conversion for Tile is not implemented for multipliers " + "passed as a tensor in implicit batch mode"); + num_mults = {1, static_cast(p.multiplier.size())}; + } else { + if (p.test_ID == 1) { + // Skip this test because in that situation it is impossible + // to do a valid check for negative multipliers. + continue; + } + + if (trt_mode_ == TrtTestMode::kDynamicShape) { + partial_input_dims = num_mults; + p.status = OkStatus(); + } + + if (p.test_ID == 2) { + p.status = Status(absl::StatusCode::kInvalidArgument, + "When replications are defined as a tensor, " + "the number of its elements (4) must be equal " + "to the rank of the input tensor (3)."); + } + } + } else { + if (trt_mode_ == TrtTestMode::kImplicitBatch && p.multiplier[0] > 1) { + p.status = + Status(absl::StatusCode::kUnimplemented, + "The Tile operation along " + "the batch dimension in 'my_tile' is not implemented."); + } + } + + Reset(); + if (input_is_tensor) { + AddTestTensor("input", p.input_dims, p.tensor); + } else { + AddTestWeights("input", p.input_dims, p.tensor, tf_type_); + } + + if (multiplier_is_tensor) { + AddTestTensor("weights", num_mults, DT_INT32, p.multiplier, + partial_input_dims); + } else { + AddTestWeights("weights", num_mults, p.multiplier); + } + + TestOpConverter(node_def, p.expected_output_dims, p.status, OkStatus(), + ElementsAreArray(p.expected_results)); + } + } + } +} + +TEST_P(OpConverter_FP32_Test, ConvertReshape) { + // Get the NodeDef for Reshape. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto weights = ops::Placeholder(s.WithOpName("weights"), DT_INT32); + auto reshape = ops::Reshape(s.WithOpName("my_reshape"), input, weights); + const NodeDef& node_def = reshape.operation.node()->def(); + + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + // Shape is a tensor, should fail in implicit batch mode. + Reset(); + AddTestTensor("input", {3, 2, 1}); + AddTestTensor("weights", {3}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "The input \"shape\" for Reshape must be a constant in implicit batch " + "mode"); + } else if (!IS_TRT_VERSION_GE(7, 1, 3, 0)) { + // Shape is a tensor, should fail before TRT 7.1.3 even in explicit batch / + // dynamic shape mode. + Reset(); + AddTestTensor("input", {3, 2, 1}); + AddTestTensor("weights", {3}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Non constant shape input tensor for Reshape requires minimum TRT " + "7.1.3"); + } + + Status reshape_from_scalar_status = + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Internal( + "Failed to convert at least one input to a TRT_TensorOrWeights:" + " Scalar input tensor is not supported since the first " + "dimension is treated as batch dimension by TRT") + : OkStatus(); + Status add_scalar_tensor_status = + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::InvalidArgument( + "removing first dim requires explicit batch dimension") + : OkStatus(); + Status reshape_to_scalar_status = + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented("Reshape to shape=[] is not supported") + : OkStatus(); + Status reshape_batch_status = + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented("Reshape on batch dimension is not supported") + : OkStatus(); + + struct TestParams { + std::vector tensor_dims; + std::vector shape; + std::vector expected_shape; + Status conversion_status; + Status runtime_status; + std::vector shape_prof; // needed concrete values if shape == -1. + Status add_test_tensor_status; + }; + + std::vector params = { + // Reshape scalar to tensor, should fail in implicit batch mode. + TestParams{{}, + {1, 1}, + {}, + reshape_from_scalar_status, + {}, + {}, + add_scalar_tensor_status}, + // Reshape tensor to scalar, should fail in implicit batch mode. + // - In explicit batch mode if shape is set as weight it works. + // - In explicit batch mode && using shape as tensor input it should + // fail. In that case we set the expected conversion status in the + // test loop. + TestParams{{1, 1}, {}, {}, reshape_to_scalar_status}, + // Reshape at batch dimension, should fail in implicit batch mode. + TestParams{{1, 1, 2, 3}, {3, 1, 1, 2}, {}, reshape_batch_status}, + TestParams{{2, 1, 2, 3}, {-1, 1, 4}, {3, 1, 4}, reshape_batch_status}, + // Tests that should succeed in every trt_mode. + TestParams{{1, 1, 2, 3}, {-1, 1, 3, 2}, {1, 1, 3, 2}}, + TestParams{{1, 1, 2, 3}, {1, 1, -1}, {1, 1, 6}}, + TestParams{{1, 1, 2, 3}, {1, 1, 3, 2}}, + TestParams{{2, 1, 2, 3}, {2, 1, 3, 2}}, + TestParams{{1, 1, 1}, {1}}, + TestParams{{1}, {1, 1}}, + TestParams{{2, 1, 1}, {2}}, + TestParams{{2}, {2, 1}}, + }; + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + // Reshape tensor with zero rank using an empty shape tensor, should fail in + // implicit batch mode. In explicit batch mode this is an identity operation + // and does not add a reshape layer therefore we do not test it. + params.push_back(TestParams{{}, + {}, + {}, + reshape_from_scalar_status, + {}, + {}, + add_scalar_tensor_status}); + } + // Testing the methods for representing the reshape shape for IShuffleLayer: + // as a weight (true) or as a tensor (false). + std::vector shape_input_options(1, true); + + if (trt_mode_ != TrtTestMode::kImplicitBatch && + IS_TRT_VERSION_GE(7, 1, 3, 0)) { + shape_input_options.push_back(false); + } + + for (auto p : params) { + for (auto shape_as_weight : shape_input_options) { + std::ostringstream oss; + oss << "shape " << PrintToString(p.shape); + SCOPED_TRACE(StrCat(oss.str(), shape_as_weight ? " weight" : " tensor")); + if (!shape_as_weight && p.shape.empty()) { + p.conversion_status = errors::Unimplemented( + "Reshape with dynamic input requires 1D input tensor"); + } + Reset(); + const int n_elements = + std::accumulate(p.tensor_dims.begin(), p.tensor_dims.end(), 1, + std::multiplies()); + std::vector input_vec(n_elements); + std::iota(input_vec.begin(), input_vec.end(), 1); + AddTestTensor("input", p.tensor_dims, tf_type_, input_vec, {}, + p.add_test_tensor_status); + if (shape_as_weight) { + AddTestWeights("weights", {static_cast(p.shape.size())}, + p.shape); + } else { + std::vector dims; + std::vector values{p.shape}; + if (!p.shape.empty()) { + dims.push_back(p.shape.size()); + } else { + // If the shape is empty we use a dummy value to ensure that + // AddTestTensor creates the corresponding entry in InputOutputData. + values.push_back(1); + } + AddTestTensor("weights", dims, DT_INT32, values, dims); + } + std::vector expected_shape = + p.expected_shape.empty() ? p.shape : p.expected_shape; + VLOG(2) << "Calling TestOpConverter"; + TestOpConverter(node_def, expected_shape, p.conversion_status, + p.runtime_status, ElementsAreArray(input_vec)); + } + } +} + +TEST_P(OpConverter_FP32_Test, ConvertShape) { + // Get the NodeDef for Shape op. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto shape = ops::Shape(s.WithOpName("my_shape"), input); + const NodeDef& node_def = shape.operation.node()->def(); + + Status conversion_status = + (trt_mode_ == TrtTestMode::kImplicitBatch) + ? errors::Unimplemented( + "Shape is only supported for explicit batch mode.") + : OkStatus(); + std::vector test_params = { +// TODO(b/166274212): Enable the test parameter for TensorRT 7.1.3. +#if !IS_TRT_VERSION_GE(7, 1, 3, 0) + TestParamBase{{1, 2, 3}, {}, {3}, {}, conversion_status}, +#endif + // Add input as weight (we use non empty param ({1}) to trigger this). + TestParamBase{{1, 2, 3}, {}, {3}, {1}, conversion_status}, + }; + + auto input_is_weight = [](const TestParamBase p) { return !p.param.empty(); }; + for (auto p : test_params) { + SCOPED_TRACE(p); + Reset(); + // The number of elements of the input tensor. We leave it 0 in case we do + // not need to add an input tensor. This happens in explicit batch mode: the + // shape is known at conversion time and therefore the shape is added to the + // network as a constant layer. In this case the single node network that + // we use for the unit test have no actual input tensor when it is converted + // to a TensorRT network. + int n_elements = 0; + if (input_is_weight(p) || trt_mode_ != TrtTestMode::kExplicitBatch) { + // Calculate the number of elements for adding input data. + n_elements = std::accumulate(p.input_dims.begin(), p.input_dims.end(), 1, + std::multiplies()); + } + std::vector input_val(n_elements, 1); + if (!input_is_weight(p)) { + AddTestTensor("input", p.input_dims, input_val); + } else { + AddTestWeights("input", p.input_dims, input_val, tf_type_); + } + TestOpConverter(node_def, p.expected_output_dims, p.status, + p.runtime_status, ElementsAreArray(p.input_dims), + {DT_INT32}); + } +} + +struct MatMulTestParams { + std::vector shape_a; + std::vector values_a; + bool transpose_a; + std::vector shape_b; + std::vector values_b; + bool transpose_b; + std::vector expected_shape; + std::vector expected_output; +}; + +// Helper function for testing MatMul and BatchMatMul. get_matmul is a function +// used to generate the node. It accepts (DataType, transpose_a, transpose_b) as +// parameters. +void TestMatMulHelper( + ParameterizedOpConverterTestBase* test, + const std::function& get_matmul, + const std::vector& params) { + { + // Unsupported data type. + test->Reset(); + NodeDef node_def = get_matmul(DT_INT32, false, false); + test->AddTestTensor("input", {1, 2}, DT_INT32, {}); + test->AddTestWeights("weights", {2, 1}, {3, 5}); + const std::vector allowed_types{DT_FLOAT, DT_HALF}; + test->RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + convert_not_supported_dtype_msg(allowed_types, DT_INT32, node_def)); + } + + // FC conversion depends on whether the last dim of A is known or not. In + // Dynamic shape mode, we will check whether A is handled correctly if it has + // a partially known input shape (last dim known). + std::vector a_test_partial_shape_values{false}; + if (test->get_trt_mode() == TrtTestMode::kDynamicShape) { + a_test_partial_shape_values.push_back(true); + } + + for (auto p : params) { + for (bool a_is_tensor : {true, false}) { + for (bool b_is_tensor : {true, false}) { + for (bool a_partial_shape : a_test_partial_shape_values) { + if (a_partial_shape && !a_is_tensor) { + // Only tensors can have partial shape. + continue; + } + if (!a_is_tensor && !b_is_tensor) { + // Skip test when both args are weights. We do not convert this + // since const folding eliminates this case. + continue; + } + SCOPED_TRACE(StrCat("A", p.transpose_a ? ".T" : "", " is ", + a_is_tensor ? "tensor" : "weight", ", B", + p.transpose_b ? ".T" : "", " is ", + b_is_tensor ? "tensor " : "weight, rank A ", + p.shape_a.size(), ", rank B ", p.shape_b.size())); + test->Reset(); + + NodeDef node_def = + get_matmul(test->get_tf_type(), p.transpose_a, p.transpose_b); + const bool is_batch_matmul = node_def.op() == "BatchMatMul"; + + if (a_is_tensor) { + if (a_partial_shape) { + // Prepare a partial shape for A where only the last dim is known. + std::vector partial_shape(p.shape_a.size(), -1); + int k = p.shape_a.size() - 1; + partial_shape.at(k) = p.shape_a.at(k); + test->AddTestTensor("input", p.shape_a, test->get_tf_type(), + p.values_a, partial_shape); + } else { + test->AddTestTensor("input", p.shape_a, p.values_a); + } + } else { + test->AddTestWeights("input", p.shape_a, p.values_a, + test->get_tf_type()); + } + if (b_is_tensor) { + if (a_is_tensor && p.shape_a[0] != p.shape_b[0] && + test->get_trt_mode() == TrtTestMode::kImplicitBatch) { + VLOG(2) << "Skipping test with inpcompatible batch dimensions"; + continue; + } + test->AddTestTensor("weights", p.shape_b, p.values_b); + } else { + test->AddTestWeights("weights", p.shape_b, p.values_b, + test->get_tf_type()); + } + + Status conversion_status = OkStatus(); + if (test->get_trt_mode() == TrtTestMode::kImplicitBatch) { + // Implicit batch mode has several restriction. We change conversion + // status accordingly. + if (is_batch_matmul) { + if (a_is_tensor && p.shape_a.size() < p.shape_b.size()) { + conversion_status = errors::InvalidArgument( + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims ", + p.shape_a.size(), " vs broadcast #dims ", p.shape_b.size(), + ")"); + } + if (b_is_tensor && p.shape_b.size() < p.shape_a.size()) { + conversion_status = errors::InvalidArgument( + "Broadcasting beyond batch dimension is not supported " + "(tensor #dims ", + p.shape_b.size(), " vs broadcast #dims ", p.shape_a.size(), + ")"); + } + if ((!a_is_tensor || !b_is_tensor) && p.shape_a[0] != 1) { + conversion_status = errors::Unimplemented( + "TensorRT does not support batched constants in implicit " + "batch mode."); + } + } else if ((a_is_tensor && p.shape_a.size() <= 2 && + (p.transpose_a || b_is_tensor)) || + (b_is_tensor && p.shape_b.size() <= 2)) { + conversion_status = errors::InvalidArgument( + "MatMul with 2D tensors requires explicit batch mode, or that" + " tensor A is not transposed and B is a constant tensor."); + } + } + + test->TestOpConverter(node_def, p.expected_shape, conversion_status, + OkStatus(), + ElementsAreArray(p.expected_output)); + if (!conversion_status.ok()) { + VLOG(2) << "Converted with status " << conversion_status; + } + VLOG(2) << "== Finished test iteration =="; + } + } + } + } +} + +template +void CheckAddedLayers(OpConverterTest* test, bool expect_found) { + bool layer_found = false; + for (int i = 0; i < test->converter_->network()->getNbLayers(); i++) { + nvinfer1::ILayer* layer = test->converter_->network()->getLayer(i); + if (dynamic_cast(layer)) { + layer_found = true; + } + } + EXPECT_EQ(expect_found, layer_found); +} + +std::vector GetMatMulTestParams() { + std::vector params{ + // clang-format off + MatMulTestParams{{2, 2}, {0, 1, 2, 3}, false, // A (shape, val, T?) + {2, 2}, {0, 1, 2, 3}, false, // B (shape, val, T?) + {2, 2}, {2, 3, 6, 11}}, // result (shape, val) + MatMulTestParams{{2, 2}, {0, 1, 2, 3}, false, + {2, 2}, {0, 1, 2, 3}, true, + {2, 2}, {1, 3, 3, 13}}, + MatMulTestParams{{2, 2}, {0, 1, 2, 3}, true, + {2, 2}, {0, 1, 2, 3}, false, + {2, 2}, {4, 6, 6, 10}}, + MatMulTestParams{{2, 2}, {0, 1, 2, 3}, true, + {2, 2}, {0, 1, 2, 3}, true, + {2, 2}, {2, 6, 3, 11}}, + MatMulTestParams{{2, 3}, {0, 1, 2, 3, 4, 5}, false, + {2, 3}, {1, 2, 3, 4, 5, 6}, true, + {2, 2}, {8, 17, 26, 62}}, + MatMulTestParams{{2, 3}, {0, 1, 2, 3, 4, 5}, true, + {2, 3}, {1, 2, 3, 4, 5, 6}, false, + {3, 3}, {12, 15, 18, 17, 22, 27, 22, 29, 36}}, + MatMulTestParams{{3, 2}, {0, 1, 2, 3, 4, 5}, false, + {2, 3}, {1, 2, 3, 4, 5, 6}, false, + {3, 3}, {4, 5, 6, 14, 19, 24, 24, 33, 42}}, + MatMulTestParams{{3, 2}, {0, 1, 2, 3, 4, 5}, true, + {2, 3}, {1, 2, 3, 4, 5, 6}, true, + {2, 2}, {16, 34, 22, 49}}, + // clang-format on + }; + return params; +} + +TEST_P(OpConverter_FP32_Test, ConvertMatMul) { + // Get the NodeDef for MatMul. + auto get_matmul_nodedef = [](DataType dtype, bool transpose_a, + bool transpose_b) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), dtype); + auto weights = ops::Placeholder(s.WithOpName("weights"), dtype); + const auto matmul_attrs = + ops::MatMul::TransposeA(transpose_a).TransposeB(transpose_b); + auto matmul = + ops::MatMul(s.WithOpName("my_matmul"), input, weights, matmul_attrs); + return matmul.operation.node()->def(); + }; + + TestMatMulHelper(this, get_matmul_nodedef, GetMatMulTestParams()); +} + +TEST_P(OpConverter_FP32_Test, ConvertBatchMatMul) { + // Get the NodeDef for BatchMatMul. + auto get_batch_matmul_nodedef = [](DataType dtype, bool transpose_a, + bool transpose_b) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), dtype); + auto weights = ops::Placeholder(s.WithOpName("weights"), dtype); + const auto matmul_attrs = + ops::BatchMatMul::AdjX(transpose_a).AdjY(transpose_b); + auto matmul = ops::BatchMatMul(s.WithOpName("my_matmul"), input, weights, + matmul_attrs); + return matmul.operation.node()->def(); + }; + + // We derive test data from the MatMul test params by adding extra leading + // dimensions. + std::vector params_2d = GetMatMulTestParams(); + std::vector params; + params.reserve(params_2d.size() * 3 + 1); + + auto insert_ones = [](std::vector v, int n) { + std::vector ones(n, 1); + ones.insert(ones.end(), v.begin(), v.end()); + return ones; + }; + + // Add a leading 1 dimension to A, B and result. + std::transform(params_2d.begin(), params_2d.end(), std::back_inserter(params), + [](MatMulTestParams p) { + p.shape_a.insert(p.shape_a.begin(), 1); + p.shape_b.insert(p.shape_b.begin(), 1); + p.expected_shape.insert(p.expected_shape.begin(), 1); + return p; + }); + + // Test with N > 1: weights cannot be batched in implicit batch mode. + // clang-format off + params.push_back( + MatMulTestParams{{2, 2, 2}, {0, 1, 2, 3, 0, 1, 2, 3}, false, // A + {2, 2, 2}, {0, 1, 2, 3, 0, 1, 2, 3}, false, // B + {2, 2, 2}, {2, 3, 6, 11, 2, 3, 6, 11}} // result + ); + + params.push_back( + MatMulTestParams{{2, 2, 3}, {0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5}, + false, + {2, 2, 3}, {1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6}, true, + {2, 2, 2}, {8, 17, 26, 62, 8, 17, 26, 62}}); + // clang-format on + + // Add two leading 1 dimensions to A, B and result. + std::transform(params_2d.begin(), params_2d.end(), std::back_inserter(params), + [insert_ones](MatMulTestParams p) { + p.shape_a = insert_ones(p.shape_a, 2); + p.shape_b = insert_ones(p.shape_b, 2); + p.expected_shape = insert_ones(p.expected_shape, 2); + return p; + }); + + // Test broadcast: add two leading 1 dimensions to A, but not to B. + std::transform(params_2d.begin(), params_2d.end(), std::back_inserter(params), + [insert_ones](MatMulTestParams p) { + p.shape_a = insert_ones(p.shape_a, 2); + p.expected_shape = insert_ones(p.expected_shape, 2); + return p; + }); + + // Test broadcast: add a leading 1 dimension to A and two leading 1s to B. + // Broadcasting A need a dynamic brodacast which will be incompatible with + // FC layer. + std::transform(params_2d.begin(), params_2d.end(), std::back_inserter(params), + [insert_ones](MatMulTestParams p) { + p.shape_a = insert_ones(p.shape_a, 1); + p.shape_b = insert_ones(p.shape_b, 2); + p.expected_shape = insert_ones(p.expected_shape, 2); + return p; + }); + + // Test with N > 1: since weights cannot be batched in implicit batch mode. + // We tests with batch size 2. + std::transform(params_2d.begin(), params_2d.end(), std::back_inserter(params), + [insert_ones](MatMulTestParams p) { + p.shape_a.insert(p.shape_a.begin(), 2); + p.values_a.reserve(p.values_a.size() * 2); + p.values_a.insert(p.values_a.end(), p.values_a.begin(), + p.values_a.end()); + + p.shape_b.insert(p.shape_b.begin(), 2); + p.values_b.reserve(p.values_b.size() * 2); + p.values_b.insert(p.values_b.end(), p.values_b.begin(), + p.values_b.end()); + + p.expected_shape.insert(p.expected_shape.begin(), 2); + p.expected_output.reserve(p.expected_output.size() * 2); + p.expected_output.insert(p.expected_output.end(), + p.expected_output.begin(), + p.expected_output.end()); + return p; + }); + + // 4D tensor where the second "batch dim" is not 1 + params.push_back(MatMulTestParams{ + {1, 2, 4, 5}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, + 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, + 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39}, + false, // A + {1, 2, 3, 5}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, + 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30}, + true, // B + {1, 2, 4, 3}, + {40, 90, 140, 115, 290, 465, 190, 490, + 790, 265, 690, 1115, 1990, 2540, 3090, 2440, + 3115, 3790, 2890, 3690, 4490, 3340, 4265, 5190}}); // result + + TestMatMulHelper(this, get_batch_matmul_nodedef, params); +} + +#if IS_TRT_VERSION_GE(7, 1, 3, 0) +TEST_P(OpConverter_FP32_Test, ConvertEinsum) { + // Get the NodeDef for Einsum. + auto get_einsum_nodedef = [](DataType dtype, std::string eq, + int n_inputs = 2) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto a = ops::Placeholder(s.WithOpName("input_a"), dtype); + std::vector input_vec{a}; + if (n_inputs > 1) { + auto b = ops::Placeholder(s.WithOpName("input_b"), dtype); + input_vec.push_back(b); + } + InputList inputs(input_vec); + auto einsum = ops::Einsum(s.WithOpName("my_einsum"), inputs, eq); + return einsum.operation.node()->def(); + }; + + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + Reset(); + NodeDef node = get_einsum_nodedef(tf_type_, "ab,cb->ac"); + AddTestTensor("input_a", {2, 3}); + AddTestTensor("input_b", {2, 3}); + const auto& err = convert_not_supported_implicit(node.op(), node.name()); + TestOpConverter(node, {2, 2}, errors::Unimplemented(err), OkStatus(), + ElementsAreArray({13, 16, 40, 52})); + // No further tests. + return; + } + + struct TestParams { + std::string equation; + std::vector shape_a; + std::vector values_a; + std::vector shape_b; + std::vector values_b; + std::vector expected_shape; + std::vector expected_output; + Status conv_status; + }; + + Status unimplemented_eq = errors::Unimplemented(""); + Status internal_err = errors::Internal(""); + Status internal_err_before_TRT82 = + IS_TRT_VERSION_GE(8, 2, 0, 0) ? OkStatus() : internal_err; + Status unimplemented_before_TRT82 = + IS_TRT_VERSION_GE(8, 2, 0, 0) ? OkStatus() : unimplemented_eq; + + Status diagonal_error = unimplemented_eq; + // The old converter only accepts 2 inputs, and the validator returns + // internal_err if only 1 input is used. + Status diagonal_error_1_input = + IS_TRT_VERSION_GE(8, 2, 0, 0) ? unimplemented_eq : internal_err; + + std::vector params{ + // Dot product. + TestParams{"i,i->", {2}, {2, 3}, {2}, {1, 2}, {}, {8}, unimplemented_eq}, + TestParams{"ik,ik->", + {2, 2}, + {2, 3, 4, 1}, + {2, 2}, + {1, 2, 1, 3}, + {}, + {15}, + unimplemented_eq}, + // Outer product. + TestParams{"i,k->ik", + {2}, + {1, 2}, + {3}, + {1, 2, 3}, + {2, 3}, + {1, 2, 3, 2, 4, 6}, + unimplemented_eq}, + TestParams{"ij,kl->ijkl", + {2, 1}, + {1, 2}, + {3, 1}, + {1, 2, 3}, + {2, 1, 3, 1}, + {1, 2, 3, 2, 4, 6}, + unimplemented_before_TRT82}, + // Transpose. + TestParams{"ik->ki", + {2, 3}, + {0, 1, 2, 3, 4, 5}, + {}, + {}, + {3, 2}, + {0, 3, 1, 4, 2, 5}, + internal_err_before_TRT82}, + // Diag. + TestParams{"ii->i", + {3, 3}, + {0, 1, 2, 3, 4, 5, 6, 7, 8}, + {}, + {}, + {3}, + {0, 4, 8}, + diagonal_error_1_input}, + // Trace. + TestParams{"ii->", // Note TF einsum op always has '->'. + {3, 3}, + {0, 1, 2, 3, 4, 5, 6, 7, 8}, + {}, + {}, + {}, + {12}, + diagonal_error_1_input}, + // MatMul with reduction. + TestParams{"abbc,dc->ad", + {1, 2, 2, 3}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + {2, 3}, + {1, 2, 3, 4, 5, 6}, + {2, 3}, + {1, 2, 3, 2, 4, 6}, + diagonal_error}, + // Ellipsis with broadcast. + TestParams{"...ik,...jk->...ij", + {1, 3, 1, 4}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + {2, 1, 1, 4}, + {1, 2, 3, 4, 5, 6, 7, 8}, + {2, 3, 1, 1}, + {20, 60, 100, 44, 148, 252}, + unimplemented_eq}, + // MatMul. + TestParams{"ab,bc->ac", + {2, 3}, + {0, 1, 2, 3, 4, 5}, + {3, 2}, + {1, 2, 3, 4, 5, 6}, + {2, 2}, + {13, 16, 40, 52}}, + // Batched MatMul. + TestParams{"abc,cde->abde", + /*shape_a=*/{1, 2, 3}, + /*values_a=*/{0, 1, 2, 3, 4, 5}, + /*shape_b=*/{3, 2, 2}, + /*values_v=*/{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + /*expected_shape=*/{1, 2, 2, 2}, + /*expected_output=*/{23, 26, 29, 32, 68, 80, 92, 104}}, + TestParams{"abcd,cde->abe", + {1, 2, 2, 3}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + {2, 3, 2}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + {1, 2, 2}, + {125, 140, 341, 392}}, + // TF assumes case sensitive labels. + TestParams{"aBAE,AEe->aBe", + {1, 2, 2, 3}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + {2, 3, 2}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + {1, 2, 2}, + {125, 140, 341, 392}}, + TestParams{"abc,cd->abd", + {1, 2, 3}, + {0, 1, 2, 3, 4, 5}, + {3, 2}, + {1, 2, 3, 4, 5, 6}, + {1, 2, 2}, + {13, 16, 40, 52}}, + TestParams{"acbe,aecd->abcd", + {1, 2, 3, 4}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}, + {1, 4, 2, 3}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, + {1, 3, 2, 3}, + {90, 96, 102, 732, 786, 840, 250, 272, 294, 940, 1010, 1080, + 410, 448, 486, 1148, 1234, 1320}}, + TestParams{"aecd,abcd->acbe", + {1, 2, 3, 4}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23}, + {1, 2, 3, 4}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24}, + {1, 3, 2, 2}, + {20, 140, 92, 788, 148, 460, 412, 1300, 404, 908, 860, 1940}}, + TestParams{"acd,dce->ae", + {1, 2, 3}, + {0, 1, 2, 3, 4, 5}, + {3, 2, 2}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + {1, 2}, + {115, 130}}, + TestParams{"abcd,bace->bade", + {2, 3, 2, 1}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + {3, 2, 2, 1}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + {3, 2, 1, 1}, + {2, 46, 28, 128, 86, 242}}, + TestParams{ + "cebfad,fageb->abcdg", + {1, 1, 3, 3, 2, 2}, + {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, + 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35}, + {3, 2, 2, 1, 3}, + {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, + 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36}, + {2, 3, 1, 2, 2}, + {252, 288, 291, 336, 768, 912, 810, 963, 1356, 1608, 1401, 1662, + 438, 492, 495, 558, 1176, 1338, 1236, 1407, 1986, 2256, 2049, 2328}}, + }; + + for (auto p : params) { + for (bool a_is_tensor : {true, false}) { + for (bool b_is_tensor : {true, false}) { + if (!a_is_tensor && !b_is_tensor) { + // Skip test when both args are weights. We do not convert this + // since const folding eliminates this case. + continue; + } + Reset(); + int n_inputs = p.shape_b.empty() ? 1 : 2; + NodeDef node_def = get_einsum_nodedef(tf_type_, p.equation, n_inputs); + if (a_is_tensor) { + AddTestTensor("input_a", p.shape_a, p.values_a); + } else { + AddTestWeights("input_a", p.shape_a, p.values_a, tf_type_); + } + if (!p.shape_b.empty()) { + if (b_is_tensor) { + AddTestTensor("input_b", p.shape_b, p.values_b); + } else { + AddTestWeights("input_b", p.shape_b, p.values_b, tf_type_); + } + } + TestOpConverter(node_def, p.expected_shape, p.conv_status, OkStatus(), + ElementsAreArray(p.expected_output)); + } + } + } +} +#endif // IS_TRT_VERSION_GE(7, 1, 3, 0) + +TEST_P(OpConverter_FP32_FP16_Test, ConvertBiasAdd) { + // Note that kINT32 is not supported by IScaleLayer, so we don't test + // DT_INT32 type here. DT_FLOAT and DT_HALF are tested. + // Get the NodeDef for BiasAdd. + auto get_biasadd_nodedef = [](const string& data_format, + DataType tf_type) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + auto weights = ops::Placeholder(s.WithOpName("weights"), tf_type); + const auto biasadd_attrs = ops::BiasAdd::DataFormat(data_format); + auto biasadd = + ops::BiasAdd(s.WithOpName("my_biasadd"), input, weights, biasadd_attrs); + return biasadd.operation.node()->def(); + }; + + for (const string& data_format : {"NHWC", "NCHW"}) { + for (const int trt_input_rank : {1, 2, 3, 4}) { + Reset(); + NodeDef node_def = get_biasadd_nodedef(data_format, tf_type_); + + // Add input, dims_array will be like {2, 1, ..., 1, 3} + std::vector dims_array(trt_input_rank + 1, 1); + if (trt_input_rank == 1) { + dims_array[1] = (data_format == "NHWC" ? 3 : 2); + } else { + dims_array[1] = 2; + dims_array[trt_input_rank] = 3; + } + const int64_t num_input = DimsAdapter(dims_array).Volume(); + ASSERT_EQ(trt_input_rank > 1 ? 6 : (data_format == "NHWC" ? 3 : 2), + num_input); + std::vector input_data(num_input, 0); + + AddTestTensor("input", dims_array, input_data); + + const int channel_size = (data_format == "NHWC" ? 3 : 2); + std::vector bias(channel_size); + for (int i = 0; i < channel_size; ++i) { + bias[i] = i + 1; // bias will be {1, 2, 3, ...} + } + AddTestWeights("weights", {channel_size}, bias, tf_type_); + + // Build and run the engine. + std::vector output_data; + + if (trt_input_rank == 1) { + if (data_format == "NHWC") { + output_data = {1, 2, 3}; + } else { + output_data = {1, 2}; + } + } else { + if (data_format == "NHWC") { + output_data = {1, 2, 3, 1, 2, 3}; + } else { + output_data = {1, 1, 1, 2, 2, 2}; + } + } + TestOpConverter(node_def, dims_array, OkStatus(), OkStatus(), + ElementsAreArray(output_data)); + } + } +} + +template +NodeDef GetBinaryOpNodeDef(DataType dtype) { + Scope s = Scope::NewRootScope(); + auto input_l = ops::Placeholder(s.WithOpName("input1"), dtype); + auto input_r = ops::Placeholder(s.WithOpName("input2"), dtype); + auto op = OpType(s.WithOpName("my_binary"), input_l, input_r); + return op.operation.node()->def(); +} + +TEST_P(OpConverter_FP32_FP16_BinaryTest, ConvertBinary) { + using OpFunc = std::function; + std::map>> op_test_info; +#define ADD_OP(name, op, v1, v2, v3, v4, v5, v6, v7, v8) \ + op_test_info[name] = \ + std::make_pair(GetBinaryOpNodeDef, \ + std::vector(v1, v2, v3, v4, v5, v6, v7, v8)) + ADD_OP("Add", ops::Add, {5, 8, 6, 9, 5, 8, 6, 9}); + ADD_OP("AddV2", ops::AddV2, {5, 8, 6, 9, 5, 8, 6, 9}); + ADD_OP("Sub", ops::Sub, {1, 4, 0, 3, 1, 4, 0, 3}); + ADD_OP("Mul", ops::Mul, {6, 12, 9, 18, 6, 12, 9, 18}); + ADD_OP("Div", ops::Div, {1.5, 3, 1, 2, 1.5, 3, 1, 2}); + ADD_OP("RealDiv", ops::RealDiv, {1.5, 3, 1, 2, 1.5, 3, 1, 2}); + ADD_OP("FloorDiv", ops::FloorDiv, {1, 3, 1, 2, 1, 3, 1, 2}); + ADD_OP("Minimum", ops::Minimum, {2, 2, 3, 3, 2, 2, 3, 3}); + ADD_OP("Maximum", ops::Maximum, {3, 6, 3, 6, 3, 6, 3, 6}); + ADD_OP("Pow", ops::Pow, {9, 36, 27, 216, 9, 36, 27, 216}); +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + ADD_OP("Greater", ops::Greater, {1, 1, 0, 1, 1, 1, 0, 1}); + ADD_OP("Less", ops::Less, {0, 0, 0, 0, 0, 0, 0, 0}); + ADD_OP("Equal", ops::Equal, {0, 0, 1, 0, 0, 0, 1, 0}); + ADD_OP("GreaterEqual", ops::Less, {1, 1, 1, 1, 1, 1, 1, 1}); + ADD_OP("LessEqual", ops::Greater, {0, 0, 1, 0, 0, 0, 1, 0}); +#endif +#undef ADD_OP + std::vector> data = { + {3, 6, 3, 6}, {3, 6}, {2, 3, 2, 3}, {2, 3}}; + RunTests(*BinaryOperationMap(), op_test_info, data); +} + +TEST_P(OpConverter_BOOL_BinaryTest, ConvertBooleanBinary) { + using OpFunc = std::function; + std::map>> op_test_info; +#define ADD_OP(name, op, v1, v2, v3, v4, v5, v6, v7, v8) \ + op_test_info[name] = \ + std::make_pair(GetBinaryOpNodeDef, \ + std::vector(v1, v2, v3, v4, v5, v6, v7, v8)) + ADD_OP("LogicalOr", ops::LogicalOr, {1, 1, 0, 1, 1, 1, 0, 1}); + ADD_OP("LogicalAnd", ops::LogicalAnd, {0, 1, 0, 0, 0, 1, 0, 0}); +#undef ADD_OP +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + std::vector> data = { + {0, 1, 0, 1}, {0, 1}, {1, 0, 1, 0}, {1, 0}}; + RunTests(*BinaryBooleanOperationMap(), op_test_info, data); +#endif +} + +NodeDef GetAddNNodeDef(const std::vector& input_names, DataType dtype) { + Scope s = Scope::NewRootScope(); + OutputList inputs; + for (const string& name : input_names) { + inputs.push_back(ops::Placeholder(s.WithOpName(name), dtype)); + } + auto op = ops::AddN(s.WithOpName("my_addn"), inputs); + return op.operation.node()->def(); +} + +struct AddNTestParams { + std::vector input_values; + std::vector input_names; + std::vector dimensions; + std::vector expected_output; + Status status; +}; + +void TestAddN(ParameterizedOpConverterTestBase* test, AddNTestParams& p) { + // All inputs are tensors. + test->Reset(); + const NodeDef node_def = GetAddNNodeDef(p.input_names, test->get_tf_type()); + + if (p.input_values.size() % p.input_names.size() != 0) { + LOG(ERROR) << "The number of input values: `" << p.input_values.size() + << "` is not a multiple of the number of inputs: `" + << p.input_names.size() << "`"; + ASSERT_TRUE(false); + } + + DataVec input_data; + int input_offset = 0; + const int window_size = p.input_values.size() / p.input_names.size(); + for (const string& name : p.input_names) { + std::vector::const_iterator start_pos = + p.input_values.begin() + input_offset; + std::vector::const_iterator end_pos = start_pos + window_size; + std::vector sub_input_val(start_pos, end_pos); + input_offset += window_size; + + test->AddTestTensor(name, p.dimensions, test->get_tf_type(), sub_input_val); + } + + test->TestOpConverter(node_def, p.dimensions, + /*expected_conversion_status=*/p.status, + /*expected_runtime_status=*/p.status, + /*matcher=*/ElementsAreArray(p.expected_output), + /*out_tf_types=*/{test->get_tf_type()}); +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertAddN) { + { + // Weights with batch dim that is not 1. + Reset(); + const NodeDef node_def = GetAddNNodeDef({"tensor", "weights"}, tf_type_); + AddTestTensor("tensor", /*dims=*/{1, 2}); + AddTestWeights("weights", {2, 1, 2}, {0, 1, 2, 3}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Weights input to AddN is required to have batch dimension 1."); + } + + const std::vector common_input = CreateVectorIota(6); + + std::vector params = { + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2", "inp3"}, + /*dimensions=*/{1, 1, 2, 1, 1}, + /*expected_output=*/{6, 9}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2"}, + /*dimensions=*/{1, 1, 3, 1, 1}, + /*expected_output=*/{3, 5, 7}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2", "inp3"}, + /*dimensions=*/{1, 2, 1, 1}, + /*expected_output=*/{6, 9}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2"}, + /*dimensions=*/{1, 1, 3, 1}, + /*expected_output=*/{3, 5, 7}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2", "inp3"}, + /*dimensions=*/{1, 2, 1}, + /*expected_output=*/{6, 9}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2"}, + /*dimensions=*/{1, 1, 3}, + /*expected_output=*/{3, 5, 7}, + /*status=*/OkStatus()}, + {/*input_value=*/common_input, + /*input_names=*/{"inp1", "inp2", "inp3"}, + /*dimensions=*/{2, 1}, + /*expected_output=*/{6, 9}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2"}, + /*dimensions=*/{1, 3}, + /*expected_output=*/{3, 5, 7}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2", "inp3"}, + /*dimensions=*/{2}, + /*expected_output=*/{6, 9}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2"}, + /*dimensions=*/{3}, + /*expected_output=*/{3, 5, 7}, + /*status=*/OkStatus()}, + {/*input_values=*/common_input, + /*input_names=*/{"inp1", "inp2", "inp3", "inp4", "inp5", "inp6"}, + /*dimensions=*/{1}, + /*expected_output=*/{15}, + /*status=*/OkStatus()}, + }; + + for (auto p : params) { + TestAddN(this, p); + } +} + +TEST_P(OpConverter_FP32_Test, ConvertQDQDynamicRangeMode) { + { + // FakeQuantWithMinMaxArgs attributes are empty, should fail. + Reset(TrtPrecisionMode::INT8); + NodeDef node_def = + MakeNodeDef("my_quantize", "FakeQuantWithMinMaxArgs", {"input"}); + AddTestTensor("input", {1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kNotFound, + "No attr named 'min'"); + } + { + // FakeQuantWithMinMaxArgs ranges set via attributes, ok. + Reset(TrtPrecisionMode::INT8); + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT); + auto quantize_attrs = ops::FakeQuantWithMinMaxArgs::Min(-6.0f).Max(6.0f); + auto quantize = ops::FakeQuantWithMinMaxArgs(s.WithOpName("my_quantize"), + input, quantize_attrs); + const NodeDef& node_def = quantize.operation.node()->def(); + AddTestTensor("input", {1, 2, 3}); + RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(GetTensorOrWeights("my_quantize", &output)); + ASSERT_TRUE(output.is_tensor()); + auto ranges = quantization_ranges(); + EXPECT_EQ(1, ranges.count(output.tensor()->trt_tensor())); + EXPECT_EQ(6.0f, ranges[output.tensor()->trt_tensor()]); + } + { + // FakeQuantWithMinMaxVars ranges set via inputs, ok. + Reset(TrtPrecisionMode::INT8); + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT); + auto weights_min = ops::Placeholder(s.WithOpName("weights_min"), DT_FLOAT); + auto weights_max = ops::Placeholder(s.WithOpName("weights_max"), DT_FLOAT); + auto quantize = ops::FakeQuantWithMinMaxVars( + s.WithOpName("my_quantize"), input, weights_min, weights_max); + const NodeDef& node_def = quantize.operation.node()->def(); + AddTestTensor("input", {1, 2, 3}); + AddTestWeights("weights_min", {1}, {-6.0f}); + AddTestWeights("weights_max", {1}, {6.0f}); + RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(GetTensorOrWeights("my_quantize", &output)); + ASSERT_TRUE(output.is_tensor()); + auto ranges = quantization_ranges(); + EXPECT_EQ(1, ranges.count(output.tensor()->trt_tensor())); + EXPECT_EQ(6.0f, ranges[output.tensor()->trt_tensor()]); + } + { + // QuantizeAndDequantizeV2 ranges set via inputs, ok. + Reset(TrtPrecisionMode::INT8); + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT); + auto weights_min = ops::Placeholder(s.WithOpName("weights_min"), DT_FLOAT); + auto weights_max = ops::Placeholder(s.WithOpName("weights_max"), DT_FLOAT); + auto quantize = ops::QuantizeAndDequantizeV2( + s.WithOpName("my_quantize"), input, weights_min, weights_max); + const NodeDef& node_def = quantize.operation.node()->def(); + AddTestTensor("input", {1, 2, 3}); + AddTestWeights("weights_min", {1}, {-6.0f}); + AddTestWeights("weights_max", {1}, {6.0f}); + RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(GetTensorOrWeights("my_quantize", &output)); + ASSERT_TRUE(output.is_tensor()); + auto ranges = quantization_ranges(); + EXPECT_EQ(1, ranges.count(output.tensor()->trt_tensor())); + EXPECT_EQ(6.0f, ranges[output.tensor()->trt_tensor()]); + } + { + // QuantizeAndDequantizeV2 Range inputs are tensors, should fail. + Reset(TrtPrecisionMode::INT8); + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT); + auto weights_min = ops::Placeholder(s.WithOpName("weights_min"), DT_FLOAT); + auto weights_max = ops::Placeholder(s.WithOpName("weights_max"), DT_FLOAT); + auto quantize = ops::QuantizeAndDequantizeV2( + s.WithOpName("my_quantize"), input, weights_min, weights_max); + const NodeDef& node_def = quantize.operation.node()->def(); + AddTestTensor("input", {1, 2, 3}); + AddTestTensor("weights_min", {1}); + AddTestTensor("weights_max", {1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"input_min\" for " + "QuantizeAndDequantizeV2 must be a constant"); + } + { + // QuantizeAndDequantizeV3 ranges set via inputs, ok. + Reset(TrtPrecisionMode::INT8); + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT); + auto weights_min = ops::Placeholder(s.WithOpName("weights_min"), DT_FLOAT); + auto weights_max = ops::Placeholder(s.WithOpName("weights_max"), DT_FLOAT); + auto num_bits = ops::Placeholder(s.WithOpName("num_bits"), DT_INT32); + auto quantize = ops::QuantizeAndDequantizeV3( + s.WithOpName("my_quantize"), input, weights_min, weights_max, num_bits); + const NodeDef& node_def = quantize.operation.node()->def(); + AddTestTensor("input", {1, 2, 3}); + AddTestWeights("weights_min", {1}, {-6.0f}); + AddTestWeights("weights_max", {1}, {6.0f}); + AddTestWeights("num_bits", {1}, {8}); + RunValidationAndConversion(node_def); + TRT_TensorOrWeights output; + TF_EXPECT_OK(GetTensorOrWeights("my_quantize", &output)); + ASSERT_TRUE(output.is_tensor()); + auto ranges = quantization_ranges(); + EXPECT_EQ(1, ranges.count(output.tensor()->trt_tensor())); + EXPECT_EQ(6.0f, ranges[output.tensor()->trt_tensor()]); + } +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertSquare) { + { + // Input is weights, should fail. + Reset(); + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto square = ops::Square(s.WithOpName("my_square"), input); + NodeDef node_def = square.operation.node()->def(); + AddTestWeights("input", {1, 2, 3}, {1, 2, 3, 4, -5, 6}, tf_type_); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"x\" for Square must be a tensor"); + } + + Reset(); + + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto square = ops::Square(s.WithOpName("my_square"), input); + NodeDef node_def = square.operation.node()->def(); + + const int num_inputs = 20; + std::vector inputs(num_inputs); + std::vector expected_outputs(num_inputs); + + for (int i = 0; i < num_inputs; ++i) { + const float value = (i - 9); + inputs[i] = value; + expected_outputs[i] = value * value; + } + AddTestTensor("input", {1, 1, 20}, tf_type_, inputs); + + TestOpConverter(node_def, {1, 1, 20}, OkStatus(), OkStatus(), + ArrayFloatNear(expected_outputs, 0)); +} + +// A function that builds the next lexicographically greater configuration +// for the current one. The configuration is described as a (0,1)-vector +// config, where config[i] is 0 or 1 when the i-th parameter is passed as +// a weight or tensor, respectively. The function returns TRUE if such +// a configuration is built, or FALSE otherwise. +bool nextTensorWeightConfiguration(std::vector& config) { + for (int i = config.size(); i-- > 0;) { + if ((config[i] = 1 - config[i])) return true; + } + return false; +} + +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertFill) { + Scope s = Scope::NewRootScope(); + auto dims = ops::Placeholder(s.WithOpName("dims"), DT_INT32); + auto value = ops::Placeholder(s.WithOpName("value"), tf_type_); + auto fill = ops::Fill(s.WithOpName("my_fill"), dims, value); + const NodeDef& node_def = fill.operation.node()->def(); + + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + Reset(); + // random data + AddTestWeights("dims", {2}, {2, 2}, DT_INT32); + AddTestWeights("value", {1}, {42}, tf_type_); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + convert_not_supported_implicit(node_def.op(), node_def.name())); + return; + } + + std::vector> output_dims_params = { + {8}, {8, 2, 4}, {32, 32, 3200}}; + std::vector> value_dims_params = {{}, {1}}; + + float val = 42.0; + Status status = OkStatus(); + for (bool dims_is_tensor : {true, false}) { + for (bool value_is_tensor : {true, false}) { + for (auto output_dims : output_dims_params) { + for (auto value_dims : value_dims_params) { + Reset(); + std::vector dims_dims = { + static_cast(output_dims.size())}; + if (dims_is_tensor) { + AddTestTensor("dims", dims_dims, DT_INT32, output_dims, dims_dims); + } else { + AddTestWeights("dims", dims_dims, output_dims, DT_INT32); + } + if (value_is_tensor) { + AddTestTensor("value", value_dims, tf_type_, + {static_cast(val)}); + } else { + AddTestWeights("value", value_dims, {static_cast(val)}, + tf_type_); + } + size_t nb_el = 1; + for (auto d : output_dims) { + nb_el *= d; + } + std::vector expected_output(nb_el, val); + TestOpConverter(node_def, output_dims, status, status, + ElementsAreArray(expected_output)); + } + } + } + } +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertRange) { + auto get_casted_value = [this](const float value, const DataType dtype) { + return dtype == DT_INT32 ? static_cast(value) : value; + }; + + auto set_parameters = [this](const std::array& name, + const std::array, 3>& value, + const std::array& type, + const std::vector& config, + int shape_idx = -1) { + Reset(); + for (int i = 0; i < 3; i++) { + if (config[i]) { + std::vector partial_shape_dims = {}; + // The correct partial shape will be provided + // (a) for all parameters, when shape_idx > 3 + // (b) for all parameters, except shape_idx, when shape_idx >= 0 + // (c) for none of the shape_idx < 0 + if (shape_idx > 3 || (shape_idx >= 0 && shape_idx != i)) { + partial_shape_dims = {1}; + } + AddTestTensor(name[i], {1}, type[i], value[i], partial_shape_dims); + } else { + AddTestWeights(name[i], {1}, value[i], type[i]); + } + } + }; + + const float start = 1.0; + const float limit = 43.0; + const float delta = 2.0; + + const std::array param_name = {"start", "limit", "delta"}; + std::array, 3> param_value; + param_value[0] = {start}; + param_value[1] = {limit}; + param_value[2] = {delta}; + const auto start_type = tf_type_; + std::array param_type = {tf_type_, tf_type_, tf_type_}; + + Scope s = Scope::NewRootScope(); + const auto range = + ops::Range(s.WithOpName("my_range"), + ops::Placeholder(s.WithOpName(param_name[0]), param_type[0]), + ops::Placeholder(s.WithOpName(param_name[1]), param_type[1]), + ops::Placeholder(s.WithOpName(param_name[2]), param_type[2])); + + const NodeDef& ndef = range.operation.node()->def(); + const std::vector param_types{DT_FLOAT, DT_HALF, DT_INT32}; + + // ConverterRange is not implemented for Implicit batch mode. + std::vector config(3, 0); + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + const auto& err = convert_not_supported_implicit(ndef.op(), ndef.name()); + do { + set_parameters(param_name, param_value, param_type, config); + RunValidationAndConversion(ndef, absl::StatusCode::kUnimplemented, err); + } while (nextTensorWeightConfiguration(config)); + + return; + } + + const auto& expect_msg = convert_range_expected_msg(ndef); + bool all_weights = true; + do { + for (auto limit_type : param_types) { + param_type[1] = limit_type; + for (auto delta_type : param_types) { + param_type[2] = delta_type; + + const auto all_integers = start_type == DT_INT32 && + limit_type == DT_INT32 && + delta_type == DT_INT32; + + if (all_weights || (all_integers && !config[2])) { + // Reject invalid parameters if delta = 0 and it's passed as a weight. + param_value[2] = {0}; + set_parameters(param_name, param_value, param_type, config); + RunValidationAndConversion( + ndef, absl::StatusCode::kInvalidArgument, + "The delta parameter of Range operation cannot be equal to 0"); + + if (!all_weights && !config[2]) { + param_value[2] = {-1}; + set_parameters(param_name, param_value, param_type, config); + const string err = StrCat( + "The delta parameter of Range operation " + "cannot be negative, when one of (start, limit) is passed as " + "a tensor, but got ", + param_value[2][0]); + RunValidationAndConversion(ndef, absl::StatusCode::kInvalidArgument, + err); + } + } + + if (all_weights) { + // Reject invalid parameters preventing the limit from + // being reached for fixed values of start and delta. + for (int j = 0; j <= 1; j++) { + param_value[j] = {get_casted_value(start, tf_type_)}; + param_value[1 - j] = {get_casted_value(limit, limit_type)}; + param_value[2] = {(2 * j - 1) * + get_casted_value(delta, delta_type)}; + set_parameters(param_name, param_value, param_type, config); + const auto error = convert_range_error_msg( + param_value[0][0], param_value[1][0], param_value[2][0]); + RunValidationAndConversion(ndef, absl::StatusCode::kInvalidArgument, + error); + } + } + + param_value[0] = {start}; + param_value[2] = {delta}; + if (all_integers) { + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // Wrong dimension for the parameter passed as a tensor. + for (int j = 0; j < 3; j++) { + if (!config[j]) continue; + + const string err = + StrCat("Dimension for '", param_name[j], + "' of Range operator should be equal to 1"); + set_parameters(param_name, param_value, param_type, config, j); + RunValidationAndConversion( + ndef, absl::StatusCode::kInvalidArgument, err); + } + } + } else { + if (!all_weights) { + // The following test should fail, when + // (a) at least one parameter is passed as a tensor; + // (b) at least one parameter is not of type DT_INT32. + set_parameters(param_name, param_value, param_type, config); + RunValidationAndConversion(ndef, absl::StatusCode::kUnimplemented, + expect_msg); + } + } + } + } + // All other configs will be set so that at least one parameter + // will be passed as a tensor + all_weights = false; + } while (nextTensorWeightConfiguration(config)); + + nvinfer1::DataType trt_type; + TF_ASSERT_OK(TfTypeToTrtType(DT_BOOL, &trt_type)); + const std::string error_msg = + "Unsupported data type " + DebugString(trt_type) + " used for '"; + do { + for (auto limit_type : param_types) { + param_type[1] = limit_type; + for (auto delta_type : param_types) { + param_type[2] = delta_type; + + for (int i = 0; i < 3; i++) { + if (!config[i]) { + const auto saved_type = param_type[i]; + param_type[i] = DT_BOOL; + set_parameters(param_name, param_value, param_type, config); + param_type[i] = saved_type; + RunValidationAndConversion(ndef, absl::StatusCode::kInvalidArgument, + error_msg + param_name[i] + "'"); + } + } + } + } + } while (nextTensorWeightConfiguration(config)); + + // The tests that pass all checks in ConvertRange::Validate(). + const Status status = OkStatus(); + const std::vector int_type{DT_INT32}; + int partial_shape_idx = -1; + all_weights = true; + do { + // For now when at least one of (start, limit, delta) is passed as a tensor + // (a) all these parameters should be of DT_INT32 type; + // (b) only positive delta could be used. + const auto& types = all_weights ? param_types : int_type; + const auto jEnd = all_weights ? 1 : 0; + for (auto limit_type : types) { + param_type[1] = limit_type; + for (auto delta_type : types) { + param_type[2] = delta_type; + // Loop for positive and negative deltas. + for (int j = 0; j <= jEnd; j++) { + // Define the expected result which should match the usage + // of DT_INT32 for one of (start, limit, delta). + const int mult = (1 - 2 * j); + param_value[j] = {get_casted_value(start, tf_type_)}; + param_value[1 - j] = {get_casted_value(limit, limit_type)}; + param_value[2] = {mult * get_casted_value(delta, delta_type)}; + + // Create expected output. + std::vector expected_output; + const float limit_curr = param_value[1][0]; + const float delta_curr = param_value[2][0]; + float value = param_value[0][0]; + int num_values = 0; + while (mult * (limit_curr - value) > 0) { + num_values++; + expected_output.push_back(value); + value += delta_curr; + } + + set_parameters(param_name, param_value, param_type, config, + partial_shape_idx); + const std::vector output_dims = {num_values}; + TestOpConverter(ndef, output_dims, status, status, + ElementsAreArray(expected_output)); + } + } + } + + if (all_weights) { + if (start_type != DT_INT32) break; + if (trt_mode_ == TrtTestMode::kDynamicShape) partial_shape_idx = 3; + + // All other configs will be set so that at least one parameter + // will be passed as a tensor + all_weights = false; + } + } while (nextTensorWeightConfiguration(config)); +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertLikeOps) { + auto get_node = [&](int value) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + if (value == 0) { + auto zeros_like = ops::ZerosLike(s.WithOpName("Zeros"), input); + return zeros_like.operation.node()->def(); + } + auto ones_like = ops::OnesLike(s.WithOpName("Ones"), input); + return ones_like.operation.node()->def(); + }; + + for (int value : {0, 1}) { + Reset(); + const NodeDef& node_def = get_node(value); + + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + std::vector input_data(8, 42.0f); + AddTestTensor("input", {8}, tf_type_, input_data); + const auto& err = convert_not_supported_implicit(node_def.name() + "Like", + node_def.name()); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + err); + continue; + } + + std::vector> output_dims_params = { + {8}, {8, 2, 4}, {32, 32, 3200}}; + + float val = 42.0; + Status status = OkStatus(); + for (bool input_is_tensor : {true, false}) { + for (auto output_dims : output_dims_params) { + Reset(); + size_t nb_el = 1; + for (auto d : output_dims) { + nb_el *= d; + } + std::vector input_data(nb_el, val); + if (input_is_tensor) { + AddTestTensor("input", output_dims, tf_type_, input_data); + } else { + AddTestWeights("input", output_dims, input_data, tf_type_); + } + std::vector expected_output(nb_el, value); + TestOpConverter(node_def, output_dims, status, status, + ElementsAreArray(expected_output)); + } + } + } +} + +#endif // IS_TRT_VERSION_GE(8, 2, 0, 0) + +#if IS_TRT_VERSION_GE(8, 2, 1, 6) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) + +TEST_P(OpConverter_FP32_Test, ConvertCombinedNMS) { + // Get the NodeDef for CombinedNMS. + auto get_nms_nodedef = [](DataType tf_type, bool clip_boxes = true, + bool pad_per_class = false) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto boxes_tensor = ops::Placeholder(s.WithOpName("boxes"), tf_type); + auto scores_tensor = ops::Placeholder(s.WithOpName("scores"), tf_type); + auto max_output_size_per_class = + ops::Placeholder(s.WithOpName("max_output_size_per_class"), DT_INT32); + auto max_total_size = + ops::Placeholder(s.WithOpName("max_total_size"), DT_INT32); + auto iou_threshold = + ops::Placeholder(s.WithOpName("iou_threshold"), tf_type); + auto score_threshold = + ops::Placeholder(s.WithOpName("score_threshold"), tf_type); + auto nms_attrs = ops::CombinedNonMaxSuppression::Attrs() + .PadPerClass(pad_per_class) + .ClipBoxes(clip_boxes); + + auto nms_op = ops::CombinedNonMaxSuppression( + s.WithOpName("my_nms"), boxes_tensor, scores_tensor, + max_output_size_per_class, max_total_size, iou_threshold, + score_threshold, nms_attrs); + return nms_op.operation.node()->def(); + }; + + struct TestParams { + const std::string description; + const std::vector boxes_tensor_dims; + const std::vector scores_tensor_dims; + const std::vector boxes_values; + const std::vector scores_values; + const int32 max_output_size_per_class; + const int32 max_total_size; + const float iou_threshold; + const float score_threshold; + const bool pad_per_class; + const bool clip_boxes; + const std::vector> expected_output_dims; + const std::vector exp_boxes; + const std::vector exp_scores; + const std::vector exp_classes; + const std::vector exp_num_detections; + Status conversion_status; + Status runtime_status; + }; + +#if IS_TRT_VERSION_GE(8, 2, 1, 6) || defined(TF_TRT_USE_EFFICIENT_NMS_PLUGIN) + Status conv_status = + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented(convert_not_supported_implicit( + "CombinedNonMaxSuppression", "my_nms")) + : OkStatus(); + + std::vector params = { + TestParams{"Test 1: clip boxes", + {1, 1, 3, 4}, // boxes dims + {1, 1, 3}, // scores dims + // boxes values: + {0, 0, 0.3, 1.4, 0, 0, 0.3, 1.4, 0, 0, 0.3, 1.4}, + {0.4, 0.7, 0.3}, // scores values + 3, // max_output_size_per_class + 2, // max_total_size + 0.1, // IOU threshold + 0, // score_threshold + false, // pad_per_class + true, // clip_boxes + {{1, 2, 4}, // expected_nmsed_boxes_dims + {1, 2}, // expected_nmsed_scores_dims + {1, 2}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {0, 0, 0.3, 1.0, 0, 0, 0.3, 1.0}, + {0.7, 0.4}, // exp_scores + {1, 0}, // exp_classes + {2}, // exp_num_detections + conv_status}, + TestParams{ + "Test 2: iou threshold", + {1, 5, 1, 4}, // boxes dims + {1, 5, 1}, // scores dims + // boxes values: + {0, 0, 5, 10, 0, 1, 5, 11, 8, 0, 12, 4, 6, 2, 10, 6, 8, 9, 11, 12}, + {5, 4, 3, 2, 1}, // scores values + 4, // max_output_size_per_class + 4, // max_total_size + 0.7, // IOU threshold + 0, // score threshold + false, // pad_per_class + false, // clip_boxes + {{1, 4, 4}, // expected nmsed_boxes_dims + {1, 4}, // expected nmsed_scores_dims + {1, 4}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {0, 0, 5, 10, 8, 0, 12, 4, 6, 2, 10, 6, 8, 9, 11, 12}, + {5, 3, 2, 1}, // exp_scores + {0, 0, 0, 0}, // exp_classes + {4}, // exp_num_detections + conv_status}, + TestParams{ + "Test 3: score threshold", + {1, 5, 1, 4}, // boxes dims + {1, 5, 1}, // scores dims + // boxes values: + {0, 0, 5, 10, 0, 1, 5, 11, 8, 0, 12, 4, 6, 2, 10, 6, 8, 9, 11, 12}, + {5, 4, 3, 2, 1}, // scores values + 4, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 2, // score threshold + false, // pad_per_class + false, // clip_boxes + {{1, 4, 4}, // expected nmsed_boxes_dims + {1, 4}, // expected nmsed_scores_dims + {1, 4}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {0, 0, 5, 10, 8, 0, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0}, + {5, 3, 0, 0}, // exp_scores + {0, 0, 0, 0}, // exp_classes + {2}, // exp_num_detections + conv_status}, + TestParams{ + "Test 4: per class size and pad", + {1, 5, 1, 4}, // boxes dims + {1, 5, 2}, // scores dims + // boxes values: + {0, 0, 5, 10, 0, 1, 5, 11, 8, 0, 12, 4, 6, 2, 10, 6, 8, 9, 11, 12}, + // scores values: + {5, 0, 0, 4, 3, 0, 2, 0, 1, 0}, + 1, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 0, // score threshold + true, // pad_per_class + false, // clip_boxes + {{1, 2, 4}, // expected nmsed_boxes_dims + {1, 2}, // expected nmsed_scores_dims + {1, 2}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {0, 0, 5, 10, 0, 1, 5, 11}, + {5, 4}, // exp_scores + {0, 1}, // exp_classes + {2}, // exp_num_detections + conv_status}, + TestParams{ + "Test 5: different box coordinate order", + {1, 5, 1, 4}, // boxes dims + {1, 5, 2}, // scores dims + // boxes values: + {5, 10, 0, 0, 5, 11, 0, 1, 12, 4, 8, 0, 10, 6, 6, 2, 11, 12, 8, 9}, + // scores values: + {5, 0, 0, 4, 3, 0, 2, 0, 1, 0}, + 1, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 0, // score threshold + true, // pad_per_class + false, // clip_boxes + {{1, 2, 4}, // expected nmsed_boxes_dims + {1, 2}, // expected nmsed_scores_dims + {1, 2}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {5, 10, 0, 0, 5, 11, 0, 1}, + {5, 4}, // exp_scores + {0, 1}, // exp_classes + {2}, // exp_num_detections + conv_status}, + }; +#else // IS_TRT_VERSION_GE(7, 1, 3, 0) + Status conv_status = + trt_mode_ == TrtTestMode::kDynamicShape + ? errors::Unimplemented( + "TensorRT BatchedNMS Plugin requires input with static shape") + : OkStatus(); + + std::vector params = { + // TODO(aaroey): there is a bug in TRT's CombinedNonMaxSuppression + // implementation that, the extra output classes that are outside of the + // range specified by valid_detections[i] are not zeros but -1s. + TestParams{ + "Test 1: Original test", + {1, 1, 3, 4}, // boxes dims + {1, 1, 3}, // scores dims + {0, 0, 0.3, 0.4, 0, 0, 0.3, 0.4, 0, 0, 0.3, 0.4}, // boxes values + {0.4, 0.7, 0.3}, // scores values + 3, // max_output_size_per_class + 2, // max_total_size + .5f, // IOU threshold + 0, // score_threshold + false, // pad_per_class + true, // clip_boxes + {{1, 2, 4}, // expected_nmsed_boxes_dims + {1, 2}, // expected_nmsed_scores_dims + {1, 2}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + {0, 0, 0.3, 0.4, 0, 0, 0.3, 0.4}, // exp_boxes_values + {0.7, 0.4}, // exp_scores + {1, 0}, // exp_classes + {2}, // exp_num_detections + conv_status}, + // Test with clip_boxes = False + TestParams{ + "Test 2: clip_boxes", + {1, 5, 1, 4}, // boxes dims + {1, 5, 1}, // scores dims + // boxes values: + {0, 0, 5, 10, 0, 4, 5, 14, 8, 0, 12, 4, 6, 2, 10, 6, 8, 9, 11, 12}, + {5, 4, 3, 2, 1}, // scores values + 4, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 0, // score threshold + false, // pad_per_class + false, // clip_boxes + {{1, 4, 4}, // expected nmsed_boxes_dims + {1, 4}, // expected nmsed_scores_dims + {1, 4}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {0, 0, 5, 10, 8, 0, 12, 4, 8, 9, 11, 12, 0, 0, 0, 0}, + {5, 3, 1, 0}, // exp_scores + {0, 0, 0, -1}, // exp_classes + {3}, // exp_num_detections + conv_status}, + // Test with clip_boxes = False, and nonzero score threshold + TestParams{ + "Test 3: score threshold", + {1, 5, 1, 4}, // boxes dims + {1, 5, 1}, // scores dims + // boxes values: + {0, 0, 5, 10, 0, 4, 5, 14, 8, 0, 12, 4, 6, 2, 10, 6, 8, 9, 11, 12}, + {5, 4, 3, 2, 1}, // scores values + 4, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 2, // score threshold + false, // pad_per_class + false, // clip_boxes + {{1, 4, 4}, // expected nmsed_boxes_dims + {1, 4}, // expected nmsed_scores_dims + {1, 4}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {0, 0, 5, 10, 8, 0, 12, 4, 0, 0, 0, 0, 0, 0, 0, 0}, + {5, 3, 0, 0}, // exp_scores + {0, 0, -1, -1}, // exp_classes + {2}, // exp_num_detections + conv_status}, + // Test where the boxes are defined as with max value first for the box + // coordinates. This test fails before TRT 7.1.3. + TestParams{ + "Test 4: max coord first", + {1, 5, 1, 4}, // boxes dims + {1, 5, 1}, // scores dims + // boxes values: + {5, 10, 0, 0, 5, 14, 0, 4, 12, 4, 8, 0, 10, 6, 6, 2, 11, 12, 8, 9}, + {5, 4, 3, 2, 1}, // scores values + 4, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 0, // score threshold + false, // pad_per_class + false, // clip_boxes + {{1, 4, 4}, // expected nmsed_boxes_dims + {1, 4}, // expected nmsed_scores_dims + {1, 4}, // expected_nmsed_classes_dims + {1}}, // expected_valid_detections_dims + // exp_boxes_values: + {5, 10, 0, 0, 12, 4, 8, 0, 11, 12, 8, 9, 0, 0, 0, 0}, + {5, 3, 1, 0}, // exp_scores + {0, 0, 0, -1}, // exp_classes + {3}, // exp_num_detections + conv_status}, + TestParams{"Test 5: TopK error", + {1, 5000, 1, 4}, // boxes dims + {1, 5000, 1}, // scores dims + {}, // boxes values: + {}, // scores values + 4, // max_output_size_per_class + 4, // max_total_size + 0.1, // IOU threshold + 0, // score threshold + false, // pad_per_class + false, // clip_boxes + {}, // expected_valid_detections_dims + {}, // exp_boxes_values + {}, // exp_scores + {}, // exp_classes + {}, // exp_num_detections + conv_status.ok() + ? errors::InvalidArgument( + "TRT NMS plugin allow top_k<=4096, where top_k = " + "max(num_boxes, max_total_size). You can override " + "this by setting TF_TRT_ALLOW_NMS_TOPK_OVERRIDE=1 " + "environment variable, but this can result in a " + "loss of accuracy.") + : conv_status}, + }; +#endif + + for (auto p : params) { + Reset(); + SCOPED_TRACE(p.description); + AddTestTensor("boxes", p.boxes_tensor_dims, p.boxes_values); + AddTestTensor("scores", p.scores_tensor_dims, p.scores_values); + AddTestWeights("max_output_size_per_class", {1}, + {p.max_output_size_per_class}); + AddTestWeights("max_total_size", {1}, {p.max_total_size}); + AddTestWeights("iou_threshold", {1}, {p.iou_threshold}, tf_type_); + AddTestWeights("score_threshold", {1}, {p.score_threshold}, + tf_type_); + + auto node_def = get_nms_nodedef(tf_type_, p.clip_boxes, p.pad_per_class); + + TestOpConverterMultiOut(node_def, p.expected_output_dims, + p.conversion_status, p.runtime_status, + { + ElementsAreArray(p.exp_boxes), + ElementsAreArray(p.exp_scores), + ElementsAreArray(p.exp_classes), + ElementsAreArray(p.exp_num_detections), + }, + {tf_type_, tf_type_, tf_type_, DT_INT32}); + } +} +#endif + +template +NodeDef CreateUnaryOp(DataType tf_type) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + return T(s.WithOpName("my_unary"), input).operation.node()->def(); +} + +constexpr float kLeakyReluAlpha = 0.2f; +template <> +NodeDef CreateUnaryOp(DataType tf_type) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + return ops::internal::LeakyRelu( + s.WithOpName("my_unary"), input, + ops::internal::LeakyRelu::Alpha(kLeakyReluAlpha)) + .operation.node() + ->def(); +} + +TEST_P(OpConverter_FP32_UnaryTest, ConvertActivation) { + constexpr float kSeluAlpha = 1.7580993408473768599402175208123f; + constexpr float kSeluScale = 1.0507009873554804934193349852946f; + using OpFunc = std::function; + using ValFunc = float (*)(float); + std::map> op_map; + +#define ADD_OP(name, op, compute) \ + op_map[name] = std::make_pair(CreateUnaryOp, compute) + ADD_OP("LeakyRelu", ops::internal::LeakyRelu, + [](float x) { return (x > 0.0f) ? x : x * kLeakyReluAlpha; }); + ADD_OP("Relu", ops::Relu, [](float x) { return (x > 0.0f) ? x : 0.0f; }); + ADD_OP("Relu6", ops::Relu6, + [](float x) { return std::min(std::max(x, 0.0f), 6.0f); }); + ADD_OP("Sigmoid", ops::Sigmoid, + [](float x) { return 1.0f / (1.0f + std::exp(-x)); }); + ADD_OP("Tanh", ops::Tanh, static_cast(std::tanh)); + ADD_OP("Elu", ops::Elu, + [](float x) { return (x > 0.0f) ? x : std::exp(x) - 1; }); + ADD_OP("Selu", ops::Selu, [](float x) { + return (x > 0.0f) ? kSeluScale * x + : kSeluScale * kSeluAlpha * (std::exp(x) - 1); + }); + ADD_OP("Softsign", ops::Softsign, + [](float x) { return x / (std::abs(x) + 1); }); + ADD_OP("Softplus", ops::Softplus, + [](float x) { return std::log(std::exp(x) + 1); }); +#undef ADD_OP + + // std::exp in Softplus will overflow for input > 88 + const std::vector input = {-100, -2, -1, 0, 1, 88}; + const bool nan_sensitive = false; + +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + // NVBug # 3322482 - Known bug with TRT 8.0 on specific GPU architectures + const float max_abs_error = 1e-4; +#else + const float max_abs_error = 0.; +#endif + RunTests("Activation", *ActivationTypeMap(), op_map, input, "input", + max_abs_error, nan_sensitive); +} + +TEST_P(OpConverter_FP32_Test, ConvertExpandDims) { + // Get the NodeDef for ExpandDims. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto weights = ops::Placeholder(s.WithOpName("weights"), DT_INT32); + auto expanddims = + ops::ExpandDims(s.WithOpName("my_expanddims"), input, weights); + const NodeDef& node_def = expanddims.operation.node()->def(); + { + // Input is weights, should fail. + Reset(); + AddTestWeights("input", {1, 2, 3}, {1, 2, 3, 4, 5, 6}); + AddTestWeights("weights", {1}, {1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"input\" for ExpandDims must be a " + "tensor"); + } + { + // Axis is a tensor, should fail. + Reset(); + AddTestTensor("input", {3, 2, 1}); + AddTestTensor("weights", {3}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"axis\" for ExpandDims must be a " + "constant"); + } + std::vector test_params = { + TestParamBase{{1, 1, 2, 3}, + {}, + {1, 1, 1, 2, 3}, + {0}, + trt_mode_ == TrtTestMode::kImplicitBatch + ? Status(absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of the " + "batch dimension") + : OkStatus()}, + TestParamBase{{1, 1, 2, 3}, + {}, + {1, 1, 1, 2, 3}, + {-5}, + trt_mode_ == TrtTestMode::kImplicitBatch + ? Status(absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of the " + "batch dimension") + : OkStatus()}, + TestParamBase{{1, 1, 2, 3}, + {}, + {}, + {5}, + Status(absl::StatusCode::kInvalidArgument, + "Axis value of 5 is out of bounds, must be in range" + " [-5, 5)")}, + TestParamBase{{1, 1, 2, 3}, + {}, + {}, + {-6}, + Status(absl::StatusCode::kInvalidArgument, + "Axis value of -6 is out of bounds, must be in range" + " [-5, 5)")}, + TestParamBase{{1, 2, 3}, {}, {1, 1, 2, 3}, {1}}, + TestParamBase{{1, 2, 3}, {}, {1, 1, 2, 3}, {-3}}, + TestParamBase{{1, 2, 3}, {}, {1, 2, 3, 1}, {3}}, + TestParamBase{{1, 2, 3}, {}, {1, 2, 3, 1}, {-1}}, + TestParamBase{{1, 2, 3}, {}, {1, 2, 1, 3}, {2}}, + TestParamBase{{1, 2, 3}, {}, {1, 2, 1, 3}, {-2}}, + TestParamBase{{1, 6}, {}, {1, 1, 6}, {1}}, + TestParamBase{{1, 6}, {}, {1, 6, 1}, {-1}}, + }; + for (auto p : test_params) { + Reset(); + AddTestTensor("input", p.input_dims, {1, 2, 3, 4, 5, 6}); + AddTestWeights("weights", {1}, {p.param[0]}); + TestOpConverter(node_def, p.expected_output_dims, p.status, + p.runtime_status, ElementsAreArray({1, 2, 3, 4, 5, 6})); + } +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertSoftmax) { + // Get the NodeDef for SoftMax. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("logits"), tf_type_); + auto softmax = ops::Softmax(s.WithOpName("my_softmax"), input); + const NodeDef& node_def = softmax.operation.node()->def(); + + struct TestParams { + std::vector input_dims; + std::vector expected_values; + }; + std::vector test_params = { + TestParams{/*input_dims=*/{2, 3}, + /*expected_values=*/{0.09003057, 0.24472848, 0.66524094, + 0.09003057, 0.24472848, 0.66524094}}, + TestParams{/*input_dims=*/{6, 1}, + /*expected_values=*/{1, 1, 1, 1, 1, 1}}, // works w/ std input + TestParams{/*input_dims=*/{1, 6}, // this works w/ arange(1,7) input + /*expected_values=*/{0.00426978, 0.01160646, 0.03154963, + 0.08576079, 0.23312202, 0.6336913}}}; + std::vector input_values{1, 2, 3, 4, 5, 6}; + for (auto p : test_params) { + Reset(); + AddTestTensor("logits", p.input_dims, input_values); + TestOpConverter(node_def, p.input_dims, OkStatus(), OkStatus(), + ArrayFloatNear(p.expected_values, 1e-3)); + } +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertLogSoftmax) { + // Get the NodeDef for LogSoftMax. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("logits"), tf_type_); + auto logsoftmax = ops::LogSoftmax(s.WithOpName("my_logsoftmax"), input); + const NodeDef& node_def = logsoftmax.operation.node()->def(); + + struct TestParams { + std::vector input_dims; + std::vector expected_values; + }; + + std::vector test_params = { + TestParams{/*input_dims=*/{2, 3}, + /*expected_values=*/{-2.4076061, -1.407606, -0.40760604, + -2.4076061, -1.407606, -0.40760604}}, + TestParams{/*input_dims=*/{1, 6}, + /*expected_values=*/{-5.4561934, -4.4561934, -3.4561934, + -2.4561934, -1.4561933, -0.45619333}}, + TestParams{/*input_dims=*/{6, 1}, + /*expected_values=*/{0, 0, 0, 0, 0, 0}}}; + std::vector input_values{1, 2, 3, 4, 5, 6}; + for (auto p : test_params) { + Reset(); + AddTestTensor("logits", p.input_dims, input_values); + TestOpConverter(node_def, p.input_dims, OkStatus(), OkStatus(), + ArrayFloatNear(p.expected_values, 1e-3)); + } +} + +TEST_P(OpConverter_FP32_Test, ConvertSqueeze) { + const bool use_implicit_batch = (trt_mode_ == TrtTestMode::kImplicitBatch); + // Get the NodeDef for Squeeze. + auto get_squeeze_nodedef = [](std::vector axes, + DataType tf_type) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + if (!axes.empty()) { + ops::Squeeze::Attrs squeeze_attrs; + squeeze_attrs.axis_ = gtl::ArraySlice(axes); // non-absl ok + auto squeeze = + ops::Squeeze(s.WithOpName("my_squeeze"), input, squeeze_attrs); + return squeeze.operation.node()->def(); + } else { + auto squeeze = ops::Squeeze(s.WithOpName("my_squeeze"), input); + return squeeze.operation.node()->def(); + } + }; + std::vector test_params = { + TestParamBase{ + {1, 2, 1, 3}, // input dims + {}, // input partial dims + {2, 3}, // expected output dims + {}, // axis + trt_mode_ == TrtTestMode::kExplicitBatch + ? OkStatus() + : Status{absl::StatusCode::kUnimplemented, + "Squeeze is not implemented for empty squeeze_dims"}}, + TestParamBase{{1, 2, 1, 3}, + {}, + {2, 1, 3}, + {0}, + use_implicit_batch + ? Status{absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of the " + "batch dimension"} + : OkStatus()}, + TestParamBase{{1, 2, 1, 3}, + {}, + {2, 1, 3}, + {-4}, + use_implicit_batch + ? Status{absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of the " + "batch dimension"} + : OkStatus()}, + TestParamBase{ + {1, 1, 2, 3}, + {}, + {}, + {4}, + Status{absl::StatusCode::kInvalidArgument, + "Axis value of 4 is out of bounds, must be in range [-4, 4)"}}, + TestParamBase{ + {1, 1, 2, 3}, + {}, + {}, + {-5}, + Status{ + absl::StatusCode::kInvalidArgument, + "Axis value of -5 is out of bounds, must be in range [-4, 4)"}}, + TestParamBase{{1, 1, 2, 3}, {}, {1, 2, 3}, {1}}, + TestParamBase{{1, 1, 2, 3}, {}, {1, 2, 3}, {-3}}, + TestParamBase{{1, 2, 3, 1}, {}, {1, 2, 3}, {3}}, + TestParamBase{{1, 2, 3, 1}, {}, {1, 2, 3}, {-1}}, + TestParamBase{{1, 1, 2, 1, 3, 1}, {}, {1, 2, 3}, {1, 3, 5}}, + TestParamBase{{1, 1, 2, 1, 3, 1}, {}, {1, 2, 3}, {3, 1, 5}}, + TestParamBase{{1, 1, 2, 1, 3, 1}, {}, {1, 2, 3}, {-1, -3, -5}}, + TestParamBase{{1, 1, 2, 1, 3, 1}, {}, {1, 2, 3}, {1, -3, 5}}, + TestParamBase{{1, 1, 6}, {}, {1, 6}, {1}}, + TestParamBase{{1, 6, 1}, {}, {1, 6}, {2}}, + }; + auto squeeze_non_singleton = TestParamBase{ + {1, 1, 2, 3}, + {}, + {}, + {2}, + Status{absl::StatusCode::kInvalidArgument, + "Dimension 2 with size 2 cannot be squeezed because it must be " + "size 1"}}; + + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // In this test we try to squeeze axis=2 which has size > 1. In dynamic + // shape mode the converter sees only -1, so it cannot catch this error. + squeeze_non_singleton.status = OkStatus(); // conversion status + squeeze_non_singleton.runtime_status = + errors::InvalidArgument("Negative number of dimensions -1"); + // Dynamic shape tests with partially known input shape + test_params.push_back(TestParamBase{{2, 1, 3}, {2, -1, 3}, {2, 3}, {1}}); + test_params.push_back(TestParamBase{{2, 1, 3}, {2, 1, -1}, {2, 3}, {1}}); + } + test_params.push_back(squeeze_non_singleton); + + for (TestParamBase p : test_params) { + SCOPED_TRACE(p); + Reset(); + NodeDef node_def = get_squeeze_nodedef(p.param, tf_type_); + AddTestTensor("input", p.input_dims, {1, 2, 3, 4, 5, 6}, + p.partial_input_dims); + TestOpConverter(node_def, p.expected_output_dims, p.status, + p.runtime_status, ElementsAreArray({1, 2, 3, 4, 5, 6})); + } +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertStridedSlice) { + // Get nodedef for StridedSlice layer. + auto get_strided_slice_nodedef = + [](DataType tf_type, int64 begin_mask = 0, int64 end_mask = 0, + int64 ellipsis_mask = 0, int64 new_axis_mask = 0, + int64 shrink_axis_mask = 0) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + auto begin = ops::Placeholder(s.WithOpName("begin"), DT_INT32); + auto end = ops::Placeholder(s.WithOpName("end"), DT_INT32); + auto strides = ops::Placeholder(s.WithOpName("strides"), DT_INT32); + ops::StridedSlice::Attrs attrs = ops::StridedSlice::Attrs() + .BeginMask(begin_mask) + .EndMask(end_mask) + .EllipsisMask(ellipsis_mask) + .NewAxisMask(new_axis_mask) + .ShrinkAxisMask(shrink_axis_mask); + auto strided_slice = ops::StridedSlice(s.WithOpName("my_strided_slice"), + input, begin, end, strides, attrs); + return strided_slice.operation.node()->def(); + }; + + { + // Input is weights, should fail. + Reset(); + NodeDef node_def = get_strided_slice_nodedef(tf_type_); + AddTestWeights("input", {1, 1, 2, 3}, {1, 2, 3, 4, 5, 6}); + AddTestWeights("begin", {4}, {0, 0, 0, 0}); + AddTestWeights("end", {4}, {1, 1, 2, 3}); + AddTestWeights("strides", {4}, {1, 1, 1, 1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"input\" for StridedSlice must " + "be a tensor"); + } + { + // Begin, end, strides are tensors, should fail. + Reset(); + NodeDef node_def = get_strided_slice_nodedef(tf_type_); + AddTestTensor("input", {4, 1, 1, 1}); + AddTestTensor("begin", {4}); + AddTestTensor("end", {4}); + AddTestTensor("strides", {4}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"begin\" for StridedSlice must be a constant"); + } + + struct TestParams { + std::vector input_dims; + std::vector begin; + std::vector end; + std::vector strides; + int begin_mask; + int end_mask; + int ellipsis_mask; + int new_axis_mask; + int shrink_axis_mask; + std::vector expected_output_dims; + std::vector expected_output; + Status conversion_status; + Status runtime_status; + std::vector partial_input_dims; + }; + + auto get_mask = [](const std::vector& mask) { + int result = 0; + for (int i = 0; i < mask.size(); i++) { + if (mask[i]) result += (1 << i); + } + return result; + }; + + // Same input is used for all tests. + const std::vector ok_input = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; + Status modified_batch_dim_status = + (trt_mode_ == TrtTestMode::kImplicitBatch) + ? errors::Unimplemented( + "TensorRT does not allow modifications to " + "the batch dimension") + : OkStatus(); + std::vector params = { + // Modify batch dim, should fail in implicit batch mode. + TestParams{/*input_dims=*/{2, 1, 1, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{1, 1, 1, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({0, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{1, 2}, + /*conversion_status=*/modified_batch_dim_status, + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{}}, + // Unknown batch size without end_mask. + TestParams{ + /*input_dims=*/{2, 1, 1, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{1, 1, 1, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({0, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{1, 2}, + modified_batch_dim_status, + OkStatus(), + /*partial_input_dims=*/{-1, 1, 1, 3}, + }, + // Test Case 2: Unknown batch size with end_mask. + TestParams{ + /*input_dims=*/{2, 1, 1, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 1, 1, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({1, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{2, 1, 1, 2}, + /*expected_output=*/{1, 2, 4, 5}, + OkStatus(), + OkStatus(), + /*partial_input_dims=*/{-1, 1, 1, 3}, + }, + // Invalid parameters: end[2] < begin[2] + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 2, 0}, + /*end=*/{1, 1, 0, 3}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/0, + /*end_mask=*/0, + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{}, + /*expected_output=*/{}, + errors::InvalidArgument("\"size\" cannot be negative for " + "StridedSlice"), + OkStatus(), + /*partial_input_dims=*/{}}, + // Slice on the last two dimensions. All dimensions are static. + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 0, 1, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{1, 2}, + }, + // Slice on the last two dimensions. The slice is fully + // specified for the dynamic dimensions. + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 0, 1, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{1, 2}, + OkStatus(), + OkStatus(), + /*partial_input_dims=*/{1, 1, -1, -1}, + }, + // End mask is provided on all dimensions. This should override the fact + // that the end value is 0. For dynamic shape, it tests + // that we can infer tensor size when "end mask" is provided. + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 1, 1}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{5, 6}, + OkStatus(), + OkStatus(), + /*partial_input_dims=*/{1, 1, -1, -1}, + }, + // End mask is provided for the batch dimension to overwrite the end value + // 0 for that dimension. + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 1, 1}, + /*end=*/{0, 1, 2, 3}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{5, 6}, + }, + // Test slice on two dimensions with negative stride, without end_mask set + // on crop dimensions. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 1, 2}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, 1, -1, -1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{6, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, 1, -1, -1}}, + // Test slice on two dimensions with negative stride, with end_mask set on + // crop dimensions. In dynamic shape mode, this tests the runtime size + // computation. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 1, 1}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, 1, -1, -1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 2}, + /*expected_output=*/{5, 4, 2, 1}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, 1, -1, -1}}, + // Test slice on two dimensions with negative stride, with begin_mask set + // on the crop dimensions. In dynamic shape mode, this tests the runtime + // size computation. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, 1, -1, -1}, + /*begin_mask=*/get_mask({0, 0, 1, 1}), + /*end_mask=*/get_mask({1, 1, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{6, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, 1, -1, -1}}, + // Test the reversal of all non-batch dimensions by providing the begin + // masks, end masks, and -1 as strides. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, -1, -1, -1}, + /*begin_mask=*/get_mask({1, 1, 1, 1}), + /*end_mask=*/get_mask({1, 1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/{6, 5, 4, 3, 2, 1}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, -1, -1, -1}}, + // Slice on dimensions 1 and 2. + TestParams{ + /*input_dims=*/{1, 2, 3, 1}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 1, 2, 1}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{1, 2}, + }, + // Slice on dimensions 1 and 2. + TestParams{ + /*input_dims=*/{1, 2, 3, 1}, + /*begin=*/{0, 1, 1, 0}, + /*end=*/{0, 2, 3, 1}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{5, 6}, + }, + // Slice on dimensions 1 and 3. + TestParams{ + /*input_dims=*/{1, 2, 1, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 1, 1, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{1, 2}, + }, + // Slice on dimensions 1 and 3 with non-zero slice start. + TestParams{ + /*input_dims=*/{1, 2, 1, 3}, + /*begin=*/{0, 1, 0, 1}, + /*end=*/{0, 2, 1, 3}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 2}, + /*expected_output=*/{5, 6}, + }, + // Slice on 3D tensor. + TestParams{ + /*input_dims=*/{1, 2, 3}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, 1, 2}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2}, + /*expected_output=*/{1, 2}, + }, + // Slice on 3D tensor using end_mask. For dynamic shape, all + // dimensions are dynamic. + TestParams{/*input_dims=*/{1, 2, 3}, + /*begin=*/{0, 1, 1}, + /*end=*/{0, 0, 0}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2}, + /*expected_output=*/{5, 6}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1}}, + // Slice on 3D tensor using end_mask. For dynamic shape, all + // dimensions are dynamic. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 0, 0, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 2}, + /*expected_output=*/{1, 2, 4, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1, -1}}, + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 1, 0}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 1, 3}, + /*expected_output=*/{4, 5, 6}, + }, + // 1D simple slice. + TestParams{/*input_dims=*/{1, 2, 3, 1}, + /*begin=*/{0, 0, 0, 0}, + /*end=*/{0, 1, 0, 0}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 3, 1}, + /*expected_output=*/{1, 2, 3}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1, -1}}, + TestParams{ + /*input_dims=*/{1, 2, 3, 1}, + /*begin=*/{0, 1, 0, 0}, + /*end=*/{0, 0, 0, 0}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 3, 1}, + /*expected_output=*/{4, 5, 6}, + }, + // Simple 1D slice on 2D input. + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 0}, + /*end=*/{0, 3}, + /*strides=*/{1, 1}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{1, 2, 3}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + TestParams{ + /*input_dims=*/{1, 1, 6}, + /*begin=*/{0, 0, 2}, + /*end=*/{0, 0, 5}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0}), + /*end_mask=*/get_mask({1, 1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 3}, + /*expected_output=*/{3, 4, 5}, + }, + TestParams{ + /*input_dims=*/{1, 6, 1}, + /*begin=*/{0, 2, 0}, + /*end=*/{0, 5, 0}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3, 1}, + /*expected_output=*/{3, 4, 5}, + }, + // Negative axis. + TestParams{ + /*input_dims=*/{1, 6, 1}, + /*begin=*/{0, -6, 0}, + /*end=*/{0, -3, 0}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3, 1}, + /*expected_output=*/{1, 2, 3}, + }, + TestParams{ + /*input_dims=*/{1, 6, 1}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, -1, 0}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 5, 1}, + /*expected_output=*/{1, 2, 3, 4, 5}, + }, + // Clamp out of bounds begin and end. + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, -9999, -9}, + /*end=*/{0, 1, 1000, 4}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + }, + // Stride values >= 2. + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 0}, + /*end=*/{0, 5}, + /*strides=*/{1, 2}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{1, 3, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 0}, + /*end=*/{0, 6}, + /*strides=*/{1, 2}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{1, 3, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 1}, + /*end=*/{0, 6}, + /*strides=*/{1, 2}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{2, 4, 6}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 2}, + /*end=*/{0, 6}, + /*strides=*/{1, 3}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 2}, + /*expected_output=*/{3, 6}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + // Stride values <= -2. + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 5}, + /*end=*/{0, 0}, + /*strides=*/{1, -2}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{6, 4, 2}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 5}, + /*end=*/{0, 0}, + /*strides=*/{1, -2}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{6, 4, 2}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 5}, + /*end=*/{0, 1}, + /*strides=*/{1, -3}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 2}, + /*expected_output=*/{6, 3}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1}}, + // Ellipsis_mask causes leading dimensions to be ignored. Begin, end, + // stride, and mask values of size 2 should be interpreted as applying to + // the last 2 dimensions, while the ellipsis applies to the first 2 (for a + // 4D input tensor). + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 1}, + /*end=*/{0, 2}, + /*strides=*/{1, 1}, + /*begin_mask=*/get_mask({0, 0}), + /*end_mask=*/get_mask({0, 0}), + /*ellipsis_mask=*/get_mask({1, 0, 0}), + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{2, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1, -1}}, + // Ellipsis_mask on single inner dimension. + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 1}, + /*end=*/{0, 0, 2}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({1, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/get_mask({0, 1, 0, 0}), + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{2, 5}, + }, + // Ellipsis_mask on single leading dimension. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 1}, + /*end=*/{0, 1, 2, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({0, 0, 0, 0}), + /*ellipsis_mask=*/get_mask({1, 0, 0, 0}), + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{2, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1, -1}}, + // Ellipsis_mask on single inner dimension overrides that dimensions' + // begin/end values. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 1, 0, 1}, + /*end=*/{1, 1, 2, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({0, 0, 0, 0}), + /*ellipsis_mask=*/get_mask({0, 1, 0, 0}), + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{2, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1, -1}}, + // Ellipsis mask on single leading dimension should throw out extra + // leading values of begin/end vectors so that only the last N-1 values of + // each remain. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 0, 1}, + /*end=*/{0, 1, 1, 2, 2}, + /*strides=*/{1, 1, 1, 1, 1}, + /*begin_mask=*/get_mask({0, 0, 0, 0}), + /*end_mask=*/get_mask({0, 0, 0, 0}), + /*ellipsis_mask=*/get_mask({1, 0, 0, 0}), + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/0, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{2, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1, -1}}, + // Shrink-axis mask set for the final dimension of final size 1 should + // remove that dimension from the final shape. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 1}, + /*end=*/{0, 0, 0, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({1, 1, 1, 0}), + /*end_mask=*/get_mask({1, 1, 1, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/get_mask({0, 0, 0, 1}), + /*expected_output_dims=*/{1, 1, 2}, + /*expected_output=*/{2, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, 1, 2, -1}}, + // Shrink-axis mask set for multiple dimensions that have a final size of + // 1 should remove those dimensions from the final shape. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*begin=*/{0, 0, 0, 1}, + /*end=*/{0, 1, 2, 2}, + /*strides=*/{1, 1, 1, 1}, + /*begin_mask=*/get_mask({1, 0, 0, 0}), + /*end_mask=*/get_mask({1, 0, 0, 0}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/get_mask({0, 1, 0, 1}), + /*expected_output_dims=*/{1, 2}, + /*expected_output=*/{2, 5}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, 1, 2, -1}}, + // Shrink-axis mask set for multiple sequential dimensions of final size 1 + // should + // remove those dimensions from the final shape. + TestParams{/*input_dims=*/{6, 1, 1}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, 0, 0}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({1, 1, 1}), + /*end_mask=*/get_mask({1, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/get_mask({0, 1, 1}), + /*expected_output_dims=*/{6}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + /*conversion_status=*/OkStatus(), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{-1, -1, -1}}, + // The new_axis_mask parameter is not supported. + TestParams{/*input_dims=*/{1, 6}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, 0, 0}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/ + get_mask({0, 1, 1}), + /*end_mask=*/get_mask({0, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/get_mask({1, 0, 0}), + /*shrink_axis_mask=*/get_mask({0, 0, 0}), + /*expected_output_dims=*/{1, 1, 6}, + /*expected_output=*/{1, 1, 6}, + /*conversion_status=*/ + errors::Unimplemented( + "new_axis_mask is not supported for StridedSlice"), + /*runtime_status=*/OkStatus(), + /*partial_input_dims=*/{1, 6}}, + // Test all axes dynamic inputs with shrink_axis_mask + TestParams{/*input_dims=*/{1, 3, 2}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, 0, 3}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 1, 1}), + /*end_mask=*/get_mask({0, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/1, + /*expected_output_dims=*/{3, 2}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + /*conversion_status=*/modified_batch_dim_status, OkStatus(), + /*partial_input_dims=*/{-1, -1, -1}}, + // Test dynamic input with shrink_axis_mask along axis=0 + TestParams{/*input_dims=*/{2, 3, 2}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, 0, 3}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 1, 1}), + /*end_mask=*/get_mask({0, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/1, + /*expected_output_dims=*/{3, 2}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + /*conversion_status=*/modified_batch_dim_status, OkStatus(), + /*partial_input_dims=*/{-1, -1, 2}}, + // Test dynamic input sizes with multiple axes shrinking + TestParams{/*input_dims=*/{2, 3, 2}, + /*begin=*/{0, 0, 0}, + /*end=*/{0, 0, 3}, + /*strides=*/{1, 1, 1}, + /*begin_mask=*/get_mask({0, 1, 1}), + /*end_mask=*/get_mask({0, 1, 1}), + /*ellipsis_mask=*/0, + /*new_axis_mask=*/0, + /*shrink_axis_mask=*/3, + /*expected_output_dims=*/{2}, + /*expected_output=*/{1, 2}, + /*conversion_status=*/modified_batch_dim_status, OkStatus(), + /*partial_input_dims=*/{-1, -1, 2}}, + }; + + int i = 0; + for (auto p : params) { + Reset(); + NodeDef node_def = get_strided_slice_nodedef( + tf_type_, p.begin_mask, p.end_mask, p.ellipsis_mask, p.new_axis_mask, + p.shrink_axis_mask); + + VLOG(2) << "Preparing test case " << i++ << " with dims " + << DebugString(p.input_dims); + + switch (trt_mode_) { + case TrtTestMode::kImplicitBatch: { + AddTestTensor("input", p.input_dims, ok_input); + break; + } + case TrtTestMode::kExplicitBatch: { + AddTestTensor("input", p.input_dims, ok_input); + break; + } + case TrtTestMode::kDynamicShape: { + if (p.partial_input_dims.size() > 0) { + AddTestTensor("input", p.input_dims, tf_type_, ok_input, + p.partial_input_dims); + } else { + AddTestTensor("input", p.input_dims, tf_type_, ok_input, + p.input_dims); + } + break; + } + } + + VLOG(2) << "Adding weights begin: " << DebugString(p.begin) + << ", end: " << DebugString(p.end) + << ", strides: " << DebugString(p.strides); + AddTestWeights("begin", {static_cast(p.begin.size())}, p.begin); + AddTestWeights("end", {static_cast(p.end.size())}, p.end); + AddTestWeights("strides", {static_cast(p.strides.size())}, + p.strides); + + TestOpConverter(node_def, p.expected_output_dims, p.conversion_status, + p.runtime_status, ElementsAreArray(p.expected_output)); + } +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertSlice) { + // Get nodedef for Slice layer. + auto get_slice_nodedef = [](DataType tf_type) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + auto begin = ops::Placeholder(s.WithOpName("begin"), DT_INT32); + auto size = ops::Placeholder(s.WithOpName("size"), DT_INT32); + auto slice = ops::Slice(s.WithOpName("my_slice"), input, begin, size); + return slice.operation.node()->def(); + }; + + struct TestParams { + std::vector input_dims; + std::vector + partial_input_dims; // Symbolic shape in dynamic shape mode. + std::vector begin; + std::vector size; + std::vector expected_output_dims; + std::vector expected_output; + Status conversion_status; + Status runtime_status; + }; + + std::vector params = { + // Slice start points must always be >= 0. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + /*begin=*/{0, 0, -1, 0}, + /*size=*/{1, 1, 2, 3}, + /*expected_output_dims=*/{}, + /*expected_output=*/{}, + /*conversion_status=*/ + errors::InvalidArgument("\"begin\" in Slice " + "is out of range")}, + // In implicit batch mode, slicing the batch dimension is not allowed. + TestParams{/*input_dims=*/{2, 1, 1, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + /*begin=*/{0, 0, 0, 0}, + /*size=*/{1, 1, 1, 3}, + /*expected_output_dims=*/{1, 1, 1, 3}, + /*expected_output=*/{1, 2, 3}, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented( + "TensorRT does not allow modifications to the batch " + "dimension in implicit batch mode") + : OkStatus()}, + // Dynamic batch size but using size[0] of -1, ok. + TestParams{{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + {0, 0, 0, 0}, + {-1, 1, 2, 2}, + {1, 1, 2, 2}, + {1, 2, 4, 5}, + OkStatus()}, + TestParams{{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + {0, 0, 0, 0}, + {-1, -1, -1, -1}, + {1, 1, 2, 3}, + {1, 2, 3, 4, 5, 6}, + OkStatus()}, + TestParams{{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + {0, 0, 0, 0}, + {1, 1, 2, 3}, + {1, 1, 2, 3}, + {1, 2, 3, 4, 5, 6}}, + TestParams{{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + /*begin=*/{0, 0, 0, 0}, + /*size=*/{1, -1, 2, 2}, + /*expected_output_dims=*/{1, 1, 2, 2}, + /*expected_output=*/{1, 2, 4, 5}, + OkStatus()}, + TestParams{/*input_dims=*/{1, 6}, + /*partial_input_dims=*/{-1, -1}, + /*being=*/{0, 1}, + /*size=*/{1, 5}, + /*expected_output_dims=*/{1, 5}, + /*expected_output=*/{2, 3, 4, 5, 6}}, + TestParams{/*input_dims=*/{1, 6}, + /*partial_input_dims=*/{-1, -1}, + /*begin=*/{0, 1}, + /*size=*/{-1, 3}, + /*expected_output_dims=*/{1, 3}, + /*expected_output=*/{2, 3, 4}, OkStatus()}, + // In dynamic shape mode we do not know the input shape during + // conversion, therefore we cannot check out of bound access. + TestParams{ + {1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + /*begin=*/{0, 0, 3, 0}, + /*end=*/{1, 1, 2, 3}, + {}, + {}, + trt_mode_ == TrtTestMode::kDynamicShape + ? OkStatus() + : errors::InvalidArgument("\"begin\" + \"size\" for dimension " + "2 in Slice is out of range"), + errors::Internal("Internal: Failed to build TensorRT engine")}, + // The slice operation should expect that the "size[i]" values are not + // less than -1. + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + /*begin=*/{0, 0, 0, 0}, + /*size=*/{1, 1, 2, -2}, + {}, + {}, + errors::InvalidArgument("\"size\" in Slice is out of range")}, + TestParams{ + /*input_dims=*/{1, 1, 2, 3}, + /*partial_input_dims=*/{-1, -1, -1, -1}, + /*begin=*/{0, 0, 0, 0}, + /*size=*/{1, 1, 3, 2}, + /*expected_output_dims=*/{}, + /*expected_output=*/{}, + /*conversion_status=*/trt_mode_ == TrtTestMode::kDynamicShape + ? OkStatus() + : errors::InvalidArgument("\"begin\" + \"size\" for dimension " + "2 in Slice is out of range"), + errors::Internal("Internal: Failed to build TensorRT engine")}, + }; + + logger_.unsuppressAllLoggerMsgs(); + int i = 0; + for (auto p : params) { + Reset(); + NodeDef node_def = get_slice_nodedef(tf_type_); + + VLOG(2) << "Preparing test case " << i++ << " with dims " + << DebugString(p.input_dims); + + // The input tensor always has size 6. + std::vector input_vals = {1, 2, 3, 4, 5, 6}; + + switch (trt_mode_) { + case TrtTestMode::kImplicitBatch: { + AddTestTensor("input", p.input_dims, input_vals); + break; + } + case TrtTestMode::kExplicitBatch: { + AddTestTensor("input", p.input_dims, input_vals); + break; + } + case TrtTestMode::kDynamicShape: { + if (p.partial_input_dims.size() > 0) { + AddTestTensor("input", p.input_dims, tf_type_, input_vals, + p.partial_input_dims); + + } else { + AddTestTensor("input", p.input_dims, tf_type_, input_vals, + p.input_dims); + } + break; + } + } + + AddTestWeights("begin", {static_cast(p.begin.size())}, p.begin); + AddTestWeights("size", {static_cast(p.size.size())}, p.size); + + const bool flag = + trt_mode_ == TrtTestMode::kDynamicShape && (i == 9 || i == 11); + if (flag) logger_.suppressLoggerMsgs(nvinfer1::ILogger::Severity::kERROR); + + TestOpConverter(node_def, p.expected_output_dims, p.conversion_status, + p.runtime_status, ElementsAreArray(p.expected_output)); + if (flag) logger_.unsuppressLoggerMsgs(nvinfer1::ILogger::Severity::kERROR); + } +} + +TEST_P(OpConverter_FP32_Test, ConvertConv2D) { + // Get nodedef for Conv2D layer. + DataType tf_type = tf_type_; + auto get_conv2d_nodedef = + [tf_type](std::vector strides = {1, 1, 1, 1}, + string padding = "SAME", string data_format = "NCHW", + std::vector dilations = {1, 1, 1, 1}) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + auto filter = ops::Placeholder(s.WithOpName("weights"), tf_type); + ops::Conv2D::Attrs attrs = + ops::Conv2D::Attrs().DataFormat(data_format).Dilations(dilations); + auto conv2d = ops::Conv2D(s.WithOpName("my_conv2d"), input, filter, strides, + padding, attrs); + return conv2d.operation.node()->def(); + }; + + { + // Input is weights, should fail. + Reset(); + NodeDef node_def = get_conv2d_nodedef(); + AddTestWeights("input", {1, 2, 3}, {1, 2, 3, 4, 5, 6}); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"input\" for Conv2D must be a tensor"); + } + { + // Filter is tensor, should fail. + Reset(); + NodeDef node_def = get_conv2d_nodedef(); + AddTestTensor("input", {3, 1, 2, 1}); + AddTestTensor("weights", {3, 3, 1, 1}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"filter\" for Conv2D must be a constant"); + } + { + // Filter is not 4D, should fail. + Reset(); + NodeDef node_def = get_conv2d_nodedef(); + AddTestTensor("input", {1, 1, 2, 3}); + AddTestWeights("weights", {3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Conv2D expects kernel of dimension 4"); + } + { + // Dilations is not 4D, should fail. + Reset(); + NodeDef node_def = + get_conv2d_nodedef({1, 1, 1, 1}, "SAME", "NCHW", {1, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Convolution dilations field must specify 4 dimensions"); + } + { + // Dilation value is not 1 for channel, should fail. + Reset(); + NodeDef node_def = + get_conv2d_nodedef({1, 1, 1, 1}, "SAME", "NCHW", {1, 2, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Dilation rate must be 1 for batch and channel " + "dimensions"); + } + { + // Dilation value is not 1 for channel (NHWC), should fail. + Reset(); + NodeDef node_def = + get_conv2d_nodedef({1, 1, 1, 1}, "SAME", "NHWC", {1, 1, 1, 2}); + AddTestTensor("input", {1, 2, 3, 1}); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Dilation rate must be 1 for batch and channel " + "dimensions"); + } + { + // Strides is not 4D, should fail. + Reset(); + NodeDef node_def = + get_conv2d_nodedef({1, 1, 1}, "SAME", "NCHW", {1, 1, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Convolution strides field must specify 4 dimensions"); + } + { + // Stride value is not 1 for channel, should fail. + Reset(); + NodeDef node_def = + get_conv2d_nodedef({1, 2, 1, 1}, "SAME", "NCHW", {1, 1, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "Stride must be 1 for batch and channel dimensions"); + } + if (trt_mode_ == TrtTestMode::kDynamicShape) { + Reset(); + NodeDef node_def = get_conv2d_nodedef(); + // Channel dim unknown, should fail. + nvinfer1::DataType trt_type; + TF_ASSERT_OK(TfTypeToTrtType(tf_type_, &trt_type)); + AddTestTensorWithTFDims("input", {-1, -1, -1, -1}, trt_type); + AddTestWeights("weights", {1, 2, 1, 1}, {-1, 1}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Channel dimension must be static"); + } + + struct TestParams { + std::vector input_dims; + std::vector input; + std::vector filter_dims; + std::vector filter; + std::vector strides; + string padding; + string data_format; + std::vector dilations; + std::vector expected_output_dims; + std::vector expected_output; + }; + + // Ok. + std::vector ok_params = { + // Basic + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*input=*/{0, 1, 2, 3, 3, 4}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 2}, + /*expected_output=*/{1, 1, 0, 1}}, + // SAME padding (Asymmetric) + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*input=*/{0, 1, 2, 3, 3, 4}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/{1, 1, -2, 0, 1, -4}}, + // SAME padding (Symmetric) + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*input=*/{0, 1, 2, 3, 3, 4}, + /*filter_dims=*/{1, 3, 1, 1}, + /*filter=*/{-1, 0, 1}, + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/{1, 2, -1, 3, 1, -3}}, + // NHWC + TestParams{/*input_dims=*/{1, 2, 3, 1}, + /*input=*/{0, 1, 2, 3, 3, 4}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NHWC", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 2, 2, 1}, + /*expected_output=*/{1, 1, 0, 1}}, + // Dilated + TestParams{/*input_dims=*/{1, 1, 2, 3}, + /*input=*/{0, 1, 2, 3, 3, 4}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 2}, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_output=*/{2, 1}}, + // Strided + TestParams{/*input_dims=*/{1, 1, 2, 4}, + /*input=*/{0, 1, 2, 2, 3, 4, 4, 7}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 2}, + /*padding=*/"VALID", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 2}, + /*expected_output=*/{1, 0, 1, 3}}, + }; + + for (int i = 0; i < ok_params.size(); i++) { + Reset(); + NodeDef node_def = + get_conv2d_nodedef(ok_params[i].strides, ok_params[i].padding, + ok_params[i].data_format, ok_params[i].dilations); + std::vector partial_input_shape; + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // The channel dim cannot have unknown size, fix that. + partial_input_shape.resize(ok_params[i].input_dims.size(), -1); + int channel_id = (ok_params[i].data_format == "NCHW") ? 1 : 3; + partial_input_shape[channel_id] = ok_params[i].input_dims[channel_id]; + } + + AddTestTensor("input", ok_params[i].input_dims, tf_type_, + ok_params[i].input, partial_input_shape); + AddTestWeights("weights", ok_params[i].filter_dims, + ok_params[i].filter); + + TestOpConverter(node_def, ok_params[i].expected_output_dims, OkStatus(), + OkStatus(), ElementsAreArray(ok_params[i].expected_output)); + } +} + +TEST_P(OpConverter_FP32_Test, ConvertConv2DBackpropInput) { + // Get nodedef for Conv2D layer. + auto get_conv2d_backprop_input_nodedef = + [](DataType tf_type, std::vector strides = {1, 1, 1, 1}, + string padding = "SAME", string data_format = "NCHW", + std::vector dilations = {1, 1, 1, 1}) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + auto filter = ops::Placeholder(s.WithOpName("weights"), tf_type); + auto input_sizes = ops::Placeholder(s.WithOpName("input_sizes"), DT_INT32); + ops::Conv2DBackpropInput::Attrs attrs = ops::Conv2DBackpropInput::Attrs() + .DataFormat(data_format) + .Dilations(dilations); + auto conv2d = ops::Conv2DBackpropInput( + s.WithOpName("my_conv2d_backprop_input"), input_sizes, filter, input, + strides, padding, attrs); + return conv2d.operation.node()->def(); + }; + + struct TestParams { + std::vector input_dims; + std::vector input; + std::vector filter_dims; + std::vector filter; + std::vector strides; + string padding; + string data_format; + std::vector dilations; + std::vector expected_output_dims; + std::vector expected_output; + Status conversion_status; + // For dynamic shape mode, we must use the partial_input_dims for + // creating the test tensor if any of the input_dims are -1. + std::vector partial_input_dims; + }; + + // Ok. + std::vector params = { + // Transpose Strided + TestParams{/*input_dims=*/{1, 1, 2, 2}, + /*input=*/{0, 1, 2, 3}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 2}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 4}, + /*expected_output=*/{0, 0, -1, 1, -2, 2, -3, 3}}, + // Transpose Strided NHWC + TestParams{/*input_dims=*/{1, 2, 2, 1}, + /*input=*/{0, 1, 2, 3}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 2, 1}, + /*padding=*/"SAME", + /*data_format=*/"NHWC", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 2, 4, 1}, + /*expected_output=*/{0, 0, -1, 1, -2, 2, -3, 3}}, + // Transpose Strided NHWC with VALID padding + TestParams{/*input_dims=*/{1, 3, 1, 1}, + /*input=*/{0, 1, 2}, + /*filter_dims=*/{2, 1, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 2, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NHWC", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 7, 1, 1}, + /*expected_output=*/{0, 0, -1, 1, -2, 2, 0}}, + TestParams{/*input_dims=*/{1, 1, 2, 2}, + /*input=*/{0, 1, 2, 3}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 2}, + /*padding=*/"EXPLICIT", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 4}, + /*expected_output=*/{0, 0, -1, 1, -2, 2, -3, 3}, + errors::Unimplemented("EXPLICIT padding type not " + "implemented, only VALID and SAME are" + " supported")}, + // Dilation + Conv2DBackpropInput, should fail. + TestParams{/*input_dims=*/{1, 1, 2, 2}, + /*input=*/{0, 1, 2, 3}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 2}, + {1, 1, 2, 2}, + {}, + errors::Unimplemented("Dilation with Conv2DBackpropInput " + "(conv2d_transpose) is not supported")}, + }; + if (trt_mode_ == TrtTestMode::kDynamicShape) { + params.push_back( + TestParams{/*input_dims=*/{1, 1, 2, 2}, + /*input=*/{0, 1, 2, 3}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 2}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 4}, + /*expected_output=*/{0, 0, -1, 1, -2, 2, -3, 3}, + errors::InvalidArgument("Channel dimension must be static"), + /*partial input dims=*/{1, -1, 2, 2}}); + // Test dynamic batch dimension. + params.push_back(TestParams{/*input_dims=*/{2, 1, 2, 2}, + /*input=*/ + // clang-format off + {0, 1, 2, 3, + 3, 2, 1, 0}, + // clang-format on + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 2}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{2, 1, 2, 4}, + /*expected_output=*/ + // clang-format off + { 0, 0, -1, 1, -2, 2, -3, 3, + -3, 3, -2, 2, -1, 1, 0, 0}, + // clang-format on + /*conversion_status=*/OkStatus(), + /*partial input dims=*/{-1, 1, 2, 2}}); + + // Test dynamic height and width. + params.push_back(TestParams{ + /*input_dims=*/{1, 1, 2, 2}, + /*input=*/{0, 1, 2, 3}, + /*filter_dims=*/{1, 2, 1, 1}, + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 2}, + /*padding=*/"SAME", + /*data_format=*/"NCHW", + /*dilations=*/{1, 1, 1, 1}, + /*expected_output_dims=*/{1, 1, 2, 4}, + /*expected_output=*/ + {0, 0, -1, 1, -2, 2, -3, 3}, + /*conversion_status=*/ + errors::Unimplemented( + "Conv2dBackpropInput does not support input with unknown spatial " + "shape"), + /*partial input dims=*/{1, 1, -1, -1}}); + } + for (auto p : params) { + for (int input_sizes_length : {2, 4}) { + Reset(); + NodeDef node_def = get_conv2d_backprop_input_nodedef( + tf_type_, p.strides, p.padding, p.data_format, p.dilations); + + switch (trt_mode_) { + case TrtTestMode::kImplicitBatch: { + AddTestTensor("input", p.input_dims, p.input); + break; + } + case TrtTestMode::kExplicitBatch: { + AddTestTensor("input", p.input_dims, p.input); + break; + } + case TrtTestMode::kDynamicShape: { + AddTestTensor("input", p.input_dims, tf_type_, p.input, + p.partial_input_dims.size() > 0 ? p.partial_input_dims + : p.input_dims); + break; + } + default: { + ASSERT_TRUE(false) << "unknown test mode"; + } + } + + AddTestWeights("weights", p.filter_dims, p.filter, tf_type_); + + if (input_sizes_length == 4) { + AddTestWeights("input_sizes", {4}, p.expected_output_dims); + } else { + std::vector tf_input_sizes(2); + // Remove the channel and batch dimensions. + if (p.data_format == "NHWC") { + std::copy(p.expected_output_dims.begin() + 1, + p.expected_output_dims.end() - 1, tf_input_sizes.begin()); + } else { + std::copy(p.expected_output_dims.begin() + 2, + p.expected_output_dims.end(), tf_input_sizes.begin()); + } + QCHECK_EQ(2, tf_input_sizes.size()); + AddTestWeights("input_sizes", {2}, tf_input_sizes); + } + + TestOpConverter(node_def, p.expected_output_dims, p.conversion_status, + OkStatus(), ElementsAreArray(p.expected_output)); + } + } +} + +// Get the NodeDef for Pack. +NodeDef GetConv3DNodeDef(std::vector strides = {1, 1, 1, 1, 1}, + string padding = "SAME", string data_format = "NCDHW", + std::vector dilations = {1, 1, 1, 1, 1}, + bool is_conv3d_backprop_input = false) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_FLOAT); + auto filter = ops::Placeholder(s.WithOpName("weights"), DT_FLOAT); + + if (is_conv3d_backprop_input) { + auto input_sizes = ops::Placeholder(s.WithOpName("input_sizes"), DT_INT32); + ops::Conv3DBackpropInputV2::Attrs attrs = + ops::Conv3DBackpropInputV2::Attrs() + .DataFormat(data_format) + .Dilations(dilations); + auto conv3d = + ops::Conv3DBackpropInputV2(s.WithOpName("my_conv3d"), input_sizes, + filter, input, strides, padding, attrs); + return conv3d.operation.node()->def(); + } else { + ops::Conv3D::Attrs attrs = + ops::Conv3D::Attrs().DataFormat(data_format).Dilations(dilations); + auto conv3d = ops::Conv3D(s.WithOpName("my_conv3d"), input, filter, strides, + padding, attrs); + return conv3d.operation.node()->def(); + } +} + +struct Conv3DTestParams { + std::vector input_dims; + std::vector input; + std::vector filter_dims; + std::vector filter; + std::vector strides; + string padding; + string data_format; + std::vector dilations; + bool is_conv3d_backprop; + std::vector expected_output_dims; + std::vector expected_output; + bool allow_dynamic_channel_dim; + Status validation_status; +}; + +void TestConv3D(ParameterizedOpConverterTestBase* test, Conv3DTestParams& p) { + test->Reset(); + NodeDef node_def = GetConv3DNodeDef(p.strides, p.padding, p.data_format, + p.dilations, p.is_conv3d_backprop); + + std::vector partial_input_shape; + if (!p.allow_dynamic_channel_dim && + test->get_trt_mode() == TrtTestMode::kDynamicShape) { + // The channel dim cannot have unknown size, fix that. + partial_input_shape.resize(p.input_dims.size(), -1); + int channel_id = (p.data_format == "NCDHW") ? 1 : 4; + partial_input_shape[channel_id] = p.input_dims[channel_id]; + } + + test->AddTestTensor("input", p.input_dims, test->get_tf_type(), p.input, + partial_input_shape); + test->AddTestWeights("weights", p.filter_dims, p.filter); + + if (p.is_conv3d_backprop) { + test->AddTestWeights("input_sizes", + {static_cast(p.expected_output.size())}, + p.expected_output); + } + + test->TestOpConverter(node_def, p.expected_output_dims, + /*expected_conversion_status=*/p.validation_status, + /*expected_runtime_status=*/OkStatus(), + /*matcher=*/ElementsAreArray(p.expected_output), + /*out_tf_types=*/{test->get_tf_type()}); +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertConv3D) { + { + // Input is weights, should fail. + Reset(); + NodeDef node_def = GetConv3DNodeDef(); + + AddTestWeights("input", {1, 1, 2, 3}, {1, 2, 3, 4, 5, 6}); + AddTestWeights("weights", {1, 3, 3, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"input\" for Conv3D must be a tensor"); + } + { + // Filter is tensor, should fail. + Reset(); + NodeDef node_def = GetConv3DNodeDef(); + AddTestTensor("input", {1, 1, 2, 3}, tf_type_, CreateVectorIota(6)); + AddTestTensor("weights", {1, 3, 3, 1}, tf_type_, + CreateVectorIota(9)); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"filter\" for Conv3D must be a constant"); + } + { + // Filter is not 5D, should fail. + Reset(); + NodeDef node_def = GetConv3DNodeDef(); + AddTestTensor("input", {1, 1, 2, 3}, tf_type_, CreateVectorIota(6)); + AddTestWeights("weights", {3, 3, 1, 1}, {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Conv3D expects kernel of dimension 5"); + } + { + // Dilations is not 5D, should fail. + Reset(); + NodeDef node_def = + GetConv3DNodeDef({1, 1, 1, 1, 1}, "SAME", "NCDHW", {1, 1, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}, tf_type_, CreateVectorIota(6)); + AddTestWeights( + "weights", {3, 3, 1, 1, 1}, + {1, 2, 3, 4, 5, 6, 7, 8, 9}); // Dimensions, then values + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Convolution dilations field must specify 5 dimensions"); + } + { + // Dilation value is not 1 for channel, should fail. + Reset(); + NodeDef node_def = + GetConv3DNodeDef({1, 1, 1, 1, 1}, "SAME", "NCDHW", {1, 2, 1, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}, tf_type_, CreateVectorIota(6)); + AddTestWeights("weights", {3, 3, 1, 1, 1}, + {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Dilation rate must be 1 for batch and channel " + "dimensions"); + } + { + // Dilation value is not 1 for channel (NDHWC), should fail. + Reset(); + NodeDef node_def = + GetConv3DNodeDef({1, 1, 1, 1, 1}, "SAME", "NDHWC", {1, 1, 1, 1, 2}); + AddTestTensor("input", {1, 2, 3, 1}, tf_type_, CreateVectorIota(6)); + AddTestWeights("weights", {3, 3, 1, 1, 1}, + {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Dilation rate must be 1 for batch and channel " + "dimensions"); + } + { + // Dilation + Conv3DBackpropInputV2, should fail. + Reset(); + NodeDef node_def = GetConv3DNodeDef({1, 1, 1, 1, 1}, "SAME", "NDHWC", + {1, 1, 2, 1, 1}, true); + AddTestTensor("input", {1, 2, 3, 1}, tf_type_, CreateVectorIota(6)); + AddTestWeights("weights", {3, 3, 1, 1, 1}, + {1, 2, 3, 4, 5, 6, 7, 8, 9}); + AddTestWeights("input_sizes", {4}, {1, 2, 3, 1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Dilation with Conv3DBackpropInputV2 " + "(conv3d_transpose) is not supported"); + } + { + // Asymmetric+ Conv3DBackpropInputV2, should fail. + Reset(); + NodeDef node_def = GetConv3DNodeDef({1, 1, 1, 1, 1}, "SAME", "NDHWC", + {1, 1, 1, 1, 1}, true); + AddTestTensor("input", {1, 2, 2, 2}, tf_type_, CreateVectorIota(8)); + AddTestWeights("weights", {1, 1, 2, 1, 1}, {1, 1}); + AddTestWeights("input_sizes", {8}, {1, 2, 3, 4, 5, 6, 7, 8}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Asymmetric padding with Conv3DBackpropInputV2 " + "(conv3d_transpose) is not supported"); + } + { + // Strides is not 5D, should fail. + Reset(); + NodeDef node_def = + GetConv3DNodeDef({1, 1, 1, 1, 1, 1}, "SAME", "NCDHW", {1, 1, 1, 1, 1}); + AddTestTensor("input", {1, 2, 2, 2}, tf_type_, CreateVectorIota(8)); + AddTestWeights("weights", {1, 1, 2, 1, 1}, {1, 1}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Convolution strides field must specify 5 dimensions"); + } + { + // Stride value is not 1 for channel, should fail. + Reset(); + NodeDef node_def = + GetConv3DNodeDef({1, 2, 1, 1, 1}, "SAME", "NCDHW", {1, 1, 1, 1, 1}); + AddTestTensor("input", {1, 1, 2, 3}, tf_type_, CreateVectorIota(6)); + AddTestWeights("weights", {3, 3, 1, 1, 1}, + {1, 2, 3, 4, 5, 6, 7, 8, 9}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "Stride must be 1 for batch and channel dimensions"); + } + + // Start here + std::vector ok_params = { + // Basic - just 1x1 conv - input = output + {/*input_dims=*/{1, 1, 3, 3, 3}, // CDHW + /*input=*/{1, 2, 15, 3, 6, -3, 22, 1, 88, 56, 36, 1, 1, 105, + 1, 16, -28, 1, 42, 9, 3, 1, 7, 1, 11, 61, 5}, + /*filter_dims=*/{1, 1, 1, 1, 1}, // DRSCK + /*filter=*/{1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_output=*/{1, 2, 15, 3, 6, -3, 22, 1, 88, + 56, 36, 1, 1, 105, 1, 16, -28, 1, + 42, 9, 3, 1, 7, 1, 11, 61, 5}, + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + // Basic - 2x1 filter + {/*input_dims=*/{1, 1, 3, 3, 3}, // CDHW + /*input=*/{1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 6}, + /*filter_dims=*/{2, 1, 1, 1, 1}, // DRSCK + /*filter=*/{1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 2, 3, 3}, + /*expected_output=*/ + {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 7}, + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + // SAME padding (Asymmetric) + {/*input_dims=*/{1, 1, 2, 3, 2}, // CDHW + /*input=*/{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + /*filter_dims=*/{2, 1, 1, 1, 1}, // DRSCK + /*filter=*/{-1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"SAME", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 2, 3, 2}, + // Diff in first 2 depths is const 6. + /*expected_output=*/{6, 6, 6, 6, 6, 6, -6, -7, -8, -9, -10, -11}, + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + // SAME padding (Symmetric) + {/*input_dims=*/{1, 1, 2, 3, 2}, // CDHW + /*input=*/{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + /*filter_dims=*/{3, 1, 1, 1, 1}, // DRSCK + /*filter=*/{-1, 0, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"SAME", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 2, 3, 2}, + // Swaps front two depths, negates + /*expected_output=*/{6, 7, 8, 9, 10, 11, 0, -1, -2, -3, -4, -5}, + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus() + + }, + // NDHWC (multi-channel) + {/*input_dims=*/{1, 2, 3, 2, 2}, // DHWC + /*input=*/{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, + 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, + /*filter_dims=*/{2, 1, 1, 2, 1}, // DRSCK + /*filter=*/{-1, 1, 1, -1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NDHWC", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 3, 2, 1}, + /*expected_output=*/{0, 0, 0, 0, 0, 0}, // Filters oppose each-other + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + // Dilated + {/*input_dims=*/{1, 1, 3, 3, 3}, // CDHW + /*input=*/{1, 1, 1, 1, 1, 1, 1, 1, 1, -10, -10, -10, -10, -10, + -10, -10, -10, -10, 7, 7, 7, 7, 7, 7, 7, 7, 7}, + /*filter_dims=*/{2, 1, 1, 1, 1}, // DRSCK + /*filter=*/{1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 2, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 1, 3, 3}, + // Only front depth is valid, skips neg values + /*expected_output=*/{8, 8, 8, 8, 8, 8, 8, 8, 8}, + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + // Strided + {/*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/{1, 0, 2, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 5, 0, 6, 0, 0, 0, 7, 0, 8}, + /*filter_dims=*/{1, 1, 1, 1, 1}, + /*filter=*/{1}, + /*strides=*/{1, 1, 2, 2, 2}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{1, 1, 2, 2, 2}, + // Should only pick up the corners + /*expected_output=*/{1, 2, 3, 4, 5, 6, 7, 8}, + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + // Transpose Strided + {/*input_dims=*/{1, 1, 2, 2, 2}, // CDHW + /*input=*/{1, 2, 3, 4, 5, 6, 7, 8}, + /*filter_dims=*/{1, 1, 1, 1, 1}, + /*filter=*/{1}, + /*strides=*/{1, 1, 2, 2, 2}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/true, + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_output=*/{1, 0, 2, 0, 0, 0, 3, 0, 4, // Cube expands and + 0, 0, 0, 0, 0, 0, 0, 0, 0, // fills center + 5, 0, 6, 0, 0, 0, 7, 0, 8}, // with zeroes + /*allow_dynamic_channel_dim=*/false, + /*validation_status=*/OkStatus()}, + }; + + if (trt_mode_ == TrtTestMode::kDynamicShape) { + ok_params.reserve(ok_params.size() + 2); + const std::vector common_input = CreateVectorIota(3 * 3 * 3); + // NCDHW - Dynamic Channel - Should fail in kDynamicShape + ok_params.push_back(Conv3DTestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*filter_dims=*/{1, 1, 1, 1, 1}, + /*filter=*/{1}, + /*strides=*/{1, 1, 2, 2, 2}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{}, // ignore, will fail anyway + /*expected_output=*/{}, // ignore, will fail anyway + /*allow_dynamic_channel_dim=*/true, + /*validation_status=*/ + Status{absl::StatusCode::kInvalidArgument, + "Channel dimension must be static"}}); + // NDHWC - Dynamic Channel - Should fail in kDynamicShape + ok_params.push_back(Conv3DTestParams{ + /*input_dims=*/{1, 3, 3, 3, 1}, + /*input=*/common_input, + /*filter_dims=*/{1, 1, 1, 1, 1}, + /*filter=*/{1}, + /*strides=*/{1, 2, 2, 2, 1}, + /*padding=*/"VALID", + /*data_format=*/"NDHWC", + /*dilations=*/{1, 1, 1, 1, 1}, + /*is_conv3d_backprop=*/false, + /*expected_output_dims=*/{}, // ignore, will fail anyway + /*expected_output=*/{}, // ignore, will fail anyway + /*allow_dynamic_channel_dim=*/true, + /*validation_status=*/ + Status{absl::StatusCode::kInvalidArgument, + "Channel dimension must be static"}}); + } + + for (auto p : ok_params) { + TestConv3D(this, p); + } +} + +template +NodeDef CreatePoolOp(DataType tf_type, std::vector ksize, + std::vector strides, string padding, + string data_format) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + typename T::Attrs attrs; + attrs.data_format_ = data_format; + return T(s.WithOpName("my_pool"), input, ksize, strides, padding, attrs) + .operation.node() + ->def(); +} +TEST_P(OpConverter_FP32_Test, ConvertPool) { + // Get nodedef for MaxPool and AvgPool layers (2D or 3D). + auto get_pool_nodedef = + [](DataType tf_type, int nDim, std::vector ksize = {}, + std::vector strides = {}, string padding = "SAME", + string data_format = "", const bool is_max_pooling = true) -> NodeDef { + if (ksize.empty()) { + ksize = nDim == 2 ? std::vector{1, 1, 1, 1} + : std::vector{1, 1, 1, 1, 1}; + } + if (strides.empty()) { + strides = nDim == 2 ? std::vector{1, 1, 1, 1} + : std::vector{1, 1, 1, 1, 1}; + } + if (data_format == "") { + data_format = nDim == 2 ? "NCHW" : "NCDHW"; + } + if (is_max_pooling) { + if (nDim == 3) { + return CreatePoolOp(tf_type, ksize, strides, padding, + data_format); + } else { + return CreatePoolOp(tf_type, ksize, strides, padding, + data_format); + } + } else { + if (nDim == 3) { + return CreatePoolOp(tf_type, ksize, strides, padding, + data_format); + } else { + return CreatePoolOp(tf_type, ksize, strides, padding, + data_format); + } + } + }; + + std::vector test_nDims{2, 3}; + + for (int nDim : test_nDims) { + // Input is weights, should fail. + Reset(); + NodeDef node_def = get_pool_nodedef(tf_type_, nDim); + + AddTestWeights("input", {1, 1, 1, 2, 3}, {1, 2, 3, 4, 5, 6}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + StrCat("The input \"input\" for ", node_def.op(), " must be a tensor")); + } + + struct TestParams { + std::vector input_dims; + std::vector input; + std::vector ksize; + std::vector strides; + string padding; + string data_format; + std::vector expected_output_dims; + // The expected outputs for the following operations: MaxPool2D, AvgPool2D, + // MaxPool3D, AvgPool3D + std::vector> expected_outputs; + Status status; + std::set skip_dims; + }; + + // We use common_input as the input to test both 2D and 3D pooling operations, + // to simplify TestParams. For 2D operations, only the first 1/3 of the values + // are used. + const std::vector common_input{-4, 2, 15, 3, 6, -3, 22, 1, 88, + 56, 36, 1, 1, 105, 1, 16, -28, 1, + 42, 9, 3, 1, 7, 1, 11, 61, 5}; + // The output of 2D ops for the case where the op is equivalent to the + // identity op. + const std::vector common_2d_output{-4, 2, 15, 3, 6, -3, 22, 1, 88}; + std::vector test_params = { + // Validation failure - kernel size too large for TRT + TestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, 1000, 1000, 1000}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_outputs=*/ + {common_2d_output, common_2d_output, common_input, common_input}, + /*status=*/ + Status(absl::StatusCode::kInvalidArgument, + "Window dimensions are not within bounds")}, + // Validation failure for 3D ops - negative kernel depth + TestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, -1, 1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_outputs=*/ + {common_2d_output, common_2d_output, common_input, common_input}, + /*status=*/ + Status(absl::StatusCode::kInvalidArgument, + "Window dimensions are not within bounds"), + /*skip_dims=*/{2}}, + // Validation failure - negative kernel height + TestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, 1, -1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_outputs=*/ + {common_2d_output, common_2d_output, common_input, common_input}, + /*status=*/ + Status(absl::StatusCode::kInvalidArgument, + "Window dimensions are not within bounds")}, + // Validation failure - negative kernel width + TestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, 1, 1, -1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_outputs=*/ + {common_2d_output, common_2d_output, common_input, common_input}, + /*status=*/ + Status(absl::StatusCode::kInvalidArgument, + "Window dimensions are not within bounds")}, + // Basic - just 1x1 max pooling - input = output + TestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, 1, 1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_outputs=*/ + {common_2d_output, common_2d_output, common_input, common_input}}, + // Basic - just 1x1 max pooling - input = output, SAME padding + TestParams{ + /*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, 1, 1, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"SAME", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 3, 3, 3}, + /*expected_outputs=*/ + {common_2d_output, common_2d_output, common_input, common_input}}, + // 3x3 pooling NCDHW + TestParams{/*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/common_input, + /*ksize=*/{1, 1, 3, 3, 3}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 1, 1, 1}, + /*expected_outputs=*/{{88}, {14.444445}, {105}, {17}}}, + // 3x3 pooling, NDHWC + TestParams{/*input_dims=*/{1, 3, 3, 3, 1}, + /*input=*/common_input, + /*ksize=*/{1, 3, 3, 3, 1}, + /*strides=*/{1, 1, 1, 1, 1}, + /*padding=*/"VALID", + /*data_format=*/"NDHWC", + /*expected_output_dims=*/{1, 1, 1, 1, 1}, + /*expected_outputs=*/{{88}, {14.444445}, {105}, {17}}}, + // Strided + TestParams{/*input_dims=*/{1, 1, 3, 3, 3}, + /*input=*/{1, 0, 2, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 5, 0, 6, 0, 0, 0, 7, 0, 8}, + /*ksize=*/{1, 1, 1, 1, 1}, + /*strides=*/{1, 1, 2, 2, 2}, + /*padding=*/"VALID", + /*data_format=*/"NCDHW", + /*expected_output_dims=*/{1, 1, 2, 2, 2}, + /*expected_outputs=*/ + {{1, 2, 3, 4}, // Should only pick up the corners + {1, 2, 3, 4}, + {1, 2, 3, 4, 5, 6, 7, 8}, + {1, 2, 3, 4, 5, 6, 7, 8}}}, + }; + + for (auto p : test_params) { + int test_counter = 0; + for (int nDim : test_nDims) { + if (p.skip_dims.find(nDim) != p.skip_dims.end()) { + continue; + } + auto input = p.input; + auto input_dims = p.input_dims; + auto ksize = p.ksize; + auto strides = p.strides; + auto expected_output_dims = p.expected_output_dims; + std::string data_format = p.data_format; + if (nDim == 2) { + input.resize(9); + data_format = p.data_format == "NDHWC" ? "NHWC" : "NCHW"; + // Remove one of the spatial dimensions + input_dims.erase(input_dims.begin() + 2); + ksize.erase(ksize.begin() + 2); + strides.erase(strides.begin() + 2); + expected_output_dims.erase(expected_output_dims.begin() + 2); + } + for (bool is_max_pooling : {true, false}) { + Reset(); + NodeDef node = get_pool_nodedef(tf_type_, nDim, ksize, strides, + p.padding, data_format, is_max_pooling); + AddTestTensor("input", input_dims, input); + TestOpConverter(node, expected_output_dims, p.status, OkStatus(), + ElementsAreArray(p.expected_outputs.at(test_counter))); + test_counter++; + } + } + } +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertTopK) { + // Get the NodeDef for TopKV2. + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type_); + auto weights = ops::Placeholder(s.WithOpName("weights"), DT_INT32); + auto topk = ops::TopK(s.WithOpName("my_topk"), input, weights); + const NodeDef& node_def = topk.operation.node()->def(); + { + // K is a tensor, should fail. + Reset(); + AddTestTensor("input", {1, 1, 2, 3}); + AddTestTensor("weights", {1}, DT_INT32, {}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"k\" for TopKV2 must be a constant"); + } + { + // Ok. + Reset(); + AddTestTensor("input", {1, 1, 2, 5}, {-9, 3, 5, 1, 6, -5, 7, 1, 0, -1}); + AddTestWeights("weights", {1}, {2}); + std::vector> expected_output_dims{{1, 1, 2, 2}, + {1, 1, 2, 2}}; + TestOpConverterMultiOut(node_def, expected_output_dims, OkStatus(), + OkStatus(), + {ElementsAre(6, 5, 7, 1), ElementsAre(4, 2, 1, 2)}, + {tf_type_, DT_INT32}); + } +} + +struct DataFormatVecPermuteTestParams { + string dst_format; + string src_format; + std::vector x_shape; + std::vector x; + bool x_is_tensor; + std::vector expected_output; + Status conversion_status; +}; + +NodeDef GetDataFormatVecPermuteNodeDef(string dst_format, string src_format, + std::vector& x_shape) { + Scope s = Scope::NewRootScope(); + PartialTensorShape tensor_shape; + auto x = ops::Placeholder(s.WithOpName("x"), DT_INT32); + const auto attrs = ops::DataFormatVecPermute::Attrs() + .DstFormat(dst_format) + .SrcFormat(src_format); + auto dfvp = ops::DataFormatVecPermute(s.WithOpName("my_dfvp"), x, attrs); + return dfvp.operation.node()->def(); +} + +TEST_P(OpConverter_INT32_Test, ConvertDataFormatVecPermute) { + const auto& error = convert_not_supported_implicit( + string("DataFormatVecPermute"), string("my_dfvp")); + const Status implicit_error = Status{absl::StatusCode::kUnimplemented, error}; + const auto conversion_status = + trt_mode_ == TrtTestMode::kImplicitBatch ? implicit_error : OkStatus(); + std::vector test_params = { + // 1D case with tensor. + DataFormatVecPermuteTestParams{/*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{4}, + /*x=*/{1, 2, 3, 4}, + /*x_is_tensor=*/true, + /*expected_output=*/{1, 4, 2, 3}, + /*conversion_status=*/conversion_status}, + // 1D case with weights. + DataFormatVecPermuteTestParams{/*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{4}, + /*x=*/{1, 2, 3, 4}, + /*x_is_tensor=*/false, + /*expected_output=*/{1, 4, 2, 3}, + /*conversion_status=*/conversion_status}, + // 2D case with tensor. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{4, 2}, + /*x=*/{1, 2, 3, 4, 5, 6, 7, 8}, + /*x_is_tensor=*/true, + /*expected_output=*/{1, 2, 7, 8, 3, 4, 5, 6}, + /*conversion_status=*/conversion_status}, + // 2D case with weights. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{4, 2}, + /*x=*/{1, 2, 3, 4, 5, 6, 7, 8}, + /*x_is_tensor=*/false, + /*expected_output=*/{1, 2, 7, 8, 3, 4, 5, 6}, + /*conversion_status=*/conversion_status}, + // Format of size 5. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCDHW", + /*src_format=*/"NDHWC", + /*x_shape=*/{5, 2}, + /*x=*/{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, + /*x_is_tensor=*/true, + /*expected_output=*/{1, 2, 9, 10, 3, 4, 5, 6, 7, 8}, + /*conversion_status=*/conversion_status}, + // Input of size 2: treat the elements as spatial dimensions. + DataFormatVecPermuteTestParams{/*dst_format=*/"NCWH", + /*src_format=*/"NHWC", + /*x_shape=*/{2, 2}, + /*x=*/{1, 2, 3, 4}, + /*x_is_tensor=*/true, + /*expected_output=*/{3, 4, 1, 2}, + /*conversion_status=*/conversion_status}, + // Input of size 3: treat the elements as spatial dimensions. + DataFormatVecPermuteTestParams{/*dst_format=*/"NCHWD", + /*src_format=*/"NDHWC", + /*x_shape=*/{3}, + /*x=*/{1, 2, 3}, + /*x_is_tensor=*/true, + /*expected_output=*/{2, 3, 1}, + /*conversion_status=*/conversion_status}, + // Invalid rank, should fail. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{2, 2, 2}, + /*x=*/{1, 2, 3, 4, 5, 6, 7, 8}, + /*x_is_tensor=*/true, + /*expected_output=*/{}, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? implicit_error + : Status{absl::StatusCode::kInvalidArgument, + "Input must be a vector or matrix, but got rank 3, at " + "my_dfvp"}}, + // Invalid size for 1D input, should fail. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{3}, + /*x=*/{1, 2, 3}, + /*x_is_tensor=*/true, + /*expected_output=*/{}, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? implicit_error + : Status{absl::StatusCode::kInvalidArgument, + "1D input must be of size 2 or 4, but got size 3, at " + "my_dfvp"}}, + // Invalid first dim for 2D input, should fail. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCDHW", + /*src_format=*/"NDHWC", + /*x_shape=*/{4, 2}, + /*x=*/{1, 2, 3, 4, 5, 6, 7, 8}, + /*x_is_tensor=*/true, + /*expected_output=*/{}, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? implicit_error + : Status{absl::StatusCode::kInvalidArgument, + "First dimension of 2D input must be of size 3 or 5, " + "but got shape (4, 2), at my_dfvp"}}, + // Invalid second dim for 2D input, should fail. + DataFormatVecPermuteTestParams{ + /*dst_format=*/"NCHW", + /*src_format=*/"NHWC", + /*x_shape=*/{4, 3}, + /*x=*/{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}, + /*x_is_tensor=*/true, + /*expected_output=*/{}, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? implicit_error + : Status{absl::StatusCode::kInvalidArgument, + "Second dimension of 2D input must be of size 2, but " + "got shape (4, 3), at my_dfvp"}}, + }; + + for (auto p : test_params) { + Reset(); + const NodeDef node_def = + GetDataFormatVecPermuteNodeDef(p.dst_format, p.src_format, p.x_shape); + + if (p.x_is_tensor) { + AddTestTensor("x", p.x_shape, DT_INT32, p.x, p.x_shape); + } else { + AddTestWeights("x", p.x_shape, p.x, DT_INT32); + } + + TestOpConverter(node_def, p.x_shape, p.conversion_status, OkStatus(), + ElementsAreArray(p.expected_output)); + } +} + +NodeDef CreateGatherOp(DataType tf_type, int batch_dims) { + // Get the NodeDef for GatherV2. + Scope s = Scope::NewRootScope(); + auto params = ops::Placeholder(s.WithOpName("params"), tf_type); + auto indices = ops::Placeholder(s.WithOpName("indices"), DT_INT32); + auto axis = ops::Placeholder(s.WithOpName("axis"), DT_INT32); + ops::GatherV2::Attrs op_attrs; + op_attrs.batch_dims_ = batch_dims; + auto gather = + ops::GatherV2(s.WithOpName("my_gather"), params, indices, axis, op_attrs); + const NodeDef& node_def = gather.operation.node()->def(); + return node_def; +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertGather) { + auto node_def = CreateGatherOp(tf_type_, /*batch_dims*/ 0); + + { + // Axis is a tensor, should fail. + Reset(); + AddTestTensor("params", {1, 1, 2, 3}, tf_type_, {}); + AddTestTensor("indices", {1, 2}, DT_INT32, {}); + AddTestTensor("axis", {1}, DT_INT32, {}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"axis\" for GatherV2 must be a constant"); + } + { + // Axis is out of bounds, should fail. + Reset(); + AddTestTensor("params", {1, 1, 2, 3}); + AddTestTensor("indices", {1, 2}, DT_INT32, {}); + AddTestWeights("axis", {1}, {4}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Axis value of 4 is out of bounds, must be in " + "range [-4, 4)"); + } + + struct TestParams { + // TF shape of the input 'params' (including batch dimension). + std::vector params_shape; + // TF shape of the input 'indices' (including batch dimension). + std::vector indices_shape; + std::vector indices; + int axis; + int batch_dims; + // Expected TF shape of the output (including batch dimension). + std::vector expected_output_shape; + std::vector expected_output; + bool params_is_tensor; + bool indices_is_tensor; + Status conversion_status; + Status runtime_status; + Status add_index_status; + }; + + // Input is the same {1, 2, 3, 4, 5, 6} for all cases. + const std::vector params_input = {1, 2, 3, 4, 5, 6}; + + std::vector test_params = { + // Axis is batch dimension, should fail in implicit batch mode. + TestParams{/*params_shape=*/{2, 1, 1, 3}, + /*indices_shape=*/{2}, + /*indices=*/{1, 0}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{2, 1, 1, 3}, + /*expected_output=*/{4, 5, 6, 1, 2, 3}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "TensorRT does not allow " + "manipulation of the batch dimension"} + : OkStatus()}, + // Batch size of indices is not 1 when params and indices are tensors. + TestParams{/*params_shape=*/{2, 1, 3}, + /*indices_shape=*/{2, 1}, + /*indices=*/{2, 0}, + /*axis=*/2, + /*batch_dims=*/0, + /*expected_output_shape=*/{2, 1, 2, 1}, + /*expected_output=*/{3, 1, 6, 4}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "Params and indices must have a" + " batch size of 1 when params and indices are " + "both tensors or both" + " constants."} + : OkStatus()}, + // Batch size of indices is not 1 when params is tensor and indices are + // constant. + TestParams{/*params_shape=*/{2, 1, 3}, + /*indices_shape=*/{2, 1}, + /*indices=*/{2, 0}, + /*axis=*/2, + /*batch_dims=*/0, + /*expected_output_shape=*/{2, 1, 2, 1}, + /*expected_output=*/{3, 1, 6, 4}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/false, + /*conversion_status=*/OkStatus()}, + // Axis is not zero when params is a weight, should fail in implicit batch + // mode. + TestParams{/*params_shape=*/{2, 1, 3}, + /*indices_shape=*/{2}, + /*indices=*/{1, 2}, + /*axis=*/2, + /*batch_dims=*/0, + /*expected_output_shape=*/{2, 1, 2}, + /*expected_output=*/{2, 3, 5, 6}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/true, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "The input axis must be zero when " + "params is a weight."} + : OkStatus()}, + // Params with only batch dimension. + TestParams{ + /*params_shape=*/{6}, + /*indices_shape=*/{2}, + /*indices=*/{1, 3}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{2}, + /*expected_output=*/{2, 4}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "TensorRT does not allow " + "manipulation of the batch dimension"} + : OkStatus(), + /*runtime_status=*/OkStatus(), + /*add_index_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kInvalidArgument, + batch_size_error("indices", + "Provided batch size does not match " + "converter batch size: 2 vs 6")} + : OkStatus()}, + // Vector indices, and output rank is rank(params). + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1}, + /*indices=*/{0}, + /*axis=*/3, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 1}, + /*expected_output=*/{1, 4}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1}, + /*indices=*/{1}, + /*axis=*/2, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 1, 3}, + /*expected_output=*/{4, 5, 6}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + // Indices with rank>1, and output rank is rank(params) + rank(indices) - + // 1 + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1, 1}, + /*indices=*/{0}, + /*axis=*/3, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 1, 1}, + /*expected_output=*/{1, 4}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1, 1}, + /*indices=*/{1}, + /*axis=*/3, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 1, 1}, + /*expected_output=*/{2, 5}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1, 1}, + /*indices=*/{2}, + /*axis=*/-1, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 1, 1}, + /*expected_output=*/{3, 6}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1, 3}, + /*indices=*/{2, 0, 1}, + /*axis=*/3, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 1, 3}, + /*expected_output=*/{3, 1, 2, 6, 4, 5}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{1, 3, 2}, + /*indices_shape=*/{1, 2, 2}, + /*indices=*/{0, 0, 1, 0}, + /*axis=*/2, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 3, 1, 2, 2}, + /*expected_output=*/{1, 1, 2, 1, 3, 3, 4, 3, 5, 5, 6, 5}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{1, 2, 3}, + /*indices_shape=*/{1}, + /*indices=*/{0}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 2, 3}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{3, 2}, + /*indices_shape=*/{1, 2}, + /*indices=*/{0, 1}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 2, 2}, + /*expected_output=*/{1, 2, 3, 4}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{2, 3}, + /*indices_shape=*/{1, 1, 2}, + /*indices=*/{0, 1}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 3}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/true, + }, + TestParams{ + /*params_shape=*/{3, 2}, + /*indices_shape=*/{2, 2}, + /*indices=*/{0, 2, 1, 0}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{2, 2, 2}, + /*expected_output=*/{1, 2, 5, 6, 3, 4, 1, 2}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/true, + }, + // Test cases in which indices constant + TestParams{ + /*params_shape=*/{1, 1, 2, 3}, + /*indices_shape=*/{1, 1}, + /*indices=*/{0}, + /*axis=*/3, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 1, 2, 1, 1}, + /*expected_output=*/{1, 4}, + /*params_is_tensor=*/true, + /*indices_is_tensor=*/false, + }, + // Test cases in which both input and indices constant + TestParams{/*params_shape=*/{1, 2, 3}, + /*indices_shape=*/{1}, + /*indices=*/{0}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{1, 2, 3}, + /*expected_output=*/{1, 2, 3, 4, 5, 6}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/false, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "Params and indices must have a" + " batch size of 1 when params and indices are " + "both tensors or both" + " constants."} + : OkStatus()}, + TestParams{/*params_shape=*/{3, 2}, + /*indices_shape=*/{2, 2}, + /*indices=*/{0, 2, 1, 0}, + /*axis=*/0, + /*batch_dims=*/0, + /*expected_output_shape=*/{2, 2, 2}, + /*expected_output=*/{1, 2, 5, 6, 3, 4, 1, 2}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/false, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "Params and indices must have a" + " batch size of 1 when params and indices are " + "both tensors or both" + " constants."} + : OkStatus()}, + TestParams{ + /*params_shape=*/{2, 3}, + /*indices_shape=*/{2, 2}, + /*indices=*/{0, 1, 1, 2}, + /*axis=*/1, + /*batch_dims=*/1, + /*expected_output_shape=*/{2, 2}, + /*expected_output=*/{1, 2, 5, 6}, + /*params_is_tensor=*/false, + /*indices_is_tensor=*/false, + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "The input axis must be zero when params is a weight."} + : OkStatus()}, + }; + + for (auto p : test_params) { + Reset(); + + auto node_def = CreateGatherOp(tf_type_, p.batch_dims); + + if (p.params_is_tensor) { + AddTestTensor("params", p.params_shape, params_input); + } else { + AddTestWeights("params", p.params_shape, params_input, tf_type_); + } + + if (p.indices_is_tensor) { + AddTestTensor("indices", p.indices_shape, DT_INT32, p.indices, {}, + p.add_index_status); + } else { + std::vector indices_shape(p.indices_shape); + AddTestWeights("indices", indices_shape, p.indices, DT_INT32); + } + + AddTestWeights("axis", {1}, {p.axis}); + TestOpConverter(node_def, p.expected_output_shape, p.conversion_status, + p.runtime_status, ElementsAreArray(p.expected_output)); + } +} + +template +NodeDef CreateReduceOp(DataType tf_type, bool keep_dims) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), tf_type); + auto axis = ops::Placeholder(s.WithOpName("axis"), DT_INT32); + typename OpType::Attrs op_attrs; + op_attrs.keep_dims_ = keep_dims; + auto op = OpType(s.WithOpName("my_reduce"), input, axis, op_attrs); + return op.operation.node()->def(); +} + +// Applies reduction op on sub-sequences of input +// output[i] = reduce(input[m * i : m * (i +1)]) +std::vector CalcReduce(string op_name, std::vector input, int m, + float (*op)(float, float), float init) { + std::vector output(input.size() / m); + for (int i = 0; i < output.size(); i++) { + auto begin = input.begin() + i * m; + auto end = input.begin() + (i + 1) * m; + output[i] = std::accumulate(begin, end, init, op); + if (op_name == "Mean") { + output[i] /= m; + } + } + return output; +} +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertReduce) { + { + // Input is weights, should fail. + Reset(); + const NodeDef node_def = CreateReduceOp(tf_type_, false); + AddTestWeights("input", {1, 2, 3}, {-3, -2, -1, 0, 1, 2}); + AddTestWeights("axis", {1}, {1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"input\" for Sum must be a tensor"); + } + { + // Axis is weights, should fail. + Reset(); + const NodeDef node_def = CreateReduceOp(tf_type_, false); + AddTestTensor("input", {1, 2, 3}, {-3, -2, -1, 0, 1, 2}); + AddTestTensor("axis", {1}, DT_INT32, {1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"axis\" for Sum must be a constant"); + } + using OpFunc = std::function; + using ValFunc = float (*)(float, float); + struct ReduceTestDescriptor { + string name; + OpFunc get_node; + ValFunc val_func; + float init_val; + }; + std::vector op_test_info{ + {"Sum", CreateReduceOp, [](float x, float y) { return x + y; }, + 0}, + {"Prod", CreateReduceOp, + [](float x, float y) { return x * y; }, 1}, + {"Mean", CreateReduceOp, + [](float x, float y) { return x + y; }, 0}, + {"Min", CreateReduceOp, + [](float x, float y) { return y < x ? y : x; }, 1000}, + {"Max", CreateReduceOp, + [](float x, float y) { return x < y ? y : x; }, -1000}}; + + std::vector input_values{1, 2, 3, 4, 5, 6}; + struct TestParams { + std::vector input_dims; + std::vector input_values; + // Helper array contains the same elements as input but permuted in a way + // that the reduction can be calculated over contiguous elements using + // CalcReduce + std::vector helper_array; + std::vector axis; + int stride; // product of input_dims along axis + Status conversion_status; + }; + std::vector params{ + // Out of range tests + TestParams{{2, 3, 1}, input_values, input_values, {3}, 3}, + TestParams{{2, 3, 1}, input_values, input_values, {-4}, 3}, + // Ok tests + TestParams{{2, 3, 1}, input_values, {1, 4, 2, 5, 3, 6}, {0}, 2}, + TestParams{{2, 3, 1}, input_values, input_values, {1}, 3}, + TestParams{{2, 3, 1}, input_values, input_values, {2}, 1}, + TestParams{{2, 3, 1}, input_values, input_values, {0, 1}, 6}, + // Ok tests with negative axis values + TestParams{{2, 3, 1}, input_values, {1, 4, 2, 5, 3, 6}, {-3}, 2}, + TestParams{{2, 3, 1}, input_values, input_values, {-2}, 3}, + TestParams{{2, 3, 1}, input_values, input_values, {-1}, 1}, + TestParams{{2, 3, 1}, input_values, input_values, {-3, 1}, 6}, + }; + + for (bool keep_dims : {false, true}) { + for (auto& op : op_test_info) { + VLOG(2) << "Processing " << op.name << " with keep_dims=" << keep_dims; + for (auto p : params) { + SCOPED_TRACE(StrCat(op.name, keep_dims ? " & keep_dims" : "")); + Reset(); + NodeDef node_def = op.get_node(tf_type_, keep_dims); + + AddTestTensor("input", p.input_dims, p.input_values); + AddTestWeights("axis", {static_cast(p.axis.size())}, + p.axis); + std::vector expected_output_dims(p.input_dims); + + // Set expected output dim and conversion error messages + for (int ax : p.axis) { + int rank = p.input_dims.size(); + if (ax >= rank || ax < -rank) { + p.conversion_status = + errors::InvalidArgument("Axis value of ", ax, + " is out of bounds, must be in " + "range [", + -rank, ", ", rank, ")"); + } else { + int ax_positive = ax >= 0 ? ax : ax + rank; + // Zero marks elements that we will remove later. + expected_output_dims[ax_positive] = keep_dims ? 1 : 0; + if (trt_mode_ == TrtTestMode::kImplicitBatch && + (ax == 0 || ax == -rank)) { + p.conversion_status = errors::Unimplemented( + "TensorRT does not allow manipulation of the batch " + "dimension"); + } + } + } + expected_output_dims.erase(std::remove(expected_output_dims.begin(), + expected_output_dims.end(), 0), + expected_output_dims.end()); + VLOG(2) << "out dims " + << absl::StrCat("[", absl::StrJoin(expected_output_dims, ","), + "]"); + std::vector expected_values = CalcReduce( + op.name, p.helper_array, p.stride, op.val_func, op.init_val); + + if (tf_type_ == DT_INT32) { + // We need to floor the float values in the `expected_values` vector. + std::for_each(expected_values.begin(), expected_values.end(), + [](float& _n) { _n = std::floor(_n); }); + } + + TestOpConverter(node_def, expected_output_dims, p.conversion_status, + OkStatus(), ArrayFloatNear(expected_values)); + } + } + } +} + +NodeDef CreateCastOp(DataType tf_type) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), DT_HALF); + return ops::Cast(s.WithOpName("my_unary"), input, DT_FLOAT) + .operation.node() + ->def(); +} + +TEST_P(OpConverter_FP32_UnaryTest, ConvertUnary) { + using OpFunc = std::function; + using ValFunc = float (*)(float); + std::map> op_map; +#define ADD_OP(name, op, compute) \ + op_map[name] = \ + std::make_pair(CreateUnaryOp, static_cast(compute)) + ADD_OP("Abs", ops::Abs, std::abs); + ADD_OP("Acos", ops::Acos, std::acos); + ADD_OP("Acosh", ops::Acosh, std::acosh); + ADD_OP("Asin", ops::Asin, std::asin); + ADD_OP("Asinh", ops::Asinh, std::asinh); + ADD_OP("Atan", ops::Atan, std::atan); + ADD_OP("Atanh", ops::Atanh, std::atanh); + op_map["Cast"] = std::make_pair(CreateCastOp, [](float x) { return x; }); + ADD_OP("Ceil", ops::Ceil, std::ceil); + ADD_OP("Cos", ops::Cos, std::cos); + ADD_OP("Cosh", ops::Cosh, std::cosh); + ADD_OP("Exp", ops::Exp, std::exp); + ADD_OP("Erf", ops::Erf, std::erf); + ADD_OP("Floor", ops::Floor, std::floor); + ADD_OP("Log", ops::Log, std::log); + ADD_OP("Neg", ops::Neg, [](float x) { return -x; }); + ADD_OP("Reciprocal", ops::Reciprocal, [](float x) { return 1.0f / x; }); +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + ADD_OP("Round", ops::Round, [](float x) { return (float)std::round(x); }); + ADD_OP("Sign", ops::Sign, + [](float x) { return x > 0 ? 1.0f : (x < 0 ? -1.0f : 0.0f); }); +#endif + ADD_OP("Rsqrt", ops::Rsqrt, [](float x) { return 1.0f / std::sqrt(x); }); + ADD_OP("Sin", ops::Sin, std::sin); + ADD_OP("Sinh", ops::Sinh, std::sinh); + ADD_OP("Sqrt", ops::Sqrt, std::sqrt); + ADD_OP("Tan", ops::Tan, std::tan); +#undef ADD_OP + + std::vector input_values{-0.9f, 0.6f, 0.0f, -3.5f, 100.0f, 2.9f}; + RunTests("Unary", *UnaryOperationMap(), op_map, input_values, "x"); +} + +TEST_P(OpConverter_BOOL_Test, ConvertBoolean) { + std::vector input_values{1, 0, 1, 0, 0, 1}; + using OpFunc = std::function; + + using ValFunc = int (*)(int); + std::map> op_map; +#define ADD_OP(name, op, compute) \ + op_map[name] = \ + std::make_pair(CreateUnaryOp, static_cast(compute)) + ADD_OP("LogicalNot", ops::LogicalNot, [](int x) { return 1 - x; }); +#undef ADD_OP + +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + // The test does not actually run for TPT versions less than 8.2 + RunTests("LogicalUnary", *UnaryBooleanOperationMap(), op_map, input_values, + "x"); +#endif +} + +// Get the NodeDef for ConcatV2. +// TODO(hinsu): Consider switching this to static function. +auto get_concat_nodedef = [](DataType dtype, int num_inputs) -> NodeDef { + Scope s = Scope::NewRootScope(); + std::vector values; + values.reserve(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + const string input_name = StrCat("values_", i); + values.push_back(ops::Placeholder(s.WithOpName(input_name), dtype)); + } + auto axis = ops::Placeholder(s.WithOpName("axis"), DT_INT32); + auto concat = ops::Concat(s.WithOpName("my_concat"), + absl::Span(values), axis); + return concat.operation.node()->def(); +}; + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertConcat) { + { + // Axis is a tensor, should fail. + Reset(); + NodeDef node_def = get_concat_nodedef(tf_type_, 2); + AddTestTensor("values_0", {1, 1, 2, 3}); + AddTestTensor("values_1", {1, 1, 2, 3}); + AddTestTensor("axis", {1}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"axis\" for ConcatV2 must be a constant"); + } + { + // Axis is out of bounds, should fail. + Reset(); + NodeDef node_def = get_concat_nodedef(tf_type_, 2); + AddTestTensor("values_0", {1, 1, 2, 3}); + AddTestTensor("values_1", {1, 1, 2, 3}); + AddTestWeights("axis", {1}, {4}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Axis value of 4 is out of bounds, must be in " + "range [-4, 4)"); + } + { + // Inputs have inconsistent ranks, should fail. + Reset(); + NodeDef node_def = get_concat_nodedef(tf_type_, 2); + AddTestTensor("values_0", {1, 1, 2, 3}); + AddTestTensor("values_1", {1, 1, 6}); + AddTestWeights("axis", {1}, {1}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Received inputs with inconsistent rank"); + } + + struct TestParams { + std::vector> input_shapes; + std::vector> input_values; + std::vector inputs_are_tensors; + int axis; + std::vector expected_output_dims; + std::vector expected_output; + Status conversion_status; + Status run_status; + }; + + const std::vector> common_input{CreateVectorIota(6), + CreateVectorIota(6, 6)}; + + std::vector params = { + { + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 2, 3}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{true, true}, + /*axis=*/1, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + }, + { + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 2, 3}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{true, true}, + /*axis=*/2, + /*expected_output_dims=*/{1, 1, 4, 3}, + /*expected_output=*/CreateVectorIota(12), + }, + { + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 2, 3}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{true, true}, + /*axis=*/3, + /*expected_output_dims=*/{1, 1, 2, 6}, + /*expected_output=*/ + {0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11}, + }, + { + /*input_shapes=*/{{1, 1}, {1, 2}, {1, 3}, {1, 1}, {1, 1}, {1, 2}}, + /*input_values=*/ + {{1}, {2, 3}, {4, 5, 6}, {7}, {8}, {9, 10}}, + /*inputs_are_tensors=*/{true, true, true, true, true, true}, + /*axis=*/1, + /*expected_output_dims=*/{1, 10}, + /*expected_output=*/ + CreateVectorIota(10, /*start_value=*/1), + }, + { + // An input is a weight + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 2, 3}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{true, false}, + /*axis=*/1, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented( + "The input \"values_1\" for ConcatV2 must be a tensor") + : OkStatus(), + /*run_status=*/OkStatus(), + }, + { + // An input is a weight + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 2, 3}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{false, false}, + /*axis=*/1, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented( + "The input \"values_0\" for ConcatV2 must be a tensor") + : OkStatus(), + /*run_status=*/OkStatus(), + }, + { + // Axis is batch dimension, should fail in implicit batch mode. + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 2, 3}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{true, true}, + /*axis=*/0, + /*expected_output_dims=*/{2, 1, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + /*conversion_status=*/trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented( + "TensorRT does not allow manipulation of the " + "batch dimension") + : OkStatus(), + }, + { + // Inconsistent input shape, runtime error in dynamic shape mode. + /*input_shapes=*/{{1, 1, 2, 3}, {1, 1, 3, 2}}, + /*input_values=*/common_input, + /*inputs_are_tensors=*/{true, true}, + /*axis=*/1, + /*expected_output_dims=*/{2, 1, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + trt_mode_ != TrtTestMode::kDynamicShape + ? errors::InvalidArgument( + "Received inputs with inconsistent shape") + : OkStatus(), + errors::InvalidArgument(""), + }}; + + for (auto p : params) { + Reset(); + const int num_inputs = p.input_shapes.size(); + EXPECT_EQ(num_inputs, p.input_values.size()); + + NodeDef node_def = get_concat_nodedef(tf_type_, num_inputs); + + // Create inputs. + for (int j = 0; j < num_inputs; ++j) { + string name = StrCat("values_", j); + + if (!p.inputs_are_tensors[j]) { + AddTestWeights(name, p.input_shapes[j], p.input_values[j], tf_type_); + } else { + AddTestTensor(name, p.input_shapes[j], p.input_values[j]); + } + } + AddTestWeights("axis", {1}, {p.axis}); + + TestOpConverter(node_def, p.expected_output_dims, p.conversion_status, + p.run_status, ElementsAreArray(p.expected_output)); + } +} + +// Get the NodeDef for Split. +auto get_split_nodedef = [](DataType dtype, int num_split) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto axis = ops::Placeholder(s.WithOpName("axis"), DT_INT32); + auto value = ops::Placeholder(s.WithOpName("value"), dtype); + auto split = ops::Split(s.WithOpName("my_split"), axis, value, num_split); + return split.operation.node()->def(); +}; + +template +void TestConvertSplit(OpConverterTest* test) { + typedef typename EnumToDataType::Type CType; + + struct TestParams { + std::vector input_shape; + std::vector value; + int axis; + int num_split; + std::vector expected_output_dims; + std::vector> expected_outputs; + }; + + const std::vector common_input = CreateVectorIota(6); + std::vector ok_params = { + // Identity (num_split = 1) + {/*input_shape=*/{1, 2, 3}, /*value=*/common_input, /*axis=*/1, + /*num_split=*/1, /*expected_output_dims=*/{1, 2, 3}, + /*expected_outputs=*/{CreateVectorIota(6)}}, + {/*input_shape=*/{1, 2, 3}, + /*value=*/common_input, + /*axis=*/3, + /*num_split=*/3, + /*expected_output_dims=*/{1, 2, 1}, + /*expected_outputs=*/ + {{CType(0), CType(3)}, {CType(1), CType(4)}, {CType(2), CType(5)}}}, + {/*input_shape=*/{1, 6}, + /*value=*/common_input, + /*axis=*/2, + /*num_split=*/6, + /*expected_output_dims=*/{1, 1}, + /*expected_outputs=*/ + {{CType(0)}, + {CType(1)}, + {CType(2)}, + {CType(3)}, + {CType(4)}, + {CType(5)}}}, + {/*input_shape=*/{1, 6}, + /*value=*/common_input, + /*axis=*/-1, + /*num_split=*/2, + /*expected_output_dims=*/{1, 3}, + /*expected_outputs=*/ + {CreateVectorIota(3), CreateVectorIota(3, CType(3))}}, + }; + + for (int i = 0; i < ok_params.size(); ++i) { + test->Reset(); + NodeDef node_def = get_split_nodedef(dtype, ok_params[i].num_split); + // Create inputs. + test->AddTestWeights("axis", {1}, {ok_params[i].axis}); + nvinfer1::DataType trt_type; + TF_ASSERT_OK(TfTypeToTrtType(dtype, &trt_type)); + test->AddTestTensor("value", ok_params[i].input_shape, 1, trt_type); + // Convert. + test->RunValidationAndConversion(node_def); + + // Get output tensors and verify output dims. + EXPECT_EQ(ok_params[i].expected_outputs.size(), ok_params[i].num_split); + std::vector outputs(ok_params[i].num_split); + DataVec output_data; + for (int j = 0; j < outputs.size(); ++j) { + const string name = j == 0 ? StrCat("my_split") : StrCat("my_split:", j); + TF_EXPECT_OK(test->GetTensorOrWeights(name, &outputs[j])); + EXPECT_TRUE(outputs[j].is_tensor()); + EXPECT_THAT(outputs[j].tensor()->getDimensions(), + DimsAreArray(ok_params[i].expected_output_dims)); + // Create buffer to store output. + output_data.push_back( + {name, test->ConstructTensor( + ok_params[i].expected_outputs[j].size())}); + } + + // Verify output values are correct. + const DataVec input_data{ + {"value", test->AsTensor(ok_params[i].value)}}; + TF_EXPECT_OK(test->BuildAndRun(input_data, &output_data)); + for (int j = 0; j < outputs.size(); ++j) { + EXPECT_THAT(GetSpanForData(output_data[j]), + ElementsAreArray(ok_params[i].expected_outputs[j])); + } + } +} + +TEST_F(OpConverterTest, ConvertSplit) { + { + // Axis is a tensor, should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 1); + AddTestTensor("axis", {1}); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"axis\" for Split must be a constant"); + } + { + // Axis is out of bounds, should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 1); + AddTestWeights("axis", {1}, {4}); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Axis value of 4 is out of bounds, must be in " + "range [-4, 4)"); + } + { + // Axis is out of bounds (negative), should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 1); + AddTestWeights("axis", {1}, {-5}); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Axis value of -5 is out of bounds, must be in " + "range [-4, 4)"); + } + { + // Axis is batch dimension, should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 1); + AddTestWeights("axis", {1}, {0}); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of the " + "batch dimension"); + } + { + // Value is a weight, should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 1); + AddTestWeights("axis", {1}, {1}); + AddTestWeights("value", {1, 2, 3}, {1, 2, 3, 4, 5, 6}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"value\" for Split must be a tensor"); + } + { + // Dim is not evenly divisibly by num_split, should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 2); + AddTestWeights("axis", {1}, {3}); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Dimension 3 of size 3 is not evenly divisible by 2"); + } + { + // num_split > dim size, should fail. + Reset(); + NodeDef node_def = get_split_nodedef(DT_FLOAT, 4); + AddTestWeights("axis", {1}, {3}); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Dimension 3 of size 3 is not evenly divisible by 4"); + } + + TestConvertSplit(this); + TestConvertSplit(this); + TestConvertSplit(this); +} + +// Get the NodeDef for Unpack (Unstack in TF API). +auto get_unpack_nodedef = [](DataType dtype, int num, int axis) -> NodeDef { + Scope s = Scope::NewRootScope(); + auto value = ops::Placeholder(s.WithOpName("value"), dtype); + auto unstack_attrs = ops::Unstack::Axis(axis); + auto unstack = + ops::Unstack(s.WithOpName("my_unpack"), value, num, unstack_attrs); + return unstack.operation.node()->def(); +}; + +struct UnpackTestParams { + std::vector input_shape; + std::vector input_value; + int axis; + int num; + std::vector expected_output_dims; + std::vector> expected_outputs; + Status run_status; +}; + +void TestConvertUnpack(ParameterizedOpConverterTestBase* test, + UnpackTestParams& p) { + test->Reset(); + NodeDef node_def = get_unpack_nodedef(test->get_tf_type(), p.num, p.axis); + // Create inputs. + test->AddTestTensor("value", p.input_shape, test->get_tf_type(), + p.input_value); + + std::vector>> matcher_vec; + std::vector datatype_vec; + std::vector> expected_output_dims; + + for (int j = 0; j < p.expected_outputs.size(); ++j) { + matcher_vec.push_back(ElementsAreArray(p.expected_outputs[j])); + datatype_vec.push_back(test->get_tf_type()); + expected_output_dims.push_back(p.expected_output_dims); + } + + test->TestOpConverterMultiOut(/*node_def=*/node_def, + /*expected_output_dims=*/expected_output_dims, + /*expected_conversion_status=*/p.run_status, + /*expected_runtime_status=*/p.run_status, + /*matcher=*/matcher_vec, + /*out_tf_type=*/datatype_vec); +} + +// TODO: Reactivate when INT32 Segfault fixed +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertUnpack) { + // We need to skip error testing for Dynamic Shape mode, as it is impossible + // to convert Unpack in Dynamic Shape Mode. + if (trt_mode_ != TrtTestMode::kDynamicShape) { + { + // Value is weights, should fail. + Reset(); + NodeDef node_def = get_unpack_nodedef(tf_type_, /*num=*/3, /*axis=*/3); + AddTestWeights("value", {1, 1, 2, 3}, {1, 2, 3, 4, 5, 6}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"value\" for Unpack must be a tensor"); + } + { + // Axis is out of bounds, should fail. + Reset(); + NodeDef node_def = get_unpack_nodedef(tf_type_, /*num=*/1, /*axis=*/4); + AddTestTensor("value", {1, 1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Axis value of 4 is out of bounds, must be in " + "range [-4, 4)"); + } + { + // Axis is out of bounds (negative), should fail. + Reset(); + NodeDef node_def = get_unpack_nodedef(tf_type_, /*num=*/1, /*axis=*/-5); + AddTestTensor("value", {1, 1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kInvalidArgument, + "Axis value of -5 is out of bounds, must be " + "in range [-4, 4)"); + } + { + if (trt_mode_ != TrtTestMode::kExplicitBatch) { + // Axis is batch dimension, should fail. + Reset(); + NodeDef node_def = get_unpack_nodedef(tf_type_, /*num=*/1, /*axis=*/0); + AddTestTensor("value", {1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of " + "the batch dimension"); + } + } + { + // Dim size does not match num, should fail. + Reset(); + NodeDef node_def = get_unpack_nodedef(tf_type_, /*num=*/5, /*axis=*/2); + AddTestTensor("value", {1, 1, 6}); + RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + "Dimension 2 has size 6 which is not equal to num of 5"); + } + { + // Output would be TF scalar, should fail. + Reset(); + NodeDef node_def = get_unpack_nodedef(tf_type_, /*num=*/1, /*axis=*/0); + AddTestTensor( + "value", {}, tf_type_, {}, {}, + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::InvalidArgument( + "removing first dim requires explicit batch dimension") + : OkStatus()); + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + RunValidationAndConversion( + node_def, absl::StatusCode::kInternal, + "Failed to convert at least one input to a TRT_TensorOrWeights: " + "Scalar input tensor is not supported since the first dimension is " + "treated as batch dimension by TRT"); + } else { + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Input \"value\" for Unpack must be rank 2 " + "or greater"); + } + } + } + + const std::vector common_input = CreateVectorIota(6); + + Status run_status = + trt_mode_ == TrtTestMode::kDynamicShape + ? errors::InvalidArgument( + "The argument `strided_slice_spec` is " + "`std::nullopt` with `dynamic_input_size_indices` non empty.") + : OkStatus(); + + std::vector params = { + {/*input_shape=*/{1, 1, 2, 1, 3, 1}, + /*input_value=*/common_input, + /*axis=*/4, + /*num=*/3, + /*expected_output_dims=*/{1, 1, 2, 1, 1}, + /*expected_outputs=*/{{0, 3}, {1, 4}, {2, 5}}, + /*run_status=*/run_status}, + {/*input_shape=*/{1, 1, 2, 1, 3}, + /*input_value=*/common_input, + /*axis=*/4, + /*num=*/3, + /*expected_output_dims=*/{1, 1, 2, 1}, + /*expected_outputs=*/{{0, 3}, {1, 4}, {2, 5}}, + /*run_status=*/run_status}, + {/*input_shape=*/{1, 1, 2, 3}, + /*input_value=*/common_input, + /*axis=*/1, + /*num=*/1, + /*expected_output_dims=*/{1, 2, 3}, + /*expected_outputs=*/{CreateVectorIota(6)}, + /*run_status=*/run_status}, + {/*input_shape=*/{1, 6, 1}, + /*input_value=*/common_input, + /*axis=*/-2, + /*num=*/6, + /*expected_output_dims=*/{1, 1}, + /*expected_outputs=*/{{0}, {1}, {2}, {3}, {4}, {5}}, + /*run_status=*/run_status}, + {/*input_shape=*/{1, 6}, + /*input_value=*/common_input, + /*axis=*/1, + /*num=*/6, + /*expected_output_dims=*/{1}, + /*expected_outputs=*/{{0}, {1}, {2}, {3}, {4}, {5}}, + /*run_status=*/run_status}, + }; + for (auto p : params) { + TestConvertUnpack(this, p); + } +} + +// Get the NodeDef for Pack. +NodeDef GetPackNodeDef(DataType dtype, int num_inputs, int axis) { + Scope s = Scope::NewRootScope(); + std::vector values; + values.reserve(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + const string input_name = StrCat("values_", i); + values.push_back(ops::Placeholder(s.WithOpName(input_name), dtype)); + } + // Pack op is renamed to Stack in APIs. + auto pack = + ops::Stack(s.WithOpName("my_pack"), absl::Span(values), + ops::Stack::Axis(axis)); + return pack.operation.node()->def(); +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertPack) { + struct TestParams { + std::vector> input_shapes; + std::vector> partial_input_shapes; + std::vector> input_values; + int axis; + std::vector expected_output_dims; + std::vector expected_output; + Status conversion_status; + Status runtime_status; + bool input_1_is_weight; + }; + + const std::vector> common_input{ + CreateVectorIota(6), + CreateVectorIota(6, /*start_value=*/6)}; + std::vector params = { + // Second input is weight, should fail in implicit batch mode + {/*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/1, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "The input \"values_1\" for Pack must be a tensor"} + : OkStatus(), + /*runtime_status*/ OkStatus(), + /*weight_input*/ true}, + // Axis is out of bounds, should fail. + { + /*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/-5, + /*expected_output_dims=*/{}, + /*expected_output=*/{}, + Status{absl::StatusCode::kInvalidArgument, + "Axis value of -5 is out of bounds, must be in" + " range [-4, 4)"}, + }, + // Axis is batch dimension, should fail in implicit batch mode. + {/*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/-4, + /*expected_output_dims=*/{2, 1, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + trt_mode_ == TrtTestMode::kImplicitBatch + ? Status{absl::StatusCode::kUnimplemented, + "TensorRT does not allow manipulation of the batch " + "dimension"} + : OkStatus()}, + // Inconsistent rank, should fail. + { + /*input_shapes=*/{{1, 2, 3}, {1, 6}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/1, + /*expected_output_dims=*/{}, + /*expected_output=*/{}, + Status{absl::StatusCode::kInvalidArgument, + "Received inputs with inconsistent rank"}, + }, + { + /*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/1, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/CreateVectorIota(12), + }, + { + /*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/2, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/ + {0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11}, + }, + { + /*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/3, + /*expected_output_dims=*/{1, 2, 3, 2}, + /*expected_output=*/ + {0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11}, + }, + { + /*input_shapes=*/{{1, 2, 3}}, + /*partial_input_shapes=*/{{}}, + /*input_values=*/{CreateVectorIota(6)}, + /*axis=*/1, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/CreateVectorIota(6), + }, + { + /*input_shapes=*/{{1, 2, 3}}, + /*partial_input_shapes=*/{{}}, + /*input_values=*/{CreateVectorIota(6)}, + /*axis=*/2, + /*expected_output_dims=*/{1, 2, 1, 3}, + /*expected_output=*/CreateVectorIota(6), + }, + }; + // Inputs have inconsistent shapes, should fail. + if (trt_mode_ != TrtTestMode::kDynamicShape) { + params.push_back( + TestParams{/*input_shapes=*/{{1, 2, 3}, {1, 3, 2}}, + /*partial_input_shapes=*/{{}, {}}, + /*input_values=*/common_input, + /*axis=*/1, + /*expected_output_dims=*/{}, + /*expected_output=*/CreateVectorIota(12), + Status{absl::StatusCode::kInvalidArgument, + "Received inputs with inconsistent shape"}}); + } else { + // In dynamic shape mode we cannot catch inconsistent shapes at conversion + // time, only during runtime. But TensorRT does not raise a proper runtime + // error, instead it aborts the program with the following message: + // Assertion failed: t->start.d[i] + t->extent.d[i] <= r.dims.d[i] + // ../builder/cudnnBuilderGraph.cpp:862 + // Aborting... + // TODO(tfeher) Add dynamic shapes test once TRT handles shape error + // decently + } + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // Test with mixed dynamic / static shape input tensors + params.push_back( + TestParams{/*input_shapes=*/{{1, 2, 3}, {1, 2, 3}}, + /*partial_input_shapes=*/{{-1, -1, -1}, {1, 2, 3}}, + /*input_values=*/common_input, + /*axis=*/2, + /*expected_output_dims=*/{1, 2, 2, 3}, + /*expected_output=*/ + {0, 1, 2, 6, 7, 8, 3, 4, 5, 9, 10, 11}}); + } + for (auto p : params) { + Reset(); + const int num_inputs = p.input_shapes.size(); + EXPECT_EQ(num_inputs, p.input_values.size()); + + NodeDef node_def = GetPackNodeDef(tf_type_, num_inputs, p.axis); + // Create inputs. + for (int j = 0; j < num_inputs; ++j) { + if (j == 1 && p.input_1_is_weight) { + AddTestWeights(StrCat("values_", j), p.input_shapes[j], + p.input_values[j], tf_type_); + } else { + AddTestTensor(StrCat("values_", j), p.input_shapes[j], tf_type_, + p.input_values[j], p.partial_input_shapes[j]); + } + } + TestOpConverter(node_def, p.expected_output_dims, p.conversion_status, + p.runtime_status, ElementsAreArray(p.expected_output)); + } +} + +// Get the NodeDef for ArgMin or ArgMax. +template +NodeDef GetArgMinMaxNodeDef(DataType input_dtype, DataType output_dtype) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), input_dtype); + auto dimension = ops::Placeholder(s.WithOpName("dimension"), DT_INT32); + auto attrs = OpType::OutputType(output_dtype); + auto arg = OpType(s.WithOpName("my_arg"), input, dimension, attrs); + return arg.operation.node()->def(); +} + +struct ArgMinMaxTestParams { + std::vector input_shape; + std::vector input_value; + int axis; + std::vector expected_output_dims; + std::vector expected_argmax_output; + std::vector expected_argmin_output; + Status status; +}; + +template +void TestConvertArgMinMax(ParameterizedOpConverterTestBase* test, + DataType _tf_type, ArgMinMaxTestParams& p) { + test->Reset(); + + NodeDef node_def = GetArgMinMaxNodeDef(_tf_type, + /*output_dtype=*/DT_INT32); + + std::vector expected_out; + if (node_def.op() == "ArgMax") { + expected_out = p.expected_argmax_output; + } else if (node_def.op() == "ArgMin") { + expected_out = p.expected_argmin_output; + } else { + ASSERT_TRUE(false); + } + + test->AddTestTensor("input", p.input_shape, _tf_type, p.input_value); + test->AddTestWeights("dimension", {1}, {p.axis}, DT_INT32); + + test->TestOpConverter(node_def, p.expected_output_dims, + /*expected_conversion_status=*/p.status, + /*expected_runtime_status=*/OkStatus(), + /*matcher=*/ElementsAreArray(expected_out), {DT_INT32}); +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertArgMinMax) { + { + // Dimension is a tensor, should fail. + Reset(); + NodeDef node_def = + GetArgMinMaxNodeDef(tf_type_, + /*output_dtype=*/DT_INT32); + AddTestTensor("input", {1, 2, 3}); + AddTestTensor("dimension", {1}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"dimension\" for ArgMax must be a constant"); + } + { + // Output type is INT64, should fail. + Reset(); + NodeDef node_def = + GetArgMinMaxNodeDef(tf_type_, + /*output_dtype=*/DT_INT64); + AddTestTensor("input", {1, 2, 3}); + AddTestWeights("dimension", {1}, {3}, DT_INT32); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "Output type int64 is not supported"); + } + + const std::vector common_input = CreateVectorIota(6); + std::vector params = { + {/*input_shape=*/{2, 3}, + /*input_value=*/common_input, + /*axis=*/0, + /*expected_output_dims=*/{3}, + /*expected_argmax_output=*/{1, 1, 1}, + /*expected_argmin_output=*/{0, 0, 0}, + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::Unimplemented("TensorRT does not allow manipulation of " + "the batch dimension") + : OkStatus()}, + { + /*input_shape=*/{1, 6}, + /*input_value=*/common_input, + /*axis=*/1, + /*expected_output_dims=*/{1}, + /*expected_argmax_output=*/{5}, + /*expected_argmin_output=*/{0}, + }, + { + /*input_shape=*/{1, 10}, + /*input_value=*/ + {-5.0f, 3.0f, 5.0f, 1.0f, 6.0f, -9.0f, 7.0f, 1.0f, 0.0f, -1.0f}, + /*axis=*/-1, + /*expected_output_dims=*/{1}, + /*expected_argmax_output=*/{6}, + /*expected_argmin_output=*/{5}, + }, + { + /*input_shape=*/{1, 2, 3}, + /*input_value=*/common_input, + /*axis=*/2, + /*expected_output_dims=*/{1, 2}, + /*expected_argmax_output=*/{2, 2}, + /*expected_argmin_output=*/{0, 0}, + }, + { + /*input_shape=*/{1, 2, 3}, + /*input_value=*/common_input, + /*axis=*/-2, + /*expected_output_dims=*/{1, 3}, + /*expected_argmax_output=*/{1, 1, 1}, + /*expected_argmin_output=*/{0, 0, 0}, + }, + { + /*input_shape=*/{1, 2, 1, 3}, + /*input_value=*/common_input, + /*axis=*/3, + /*expected_output_dims=*/{1, 2, 1}, + /*expected_argmax_output=*/{2, 2}, + /*expected_argmin_output=*/{0, 0}, + }, + { + /*input_shape=*/{1, 2, 1, 3}, + /*input_value=*/common_input, + /*axis=*/-3, + /*expected_output_dims=*/{1, 1, 3}, + /*expected_argmax_output=*/{1, 1, 1}, + /*expected_argmin_output=*/{0, 0, 0}, + }, + {/*input_shape=*/{1, 2, 1, 1, 3}, + /*input_value=*/common_input, + /*axis=*/4, + /*expected_output_dims=*/{1, 2, 1, 1}, + /*expected_argmax_output=*/{2, 2}, + /*expected_argmin_output=*/{0, 0}, +#if !IS_TRT_VERSION_GE(7, 0, 0, 11) + errors::Unimplemented("op is not able to support tensors with 4+" + " dimensions (excluding batch size)") +#else + OkStatus() +#endif + }, + {/*input_shape=*/{1, 2, 1, 1, 3}, + /*input_value=*/common_input, + /*axis=*/-4, + /*expected_output_dims=*/{1, 1, 1, 3}, + /*expected_argmax_output=*/{1, 1, 1}, + /*expected_argmin_output=*/{0, 0, 0}, +#if !IS_TRT_VERSION_GE(7, 0, 0, 11) + errors::Unimplemented("op is not able to support tensors with 4+" + " dimensions (excluding batch size)") +#else + OkStatus() +#endif + }, + }; + + for (auto p : params) { + TestConvertArgMinMax(this, tf_type_, p); + TestConvertArgMinMax(this, tf_type_, p); + } +} + +// Get the NodeDef for DepthToSpace or SpaceToSpace. +template +NodeDef GetDepthSpaceShuffleNodeDef(DataType dtype, int block_size, + string data_format) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), dtype); + auto attrs = OpType::DataFormat(data_format); + auto shuffle = OpType(s.WithOpName("my_shuffle"), input, block_size, attrs); + return shuffle.operation.node()->def(); +} + +struct DepthSpaceShuffleTestParams { + std::vector input_dims; + std::vector input_value; + int block_size; + string data_format; + std::vector expected_output_dims; + std::vector expected_output; +}; + +template +void TestConvertDepthSpaceShuffle( + ParameterizedOpConverterTestBase* test, + const std::vector& params) { + Status status = OkStatus(); + + { + // Input is a weight, should fail. + test->Reset(); + NodeDef node_def = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), 2, "NCHW"); + test->AddTestWeights("input", {1, 4, 1, 1}, {1, 2, 3, 4}); + test->RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + StrCat("The input \"input\" for ", node_def.op(), " must be a tensor")); + } + { + // Input rank != 4 + test->Reset(); + NodeDef node_def = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), 2, "NCHW"); + test->AddTestTensor("input", {1, 16, 32}); + test->RunValidationAndConversion( + node_def, absl::StatusCode::kInvalidArgument, + StrCat("The input to ", node_def.op(), " must be rank 4")); + } + { + // Unsupported format, should fail. + test->Reset(); + NodeDef node_def = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), 2, "NCHW_VECT_C"); + test->AddTestTensor("input", {1, 16, 32, 32}); + test->RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "Data format NCHW_VECT_C is not supported"); + } + if (test->get_trt_mode() != TrtTestMode::kDynamicShape) { + // In dynamic shape mode, we cannot check input dimension values at + // conversion time therefore we cannot confirm block_size vs input dim + // consistency. We rely on the user to provide a valid TF graph. Otherwise + // TRT will fail with a runtime error. + if (std::is_same::value) { + // Channels not divisible by block_size, should fail. + test->Reset(); + NodeDef node_def = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), 3, "NCHW"); + test->AddTestTensor("input", {1, 16, 32, 32}); + test->RunValidationAndConversion(node_def, + absl::StatusCode::kInvalidArgument, + "Number of channels must be divisible by" + " block_size*block_size"); + } else { + { // Width not divisible by block_size, should fail. + test->Reset(); + NodeDef node_def = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), 3, "NCHW"); + test->AddTestTensor("input", {1, 16, 9, 32}); + test->RunValidationAndConversion(node_def, + absl::StatusCode::kInvalidArgument, + "Width and height must be divisible by" + " block_size"); + } + { + // Height not divisible by block_size, should fail. + test->Reset(); + NodeDef node_def = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), 3, "NCHW"); + test->AddTestTensor("input", {1, 16, 32, 9}); + test->RunValidationAndConversion(node_def, + absl::StatusCode::kInvalidArgument, + "Width and height must be divisible by" + " block_size"); + } + } + } + + for (auto p : params) { + test->Reset(); + const NodeDef node = GetDepthSpaceShuffleNodeDef( + test->get_tf_type(), p.block_size, p.data_format); + test->AddTestTensor("input", p.input_dims, p.input_value); + test->TestOpConverter(node, p.expected_output_dims, status, OkStatus(), + ElementsAreArray(p.expected_output)); + } +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertDepthToSpace) { + const std::vector common_input = CreateVectorIota(16); + std::vector params = { + { + /*input_shape=*/{1, 4, 2, 2}, + /*input_value=*/common_input, + /*block_size=*/2, + /*data_format=*/"NCHW", + /*expected_output_dims=*/{1, 1, 4, 4}, + /*expected_output=*/ + {0, 4, 1, 5, 8, 12, 9, 13, 2, 6, 3, 7, 10, 14, 11, 15}, + }, + { + /*input_shape=*/{1, 2, 2, 4}, + /*input_value=*/common_input, + /*block_size=*/2, + /*data_format=*/"NHWC", + /*expected_output_dims=*/{1, 4, 4, 1}, + /*expected_output=*/ + {0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15}, + }, + { + /*input_shape=*/{1, 16, 1, 1}, + /*input_value=*/common_input, + /*block_size=*/4, + /*data_format=*/"NCHW", + /*expected_output_dims=*/{1, 1, 4, 4}, + /*expected_output=*/CreateVectorIota(16), + }, + { + /*input_shape=*/{1, 2, 2, 8}, + /*input_value=*/CreateVectorIota(32), + /*block_size=*/2, + /*data_format=*/"NHWC", + /*expected_output_dims=*/{1, 4, 4, 2}, + /*expected_output=*/{0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, + 7, 12, 13, 14, 15, 16, 17, 18, 19, 24, 25, + 26, 27, 20, 21, 22, 23, 28, 29, 30, 31}, + }}; + + TestConvertDepthSpaceShuffle(this, params); +} + +TEST_P(OpConverter_FP32_FP16_INT32_Test, ConvertSpaceToDepth) { + const std::vector common_input = CreateVectorIota(16); + std::vector params = { + { + /*input_shape=*/{1, 1, 4, 4}, + /*input_value=*/common_input, + /*block_size=*/2, + /*data_format=*/"NCHW", + /*expected_output_dims=*/{1, 4, 2, 2}, + /*expected_output=*/ + {0, 2, 8, 10, 1, 3, 9, 11, 4, 6, 12, 14, 5, 7, 13, 15}, + }, + { + /*input_shape=*/{1, 4, 4, 1}, + /*input_value=*/common_input, + /*block_size=*/2, + /*data_format=*/"NHWC", + /*expected_output_dims=*/{1, 2, 2, 4}, + /*expected_output=*/ + {0, 1, 4, 5, 2, 3, 6, 7, 8, 9, 12, 13, 10, 11, 14, 15}, + }, + { + /*input_shape=*/{1, 1, 4, 4}, + /*input_value=*/common_input, + /*block_size=*/4, + /*data_format=*/"NCHW", + /*expected_output_dims=*/{1, 16, 1, 1}, + /*expected_output=*/CreateVectorIota(16), + }, + { + /*input_shape=*/{1, 4, 4, 2}, + /*input_value=*/CreateVectorIota(32), + /*block_size=*/2, + /*data_format=*/"NHWC", + /*expected_output_dims=*/{1, 2, 2, 8}, + /*expected_output=*/{0, 1, 2, 3, 8, 9, 10, 11, 4, 5, 6, + 7, 12, 13, 14, 15, 16, 17, 18, 19, 24, 25, + 26, 27, 20, 21, 22, 23, 28, 29, 30, 31}, + }, + }; + TestConvertDepthSpaceShuffle(this, params); +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertClipByValue) { + Scope s = Scope::NewRootScope(); + auto t = ops::Placeholder(s.WithOpName("t"), tf_type_); + auto clip_value_min = + ops::Placeholder(s.WithOpName("clip_value_min"), tf_type_); + auto clip_value_max = + ops::Placeholder(s.WithOpName("clip_value_max"), tf_type_); + auto clip = ops::ClipByValue(s.WithOpName("my_clip"), t, clip_value_min, + clip_value_max); + const NodeDef& node_def = clip.operation.node()->def(); + + nvinfer1::DataType trt_type_; + TF_ASSERT_OK(TfTypeToTrtType(tf_type_, &trt_type_)); + + { + // Input is a weight, should fail. + Reset(); + AddTestWeights("t", {1, 2, 3}, {1, 2, 3, 4, 5, 6}, tf_type_); + AddTestWeights("clip_value_min", {1}, {1}, tf_type_); + AddTestWeights("clip_value_max", {1}, {5}, tf_type_); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"t\" for ClipByValue must be a " + "tensor"); + } + { + // Clip min is a tensor, should fail. + Reset(); + AddTestTensor("t", {1, 2, 3}); + AddTestTensor("clip_value_min", {1}); + AddTestWeights("clip_value_max", {1}, {1}, tf_type_); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"clip_value_min\" for ClipByValue " + "must be a constant"); + } + { + // Clip max is a tensor, should fail. + Reset(); + AddTestTensor("t", {1, 2, 3}); + AddTestWeights("clip_value_min", {1}, {1}, tf_type_); + AddTestTensor("clip_value_max", {1}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"clip_value_max\" for ClipByValue " + "must be a constant"); + } + + struct TestParams { + std::vector dims; + int clip_value_min; + int clip_value_max; + std::vector expected_output; + }; + + const std::vector common_input = CreateVectorIota(6); + + std::vector params = {{ + /*dims=*/{6}, + /*clip_value_min=*/2, + /*clip_value_max=*/4, + /*expected_output=*/{2, 2, 2, 3, 4, 4}, + }, + { + /*dims=*/{1, 6}, + /*clip_value_min=*/2, + /*clip_value_max=*/4, + /*expected_output=*/{2, 2, 2, 3, 4, 4}, + }, + { + /*dims=*/{1, 2, 3}, + /*clip_value_min=*/2, + /*clip_value_max=*/4, + /*expected_output=*/{2, 2, 2, 3, 4, 4}, + }, + { + /*dims=*/{1, 2, 3, 1}, + /*clip_value_min=*/2, + /*clip_value_max=*/4, + /*expected_output=*/{2, 2, 2, 3, 4, 4}, + }, + { + /*dims=*/{1, 1, 3, 1, 2}, + /*clip_value_min=*/2, + /*clip_value_max=*/4, + /*expected_output=*/{2, 2, 2, 3, 4, 4}, + }, + { + /*dims=*/{1, 1, 3, 1, 2, 1}, + /*clip_value_min=*/2, + /*clip_value_max=*/4, + /*expected_output=*/{2, 2, 2, 3, 4, 4}, + }, + { + /*dims=*/{2, 1, 3}, + /*clip_value_min=*/-1, + /*clip_value_max=*/8, + /*expected_output=*/common_input, + }}; + + for (auto p : params) { + Reset(); + + AddTestTensor("t", p.dims, tf_type_, common_input); + AddTestWeights("clip_value_min", {1}, {p.clip_value_min}, tf_type_); + AddTestWeights("clip_value_max", {1}, {p.clip_value_max}, tf_type_); + + TestOpConverter(node_def, p.dims, + /*expected_conversion_status=*/OkStatus(), + /*expected_runtime_status=*/OkStatus(), + /*matcher=*/ElementsAreArray(p.expected_output)); + } +} + +// Get the NodeDef for SquaredDifference. +NodeDef GetSquaredDifferenceNodeDef(DataType dtype) { + Scope s = Scope::NewRootScope(); + auto x = ops::Placeholder(s.WithOpName("x"), dtype); + auto y = ops::Placeholder(s.WithOpName("y"), dtype); + auto squared_diff = + ops::SquaredDifference(s.WithOpName("my_squared_diff"), x, y); + return squared_diff.operation.node()->def(); +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertSquaredDifference) { + { + // Input is a weight, should fail. + Reset(); + NodeDef node_def = GetSquaredDifferenceNodeDef(tf_type_); + AddTestWeights("x", {1, 2, 3}, {1, 2, 3, 4, 5, 6}); + AddTestTensor("y", {1, 1, 2, 3}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"x\" for SquaredDifference must be " + "a tensor"); + } + + struct TestParams { + std::vector dims_x; + std::vector dims_y; + std::vector value_x; + std::vector value_y; + std::vector expected_output_dims; + std::vector expected_output; + Status status; + Status runtime_status; + }; + + const std::vector common_input = CreateVectorIota(6); + std::vector params = { + {/*dims_x=*/{1, 2, 3}, + /*dims_y=*/{1, 7, 5}, + /*value_x=*/common_input, + /*value_y=*/std::vector(7 * 5, 0), + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/common_input, + trt_mode_ == TrtTestMode::kDynamicShape + ? OkStatus() + : errors::InvalidArgument("Infeasible broadcast scheme"), + errors::Internal( + "Binding index out of range. This can happen if profile is not set, " + "or the network is invalid for the current profile.")}, + { + /*dims_x=*/{1, 1, 2, 3}, + /*dims_y=*/{1, 1, 2, 3}, + /*value_x=*/common_input, + /*value_y=*/{0, -1, 3, 0, 10, -7}, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/{0, 4, 1, 9, 36, 144}, + }, + { + /*dims_x=*/{1, 1, 2, 3}, + /*dims_y=*/{1, 1, 1, 3}, + /*value_x=*/common_input, + /*value_y=*/{0, 1, 2}, + /*expected_output_dims=*/{1, 1, 2, 3}, + /*expected_output=*/{0, 0, 0, 9, 9, 9}, + }, + }; + + for (auto p : params) { + Reset(); + const NodeDef node = GetSquaredDifferenceNodeDef(tf_type_); + AddTestTensor("x", p.dims_x, p.value_x); + AddTestTensor("y", p.dims_y, p.value_y); + TestOpConverter(node, p.expected_output_dims, p.status, p.runtime_status, + ElementsAreArray(p.expected_output)); + } +} + +template +NodeDef MakeResizeNodeDef(DataType dtype, bool align_corners) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), dtype); + auto size = ops::Placeholder(s.WithOpName("size"), DT_INT32); + auto attrs = typename OpType::Attrs().AlignCorners(align_corners); + auto resize = OpType(s.WithOpName("my_resize"), input, size, attrs); + return resize.operation.node()->def(); +} + +struct ResizeTestParams { + std::vector input_dims; + std::vector output_resize_dims; + std::vector input_value; + bool size_as_tensor; + bool align_corners; + std::vector expected_output_dims; + std::vector expected_nearest_output_values; + std::vector expected_bilinear_output_values; + Status status; +}; + +template +void TestConvertResize(ParameterizedOpConverterTestBase* test, + ResizeTestParams& p) { + test->Reset(); + // Create resize node. + NodeDef node_def = + MakeResizeNodeDef(test->get_tf_type(), p.align_corners); + + test->AddTestTensor("input", p.input_dims, test->get_tf_type(), + p.input_value); + // Create output size. + if (p.size_as_tensor) { + std::vector size_dims{2}; + std::vector size_values{p.output_resize_dims}; + test->AddTestTensor("size", size_dims, DT_INT32, size_values, size_dims); + } else { + test->AddTestWeights("size", {2}, p.output_resize_dims, DT_INT32); + } + + std::vector expected_out; + + if (node_def.op() == "ResizeBilinear") { + expected_out = p.expected_bilinear_output_values; + } else if (node_def.op() == "ResizeNearestNeighbor") { + expected_out = p.expected_nearest_output_values; + } else { + ASSERT_TRUE(false); + } + + test->TestOpConverter(node_def, p.expected_output_dims, + /*expected_conversion_status=*/p.status, + /*expected_runtime_status=*/p.status, + /*matcher=*/ElementsAreArray(expected_out), + /*out_tf_types=*/{DT_FLOAT}); +} + +TEST_P(OpConverter_FP32_FP16_Test, ConvertResize) { + { + // First input is weight, should fail. + Reset(); + NodeDef node_def = MakeResizeNodeDef(tf_type_, + /*align_corners=*/ + true); + AddTestWeights("input", {1, 2}, {1, 2}); + AddTestWeights("size", {1, 2}, {1, 2}); + RunValidationAndConversion( + node_def, absl::StatusCode::kUnimplemented, + "The input \"input\" for ResizeBilinear must be a " + "tensor"); + } + + std::vector params{ + {/*input_dims=*/{1, 1, 2, 1}, // N, H, W, C + /*output_resize_dims=*/{2, 3}, // H_out, W_out + /*input_values=*/{2.0f, -1.0f}, + /*size_as_tensor=*/false, + /*align_corners=*/false, + /*expected_output_dims=*/{1, 2, 3, 1}, // N, H, W, C + /*expected_nearest_output_values=*/ + {2.0f, 2.0f, -1.0f, 2.0f, 2.0f, -1.0f}, + /*expected_bilinear_output_values=*/ + {2.0f, 0.f, -1.0f, 2.0f, 0.f, -1.0f}, + /*status=*/OkStatus()}, + {/*input_dims=*/{1, 1, 2, 1}, // N, H, W, C + /*output_resize_dims=*/{2, 3}, // H_out, W_out + /*input_values=*/{2.0f, -1.0f}, + /*size_as_tensor=*/false, + /*align_corners=*/true, + /*expected_output_dims=*/{1, 2, 3, 1}, // N, H, W, C + /*expected_nearest_output_values=*/ + {2.0f, 2.0f, -1.0f, 2.0f, 2.0f, -1.0f}, + /*expected_bilinear_output_values=*/ + {2.0f, 0.5f, -1.0f, 2.0f, 0.5f, -1.0f}, + /*status=*/OkStatus()}}; + + if (trt_mode_ != TrtTestMode::kImplicitBatch) { + // Size as a tensor is not supported in implicit batch mode. + params.push_back({/*input_dims=*/{1, 1, 2, 1}, // N, H, W, C + /*output_resize_dims=*/{2, 3}, // H_out, W_out + /*input_values=*/{2.0f, -1.0f}, + /*size_as_tensor=*/true, + /*align_corners=*/true, + /*expected_output_dims=*/{1, 2, 3, 1}, // N, H, W, C + /*expected_nearest_output_values=*/ + {2.0f, 2.0f, -1.0f, 2.0f, 2.0f, -1.0f}, + /*expected_bilinear_output_values=*/ + {2.0f, 0.5f, -1.0f, 2.0f, 0.5f, -1.0f}, + /*status=*/OkStatus()}); + } + + for (auto p : params) { + TestConvertResize(this, p); + +// This use case is not supported as of TRT version 7.1 +#if IS_TRT_VERSION_GE(7, 1, 0, 0) + if (!p.align_corners) { + p.status = errors::InvalidArgument( + "Cannot Convert Bilinear Resize when align_corners=False"); + } +#endif + + TestConvertResize(this, p); + } +} + +NodeDef MakePadNodeDef(std::string name, DataType dtype) { + Scope s = Scope::NewRootScope(); + auto input = ops::Placeholder(s.WithOpName("input"), dtype); + auto padding = ops::Placeholder(s.WithOpName("padding"), DT_INT32); + auto pad = ops::Pad(s.WithOpName(name), input, padding); + return pad.operation.node()->def(); +} + +struct PadTestParams { + std::vector input_dims; + std::vector pad_dims; + std::vector pad_values; + std::vector input_values; + std::vector expected_output_dims; + std::vector expected_output_values; + Status status; +}; + +TEST_P(OpConverter_FP32_FP16_Test, ConvertPad) { + { + // First input is weight, should fail. + Reset(); + NodeDef node_def = MakePadNodeDef("my_pad", tf_type_); + AddTestWeights("input", {1, 2}, {1, 2}, tf_type_); + AddTestWeights("padding", {1, 2}, {1, 2}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"tensor\" for Pad must be a " + "tensor"); + } + { + // padding is a tensor, should fail. + Reset(); + NodeDef node_def = MakePadNodeDef("my_pad", tf_type_); + AddTestTensor("input", {1, 2}); + AddTestTensor("padding", {1, 2}); + RunValidationAndConversion(node_def, absl::StatusCode::kUnimplemented, + "The input \"paddings\" for Pad must be a " + "constant"); + } + { + // Make sure that ranges are inferred across a Pad. + Reset(); + NodeDef node_def = MakePadNodeDef("my_pad", tf_type_); + AddTestTensor("input", {1, 1, 2, 1}); + AddTestWeights("padding", {4, 2}, {0, 0, 1, 0, 0, 1, 0, 0}); + TRT_TensorOrWeights input; + TRT_TensorOrWeights output; + RunValidationAndConversion(node_def); + TF_EXPECT_OK(GetTensorOrWeights("input", &input)); + TF_EXPECT_OK(GetTensorOrWeights("my_pad", &output)); + ITensorProxyPtr input_tensor = input.tensor(); + converter_->ProvideQuantizationRange(&input_tensor, -5.0f, 5.0f); + auto ranges = quantization_ranges(); + EXPECT_EQ(5.0f, ranges[input.tensor()->trt_tensor()]); + } + + std::vector params{ + // 1 padding dim + { + /*input_dims=*/{1, 1, 3, 2}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 0, 0, 0, 1, 0, 0}, + /*input_values=*/{1, 2, 3, 4, 5, 6}, + /*expected_output_dims=*/{1, 1, 4, 2}, // N, H, W, C + /*expected_output_values=*/ + {1, 2, 3, 4, 5, 6, 0, 0}, + }, + { + /*input_dims=*/{1, 1, 3, 2}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 0, 0, 0, 0, 0, 1}, + /*input_values=*/{1, 2, 3, 4, 5, 6}, + /*expected_output_dims=*/{1, 1, 3, 3}, // N, H, W, C + /*expected_output_values=*/ + {1, 2, 0, 3, 4, 0, 5, 6, 0}, + }, + { + /*input_dims=*/{1, 1, 3, 2}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 1, 0, 0, 0, 0, 0}, + /*input_values=*/{1, 2, 3, 4, 5, 6}, + /*expected_output_dims=*/{1, 2, 3, 2}, // N, H, W, C + /*expected_output_values=*/ + {0, 0, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6}, + }, + // 2 padding dims + { + /*input_dims=*/{1, 1, 2, 1}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 1, 0, 0, 1, 0, 0}, + /*input_values=*/{2.0f, -1.0f}, + /*expected_output_dims=*/{1, 2, 3, 1}, // N, H, W, C + /*expected_output_values=*/ + {0.0, 0.0, 0.0, 2.0f, -1.0f, 0.0}, + }, + PadTestParams{ + /*input_dims=*/{1, 1, 2, 2}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 1, 0, 0, 1, 0, 0}, + /*input_values=*/{2, -1, 3., 4}, + /*expected_output_dims=*/{1, 2, 3, 2}, // N, H, W, C + /*expected_output_values=*/ + {0, 0, 0, 0, 0, 0, 2, -1, 3, 4, 0, 0}, + }, + PadTestParams{ + /*input_dims=*/{1, 1, 2, 1, 2}, // N, C, H, W, D + /*pad_dims=*/{5, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 1, 0, 0, 1, 0, 0, 0, 0}, + /*input_values=*/{2, -1, 3., 4}, + /*expected_output_dims=*/{1, 2, 3, 1, 2}, // N, H, W, C + /*expected_output_values=*/ + {0, 0, 0, 0, 0, 0, 2, -1, 3, 4, 0, 0}, + }, + PadTestParams{ + /*input_dims=*/{1, 1, 2, 1, 2}, // N, C, H, W, D + /*pad_dims=*/{5, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 0, 1, 0, 0, 1, 1, 0, 0}, + /*input_values=*/{2, -1, 3., 4}, + /*expected_output_dims=*/{1, 2, 2, 3, 2}, // N, H, W, C + /*expected_output_values=*/ + {0., 0., 2., -1., 0., 0., 0., 0., 3., 4., 0., 0., + 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0}, + }, + PadTestParams{ + /*input_dims=*/{1, 1, 2, 1}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {1, 0, 0, 0, 0, 1, 0, 0}, + /*input_values=*/{2.0f, -1.0f}, + /*expected_output_dims=*/{2, 1, 3, 1}, // N, H, W, C + /*expected_output_values=*/{0.0, 0.0, 0.0, 2.0f, -1.0f, 0.0}, + trt_mode_ == TrtTestMode::kImplicitBatch + ? errors::InvalidArgument("Padding layer does not support " + "padding on batch dimension") + : OkStatus()}, + PadTestParams{ + /*input_dims=*/{1, 1, 2, 1}, // N, H, W, C + /*pad_dims=*/{4, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 1, 0, 0, 1, 1, 1}, + /*input_values=*/{2.0f, -1.0f}, + /*expected_output_dims=*/{}, // N, H, W, C + /*expected_output_values=*/{}, + errors::InvalidArgument("Padding layer does not support padding on " + "> 2")}, + PadTestParams{ + /*input_dims=*/{1, 2, 2}, // N, H, W + /*pad_dims=*/{3, 2}, // #dims, {pad_before, pad_after} + /*pad_values*/ {0, 0, 1, 0, 0, 1}, + /*input_values=*/{2, -1, 3., 4}, + /*expected_output_dims=*/{1, 3, 3}, // N, H, W, C + /*expected_output_values=*/ + {0., 0., 0., 2., -1., 0., 3., 4., 0.}, + errors::InvalidArgument("Convertpad requires at least 4D input")}}; + + for (auto p : params) { + Reset(); + // Create pad node. + NodeDef node_def = MakePadNodeDef("my_pad", tf_type_); + // Create input tensor. + AddTestTensor("input", p.input_dims, p.input_values); + // Create output size. + AddTestWeights("padding", p.pad_dims, p.pad_values); + TestOpConverter(node_def, p.expected_output_dims, p.status, p.status, + ElementsAreArray(p.expected_output_values)); + } +} + +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + +class OpConverter_Select : public ParameterizedOpConverterTestBase { + public: + void RunTest(const string& opName); +}; + +void OpConverter_Select::RunTest(const string& opName) { + const auto testing_SelectV2 = opName == "SelectV2"; + const int maxVal = 32; + const std::array par_name = {"cond", "then", "else"}; + std::array par_type = {DT_BOOL, tf_type_, tf_type_}; + std::vector config(3, 0); + std::array*, 3> par_dims; + std::vector data_then(1, 0), data_else(1, maxVal), + expected_output(1, maxVal); + std::array*, 3> par_value = {nullptr, &data_then, + &data_else}; + std::vector data_cond(1, 0); + + auto set_parameters = [&](DataType cond_type = DT_BOOL) { + Reset(); + if (config[0]) { + AddTestTensor(par_name[0], *par_dims[0], cond_type, data_cond); + } else { + AddTestWeights(par_name[0], {1}, data_cond, cond_type); + } + for (int i = 1; i < 3; i++) { + if (config[i]) { + AddTestTensor(par_name[i], *par_dims[i], par_type[i], *par_value[i]); + } else { + AddTestWeights(par_name[i], {1}, *par_value[i], par_type[i]); + } + } + }; + + auto set_dimension = [this](const nvinfer1::Dims* dims, + std::vector& dims_param, + std::string* comment = nullptr) { + const auto nbDims = dims->nbDims; + if (comment) { + *comment = "batch_dim: " + std::to_string(nbDims + 1) + ", " + + DebugString(*dims); + } + + dims_param.resize(nbDims); + for (int i = 0; i < nbDims; i++) dims_param[i] = dims->d[i]; + }; + + auto adjust_comments = [this](const nvinfer1::Dims* p_dims, + std::string* p_comment) { + if (p_dims[0].nbDims == p_dims[1].nbDims) return; + + const int idx = p_dims[0].nbDims < p_dims[1].nbDims ? 0 : 1; + + nvinfer1::Dims dims; + dims.nbDims = p_dims[1 - idx].nbDims; + int i = 0; + for (; i < dims.nbDims - p_dims[idx].nbDims; i++) dims.d[i] = 1; + + for (int j = i; i < dims.nbDims; i++) dims.d[i] = p_dims[idx].d[i - j]; + + *(p_comment + idx) = + "batch_dim: " + std::to_string(1) + ", " + DebugString(dims); + *(p_comment + 1 - idx) = + "batch_dim: " + std::to_string(p_dims[idx].nbDims + 1) + ", " + + DebugString(p_dims[1 - idx]); + }; + + auto assign_values = [this]( + const std::array*, 3>& dims, + std::array*, 3> par_value, + std::vector& data_cond, int use_indices = 0, + const std::vector* expected_out = nullptr, + std::vector* expect_dims_pntr = nullptr) { + size_t rank[3]; + const auto dim_len = + dims[0]->size() > dims[1]->size() ? dims[0]->size() : dims[1]->size(); + std::vector exp_dims; + if (!expect_dims_pntr) expect_dims_pntr = &exp_dims; + + auto& expect_dims = *expect_dims_pntr; + expect_dims.resize(dim_len); + expect_dims.assign(dim_len, 0); + for (int i = 0; i < 3; i++) { + if (dims[i]) { + const auto& dim = *dims[i]; + for (auto j = 0; j < dims[i]->size(); j++) { + if (expect_dims[j] < dim[j]) expect_dims[j] = dim[j]; + } + + rank[i] = std::accumulate(std::begin(dim), std::end(dim), 1, + std::multiplies()); + } else { + assert(i >= 2); + rank[i] = rank[i - 1]; + } + } + + // Create data for ConvertSelectV2 testing. + for (int k = 1; k <= 2; k++) { + auto& data = *par_value[k]; + data.resize(rank[k]); + if (use_indices) { + const int mult = k == 1 ? 1 : -1; + for (int i = 0; i < rank[k]; i++) { + data[i] = mult * (i + 1); + } + } else { + for (int i = 0; i < rank[k]; i++) { + data[i] = k == 1 ? data[i >> 1] + i % 2 : maxVal - (*par_value[1])[i]; + } + } + } + + data_cond.resize(rank[0]); + data_cond[0] = 0; + for (int i = 0; i < rank[0]; i++) { + data_cond[i] = i % 2 ? 1 - data_cond[i >> 1] : data_cond[i >> 1]; + } + + if (!expected_out || expected_out->size() > 0) { + auto& expected_output = *par_value[0]; + const auto rank_out = + std::accumulate(std::begin(expect_dims), std::end(expect_dims), 1, + std::multiplies()); + + assert(rank_out == (expected_out ? expected_out->size() + : rank[use_indices >= 0 ? 0 : 1])); + + expected_output.resize(rank_out); + const auto& data_then = *par_value[1]; + const auto& data_else = *par_value[2]; + const auto div = use_indices >= 0 ? 1 : rank_out / rank[0]; + for (int i = 0; i < rank_out; i++) { + expected_output[i] = expected_out ? (*expected_out)[i] + : data_cond[i / div] ? data_then[i] + : data_else[i]; + } + } + }; + + auto shape_error_msg = [&](const NodeDef& node, bool same_then_else = true) { + nvinfer1::Dims shape[3]; + const auto j = same_then_else ? 0 : 1; + if (trt_mode_ == TrtTestMode::kDynamicShape) { + // Creating dynamic shapes corresponding to 'cond' and 'then' parameters. + for (int i = 0; i < 2; i++) { + for (int j = shape[i].nbDims = par_dims[i]->size(); j--;) { + shape[i].d[j] = -1; + } + } + } else { + for (int i = 0; i < 2; i++) { + DimsAdapter(*par_dims[i + j]).TrtDims(&shape[i + j]); + } + } + + return input_shapes_error_msg(shape[j], shape[j + 1], node, + !same_then_else); + }; + + auto run_test = [&](const NodeDef& node, const std::vector& exp_dims) { + const bool same_then_else_shapes = *par_dims[1] == *par_dims[2]; + const bool same_cond_chape = *par_dims[0] == *par_dims[1]; + const auto nMax = testing_SelectV2 ? 2 : 1; + for (int n = 0; n < nMax; n++) { + set_parameters(); + if (testing_SelectV2 || (same_then_else_shapes && same_cond_chape)) { + TestOpConverter(node, exp_dims, OkStatus(), OkStatus(), + ElementsAreArray(expected_output)); + } else { + const auto err_msg = shape_error_msg(node, same_then_else_shapes); + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + err_msg); + } + + if (!n) { + // Changing the condition and expected_output. + for (auto idx = data_cond.size(); idx--;) + data_cond[idx] = 1 - data_cond[idx]; + + // Compare of the shapes if the tensors "then" and "else". + if (!same_then_else_shapes) { + // Shapes are different: + // assigning +1's and -1's to the elements + // of the tensors "then" and "else", respectively + for (int p = 1; p <= 2; p++) { + auto& values = *par_value[p]; + const auto val = p == 1 ? 1 : -1; + for (auto idx = values.size(); idx--;) values[idx] = val; + } + // and set the appropriate expected values. + for (auto idx = expected_output.size(); idx--;) + expected_output[idx] = expected_output[idx] > 0 ? -1 : 1; + } else { + // Shapes are the same: + // just change the signs of the expected values. + for (auto idx = expected_output.size(); idx--;) + expected_output[idx] = -expected_output[idx]; + } + } + } + }; + + std::array data_types = {DT_FLOAT, DT_HALF, DT_INT32}; + NodeDef node; + TF_CHECK_OK(NodeDefBuilder("op", opName) + .Input("cond", 0, DT_BOOL) + .Input("then", 0, tf_type_) + .Input("else", 0, tf_type_) + .Finalize(&node)); + + const std::vector> dims_params = { + {8}, {8, 2, 4}, {32, 32, 3200}}; + + // All parameters passed as the weights OR 1-element tensors. + par_dims = {&dims_params[0], &dims_params[0], &dims_params[0]}; + if (trt_mode_ == TrtTestMode::kImplicitBatch) { + const auto& err = convert_not_supported_implicit(node.op(), node.name()); + do { + set_parameters(); + RunValidationAndConversion(node, absl::StatusCode::kUnimplemented, err); + } while (nextTensorWeightConfiguration(config)); + return; + } + + // Parameter 'cond' can only be of type DT_BOOL. + do { + for (auto cond_type : {DT_INT32, DT_FLOAT, DT_HALF}) { + nvinfer1::DataType trt_type; + TF_ASSERT_OK(TfTypeToTrtType(cond_type, &trt_type)); + const auto error_msg = + unexpected_type_error_msg(trt_type, nvinfer1::DataType::kBOOL, node); + set_parameters(cond_type); + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + error_msg); + } + } while (nextTensorWeightConfiguration(config)); + + std::string err_msg = bool_weight_error_msg(node); + + std::vector dims_const = {1}; + par_dims = {&dims_const, &dims_const, &dims_const}; + // Loop when condition is reversed and the expected_output + // should change from 'else' to 'then'. + for (int i = 0; i < 2; i++) { + do { + set_parameters(); + if (config[0]) { + TestOpConverter(node, {1}, OkStatus(), OkStatus(), + ElementsAreArray(expected_output)); + } else { + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + err_msg); + } + } while (nextTensorWeightConfiguration(config)); + + // Changing the condition and expected_output. + data_cond[0] = 1 - data_cond[0]; + expected_output[0] = (*par_value[1 + i])[0]; + } + + // All parameters passed as the tensors. + for (int i = 0; i < 3; i++) { + config[i] = 1; + } + + par_value[0] = &expected_output; + if (trt_mode_ == TrtTestMode::kExplicitBatch) { + // Testing infeasible broadcast schemes. + // For that subtest dims('then') will be equal to dims('else'). + std::string bc_comment[2]; + std::vector dims[4]; + par_dims = {dims, dims + 1, dims + 1}; + const nvinfer1::Dims infeasible_dims[] = { + {3, {4, 3, 2}}, {4, {4, 3, 2, 5}}, {3, {4, 1, 3}}, + {3, {4, 3, 2}}, {3, {4, 3, 2}}, {5, {4, 3, 2, 5, 2}}}; + + auto iMax = sizeof(infeasible_dims) / sizeof(infeasible_dims[0]); + // Loop for all pairs of nvinfer1::Dims from infeasible_dims. + for (int i = 0; i < iMax; i += 2) { + // Loop for all permutations on 2 elements which will assign + // each pairs of nvinfer1::Dims from infeasible_dims to + // (dims('cond'), dims('then')) and (dims('then'), dims('cond')), + // respectively. + for (int k = 0; k < 2; k++) { + for (int j = 0; j < 2; j++) { + set_dimension(infeasible_dims + i + (j + k) % 2, dims[j], + bc_comment + (j + k) % 2); + } + + if (testing_SelectV2) { + adjust_comments(infeasible_dims + i, bc_comment); + err_msg = "Infeasible broadcast scheme (" + bc_comment[k] + " vs " + + bc_comment[1 - k]; + } else { + err_msg = shape_error_msg(node); + } + + set_parameters(); + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + err_msg); + } + } + + // Tests for exactly two identical dims for any two out of 3 tensors. + const nvinfer1::Dims feasible_dims_2[] = { + {3, {1, 3, 2}}, {3, {4, 3, 2}}, {3, {4, 1, 2}}, {3, {4, 3, 2}}, + {3, {4, 3, 1}}, {3, {4, 3, 2}}, {3, {1, 1, 2}}, {3, {4, 3, 2}}, + {3, {1, 3, 1}}, {3, {4, 3, 2}}, {3, {4, 1, 1}}, {3, {4, 3, 2}}, + {3, {1, 1, 1}}, {3, {4, 3, 2}}, {3, {1, 3, 2}}, {3, {4, 1, 2}}, + }; + + // Expected values will be definded directly. + const std::vector expected_val_2[] = { + // Expected values for all feasible ordered pairs of dims + // for dims('then') == dims('else'), dims('then') != dims('cond'). + {-1, 2, 3, -4, 5, -6, -7, 8, 9, -10, 11, -12, + -13, 14, 15, -16, 17, -18, -19, 20, 21, -22, 23, -24}, + {-1, 2, 3, -4, 5, -6, -1, 2, 3, -4, -5, 6, + -1, 2, 3, -4, 5, -6, -1, 2, -3, 4, 5, -6}, + {-1, 2, -3, 4, -5, 6, 7, -8, 9, -10, 11, -12, + 13, -14, 15, -16, 17, -18, -19, 20, -21, 22, -23, 24}, + {-1, 2, 1, -2, 1, -2, -3, 4, 3, -4, -3, 4, + -5, 6, 5, -6, 5, -6, -7, 8, -7, 8, 7, -8}, + {-1, -2, 3, 4, 5, 6, -7, -8, 9, 10, -11, -12, + -13, -14, 15, 16, 17, 18, -19, -20, -21, -22, 23, 24}, + {-1, 1, 2, -2, 3, -3, -4, 4, 5, -5, -6, 6, + -7, 7, 8, -8, 9, -9, -10, 10, -11, 11, 12, -12}, + {-1, 2, -3, 4, -5, 6, -7, 8, -9, 10, -11, 12, + -13, 14, -15, 16, -17, 18, -19, 20, -21, 22, -23, 24}, + {-1, 2, 1, -2, 1, -2, -1, 2, 1, -2, -1, 2, + -1, 2, 1, -2, 1, -2, -1, 2, -1, 2, 1, -2}, + {-1, -2, 3, 4, 5, 6, -7, -8, 9, 10, 11, 12, + -13, -14, 15, 16, 17, 18, -19, -20, 21, 22, 23, 24}, + {-1, 1, 2, -2, 3, -3, -1, 1, 2, -2, -3, 3, + -1, 1, 2, -2, 3, -3, -1, 1, -2, 2, 3, -3}, + {-1, -2, -3, -4, -5, -6, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, -19, -20, -21, -22, -23, -24}, + {-1, 1, 1, -1, 1, -1, -2, 2, 2, -2, -2, 2, + -3, 3, 3, -3, 3, -3, -4, 4, -4, 4, 4, -4}, + {-1, -2, -3, -4, -5, -6, -7, -8, -9, -10, -11, -12, + -13, -14, -15, -16, -17, -18, -19, -20, -21, -22, -23, -24}, + {-1, 1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, + -1, 1, 1, -1, 1, -1, -1, 1, -1, 1, 1, -1}, + {-1, 2, 1, -2, 1, -2, -3, 4, 3, -4, 3, -4, + -5, 6, 5, -6, 5, -6, -7, 8, 7, -8, 7, -8}, + {-1, 2, -3, 4, -5, 6, 1, -2, 3, -4, 5, -6, + 1, -2, 3, -4, 5, -6, -1, 2, -3, 4, -5, 6}, + // Expected values for all feasible ordered pairs of dims + // for dims('cond') == dims('else'), dims('then') != dims('else'). + {-1, 2, 3, -4, 5, -6, -7, 2, 3, -10, -11, 6, + -13, 2, 3, -16, 5, -18, -19, 2, -21, 4, 5, -24}, + {-1, 2, 3, -4, 5, -6, -1, 8, 9, -4, 11, -6, + -1, 14, 15, -4, 17, -6, -1, 20, 21, -4, 23, -6}, + {-1, 2, 1, -4, 1, -6, -7, 4, 3, -10, -11, 4, + -13, 6, 5, -16, 5, -18, -19, 8, -21, 8, 7, -24}, + {-1, 2, -1, 4, -1, 6, 7, -4, 9, -4, 11, -4, + 13, -6, 15, -6, 17, -6, -7, 20, -7, 22, -7, 24}, + {-1, 1, 2, -4, 3, -6, -7, 4, 5, -10, -11, 6, + -13, 7, 8, -16, 9, -18, -19, 10, -21, 11, 12, -24}, + {-1, -1, 3, 4, 5, 6, -4, -4, 9, 10, -6, -6, + -7, -7, 15, 16, 17, 18, -10, -10, -11, -11, 23, 24}, + {-1, 2, 1, -4, 1, -6, -7, 2, 1, -10, -11, 2, + -13, 2, 1, -16, 1, -18, -19, 2, -21, 2, 1, -24}, + {-1, 2, -1, 4, -1, 6, -1, 8, -1, 10, -1, 12, + -1, 14, -1, 16, -1, 18, -1, 20, -1, 22, -1, 24}, + {-1, 1, 2, -4, 3, -6, -7, 1, 2, -10, -11, 3, + -13, 1, 2, -16, 3, -18, -19, 1, -21, 2, 3, -24}, + {-1, -1, 3, 4, 5, 6, -1, -1, 9, 10, 11, 12, + -1, -1, 15, 16, 17, 18, -1, -1, 21, 22, 23, 24}, + {-1, 1, 1, -4, 1, -6, -7, 2, 2, -10, -11, 2, + -13, 3, 3, -16, 3, -18, -19, 4, -21, 4, 4, -24}, + {-1, -1, -1, -1, -1, -1, 7, 8, 9, 10, 11, 12, + 13, 14, 15, 16, 17, 18, -4, -4, -4, -4, -4, -4}, + {-1, 1, 1, -4, 1, -6, -7, 1, 1, -10, -11, 1, + -13, 1, 1, -16, 1, -18, -19, 1, -21, 1, 1, -24}, + {-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1}, + {-1, 2, -1, 4, -1, 6, 1, -4, 3, -4, 5, -4, + 1, -6, 3, -6, 5, -6, -7, 2, -7, 4, -7, 6}, + {-1, 2, 1, -4, 1, -6, -1, 4, 3, -4, 3, -6, + -1, 6, 5, -4, 5, -6, -1, 8, 7, -4, 7, -6}}; + + const auto exp_dims = dims + 3; + const int kMax2 = 2; // number of permutations on 2 elements + iMax = sizeof(feasible_dims_2) / sizeof(feasible_dims_2[0]); + assert(kMax2 * iMax / 3 == + sizeof(expected_val_2) / sizeof(expected_val_2[0])); + // Broadcast shapes defined for `cond` OR for `then` and `else`. + // Loop for all pairs of nvinfer1::Dims from feasible_dims_2. + for (int i = 0; i < iMax; i += 2) { + // Loop for all permutations on 2 elements. + for (int k = 0; k < kMax2; k++) { + // Constructing dims for tensors 'cond' and 'then'. + // NOTE: dims('else') will be the same as dims('then'). + for (int j = 0; j < 2; j++) + set_dimension(feasible_dims_2 + i + (j + k) % 2, dims[j]); + + const std::vector* expect = expected_val_2 + i + k; + // Loop where the tensor shapes for 'cond' and 'then' are swapping. + for (int m = 0; m < 2; m++) { + assign_values(par_dims, par_value, data_cond, 1, expect, exp_dims); + run_test(node, *exp_dims); + + // Swapping dims for 'cond' and 'then' tensors. + const auto tmp = par_dims[0]; + par_dims[0] = par_dims[1]; + par_dims[1] = tmp; + expect += iMax; + } + } + } + + // Tests for pairwise different dims('cond'), dims('then'), dims('else'). + const nvinfer1::Dims feasible_dims_3[] = { + {2, {3, 2}}, {2, {3, 1}}, {2, {1, 1}}, {3, {2, 2, 1}}, + {3, {2, 1, 2}}, {3, {1, 2, 2}}, {3, {2, 1, 1}}, {3, {2, 1, 2}}, + {3, {1, 2, 2}}, {3, {2, 1, 1}}, {3, {1, 1, 2}}, {3, {1, 2, 1}}, + }; + + const std::vector expected_val_3[] = { + {-1, 1, 2, -1, 3, -1}, {-1, 1, 1, -2, 1, -3}, + {-1, -1, 3, 4, 5, 6}, {-1, -2, 1, 1, 1, 1}, + {-1, -1, -2, -2, -3, -3}, {-1, -2, -3, -4, -5, -6}, + {-1, -2, 1, 2, 3, 4, -3, -4}, {-1, -2, 3, 4, 1, 2, -3, -4}, + {-1, 1, -3, 2, 3, -2, 4, -4}, {-1, 2, -2, 4, 1, -3, 3, -4}, + {-1, 1, 2, -2, -3, 3, 4, -4}, {-1, 2, 1, -2, -3, 4, 3, -4}, + {-1, -2, -3, -4, 3, 4, 3, 4}, {-1, -2, -1, -2, 1, 2, 3, 4}, + {-1, 1, -3, 1, 2, -2, 2, -4}, {-1, 2, -1, 4, 1, -2, 3, -2}, + {-1, 1, 1, -2, -3, 2, 2, -4}, {-1, 2, 1, -1, -2, 4, 3, -2}, + {-1, -1, -2, -2, 1, 2, 1, 2}, {-1, -2, -1, -2, 1, 1, 2, 2}, + {-1, 1, -2, 1, -1, 2, -2, 2}, {-1, 1, -1, 2, -2, 1, -2, 2}, + {-1, -2, 1, 1, -1, -2, 2, 2}, {-1, -1, 1, 2, -2, -2, 1, 2}, + }; + + const int kMax3 = 6; // number of permutations on 3 elements + const std::array perm[kMax3] = {{0, 1, 2}, {0, 2, 1}, {1, 0, 2}, + {1, 2, 0}, {2, 0, 1}, {2, 1, 0}}; + par_dims = {dims, dims + 1, dims + 2}; + iMax = sizeof(feasible_dims_3) / sizeof(feasible_dims_3[0]); + assert(kMax3 * iMax / 3 == + sizeof(expected_val_3) / sizeof(expected_val_3[0])); + // Loop for all triples of nvinfer1::Dims from feasible_dims_3. + for (int i = 0; i < iMax; i += 3) { + // Loop for all permutations on 3 elements. + for (int k = 0; k < kMax3; k++) { + // Constructing dims for tensors 'cond', 'then' and 'else`. + for (int j = 0; j < 3; j++) + set_dimension(feasible_dims_3 + i + perm[k][j], dims[j]); + + const auto* expect = expected_val_3 + kMax3 * (i / 3) + k; + assign_values(par_dims, par_value, data_cond, 1, expect, exp_dims); + run_test(node, *exp_dims); + } + } + + if (!testing_SelectV2) { + // Tests for `cond` passed as a vector with N elements, where N is a batch + // size. The subtest should not pass a ConvertSelect::Validate() when one + // of following is true: + // (a) N is NOT equal to the first dimension of dims('then'); + // (b dims('cond').nbDims > 1. + // + // For all these subtest dims('then') == dims('else'). + const nvinfer1::Dims vect_dim[] = { + {1, {4}}, {3, {5, 2, 3}}, {2, {5, 2}}, {3, {5, 2, 3}}, + {1, {5}}, {3, {5, 2, 3}}, {1, {4}}, {4, {4, 3, 5, 2}}, + }; + + std::vector dims[4]; + par_dims = {dims, dims + 1, dims + 1}; + auto iMax = sizeof(vect_dim) / sizeof(vect_dim[0]); + // Loop for all pairs of nvinfer1::Dims from vector_dims. + for (int i = 0; i < iMax; i += 2) { + err_msg = + vect_dim[i].nbDims != 1 || vect_dim[i].d[0] != vect_dim[i + 1].d[0] + ? input_shapes_error_msg(vect_dim[i], vect_dim[i + 1], node) + : ""; + + for (int j = 0; j < 2; j++) { + set_dimension(vect_dim + i + j, dims[j]); + } + + assign_values(par_dims, par_value, data_cond, -1); + set_parameters(); + if (err_msg.empty()) { + TestOpConverter(node, dims[1], OkStatus(), OkStatus(), + ElementsAreArray(expected_output)); + } else { + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + err_msg); + } + } + } + } // trt_mode_ == TrtTestMode::kExplicitBatch + + // Tests for dims('cond') == dims('then') == dims('else'). + for (auto dims : dims_params) { + par_dims = {&dims, &dims, &dims}; + assign_values(par_dims, par_value, data_cond); + + // Loop over all possible values of type_else (type_then = tf_type_). + for (const auto type_else : data_types) { + par_type[2] = type_else; + set_parameters(); + if ((par_type[1] == DT_INT32 || par_type[2] == DT_INT32) && + par_type[1] != par_type[2]) { + // ConvertSelectV2::Validation() should fail when exactly one of + // (type_then, type_else) is equal to nvinfer1::DataType::kINT32. + nvinfer1::DataType trt_type[2]; + for (int i = 0; i < 2; i++) { + TF_ASSERT_OK(TfTypeToTrtType(par_type[i + 1], trt_type + i)); + } + + err_msg = then_else_dtypes_error_msg(trt_type[0], trt_type[1], node); + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + err_msg); + } else { + TestOpConverter(node, dims, OkStatus(), OkStatus(), + ElementsAreArray(expected_output)); + } + } + + // Restoring the original value. + par_type[2] = tf_type_; + } + + if (trt_mode_ == TrtTestMode::kDynamicShape) { + std::vector values_then{1, 2, 3, 4, 5, 6}; + std::vector values_else{-1, -2, -3, -4, -5, -6}; + std::vector expected_output{1, -2, 3, 4, -5, 6}; + data_cond = std::vector{1, 0, 1}; + const std::vector cond_dims{1, 3}, input_dims{1, 2, 3}; + par_dims = {&cond_dims, &input_dims, &input_dims}; + // Loop when condition is reversed and the expected_output + // should change from 'else' to 'then'. + const auto len_cond = data_cond.size(); + for (int i = 0; i < 2; i++) { + par_value[i + 1] = &values_then; + par_value[2 - i] = &values_else; + for (int j = 0; j < values_then.size(); j++) { + expected_output[j] = par_value[2 - data_cond[j % len_cond]]->at(j); + } + + set_parameters(); + if (testing_SelectV2) { + TestOpConverter(node, input_dims, OkStatus(), OkStatus(), + ElementsAreArray(expected_output)); + } else { + const auto err_msg = shape_error_msg(node); + RunValidationAndConversion(node, absl::StatusCode::kInvalidArgument, + err_msg); + } + // Changing the condition and expected_output. + for (int j = len_cond; j--;) { + data_cond[j] = 1 - data_cond[j]; + } + } + } +} + +INSTANTIATE_TEST_CASE_P( + OpConvTestInstantiation, OpConverter_Select, + ::testing::Combine(::testing::ValuesIn(ValidTrtModes), + ::testing::Values(DT_FLOAT, DT_HALF, DT_INT32), + ::testing::Values(TrtPrecisionMode::FP32))); + +TEST_P(OpConverter_Select, ConvertSelectV2) { RunTest("SelectV2"); } + +TEST_P(OpConverter_Select, Convert_Select) { RunTest("Select"); } + +TEST_F(OpConverterTest, DuplicateSqueeze) { + // Define a custom converter which performs multiple squeezes. + auto op_converter = [](const OpConverterParams* params) -> Status { + if (params->validation_only) return OkStatus(); + auto input = params->inputs.at(0).tensor(); + ITensorProxyPtr output; + // Squeeze the first dimension. + std::vector new_dims = {0, 1, 2, 3}; + TF_EXPECT_OK(params->converter->SqueezeTensor( + /*input=*/input, /*input_dims=*/&new_dims, /*params=*/params, + /*output=*/&output, /*op_instance=*/0)); + // Squeeze the second dimension. + new_dims = {0, 2, 3}; + TF_EXPECT_OK(params->converter->SqueezeTensor( + /*input=*/output, /*input_dims=*/&new_dims, /*params=*/params, + /*output=*/&output, /*op_instance=*/1)); + params->outputs->push_back(TRT_TensorOrWeights(output)); + return OkStatus(); + }; + // Use a simple unary op for the custom converter and add an input. + NodeDef node_def = CreateUnaryOp(DataType::DT_FLOAT); + AddTestTensor("input", {1, 1, 2, 3}); + // Override the converter for Abs to use the custom converter for this test + // only, and run conversion. + GetOpConverterRegistry()->Register("Abs", kDefaultConverterPriority + 1, + op_converter); + RunValidationAndConversion(node_def); + // Set up the inputs and outputs. + DataVec input_data; + DataVec output_data; + InputOutputData abs_input{ + "input", ConstructTensor(/*data_size=*/6, /*value=*/0, + /*tf_type=*/DataType::DT_FLOAT)}; + InputOutputData abs_output{ + "my_unary", ConstructTensor(/*data_size=*/6, /*value=*/0, + /*tf_type=*/DataType::DT_FLOAT)}; + input_data.push_back(abs_input); + output_data.push_back(abs_output); + // Build and run the cuda engine. + TF_EXPECT_OK(BuildAndRun(input_data, &output_data)); +} + +#endif + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +int main(int argc, char** argv) { +// TRT >= 8.2 optimizes memory management in the builder. When all builders +// are destroyed, it unloads many resources. This test fixture will create and +// destroy hundreds of builders when run sequentially for parameterized +// tests. We can hold open an IBuilder in order to prevent TRT from unloading +// shared resources between engine builds when using TRT shared library. This +// greatly speeds up unit tests and is safe to do. +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + // This builder holds a copy of cask::KernelLibrary, which is shared with + // other builders. Other builders used during testing won't trigger costly + // loading of cask::KernelLibrary. + std::unique_ptr const holder{ + nvinfer1::createInferBuilder(*tensorflow::tensorrt::Logger::GetLogger())}; +#endif + ::testing::InitGoogleTest(&argc, argv); + return RUN_ALL_TESTS(); +} +#else +int main(int, char**) { return 0; } +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry.cc new file mode 100644 index 0000000000000000000000000000000000000000..11825ed970a633173f4f64e8bdf914463a4ee86a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry.cc @@ -0,0 +1,60 @@ +/* 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/logger_registry.h" + +#include + +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { +namespace tensorrt { + +class LoggerRegistryImpl : public LoggerRegistry { + Status Register(const string& name, nvinfer1::ILogger* logger) override { + mutex_lock lock(mu_); + if (!registry_.emplace(name, std::unique_ptr(logger)) + .second) { + return errors::AlreadyExists("Logger ", name, " already registered"); + } + return OkStatus(); + } + + nvinfer1::ILogger* LookUp(const string& name) override { + mutex_lock lock(mu_); + const auto found = registry_.find(name); + if (found == registry_.end()) { + return nullptr; + } + return found->second.get(); + } + + private: + mutable mutex mu_; + mutable std::unordered_map> + registry_ TF_GUARDED_BY(mu_); +}; + +LoggerRegistry* GetLoggerRegistry() { + static LoggerRegistryImpl* registry = new LoggerRegistryImpl; + return registry; +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..46544227e5b5f3a8677fb7ad34da7921f3e99b7e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry.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_TF2TENSORRT_CONVERT_LOGGER_REGISTRY_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_LOGGER_REGISTRY_H_ + +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +class LoggerRegistry { + public: + virtual Status Register(const string& name, nvinfer1::ILogger* logger) = 0; + virtual nvinfer1::ILogger* LookUp(const string& name) = 0; + virtual ~LoggerRegistry() {} +}; + +LoggerRegistry* GetLoggerRegistry(); + +class RegisterLogger { + public: + RegisterLogger(const string& name, nvinfer1::ILogger* logger) { + TF_CHECK_OK(GetLoggerRegistry()->Register(name, logger)); + } +}; + +#define REGISTER_TENSORRT_LOGGER(name, logger) \ + REGISTER_TENSORRT_LOGGER_UNIQ_HELPER(__COUNTER__, name, logger) +#define REGISTER_TENSORRT_LOGGER_UNIQ_HELPER(ctr, name, logger) \ + REGISTER_TENSORRT_LOGGER_UNIQ(ctr, name, logger) +#define REGISTER_TENSORRT_LOGGER_UNIQ(ctr, name, logger) \ + static ::tensorflow::tensorrt::RegisterLogger register_trt_logger##ctr \ + TF_ATTRIBUTE_UNUSED = \ + ::tensorflow::tensorrt::RegisterLogger(name, logger) + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_LOGGER_REGISTRY_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..c5516a9dc794ba5cf5b01a1fa03cd283c9925a95 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/logger_registry_test.cc @@ -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. +==============================================================================*/ + +#include +#include + +namespace { + +class TestLogger : public nvinfer1::ILogger { + void log(nvinfer1::ILogger::Severity severity, const char* msg) override {} +}; + +TestLogger test_logger; + +REGISTER_TENSORRT_LOGGER("test_logger", &test_logger); + +TEST(LoggerRegistryTest, RegistersCorrectly) { + auto registered_logger = GetLoggerRegistry()->LookUp("test_logger"); + EXPECT_THAT(registered_logger, Eq(&test_logger)); +} + +} // namespace diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter.h new file mode 100644 index 0000000000000000000000000000000000000000..fdefd37911b3a49975c9806ef9500d49e981d0f1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter.h @@ -0,0 +1,224 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_OP_CONVERTER_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OP_CONVERTER_H_ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include + +#include "absl/strings/str_format.h" +#include "tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h" +#include "tensorflow/compiler/tf2tensorrt/convert/weights.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class Converter; + +// Specifies the expected type taken by a TRT_TensorOrWeights input during op +// conversion. +// kResource is only used for resource variable ops. For an operation like +// Add(tensor, ReadVariableOp(...)), the second operand of Add is the result of +// the ReadVariableOp, which is a kWeight. +enum class TrtInputArg { kTensor = 1, kWeight = 2, kBoth = 3, kResource = 4 }; + +// Parameters for each op converter. +struct OpConverterParams { + // Constructor used for validation only. + OpConverterParams(const NodeDef& node_def, + const std::vector& inputs, + std::vector* outputs, + TrtWeightStore* weight_store, + TrtPrecisionMode precision_mode, bool use_calibration, + bool use_implicit_batch, bool use_explicit_precision); + + // Constructor used for conversion. + OpConverterParams(Converter* converter, const NodeDef& node_def, + const std::vector& inputs, + std::vector* outputs, + TrtWeightStore* weight_store); + + Converter* converter = nullptr; + const NodeDef& node_def; + const std::vector& inputs; + std::vector* outputs; + const bool validation_only; + TrtWeightStore* weight_store; + const TrtPrecisionMode precision_mode; + const bool use_calibration; + const bool use_implicit_batch; + const bool use_explicit_precision; +}; + +// Operation converter function specification. +using OpConverter = std::function; + +struct InputArgSpec { + absl::string_view name; + TrtInputArg allowed_roles; + + static constexpr InputArgSpec Create(absl::string_view n, TrtInputArg role) { + return InputArgSpec{n, role}; + } +}; + +template +std::string convert_not_supported_dtype_msg(const T& allowed_types, + DataType tf_type, + const NodeDef& node) { + string allowed_types_string = + absl::StrJoin(allowed_types, ", ", [](string* out, const DataType& type) { + absl::StrAppendFormat(out, "%s", DataTypeString(type)); + }); + + return absl::StrCat("Data type ", DataTypeString(tf_type), + " is not supported for ", node.op(), ", must be one of [", + allowed_types_string, "]"); +} + +std::string convert_not_supported_implicit(const std::string& pOpName, + const std::string& pNodeName, + const char* pOpType = NULL); + +// A Curiously recurring template pattern (CRTP) template class for operation +// converters. +template +class OpConverterBase { + public: + explicit OpConverterBase(const OpConverterParams* params, + const std::vector& data_types = + {DataType::DT_FLOAT, DataType::DT_HALF}) + : params_(params), + node_def_attrs_(params->node_def), + allowed_dtypes_(data_types) {} + + // Default NodeDef attribute name to inspect in order to determine node data + // type. The Impl class can override this by implementing the same function. + static constexpr const char* NodeDefDataTypeAttributeName() { return "T"; } + + // Validate data type of the given NodeDef against allowed types. + Status ValidateNodeDefDataType() { + // If the attribute name is empty, we should skip this check. + if (absl::string_view(Impl::NodeDefDataTypeAttributeName()).empty()) { + return OkStatus(); + } + + // Get the NodeDef data type. + auto dtype = GetAttrValue(Impl::NodeDefDataTypeAttributeName()); + if (!dtype.ok()) { + return errors::InvalidArgument("Attribute with name ", + Impl::NodeDefDataTypeAttributeName(), + " not found."); + } + + // Check allowed data types.; + if (std::find(allowed_dtypes_.begin(), allowed_dtypes_.end(), *dtype) == + allowed_dtypes_.end()) { + return errors::Unimplemented(convert_not_supported_dtype_msg( + allowed_dtypes_, *dtype, params_->node_def)); + } + return OkStatus(); + } + + static constexpr bool HasFixNumberOfInputs() { return true; } + + // Validates input argument roles and data types. + Status ValidateInputs() { + const NodeDef& node_def = params_->node_def; + const auto& inputs = params_->inputs; + if (Impl::HasFixNumberOfInputs()) { + TRT_ENSURE(inputs.size() == Impl::InputSpec().size()); + } else { + TRT_ENSURE(inputs.size() <= Impl::InputSpec().size()); + } + for (int i = 0; i < inputs.size(); i++) { + const InputArgSpec arg_spec = Impl::InputSpec()[i]; + if (arg_spec.allowed_roles == TrtInputArg::kWeight && + inputs.at(i).is_tensor()) { + return errors::Unimplemented("The input \"", arg_spec.name, "\" for ", + node_def.op(), " must be a constant, at ", + node_def.name()); + } + if (arg_spec.allowed_roles == TrtInputArg::kTensor && + inputs.at(i).is_weights()) { + return errors::Unimplemented("The input \"", arg_spec.name, "\" for ", + node_def.op(), " must be a tensor, at ", + node_def.name()); + } + } + return OkStatus(); + } + + Status operator()() { + // Validate data type and inputs. + TF_RETURN_IF_ERROR(this->ValidateNodeDefDataType()); + TF_RETURN_IF_ERROR(this->ValidateInputs()); + + // Perform op-level validation. + TF_RETURN_IF_ERROR(reinterpret_cast(this)->Validate()); + if (params_->validation_only) { + return OkStatus(); + } + + // Perform conversion. + return reinterpret_cast(this)->Convert(); + } + + protected: + Status NotSupportedInImplicitBatch(const char* pOpType = nullptr) { + if (params_->use_implicit_batch) { + const auto& op = params_->node_def.op(); + const auto& nodeName = params_->node_def.name(); + const auto& error = convert_not_supported_implicit(op, nodeName, pOpType); + return errors::Unimplemented(error); + } + return OkStatus(); + } + + void AddOutput(const TRT_TensorOrWeights& out) { + params_->outputs->push_back(out); + } + + template + StatusOr GetAttrValue(absl::string_view key) const { + T result; + TF_RETURN_IF_ERROR(GetNodeAttr(node_def_attrs_, key, &result)); + return result; + } + + const OpConverterParams* const params_; + const AttrSlice node_def_attrs_; + const std::vector allowed_dtypes_; +}; + +// Constructs and returns a converter function for a given operation converter +// class T. This requires T to be a derived class of StructuredOpConverter. +template +OpConverter MakeConverterFunction() { + return [](const OpConverterParams* params) -> Status { + T converter(params); + return converter(); + }; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OP_CONVERTER_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.cc new file mode 100644 index 0000000000000000000000000000000000000000..b70ffdcd88dc71323b9b6d4e3928ebb36c7b01ad --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.cc @@ -0,0 +1,157 @@ +/* Copyright 2021 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/tf2tensorrt/convert/op_converter_registry.h" + +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/util/env_var.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +struct OpConverterRegistration { + OpConverter converter; + int priority; +}; +class OpConverterRegistry::Impl { + public: + ~Impl() = default; + + InitOnStartupMarker Register(const string& name, const int priority, + OpConverter converter) { + mutex_lock lock(mu_); + auto item = registry_.find(name); + if (item != registry_.end()) { + const int existing_priority = item->second.priority; + if (priority <= existing_priority) { + LOG(WARNING) << absl::StrCat( + "Ignoring TF->TRT ", name, " op converter with priority ", + existing_priority, " due to another converter with priority ", + priority); + return {}; + } else { + LOG(WARNING) << absl::StrCat( + "Overwriting TF->TRT ", name, " op converter with priority ", + existing_priority, " using another converter with priority ", + priority); + registry_.erase(item); + } + } + registry_.insert({name, OpConverterRegistration{converter, priority}}); + return {}; + } + + StatusOr LookUp(string name) { + // Fetch the user-provide TF operations denylisted for conversion by TF-TRT. + static const absl::flat_hash_set tftrt_op_fakelist = [] { + string tftrt_op_fakelist_str; + TF_CHECK_OK(ReadStringFromEnvVar("TF_TRT_OP_FAKELIST", + /*default_value=*/"", + &tftrt_op_fakelist_str)); + absl::flat_hash_set tftrt_op_fakelist{}; + for (const auto& x : str_util::Split(tftrt_op_fakelist_str, ",")) { + tftrt_op_fakelist.insert(x); + } + // Force a rehash of the flat hash set + tftrt_op_fakelist.rehash(0); + return tftrt_op_fakelist; + }(); + + // In case the TensorFlow OP `name` matches any of the names passed to + // TF_TRT_OP_FAKELIST environment variable, force ::LookUp to resolves to + // ConvertFake OP converter. + if (tftrt_op_fakelist.contains(name)) { + LOG_FIRST_N(INFO, 2) << "Emulating OP Converter: `" << name << "`. It " + << "will cause TRT engine building to fail. This " + << "feature is only intended to be used for " + << "TF-TRT graph segmentation experiments. This " + << "feature is controlled using: " + << "`TF_TRT_OP_FAKELIST=OpName1,OpName2`."; + // Forces ::LookUp to resolve to `ConvertFake` registered to `FakeOp`. + mutex_lock lock(mu_); + return registry_.find("FakeOp")->second.converter; + } + + mutex_lock lock(mu_); + auto found = registry_.find(name); + if (found != registry_.end()) { + return found->second.converter; + } + return errors::NotFound("No converter for op ", name); + } + + void Clear(const std::string& name) { + mutex_lock lock(mu_); + auto itr = registry_.find(name); + if (itr == registry_.end()) { + return; + } + registry_.erase(itr); + } + + std::vector ListRegisteredOps() const { + mutex_lock lock(mu_); + std::vector result; + result.reserve(registry_.size()); + for (const auto& item : registry_) { + result.push_back(item.first); + } + return result; + } + + private: + mutable mutex mu_; + mutable std::unordered_map registry_ + TF_GUARDED_BY(mu_); +}; + +OpConverterRegistry::OpConverterRegistry() : impl_(std::make_unique()) {} + +StatusOr OpConverterRegistry::LookUp(const string& name) { + return impl_->LookUp(name); +} + +InitOnStartupMarker OpConverterRegistry::Register(const string& name, + const int priority, + OpConverter converter) { + return impl_->Register(name, priority, converter); +} + +std::vector OpConverterRegistry::ListRegisteredOps() const { + return impl_->ListRegisteredOps(); +} + +void OpConverterRegistry::Clear(const std::string& name) { impl_->Clear(name); } + +OpConverterRegistry* GetOpConverterRegistry() { + static OpConverterRegistry* registry = new OpConverterRegistry(); + return registry; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..65f2613980b5df16a058b61af9a00eabc37e9b4b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h @@ -0,0 +1,104 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_OP_CONVERTER_REGISTRY_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OP_CONVERTER_REGISTRY_H_ + +#include +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class OpConverterRegistry { + public: + OpConverterRegistry(); + ~OpConverterRegistry() = default; + + InitOnStartupMarker Register(const string& name, const int priority, + OpConverter converter); + + InitOnStartupMarker Register(const std::initializer_list& names, + const int priority, OpConverter converter) { + for (const auto& name : names) { + Register(name, priority, converter); + } + return {}; + } + + template ::value>::type* = nullptr> + InitOnStartupMarker Register(const T& names, const int priority, + OpConverter converter) { + for (const auto& name : names) { + Register(name, priority, converter); + } + return {}; + } + + // Clear all registered converters for the given Tensorflow operation name. + void Clear(const std::string& name); + + StatusOr LookUp(const string& name); + + std::vector ListRegisteredOps() const; + + private: + class Impl; + std::unique_ptr impl_; +}; + +OpConverterRegistry* GetOpConverterRegistry(); + +class RegisterOpConverter { + public: + RegisterOpConverter(const string& name, const int priority, + OpConverter converter) { + GetOpConverterRegistry()->Register(name, priority, converter); + } +}; + +constexpr int kDefaultConverterPriority = 1; + +} // namespace convert +} // namespace tensorrt + +#define REGISTER_TRT_OP_CONVERTER_IMPL(ctr, func, priority, ...) \ + static ::tensorflow::InitOnStartupMarker const \ + register_trt_op_converter##ctr TF_ATTRIBUTE_UNUSED = \ + TF_INIT_ON_STARTUP_IF(true) \ + << tensorrt::convert::GetOpConverterRegistry()->Register( \ + __VA_ARGS__, priority, func) + +#define REGISTER_TRT_OP_CONVERTER(func, priority, ...) \ + TF_NEW_ID_FOR_INIT(REGISTER_TRT_OP_CONVERTER_IMPL, func, priority, \ + __VA_ARGS__) + +#define REGISTER_DEFAULT_TRT_OP_CONVERTER(func, ...) \ + REGISTER_TRT_OP_CONVERTER( \ + func, tensorrt::convert::kDefaultConverterPriority, __VA_ARGS__) + +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OP_CONVERTER_REGISTRY_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..3cd135379c43247bf262694c0ec11f187fc040e5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_registry_test.cc @@ -0,0 +1,67 @@ +/* Copyright 2021 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" + +#include +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +TEST(TestOpConverterRegistry, TestOpConverterRegistry) { + bool flag{false}; + + auto set_true_func = [&flag](const OpConverterParams*) -> Status { + flag = true; + return OkStatus(); + }; + + auto set_false_func = [&flag](const OpConverterParams*) -> Status { + flag = false; + return OkStatus(); + }; + + GetOpConverterRegistry()->Register("FakeFunc", kDefaultConverterPriority, + set_true_func); + + // Lower priority fails to override. + GetOpConverterRegistry()->Register("FakeFunc", kDefaultConverterPriority - 1, + set_false_func); + + // The lookup should return set_true_func (default). + auto func = GetOpConverterRegistry()->LookUp("FakeFunc"); + EXPECT_TRUE(func.ok()); + EXPECT_TRUE(((*func)(nullptr)).ok()); + EXPECT_TRUE(flag); + + // Override with higher priority. + GetOpConverterRegistry()->Register("FakeFunc", kDefaultConverterPriority + 1, + set_false_func); + func = GetOpConverterRegistry()->LookUp("FakeFunc"); + EXPECT_TRUE(func.ok()); + EXPECT_TRUE((*func)(nullptr).ok()); + EXPECT_FALSE(flag); + + // After clearing the op, lookup should return an error. + GetOpConverterRegistry()->Clear("FakeFunc"); + EXPECT_FALSE(GetOpConverterRegistry()->LookUp("FakeFunc").ok()); +} +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ddad81d6394b49eab81c8cb614e6b77ba27a1d27 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/op_converter_test.cc @@ -0,0 +1,123 @@ +/* Copyright 2021 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" + +#include +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/status_matchers.h" +#include "tensorflow/core/protobuf/error_codes.pb.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +using ::tensorflow::testing::IsOk; +using ::tensorflow::testing::StatusIs; +using ::testing::HasSubstr; + +class ExampleOpConverter : public OpConverterBase { + public: + explicit ExampleOpConverter(const OpConverterParams* params) + : OpConverterBase(params, {DataType::DT_FLOAT}) {} + + static constexpr const char* NodeDefDataTypeAttributeName() { + return "data_type"; + } + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("input_tensor", TrtInputArg::kTensor), + InputArgSpec::Create("weight", TrtInputArg::kWeight)}; + } + + Status Validate() { return OkStatus(); } + + Status Convert() { + AddOutput(TRT_TensorOrWeights(nvinfer1::DataType::kFLOAT, + nvinfer1::Dims{1, {1, 1, 1}}, 1)); + return OkStatus(); + } +}; + +TEST(TestOpConverterBase, TestOpConverterBase) { + // Register a converter which uses the base converter class. + GetOpConverterRegistry()->Register( + "FakeFunc", 1, MakeConverterFunction()); + + NodeDef def; + def.set_op("FakeFunc"); + auto converter = Converter::Create(TrtPrecisionMode::FP32, false, + Logger::GetLogger(), false, "test_engine"); + EXPECT_THAT(converter, IsOk()); + + // Base class should check attribute with key given by + // Impl::NodeDefDataTypeAttributeName(). + Status conversion_status = (*converter)->ConvertNode(def); + EXPECT_THAT(conversion_status, + StatusIs(error::INVALID_ARGUMENT, + HasSubstr("Attribute with name data_type not found"))); + + // Add partial inputs to the node and make the converter aware. + def.mutable_input()->Add("input1"); + conversion_status = (*converter) + ->AddInputTensor("input1", nvinfer1::DataType::kFLOAT, + nvinfer1::Dims{4, {1, 1, 1, 1}}, 1); + EXPECT_THAT(conversion_status, IsOk()); + + // Base class method should check number of inputs. + AddNodeAttr("data_type", DT_FLOAT, &def); + conversion_status = (*converter)->ConvertNode(def); + EXPECT_THAT(conversion_status, StatusIs(error::INTERNAL)); + + // Add second input to the node and make the converter aware. + def.mutable_input()->Add("input2"); + conversion_status = (*converter) + ->AddInputTensor("input2", nvinfer1::DataType::kFLOAT, + nvinfer1::Dims{4, {1, 1, 1, 1}}, 1); + EXPECT_THAT(conversion_status, IsOk()); + + // Base class validation should check the type (Constant or Tensor) of the + // inputs. + conversion_status = (*converter)->ConvertNode(def); + EXPECT_THAT( + conversion_status, + StatusIs(error::UNIMPLEMENTED, + HasSubstr("input \"weight\" for FakeFunc must be a constant"))); + + // Correct input2 so that it is a weight. + (*converter)->TensorsMap().erase("input2"); + (*converter) + ->TensorsMap() + .insert(std::make_pair("input2", TRT_TensorOrWeights(TRT_ShapedWeights( + nvinfer1::DataType::kFLOAT)))); + + // With the correct input types, check that the converter is called and sets + // one output tensor. + conversion_status = (*converter)->ConvertNode(def); + EXPECT_THAT(conversion_status, IsOk()); + EXPECT_EQ((*converter)->TensorsMap().size(), 3U); + + GetOpConverterRegistry()->Clear("FakeFunc"); +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/binary_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/binary_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..d53d61a2da4fdef5bbc4f298e0867416320fa2dd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/binary_ops.cc @@ -0,0 +1,235 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +const BinaryOperationMapType* BinaryOperationMap() { + static const auto* map = new BinaryOperationMapType({ + {"Add", nvinfer1::ElementWiseOperation::kSUM}, + {"AddV2", nvinfer1::ElementWiseOperation::kSUM}, + {"Mul", nvinfer1::ElementWiseOperation::kPROD}, + {"Sub", nvinfer1::ElementWiseOperation::kSUB}, + {"Div", nvinfer1::ElementWiseOperation::kDIV}, + {"FloorDiv", nvinfer1::ElementWiseOperation::kFLOOR_DIV}, + {"RealDiv", nvinfer1::ElementWiseOperation::kDIV}, + {"Minimum", nvinfer1::ElementWiseOperation::kMIN}, + {"Maximum", nvinfer1::ElementWiseOperation::kMAX}, + {"Pow", nvinfer1::ElementWiseOperation::kPOW}, +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + {"Greater", nvinfer1::ElementWiseOperation::kGREATER}, + {"Less", nvinfer1::ElementWiseOperation::kLESS}, + {"Equal", nvinfer1::ElementWiseOperation::kEQUAL}, + // Operators are implemented as NOT Less and NOT Greater, respectively. + {"GreaterEqual", nvinfer1::ElementWiseOperation::kLESS}, + {"LessEqual", nvinfer1::ElementWiseOperation::kGREATER}, +#endif + }); + return map; +} + +const BinaryOperationMapType* BinaryBooleanOperationMap() { + static const auto* map = new BinaryOperationMapType({ + {"LogicalOr", nvinfer1::ElementWiseOperation::kOR}, + {"LogicalAnd", nvinfer1::ElementWiseOperation::kAND}, + }); + return map; +} + +namespace { +class ConvertBinaryImpl { + protected: + ConvertBinaryImpl(const BinaryOperationMapType* pOperMap) + : pOperMap_(pOperMap) {} + + Status ValidateImpl( + const OpConverterParams& params, + const std::vector& implicit_batch_not_supported_ops = {}, + bool both_tensors = false) { + const auto& node_def = params.node_def; + const auto& op = node_def.op(); + const auto op_pair = pOperMap_->find(op); + if (op_pair == pOperMap_->end()) { + return errors::Unimplemented("Binary op: ", op, " not supported"); + } + + // Constant folding should have been done by TensorFlow. + const auto& inputs = params.inputs; + if (inputs.at(0).is_weights() && inputs.at(1).is_weights()) { + return errors::Unimplemented( + "Constant folding is falled back to TensorFlow, binary op '", op, + "' received both input as constant"); + } + + if ((convertToBool_ = find_name(op, implicit_batch_not_supported_ops))) { + if (params.use_implicit_batch) { + return errors::Unimplemented( + convert_not_supported_implicit(op, node_def.name(), "Binary")); + } + } + + if (both_tensors) { + if (inputs.at(0).is_weights() || inputs.at(1).is_weights()) { + return errors::InvalidArgument("Both inputs of '", op, + "' are expected to be tensors"); + } + // No need to convert the output of "LogicalOr" and "LogicalAnd" + convertToBool_ = false; + } + + nvinfer1::Dims broadcasted_dims[2]; + TF_RETURN_IF_ERROR(GetTrtBroadcastShape( + inputs.at(0), inputs.at(1), true, params.use_implicit_batch, + broadcasted_dims, broadcasted_dims + 1)); + + for (int i = 0; i < tensor_.size(); i++) { + // This will also convert constants to tensors. + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params.converter, inputs.at(i), broadcasted_dims[i], + params.validation_only, &tensor_[i], node_def, i)); + } + operation_ = op_pair->second; + return OkStatus(); + } + + Status ConvertImpl(const OpConverterParams& params, + const std::vector& revert_bool_ops = {}) { + const auto& node_def = params.node_def; + // Add ElementWise layer. + auto* network = params.converter->network(); + nvinfer1::ILayer* layer = network->addElementWise( + *tensor_[0]->trt_tensor(), *tensor_[1]->trt_tensor(), operation_); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + + if (params.use_explicit_precision) { + layer->setPrecision(nvinfer1::DataType::kFLOAT); + } + + params.converter->SetLayerName(layer, node_def); + const auto& output = layer->getOutput(0); + if (convertToBool_) { + output->setType(nvinfer1::DataType::kBOOL); + if (find_name(node_def.op(), revert_bool_ops)) { + nvinfer1::IUnaryLayer* unary_layer = + network->addUnary(*output, nvinfer1::UnaryOperation::kNOT); + TFTRT_RETURN_ERROR_IF_NULLPTR(unary_layer, node_def.name()); + params.outputs->push_back( + TRT_TensorOrWeights(unary_layer->getOutput(0))); + return OkStatus(); + } + } + + params.outputs->push_back(TRT_TensorOrWeights(output)); + return OkStatus(); + } + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("x", TrtInputArg::kBoth), + InputArgSpec::Create("y", TrtInputArg::kBoth)}; + } + + private: + const BinaryOperationMapType* pOperMap_; + std::array tensor_{nullptr, nullptr}; + nvinfer1::ElementWiseOperation operation_; + bool convertToBool_; +}; + +class ConvertBinary : public OpConverterBase, + protected ConvertBinaryImpl { + public: + explicit ConvertBinary(const OpConverterParams* params) + : OpConverterBase( + params, + {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32}), + ConvertBinaryImpl(BinaryOperationMap()) {} + + static constexpr std::array InputSpec() { + return ConvertBinaryImpl::InputSpec(); + } + + Status Validate() { + const std::vector implicit_batch_not_supported_ops { +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + "Greater", "Less", "Equal", "GreaterEqual", "LessEqual" +#endif + }; + return ValidateImpl(*params_, implicit_batch_not_supported_ops); + } + Status Convert() { + const std::vector implemented_with_reverted_ops { +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + "GreaterEqual", "LessEqual" +#endif + }; + return ConvertImpl(*params_, implemented_with_reverted_ops); + } +}; + +class ConvertBooleanBinary : public OpConverterBase, + public ConvertBinaryImpl { + public: + explicit ConvertBooleanBinary(const OpConverterParams* params) + : OpConverterBase(params, {DataType::DT_BOOL}), + ConvertBinaryImpl(BinaryBooleanOperationMap()) {} + + static constexpr std::array InputSpec() { + return ConvertBinaryImpl::InputSpec(); + } + + static constexpr const char* NodeDefDataTypeAttributeName() { + /* + node { + name: "..." + op: "LogicalOr" + input: "..." + input: "..." + attr { + key: "_output_shapes" + ... + } + } + */ + return ""; + } + Status Validate() { +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + return ValidateImpl(*params_, {"LogicalOr", "LogicalAnd"}, true); +#else + return errors::Unimplemented("Boolean op: ", params_->node_def.op(), + " is not supported in TRT version < 8.2"); +#endif + } + Status Convert() { return ConvertImpl(*params_); } +}; +} // namespace + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + GetOperationNames(*BinaryOperationMap())); +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction(), + GetOperationNames(*BinaryBooleanOperationMap())); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/data_format_vec_permute.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/data_format_vec_permute.cc new file mode 100644 index 0000000000000000000000000000000000000000..f6570d60116f72400d76db5e59353bbab155f3d1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/data_format_vec_permute.cc @@ -0,0 +1,176 @@ +/* Copyright 2021 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "third_party/tensorrt/NvInfer.h" +#include "third_party/tensorrt/NvInferRuntimeCommon.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +int get_spatial_dim_count(string format) { + // Spatial dimensions are the dimensions besides NC, and here we assume NC + // always appear in the format string. + return format.size() - 2; +} + +class ConvertDataFormatVecPermute + : public OpConverterBase { + public: + ConvertDataFormatVecPermute(const OpConverterParams* params) + : OpConverterBase(params, + {DataType::DT_INT32}) {} + + struct DataFormatVecPermuteAttributes { + string dst_format; + string src_format; + int x_dim_count; + }; + + static constexpr std::array InputSpec() { + return {InputArgSpec::Create("x", TrtInputArg::kBoth)}; + } + + Status Validate() { + TF_RETURN_IF_ERROR(NotSupportedInImplicitBatch()); + const auto& inputs = params_->inputs; + const auto& nodeName = params_->node_def.name(); + + x_input_ = inputs.at(0); + + // Check input rank. + const auto x_dims = x_input_.GetTrtDims(); + int input_rank = x_dims.nbDims; + if (input_rank != 1 && input_rank != 2) { + return errors::InvalidArgument( + "Input must be a vector or matrix, but got rank ", input_rank, + ", at ", nodeName); + } + + // Verify and consume node attributes. + StatusOr dst_format = GetAttrValue("dst_format"); + StatusOr src_format = GetAttrValue("src_format"); + TRT_ENSURE_OK(dst_format); + TRT_ENSURE_OK(src_format); + + // Check input dims. + const int full_dim_count = src_format->size(); + const int spatial_dim_count = get_spatial_dim_count(*src_format); + if (input_rank == 1) { + if (x_dims.d[0] != spatial_dim_count && x_dims.d[0] != full_dim_count) { + return errors::InvalidArgument( + "1D input must be of size ", spatial_dim_count, " or ", + full_dim_count, ", but got size ", x_dims.d[0], ", at ", nodeName); + } + } else if (input_rank == 2) { + if (x_dims.d[0] != spatial_dim_count && x_dims.d[0] != full_dim_count) { + return errors::InvalidArgument( + "First dimension of 2D input must be of size ", spatial_dim_count, + " or ", full_dim_count, ", but got shape (", x_dims.d[0], ", ", + x_dims.d[1], "), at ", nodeName); + } + if (x_dims.d[1] != 2) { + return errors::InvalidArgument( + "Second dimension of 2D input must be of size 2, but got shape (", + x_dims.d[0], ", ", x_dims.d[1], "), at ", nodeName); + } + } + + // Set custom attributes. + attrs_.x_dim_count = x_dims.d[0]; + attrs_.dst_format = *dst_format; + attrs_.src_format = *src_format; + + return OkStatus(); + } + + Status Convert() { + // Copy format strings in case they need to be modified. + string dst_format = attrs_.dst_format; + string src_format = attrs_.src_format; + const int& spatial_dim_count = get_spatial_dim_count(src_format); + + // If the input is a vector of size spatial_dim_count, treat the elements + // as spatial dimensions. + if (attrs_.x_dim_count == spatial_dim_count) { + auto keep_only_spatial_dimensions = + [spatial_dim_count](string* format_str) -> void { + auto new_end = std::remove_if(format_str->begin(), format_str->end(), + [spatial_dim_count](const char dim) { + return dim == 'N' || dim == 'C'; + }); + format_str->erase(new_end, format_str->end()); + }; + keep_only_spatial_dimensions(&src_format); + keep_only_spatial_dimensions(&dst_format); + } + + // Create indices for the gather layer and make weights out of them. + std::vector dst_indices(attrs_.x_dim_count); + for (int i = 0; i < attrs_.x_dim_count; ++i) { + for (int j = 0; j < attrs_.x_dim_count; ++j) { + if (src_format[i] == dst_format[j]) { + dst_indices[j] = i; + break; + } + } + } + nvinfer1::Dims indices_dims = {1, {attrs_.x_dim_count}}; + StatusOr indices_weights = + params_->weight_store->GetTempWeights(nvinfer1::DataType::kINT32, + indices_dims); + TRT_ENSURE_OK(indices_weights); + int32* indices_ptr = indices_weights->GetPointer(); + std::copy(dst_indices.data(), dst_indices.data() + attrs_.x_dim_count, + indices_ptr); + ITensorProxyPtr x_tensor = + x_input_.is_weights() ? params_->converter->CreateConstantLayer( + x_input_.weights(), x_input_.GetTrtDims()) + : x_input_.tensor(); + ITensorProxyPtr indices_tensor = + params_->converter->CreateConstantLayer(*indices_weights, indices_dims); + + // Gather layer with 1D indices on axis 0, conserves shape. + nvinfer1::IGatherLayer* layer = params_->converter->network()->addGather( + *x_tensor->trt_tensor(), *indices_tensor->trt_tensor(), 0); + TRT_ENSURE(layer); + params_->converter->SetLayerName(layer, params_->node_def); + + ITensorProxyPtr output_tensor = layer->getOutput(0); + + params_->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } + + private: + TRT_TensorOrWeights x_input_; + DataFormatVecPermuteAttributes attrs_{}; +}; +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction(), + {"DataFormatVecPermute"}); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/einsum.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/einsum.cc new file mode 100644 index 0000000000000000000000000000000000000000..6acc3b723650561b0258a51064b045361784f234 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/einsum.cc @@ -0,0 +1,908 @@ +/* Copyright 2022 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/util/einsum_op_util.h" +#include "third_party/tensorrt/NvInfer.h" + +#if IS_TRT_VERSION_GE(7, 1, 3, 0) + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +namespace { + +#if !IS_TRT_VERSION_GE(8, 2, 0, 0) + +// Finds the indices of elements in [begin, end) in array +// [array_begin, array_end), and appends the indices to permute. This is used to +// construct the permutation sequence for the operand with input labels +// [array_begin, array_end) to the desired permuted labels [begin, end). +template +Status FindIndicesoOfAllValuesInSrc(absl::Span values, + absl::Span src, + std::vector* indices) { + if (src.size() < values.size()) { + return errors::Internal( + "Span 'src' cannot contain all elements of 'values'"); + } + for (auto i = 0; i < values.size(); i++) { + auto iter = absl::c_find(src, values[i]); + if (iter == src.end()) { + return errors::Internal("Label ", values[i], " not found"); + } + int idx = std::distance(src.begin(), iter); + indices->push_back(idx); + } + return OkStatus(); +} + +// Layout of the einsum dimensions: Batch, Free and Contraction indices. +// Example: adbc,adce -> adbe. The first tensor has layout BFC, the second BCF. +enum class EinsumLayout { BFC, BCF, MIX }; + +using DimType = EinsumDimensionType; +constexpr auto kBatch = DimType::kBatch; +constexpr auto kFree = DimType::kFree; +constexpr auto kContract = DimType::kContract; + +// Describes an operand: input shape, number of batch, free and contract +// dimensions, and the permutation that is needed to bring it to a matmul +// compatible form. +class EinsumDescriptor { + private: + // Checks whether input_labels[offset:offset+m] matches labels from other. + static bool OrderMatches(const Labels& input_labels, int offset, int m, + EinsumDimensionType dim_type, + const std::unique_ptr& other) { + if (other == nullptr) { + return true; + } + int offset_other = 0; + if (dim_type == kFree) { + offset = other->offset_f; + } else if (dim_type == kContract) { + offset = other->offset_c; + } + return std::equal(input_labels.begin() + offset, + input_labels.begin() + offset + m, + other->permuted_labels.begin() + offset_other); + } + + using label_t_iterator = std::vector::const_iterator; + static int32_t CountLabels(label_t_iterator begin, label_t_iterator end, + EinsumDimensionType val) { + return static_cast(std::count_if( + begin, end, [val](EinsumDimensionType t) { return t == val; })); + } + + // Appends indices to the "permute" vector where types matches value. + void AppendMatchingIndicesToPermute( + const std::vector& types, EinsumDimensionType val) { + for (int i = 0; i < types.size(); i++) { + if (types[i] == val) { + permute.push_back(i); + } + } + } + + Status DetermineLayout(const Labels& input_labels, + const std::vector& types, + const std::unique_ptr& other) { + // Check if the current layout is BFC or BCF. In that case we could avoid + // transpose. + layout = EinsumLayout::MIX; + if (CountLabels(types.begin(), types.begin() + b, kBatch) == b && + OrderMatches(input_labels, 0, b, kBatch, other)) { + // Batch dims are the leading dims. They have the same order as other. + if (CountLabels(types.begin() + b, types.begin() + b + f, kFree) == f) { + // All the free dims are placed consecutively after the batch dims. + // Their order is arbitrary. The final transpose will ensure that the + // output has correct order. We still have to check that the contract + // indices have correct order. + if (OrderMatches(input_labels, b + f, c, kContract, other)) { + layout = EinsumLayout::BFC; + } + } else if (CountLabels(types.begin() + b, types.begin() + b + c, + kContract) == c) { + // All the contract dims are placed consecutively after the batch + // dims. Check whether the contract dims have the same order as the + // contract dims in other. + if (OrderMatches(input_labels, b, c, kContract, other)) { + layout = EinsumLayout::BCF; + } + } + } + return OkStatus(); + } + + Status CalculateMixedLayoutPermutation( + const EinsumLayout preferred_layout, const Labels& input_labels, + const std::vector& types, + const std::unique_ptr& other) { + // Input label types are mixed. Calculate a permutation that maps them + // to the preferred layout (BCF or BFC). + layout = preferred_layout; + if (other == nullptr) { + AppendMatchingIndicesToPermute(types, kBatch); + } else { + TF_RETURN_IF_ERROR( + FindIndicesoOfAllValuesInSrc(/*values=*/ + absl::MakeConstSpan( + other->permuted_labels.begin(), + other->b), + /*src=*/ + absl::MakeConstSpan(input_labels.begin(), + input_labels.size()), + /*indices=*/&permute)); + } + if (layout == EinsumLayout::BFC) { + AppendMatchingIndicesToPermute(types, kFree); + if (other == nullptr) { + AppendMatchingIndicesToPermute(types, kContract); + } else { + TF_RETURN_IF_ERROR(FindIndicesoOfAllValuesInSrc( + /*values=*/absl::MakeConstSpan( + other->permuted_labels.begin() + other->offset_c, other->c), + /*src=*/ + absl::MakeConstSpan(input_labels.begin(), input_labels.size()), + /*indices=*/&permute)); + } + return OkStatus(); + } + if (other == nullptr) { + AppendMatchingIndicesToPermute(types, kContract); + } else { + TF_RETURN_IF_ERROR(FindIndicesoOfAllValuesInSrc( + /*values=*/absl::MakeConstSpan( + other->permuted_labels.begin() + other->offset_c, other->c), + /*src=*/absl::MakeConstSpan(input_labels.begin(), input_labels.end()), + /*indices=*/&permute)); + } + AppendMatchingIndicesToPermute(types, kFree); + return OkStatus(); + } + + Status Initialize(const TRT_TensorOrWeights& operand, Labels input_labels, + std::vector& label_types, + EinsumLayout preferred_layout, + const std::unique_ptr& other = nullptr) { + if (preferred_layout == EinsumLayout::MIX) { + return errors::Internal("Preferred einsum layout cannot be MIX"); + } + // Map label indices to label types. + std::vector types; // Input label types. + std::transform(input_labels.begin(), input_labels.end(), + std::back_inserter(types), + [&label_types](int i) { return label_types.at(i); }); + + b = CountLabels(types.begin(), types.end(), kBatch); + f = CountLabels(types.begin(), types.end(), kFree); + c = CountLabels(types.begin(), types.end(), kContract); + + if (c == 0 || f == 0) { + VLOG(2) << "Einsum equation needs to have at least one free and one " + "contract dimension"; + return errors::Unimplemented("No conversion for einsum equation."); + } + + TF_RETURN_IF_ERROR(DetermineLayout(input_labels, types, other)); + if (layout == EinsumLayout::MIX) { + TF_RETURN_IF_ERROR(CalculateMixedLayoutPermutation( + preferred_layout, input_labels, types, other)); + } + + if (layout == EinsumLayout::BFC) { + offset_f = b; + offset_c = f + b; + } else { + offset_f = b + c; + offset_c = b; + } + + dims = operand.GetTrtDims(); + for (int i = 0; i < b; i++) { + // Set unknown batch dims to zero. These dims will be used in reshape op, + // where zero is a special value for retaining the original dim size. + if (dims.d[i] == -1) { + dims.d[i] = 0; + } + } + permuted_labels = input_labels; + if (!permute.empty()) { + // Apply the permutation on the dimension array. + nvinfer1::Dims orig_dims = dims; + for (int i = 0; i < permute.size(); i++) { + dims.d[i] = orig_dims.d[permute[i]]; + permuted_labels[i] = input_labels[permute[i]]; + } + } + size_tensors.resize(dims.nbDims, nullptr); + return OkStatus(); + } + + public: + EinsumDescriptor() : b(0), f(0), c(0) {} + + // Deduces the number of batch, free, contract dimensions from the input + // labels, decides what layout to use, and determines permutation indices for + // that layout. + static StatusOr> Create( + const TRT_TensorOrWeights& operand, Labels input_labels, + std::vector& label_types, + EinsumLayout preferred_layout, + const std::unique_ptr& other = nullptr) { + auto desc = std::make_unique(); + TF_RETURN_IF_ERROR(desc->Initialize(operand, input_labels, label_types, + preferred_layout, other)); + VLOG(2) << desc->DebugString(); + return desc; + } + + int NumBatchDims() const { return b; } + int NumContractDims() const { return c; } + int NumFreeDims() const { return f; } + int ContractDimOffset() const { return offset_c; } + const Labels& PermutedLabels() const { return permuted_labels; } + + std::string DebugString() const { + return absl::StrCat("Descriptor with ", + (layout == EinsumLayout::BFC ? "BFC" : "BCF"), + " layout, b=", b, ", f=", f, ", c=", c); + } + + // Returns whether the free and contract dimension have static shape. + bool HasStaticShape() const { + return !std::any_of(dims.d + b, dims.d + dims.nbDims, + [](int k) { return k == -1; }); + } + + nvinfer1::Permutation GetPermutation() const { + nvinfer1::Permutation p; + std::copy(permute.begin(), permute.end(), p.order); + return p; + } + + std::vector PermuteVector() const { return permute; } + + // Sets the "size_tensors" vector to be filled with scalar constant tensors + // representing the shape of the operand. + Status SetDynamicSize(TRTNetworkBuilder* builder, + const TRT_TensorOrWeights& operand) { + TRT_ENSURE(operand.GetTrtDims().nbDims == dims.nbDims); + if (operand.is_weights()) { + // Generate constants for each dimension of the constant weight tensor's + // shape. + for (int i = 0; i < operand.GetTrtDims().nbDims; i++) { + StatusOr size_tensor = + builder->Constant(dims.d[i], 1); + TRT_ENSURE_PTR_OK(size_tensor); + size_tensors[i] = (*size_tensor)->getOutput(0); + } + return OkStatus(); + } + + // If the operand is a dynamic tensor, compute the shape value dynamically. + StatusOr shape_layer = + builder->Shape(operand.tensor()->trt_tensor()); + TRT_ENSURE_PTR_OK(shape_layer); + nvinfer1::ITensor* shape = (*shape_layer)->getOutput(0); + for (int i = 0; i < operand.GetTrtDims().nbDims; i++) { + int idx = permute.empty() ? i : permute.at(i); + StatusOr slice_layer = + builder->Slice(shape, {1, {idx}}, {1, {1}}, {1, {1}}); + TRT_ENSURE_PTR_OK(slice_layer); + size_tensors[i] = (*slice_layer)->getOutput(0); + } + return OkStatus(); + } + + EinsumLayout layout; + int b; // number of batch dims + int f; // number of free dims + int c; // number of conraction dims + int offset_f; + int offset_c; + nvinfer1::Dims dims; + std::vector permute; + std::vector size_tensors; + Labels permuted_labels; +}; + +// Reshapes operand so that the free dimensions are combined into a single dim, +// and the contract dimensions are combined into another single dim. +Status GetEinsumNewDynamicShape(TRTNetworkBuilder* builder, + const EinsumDescriptor& desc, + ITensorProxyPtr* new_shape) { + std::vector size; + size.reserve(desc.b + 2); + absl::c_transform(absl::MakeSpan(desc.size_tensors).subspan(0, desc.b + 2), + std::back_inserter(size), + [](const ITensorProxyPtr x) { return x->trt_tensor(); }); + + int idx_f = desc.layout == EinsumLayout::BFC ? desc.b : desc.b + 1; + int idx_c = desc.layout == EinsumLayout::BFC ? desc.b + 1 : desc.b; + + std::vector size_tensors; + size_tensors.reserve(desc.size_tensors.size()); + absl::c_transform(desc.size_tensors, std::back_inserter(size_tensors), + [](const ITensorProxyPtr x) -> nvinfer1::ITensor* { + return x->trt_tensor(); + }); + + StatusOr shape_vol = builder->CumulativeProd( + absl::MakeSpan(size_tensors).subspan(desc.offset_f, desc.f)); + TRT_ENSURE_PTR_OK(shape_vol); + size[idx_f] = (*shape_vol)->getOutput(0); + + shape_vol = builder->CumulativeProd( + absl::MakeSpan(size_tensors).subspan(desc.offset_c, desc.c)); + TRT_ENSURE_PTR_OK(shape_vol); + size[idx_c] = (*shape_vol)->getOutput(0); + StatusOr layer = + builder->Concat(size, /*axis=*/0); + TRT_ENSURE_PTR_OK(layer); + *new_shape = (*layer)->getOutput(0); + return OkStatus(); +} + +// Reshapes operand so that the free dimensions are combined into a single dim, +// and the contract dimensions are combined into another single dim. +Status GetEinsumNewStaticShape(const EinsumDescriptor& desc, + nvinfer1::Dims* new_dims) { + // Copy the batch dims and append two additional dimensions. + DimsAdapter adap( + absl::MakeSpan(static_cast(desc.dims.d), desc.b)); + adap.Append(1).Append(1); + + // Combine free dims and contract dims. + int idx_f = desc.layout == EinsumLayout::BFC ? desc.b : desc.b + 1; + int idx_c = desc.layout == EinsumLayout::BFC ? desc.b + 1 : desc.b; + + // Find the volume of the free dimensions. + int64_t vol_f = + DimsAdapter( + absl::MakeSpan( + static_cast(desc.dims.d) + desc.offset_f, desc.f)) + .Volume(); + + // Find the volume of the contracted dimensions. + int64_t vol_c = + DimsAdapter( + absl::MakeSpan( + static_cast(desc.dims.d) + desc.offset_c, desc.c)) + .Volume(); + + adap.dim(idx_f) = vol_f; + adap.dim(idx_c) = vol_c; + *new_dims = adap.AsTrtDims(); + return OkStatus(); +} + +StatusOr ConditionEinsumWeights( + TRTNetworkBuilder* builder, const TRT_TensorOrWeights& operand, + const EinsumDescriptor& desc, const bool need_transpose) { + TRT_ENSURE(operand.is_weights()); + if (!need_transpose) { + // If we don't need to transpose, then the operand remains as a weights + // constant. In this case we also don't need a reshape. + TRT_ShapedWeights weights(operand.weights()); + nvinfer1::Dims new_dims; + TF_RETURN_IF_ERROR(GetEinsumNewStaticShape(desc, &new_dims)); + TF_RETURN_IF_ERROR(weights.SetShape(new_dims)); + return TRT_TensorOrWeights(weights); + } + + // Let TensorRT handle constant folding where possible. + StatusOr tensor = builder->WeightsToConstant( + operand.weights().GetTrtWeights(), operand.GetTrtDims()); + TRT_ENSURE_PTR_OK(tensor); + return TRT_TensorOrWeights((*tensor)->getOutput(0)); +} + +// Builds a TRT shuffle operation for the given operand. Replaces operand with a +// pointer to the shuffle output. +Status ConditionEinsumTensor(TRTNetworkBuilder* builder, + std::unique_ptr* operand, + const EinsumDescriptor& desc, + const bool need_transpose, + const bool need_reshape) { + StatusOr shuffle = + ShuffleBuilder::Create(builder, (*operand)->tensor()->trt_tensor()); + TRT_ENSURE_OK(shuffle); + + // Set new shape. + if (need_reshape) { + if (desc.HasStaticShape()) { + nvinfer1::Dims new_dims; + TF_RETURN_IF_ERROR(GetEinsumNewStaticShape(desc, &new_dims)); + shuffle->SetReshape(new_dims); + } else { + ITensorProxyPtr new_shape; + TF_RETURN_IF_ERROR(GetEinsumNewDynamicShape(&*builder, desc, &new_shape)); + shuffle->SetReshape(new_shape->trt_tensor()); + } + } + + if (need_transpose) { + shuffle->SetFirstTranspose(desc.GetPermutation()); + } + + StatusOr shuffle_out = shuffle->Output(); + TRT_ENSURE_PTR_OK(shuffle_out); + *operand = std::make_unique(*shuffle_out); + return OkStatus(); +} + +// Handles einsum operand conditioning for both constant and non-constant +// inputs. This is supported using the ShuffleEinsumWeights and +// ShuffleEinsumTensor routines. +Status ConditionEinsumOperand(TRTNetworkBuilder* builder, + std::unique_ptr* operand, + const EinsumDescriptor& desc) { + bool need_reshape = (desc.f != 1 || desc.c != 1); + bool need_transpose = !desc.permute.empty(); + + VLOG(2) << "Condition operand. Need reshape: " << need_reshape + << ". Need transpose: " << need_transpose; + + if ((*operand)->is_weights()) { + StatusOr result = + ConditionEinsumWeights(builder, **operand, desc, need_transpose); + TRT_ENSURE_OK(result); + *operand = std::make_unique(std::move(result).value()); + } + + // If we didn't convert the operand to a tensor, we can return here. + if ((*operand)->is_weights()) { + return OkStatus(); + } + + TF_RETURN_IF_ERROR(ConditionEinsumTensor(builder, operand, desc, + need_transpose, need_reshape)); + + return OkStatus(); +} + +// Combines output dims/labels by copying batch and free dims/labels from input +// A, and concatenating free values from input B. +template +void AssembleOutput(InputIterator begin_a, InputIterator begin_b, + const EinsumDescriptor& desc_a, + const EinsumDescriptor& desc_b, OutputIterator out) { + std::copy(begin_a, begin_a + desc_a.b, out); + begin_a += desc_a.offset_f; + std::copy(begin_a, begin_a + desc_a.f, out + desc_a.b); + begin_b += desc_b.offset_f; + std::copy(begin_b, begin_b + desc_b.f, out + desc_a.b + desc_a.f); +} + +// Restores free dimensions and sets final index order. Consider C = A * B, +// batched MatMul op, where A.shape = [B, x, k] and B.shape = [B, k, y]. Then +// C.shape = [B, x, y]. Here B can denote multiple batch indices while x, y, k +// are single indices. The original inputs to Einsum can have multiple free +// indices. These were combined into a singe free dimension x and y, for example +// x = f_a1 * f_a2 * f_a3, y = f_b1 * f_b2. This routine creates a shuffle layer +// to expand x into and y the original free dims, e.g. C is reshaped to +// [B, f_a1, f_a2, f_a3, f_b1, f_b2]. Finally, a permutation is applied to +// transform the shape to the shape of the original Einsum output. +Status ShuffleEinsumOutput(const OpConverterParams* params, + EinsumDescriptor desc_a, EinsumDescriptor desc_b, + const std::vector& permutation, + ITensorProxyPtr* output) { + if (permutation.empty() && (desc_a.f == 1 && desc_b.f == 1)) { + return OkStatus(); + } + + nvinfer1::IShuffleLayer* layer = + params->converter->network()->addShuffle(*(*output)->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, params->node_def.name()); + params->converter->SetLayerName(layer, params->node_def, "shuffle", + /*sub_op_instance=*/2); + + int output_rank = desc_a.b + desc_a.f + desc_b.f; + if (desc_a.f != 1 || desc_b.f != 1) { + if (desc_a.HasStaticShape() && desc_b.HasStaticShape()) { + nvinfer1::Dims dims_out = {output_rank, {}}; + AssembleOutput(desc_a.dims.d, desc_b.dims.d, desc_a, desc_b, dims_out.d); + layer->setReshapeDimensions(dims_out); + } else { + std::vector size_tensors(output_rank); + AssembleOutput(desc_a.size_tensors.begin(), desc_b.size_tensors.begin(), + desc_a, desc_b, size_tensors.begin()); + ITensorProxyPtr new_shape; + auto builder = TRTNetworkBuilder::Create(params->converter->network(), + params->weight_store); + TRT_ENSURE_OK(builder); + std::vector size_itensors; + absl::c_transform(size_tensors, std::back_inserter(size_itensors), + [](auto x) { return x->trt_tensor(); }); + StatusOr concat = + builder->Concat(size_itensors, /*axis=*/0); + TRT_ENSURE_PTR_OK(concat); + new_shape = (*concat)->getOutput(0); + layer->setInput(1, *new_shape->trt_tensor()); + } + } + + if (!permutation.empty()) { + nvinfer1::Permutation p; + std::copy(permutation.begin(), permutation.end(), p.order); + layer->setSecondTranspose(p); + } + *output = layer->getOutput(0); + return OkStatus(); +} + +// Updates "final_transpose" according to the given descriptors and output +// labels. +StatusOr> GetOutputTranspose( + const EinsumDescriptor& descriptor_a, const EinsumDescriptor& descriptor_b, + Labels output_labels) { + // Get final transpose. + std::vector final_transpose; + final_transpose.reserve(descriptor_a.b + descriptor_a.f + descriptor_b.f); + Labels matmul_output_labels(descriptor_a.b + descriptor_a.f + descriptor_b.f); + AssembleOutput(descriptor_a.permuted_labels.begin(), + descriptor_b.permuted_labels.begin(), descriptor_a, + descriptor_b, matmul_output_labels.begin()); + TF_RETURN_IF_ERROR( + FindIndicesoOfAllValuesInSrc(/*values=*/ + absl::MakeConstSpan(output_labels.begin(), + output_labels.end()), + /*src=*/ + absl::MakeConstSpan( + matmul_output_labels.begin(), + matmul_output_labels.end()), + /*indices=*/&final_transpose)); + // Clear identity transpose. + bool identity_transpose = true; + for (int i = 0; i < final_transpose.size() && identity_transpose; i++) { + identity_transpose &= final_transpose.at(i) == i; + } + if (identity_transpose) { + final_transpose.clear(); + } + return final_transpose; +} + +// Prepares EinsumDescriptors after parsing the equation and determines the +// final transpose. +Status ParseEquation(const std::string& equation, + std::unique_ptr* input_a, + std::unique_ptr* input_b, + std::unique_ptr* descriptor_a, + std::unique_ptr* descriptor_b, + std::vector* final_transpose) { + VLOG(2) << "Einsum equation " << equation; + OperandLabels input_labels; + Labels output_labels; + std::vector label_types; + OperandLabelCounts input_label_counts; + LabelCounts output_label_counts; + absl::InlinedVector input_has_ellipsis; + bool output_has_ellipsis; + TF_RETURN_IF_ERROR( + ParseEinsumEquation(equation, &input_labels, &output_labels, &label_types, + &input_label_counts, &output_label_counts, + &input_has_ellipsis, &output_has_ellipsis)); + + if (input_has_ellipsis[0] || input_has_ellipsis[1] || output_has_ellipsis) { + // TODO(tfeher): Handle ellipsis like EinsumHelper::ProcessDimensions. + // Note: ProcessDimensions would introduce kBroadcasting labels, which we + // need to replace with kBatch before we call InitDescriptor. + VLOG(2) << "Ellipsis not yet supported"; + return errors::Unimplemented("No conversion for einsum equation."); + } + + if (absl::c_any_of(label_types, [](auto l) { + return l == EinsumDimensionType::kReduce || + l == EinsumDimensionType::kBroadcasting; + })) { + VLOG(2) << "Einsum reductions not implemented"; + return errors::Unimplemented("No conversion for einsum equation."); + } + + auto no_duplicated_labels = [](const LabelCounts& label_counts) { + return absl::c_any_of(label_counts, [](int i) { return i > 1; }); + }; + if (no_duplicated_labels(input_label_counts[0]) || + no_duplicated_labels(input_label_counts[1]) || + no_duplicated_labels(output_label_counts)) { + VLOG(2) << "Einsum invalid label count"; + return errors::Unimplemented("No conversion for einsum equation."); + } + + if ((*input_a)->is_weights() && (*input_b)->is_tensor()) { + // We prefer to use FC layer, needs A as tensor and B as weight. + std::swap(*input_a, *input_b); + std::swap(input_labels[0], input_labels[1]); + std::swap(input_label_counts[0], input_label_counts[1]); + } + + auto desc = EinsumDescriptor::Create(**input_a, input_labels[0], label_types, + EinsumLayout::BFC); + TF_RETURN_IF_ERROR(desc.status()); + *descriptor_a = std::move(desc).value(); + + desc = EinsumDescriptor::Create(**input_b, input_labels[1], label_types, + EinsumLayout::BCF, *descriptor_a); + TF_RETURN_IF_ERROR(desc.status()); + *descriptor_b = std::move(desc).value(); + + auto out_transpose = + GetOutputTranspose(**descriptor_a, **descriptor_b, output_labels); + + TRT_ENSURE_OK(out_transpose) + *final_transpose = std::move(out_transpose).value(); + return OkStatus(); +} + +class ConvertEinsum : public OpConverterBase { + public: + explicit ConvertEinsum(const OpConverterParams* params) + : OpConverterBase(params) {} + + static constexpr std::array InputSpec() { + return {InputArgSpec::Create("input_a", TrtInputArg::kBoth), + InputArgSpec::Create("input_b", TrtInputArg::kBoth)}; + } + + Status Validate() { + TF_RETURN_IF_ERROR(NotSupportedInImplicitBatch()); + const auto& inputs = params_->inputs; + input_a = std::make_unique(inputs.at(0)); + input_b = std::make_unique(inputs.at(1)); + + StatusOr eq = GetAttrValue("equation"); + TRT_ENSURE_OK(eq); + TF_RETURN_IF_ERROR(ParseEquation(*eq, &input_a, &input_b, &descriptor_a, + &descriptor_b, &final_transpose)); + return OkStatus(); + } + + Status Convert() { + auto builder = TRTNetworkBuilder::Create(params_->converter->network(), + params_->weight_store); + TRT_ENSURE_OK(builder); + TRT_ENSURE(input_a && input_b); + TRT_ENSURE(descriptor_a && descriptor_b); + + // Populate the size_tensor vector in the descriptor. + TF_RETURN_IF_ERROR(descriptor_a->SetDynamicSize(&*builder, *input_a)); + TF_RETURN_IF_ERROR(descriptor_b->SetDynamicSize(&*builder, *input_b)); + + // Condition the operands for lowering to matmul. + TF_RETURN_IF_ERROR( + ConditionEinsumOperand(&*builder, &input_a, *descriptor_a)); + TF_RETURN_IF_ERROR( + ConditionEinsumOperand(&*builder, &input_b, *descriptor_b)); + + // Build the matmul implementation. + StatusOr result = ConvertMatMulImpl( + params_, *input_a, *input_b, descriptor_a->layout == EinsumLayout::BCF, + descriptor_b->layout == EinsumLayout::BFC); + TF_RETURN_IF_ERROR(result.status()); + ITensorProxyPtr output = result.value(); + + // Reshape and permute the output. + TF_RETURN_IF_ERROR(ShuffleEinsumOutput( + params_, *descriptor_a, *descriptor_b, final_transpose, &output)); + this->AddOutput(output); + return OkStatus(); + } + + private: + std::unique_ptr input_a{nullptr}; + std::unique_ptr input_b{nullptr}; + std::vector final_transpose; + std::unique_ptr descriptor_a{nullptr}; + std::unique_ptr descriptor_b{nullptr}; +}; +#else + +// Helper class to reindex equations to contain only lowercase characters. We +// simply define a mapping from the old character set to a new set. +// - The input is assumed to be a valid TF equation. +// - The input is TRT compatible, therefore it has max 8 dims. (Thus we have +// enough lowercase English characters to represent the equation.) +// How do we reindex/map equations: +// - Only uppercase letters are changed, if possible we just lowercase them. +// - If the equation contains both upper and lowercase variant of a letter, say +// X and x, then we map X to the first unused lowercase letter. +class ReIndexer { + public: + // Initializes the index map with existing lowercase labels. + ReIndexer(std::string eq) { + for (char c : eq) { + if (absl::ascii_islower(c)) { + idx_map_[c] = c; + } + } + } + // Finds new character for uppercase character c. + char operator()(char c) { + if (!absl::ascii_isupper(c)) return c; + if (idx_map_.count(c) > 0) return idx_map_[c]; + char new_idx = absl::ascii_tolower(c); + + // If lower(c) is not used in the equation, use it to replace c. + if (idx_map_.count(new_idx) == 0) { + idx_map_[c] = new_idx; + idx_map_[new_idx] = new_idx; // mark that new_idx is taken + return new_idx; + } + + // Otherwise, find the first available lower case to replace c. + for (char k = 'a'; k <= 'z'; k++) { + if (idx_map_.count(k) == 0) { + new_idx = k; + idx_map_[c] = new_idx; + idx_map_[new_idx] = new_idx; // mark that new_idx is taken + break; + } + } + return new_idx; + } + + private: + // Each key is an index used in the original or in the reindexed equation. + // The values are the corresponding new lowercase indices. + std::map idx_map_; +}; + +class ConvertEinsum : public OpConverterBase { + public: + explicit ConvertEinsum(const OpConverterParams* params) + : OpConverterBase(params) {} + + Status ValidateInputs() { + TRT_ENSURE(params_->inputs.size() <= 2); + return OkStatus(); + } + static constexpr bool HasFixNumberOfInputs() { return false; } + + static constexpr std::array InputSpec() { + return {InputArgSpec::Create("input_a", TrtInputArg::kBoth), + InputArgSpec::Create("input_b", TrtInputArg::kBoth)}; + } + + std::string MakeLowerCase(const std::string& eq) { + std::string res = eq; + ReIndexer reindexer(eq); + std::transform(eq.begin(), eq.end(), res.begin(), reindexer); + return res; + } + + // Checks if the equation is supported by TRT. + Status ValidateEinsumEquation(const std::string& eq) { + const auto& inputs = params_->inputs; + OperandLabels input_labels; + Labels output_labels; + std::vector label_types; + OperandLabelCounts input_label_counts; + LabelCounts output_label_counts; + absl::InlinedVector input_has_ellipsis; + bool output_has_ellipsis; + VLOG(2) << "Parsing equation " << eq; + TF_RETURN_IF_ERROR(ParseEinsumEquation( + eq, &input_labels, &output_labels, &label_types, &input_label_counts, + &output_label_counts, &input_has_ellipsis, &output_has_ellipsis)); + + Status unimplemented = + errors::Unimplemented("No conversion for einsum equation."); + if (input_has_ellipsis[0] || (inputs.size() > 1 && input_has_ellipsis[1]) || + output_has_ellipsis) { + VLOG(2) << "Ellipsis not yet supported"; + return unimplemented; + } + for (int i = 0; i < input_label_counts.size(); i++) { + for (int k = 0; k < input_label_counts[i].size(); k++) { + if (input_label_counts[i][k] > 1) { + VLOG(2) << "Diagonal operation or reduction not yet supported"; + return unimplemented; + } + } + } + bool has_out_idx = + std::reduce(output_label_counts.begin(), output_label_counts.end(), + false, std::logical_or()); + if (!has_out_idx) { + VLOG(2) << "Scalar output not allowed in dynamic shape mode"; + return unimplemented; + } + // Check for outer product + if (input_label_counts.size() == 2 && output_label_counts.size() == 2 && + output_label_counts[0] == 1 && output_label_counts[1] == 1) { + VLOG(2) << "Outer product not supported"; + return unimplemented; + } + return OkStatus(); + } + + Status Validate() { + VLOG(2) << "Running validation using the new einsum " + "converter"; + TF_RETURN_IF_ERROR(NotSupportedInImplicitBatch()); + StatusOr eq = GetAttrValue("equation"); + TRT_ENSURE_OK(eq); + + TF_RETURN_IF_ERROR(ValidateEinsumEquation(*eq)); + + // While TF has case sensitive equations, TensorRT expects lowercase eq (as + // of version 8.4). See + // https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html#einsum-layer + equation = MakeLowerCase(*eq); + + return OkStatus(); + } + + Status Convert() { + auto builder = TRTNetworkBuilder::Create(params_->converter->network(), + params_->weight_store); + TRT_ENSURE_OK(builder); + + std::vector trt_input; + for (const TRT_TensorOrWeights& input_arg : params_->inputs) { + ITensorProxyPtr ptr = nullptr; + if (input_arg.is_tensor()) { + ptr = input_arg.tensor(); + } else { + StatusOr const_layer = + builder->WeightsToConstant(input_arg.weights().GetTrtWeights(), + input_arg.GetTrtDims()); + TRT_ENSURE_PTR_OK(const_layer); + ptr = (*const_layer)->getOutput(0); + } + trt_input.push_back(ptr->trt_tensor()); + } + nvinfer1::IEinsumLayer* layer = params_->converter->network()->addEinsum( + trt_input.data(), trt_input.size(), equation.c_str()); + TRT_ENSURE(layer); + + ITensorProxyPtr output = layer->getOutput(0); + this->AddOutput(output); + return OkStatus(); + } + + private: + std::string equation; +}; + +#endif + +} // namespace + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + "Einsum"); +#endif + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/fill_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/fill_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..b4b82bf5b1ecf8ed256ed4af125a1eedf479a5c1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/fill_ops.cc @@ -0,0 +1,313 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + +template +class ConvertFillBase : public OpConverterBase { + public: + explicit ConvertFillBase(const OpConverterParams* params) + : OpConverterBase(params, {DataType::DT_FLOAT, DataType::DT_HALF, + DataType::DT_INT32}) {} +}; + +class ConvertFill : public ConvertFillBase { + public: + explicit ConvertFill(const OpConverterParams* params) + : ConvertFillBase(params) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("dims", TrtInputArg::kBoth), + InputArgSpec::Create("value", TrtInputArg::kBoth)}; + } + + Status Validate() { + const auto& params = *this->params_; + TF_RETURN_IF_ERROR(NotSupportedInImplicitBatch()); + + const auto& inputs = params.inputs; + const auto& node_def = params.node_def; + const TRT_TensorOrWeights& dims_input = inputs.at(0); + + const auto dims_type = dims_input.TrtDType(); + if (dims_type != nvinfer1::DataType::kINT32) { + return errors::InvalidArgument("The dims parameter of ", node_def.op(), + " operation in ", node_def.name(), + " is expected to be of type ", + DebugString(nvinfer1::DataType::kINT32), + " type, got ", DebugString(dims_type)); + } + + const auto nbDims = dims_input.GetTrtDims().nbDims; + if (nbDims < 0) { + return errors::InvalidArgument("The shape of parameter ", node_def.op(), + " operation in ", node_def.name(), + " cannot be partial."); + } + return OkStatus(); + } + + Status Convert() { + const auto& params = *this->params_; + auto* network = params.converter->network(); + const auto& inputs = params.inputs; + + const bool is_dims_static = inputs[0].is_weights(); + const bool is_value_static = inputs[1].is_weights(); + + const TRT_TensorOrWeights& dims_input = inputs.at(0); + const TRT_TensorOrWeights& value_input = inputs.at(1); + + int nbDims = dims_input.GetTrtDims().d[0]; + + nvinfer1::Dims trt_dims{0}; + if (is_dims_static) { + const auto dims_weights = dims_input.weights(); + DimsAdapter dims_adapter(dims_weights.GetSpan()); + dims_adapter.TrtDims(&trt_dims); + } + + auto builder = TRTNetworkBuilder::Create(network, params.weight_store); + StatusOr layer = + builder->AddFill(value_input, dims_input, is_value_static, + is_dims_static, nbDims, trt_dims); + ITensorProxyPtr output_tensor = (*layer)->getOutput(0); + this->AddOutput(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } +}; + +class ConvertRange : public ConvertFillBase { + public: + explicit ConvertRange(const OpConverterParams* params) + : ConvertFillBase(params) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("start", TrtInputArg::kBoth), + InputArgSpec::Create("limit", TrtInputArg::kBoth), + InputArgSpec::Create("delta", TrtInputArg::kBoth)}; + } + + static constexpr const char* NodeDefDataTypeAttributeName() { + /* + node { + name: "..." + op: "Range" + ... + attr { + key: "Tidx" + value { + type: DT_INT32 + } + } + } + */ + return "Tidx"; + } + Status Validate() { + TF_RETURN_IF_ERROR(NotSupportedInImplicitBatch()); + const auto& params = *this->params_; + const auto& inputs = params.inputs; + const auto& node_def = params.node_def; + + float param[3]; + all_weights_ = all_integers_ = true; + for (int i = 0; i < 3; i++) { + const auto& input = inputs.at(i); + all_integers_ &= input.TrtDType() == nvinfer1::DataType::kINT32; + if (input.is_weights()) { + switch (input.TrtDType()) { + case nvinfer1::DataType::kFLOAT: + param[i] = get_input_param(input); + break; + case nvinfer1::DataType::kHALF: + param[i] = get_input_param(input); + break; + case nvinfer1::DataType::kINT32: + param[i] = get_input_param(input); + break; + default: + return errors::InvalidArgument( + "Unsupported data type ", DebugString(input.TrtDType()), + " used for '", InputSpec()[i].name, "'"); + } + } else { + all_weights_ = false; + } + } + + if (!(all_weights_ || all_integers_)) { + // As of 06/03/2022, when at least one of the (start, limit, delta) + // is passed as a tensor, they must all be of type kINT32 + return errors::Unimplemented(convert_range_expected_msg(node_def)); + } + + if (inputs.at(2).is_weights()) { + if ((delta_ = param[2]) == 0) { + return errors::InvalidArgument("The delta parameter of ", node_def.op(), + " operation cannot be equal to 0"); + } + + if (!all_weights_ && delta_ < 0) { + return errors::InvalidArgument( + "The delta parameter of Range operation " + "cannot be negative, when one of (start, limit) is passed as " + "a tensor, but got ", + delta_); + } + } + + for (int i = 0; i < 3; i++) { + const auto& input = inputs.at(i); + const auto& dims = input.GetTrtDims(); + if (dims.nbDims != 1 || dims.d[0] != 1) { + return errors::InvalidArgument("Dimension for '", InputSpec()[i].name, + "' of ", node_def.op(), " operator ", + "should be equal to 1"); + } + } + + if (all_weights_) { + const auto num_intervals_float = + (param[1] - (start_ = param[0])) / delta_; + if (num_intervals_float < 0) { + const auto error = convert_range_error_msg(start_, param[1], delta_); + return errors::InvalidArgument(error); + } + + num_values_ = static_cast(num_intervals_float); + if (start_ + delta_ * num_values_ != param[1]) { + num_values_++; + } + } + + return OkStatus(); + } + + Status Convert() { + const auto& params = *this->params_; + const auto& inputs = params.inputs; + const TRT_TensorOrWeights& input = inputs.at(0); + TRT_TensorOrWeights value_input; + nvinfer1::Dims trt_dims{1}; + auto builder = TRTNetworkBuilder::Create(params.converter->network(), + params.weight_store); + TRT_ENSURE_OK(builder); + ITensorProxyPtr dims_input_tensor = nullptr; + ITensorProxyPtr beta_tensor = nullptr; + ITensorProxyPtr scalar_tensor = nullptr; + if (!all_weights_) { + ITensorProxyPtr tensors[3]; + for (int i = 0; i < 3; i++) { + TF_RETURN_IF_ERROR( + builder->get_tensor4TensorOrWeights(inputs.at(i), tensors + i)); + } + + StatusOr num = + builder->Sub(/*limit*/ tensors[1]->trt_tensor(), + /*start*/ tensors[0]->trt_tensor()); + + TRT_ENSURE_PTR_OK(num); + StatusOr ceil_div = builder->FloorDiv( + (*num)->getOutput(0), (beta_tensor = tensors[2])->trt_tensor()); + TRT_ENSURE_PTR_OK(ceil_div); + dims_input_tensor = (*ceil_div)->getOutput(0); + dims_input_tensor->setType(nvinfer1::DataType::kINT32); + + nvinfer1::Dims scalar_dims{0}; + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params.converter, params.inputs.at(0), scalar_dims, false, + &scalar_tensor, params.node_def)); + } else { + DimsAdapter value_input_dims(std::vector{1}); + StatusOr value_weights = + params.weight_store->GetTempWeights(input.TrtDType(), + value_input_dims); + + TF_RETURN_IF_ERROR(value_weights.status()); + TF_RETURN_IF_ERROR(value_weights->SetValues(start_)); + value_input = TRT_TensorOrWeights(value_weights.value()); + + trt_dims.d[0] = num_values_; + StatusOr const_layer = + builder->ConstantShape(value_input_dims); + TRT_ENSURE_PTR_OK(const_layer); + dims_input_tensor = (*const_layer)->getOutput(0); + } + + TRT_TensorOrWeights dims_input(dims_input_tensor); + + StatusOr layer = + builder->AddFill(value_input, dims_input, all_weights_, all_weights_, 1, + trt_dims, scalar_tensor, beta_tensor, delta_); + + ITensorProxyPtr output_tensor = (*layer)->getOutput(0); + if (all_integers_) { + output_tensor->setType(nvinfer1::DataType::kINT32); + } + + this->AddOutput(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } + + private: + template + float get_input_param(const TRT_TensorOrWeights& input) { + return static_cast(*input.weights().GetPointer()); + } + + float start_; + float delta_; + int num_values_; + bool all_weights_; + bool all_integers_; +}; + +std::string convert_range_error_msg(float start, float limit, float delta) { + constexpr const char* format_string = + "For parameters (start, limit) = (%.2f, %.2f) " + "of the Range operation delta cannot be %s, got %.2f"; + return absl::StrFormat(format_string, start, limit, + start < limit ? "negative" : "positive", delta); +} + +std::string convert_range_expected_msg(const NodeDef& node_def) { + return "When at least one of parameters (start, limit, delta) of " + + node_def.op() + " operation in " + node_def.name() + + " is passed as a tensor, they must all be of type kINT32"; +} + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), "Fill"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + "Range"); + +#endif // IS_TRT_VERSION_GE(8, 2, 0, 0) + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..fc14c530ca550c441a5da9709e8b9acc862d746c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h @@ -0,0 +1,715 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_OPS_LAYER_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_LAYER_UTILS_H_ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include + +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/statusor.h" +#include "third_party/tensorrt/NvInfer.h" +#include "third_party/tensorrt/NvInferRuntimeCommon.h" + +namespace tensorflow { +namespace tensorrt { + +namespace convert { + +// Facilitates the creation of TensorRT layers inside a network. The user +// provides a INetworkDefinition pointer during construction. They can then add +// operations to the network through the provided functions. Each function +// returns a struct which contains the symbolic result of the operation (ITensor +// pointer) as well as a pointer to the last TensorRT ILayer created. Some +// operations may create multiple layers in order to accomplish the desired +// result (e.g. Sign). +class TRTNetworkBuilder { + public: + static StatusOr Create( + nvinfer1::INetworkDefinition* network, TrtWeightStore* weight_store) { + TRT_ENSURE(network); + TRT_ENSURE(weight_store); + return TRTNetworkBuilder(network, weight_store); + } + + private: + TRTNetworkBuilder(nvinfer1::INetworkDefinition* network, + TrtWeightStore* weight_store) + : network_(network), weight_store_(weight_store) {} + + public: + // Adds an Add operation to the network. + StatusOr Add(nvinfer1::ITensor* lhs, + nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kSUM); + TRT_ENSURE(layer); + return layer; + }; + + // Adds an elementwise min(lhs, rhs) operation to the network. The output has + // the same data type as the input. + StatusOr Min(nvinfer1::ITensor* lhs, + nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kMIN); + TRT_ENSURE(layer); + return layer; + }; + + // Adds an elementwise max(lhs, rhs) operation to the network. The output has + // the same datatype as the input. + StatusOr Max(nvinfer1::ITensor* lhs, + nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kMAX); + TRT_ENSURE(layer); + return layer; + }; + + // Adds an absolute value operation to the network. Note that this unary + // operation will do an implicit float conversion. For int32 tensors, use + // "AbsInt". + StatusOr AbsFloat(nvinfer1::ITensor* input) noexcept { + TRT_ENSURE(input); + TRT_ENSURE(input->getType() != nvinfer1::DataType::kFLOAT && + input->getType() != nvinfer1::DataType::kHALF); + nvinfer1::IUnaryLayer* layer = + network_->addUnary(*input, nvinfer1::UnaryOperation::kABS); + TRT_ENSURE(layer); + return layer; + } + + // Performs Abs without implicit float conversion. The input should be of type + // kInt32. For float datatypes, use "Abs". + StatusOr AbsInt( + nvinfer1::ITensor* input) noexcept { + TRT_ENSURE(input); + TRT_ENSURE(input->getType() == nvinfer1::DataType::kINT32); + StatusOr sign = this->SignInt(input); + return this->Mul(input, (*sign)->getOutput(0)); + } + + // Returns elementwise sign(x) for int32 input tensors where sign(x) is + // defined as 1 where x > 0, -1 where x < 0 and 0 where x == 0. + StatusOr SignInt( + nvinfer1::ITensor* input) noexcept { + TRT_ENSURE(input); + + // Create constants +1 and -1. + StatusOr one = + this->Constant(1, input->getDimensions().nbDims); + TRT_ENSURE_PTR_OK(one); + + StatusOr neg_one = + this->Constant(-1, input->getDimensions().nbDims); + TRT_ENSURE_PTR_OK(neg_one); + + // Turn all negaitve elements into -1, positive and zero elements + // unaffected. + StatusOr max = + this->Max(input, (*neg_one)->getOutput(0)); + TRT_ENSURE_PTR_OK(max); + + // Turn all positive elements into +1, negative and zero elements + // unaffected. + StatusOr min = + this->Min((*max)->getOutput(0), (*one)->getOutput(0)); + TRT_ENSURE_PTR_OK(min); + return min; + } + + // Adds a Sub operation to the network. + StatusOr Sub(nvinfer1::ITensor* lhs, + nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kSUB); + TRT_ENSURE(layer); + return layer; + } + + // Adds an Greater operation to the network. + StatusOr Greater( + nvinfer1::ITensor* lhs, nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kGREATER); + TRT_ENSURE(layer); + return layer; + } + + // Adds an Equal operation to the network. + StatusOr Equal( + nvinfer1::ITensor* lhs, nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kEQUAL); + TRT_ENSURE(layer); + return layer; + } + + // Adds a FloorDiv operation to the network. + StatusOr FloorDiv( + nvinfer1::ITensor* lhs, nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kFLOOR_DIV); + TRT_ENSURE(layer); + return layer; + } + + // Returns the equivalent of ceil_divide(abs(x)/abs(y))) operation. The inputs + // "lhs" and "rhs" should be int32 tensors. + StatusOr AbsCeilDivInt( + nvinfer1::ITensor* lhs, nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + TRT_ENSURE(lhs->getType() == nvinfer1::DataType::kINT32); + TRT_ENSURE(rhs->getType() == nvinfer1::DataType::kINT32); + + StatusOr rhs_abs = this->AbsInt(rhs); + TRT_ENSURE_PTR_OK(rhs_abs); + StatusOr lhs_abs = this->AbsInt(lhs); + TRT_ENSURE_PTR_OK(lhs_abs); + StatusOr add1 = + this->Add((*lhs_abs)->getOutput(0), (*rhs_abs)->getOutput(0)); + TRT_ENSURE_PTR_OK(add1); + StatusOr one_const = + this->Constant(1, rhs->getDimensions().nbDims); + TRT_ENSURE_PTR_OK(one_const); + StatusOr numerator = + this->Sub((*add1)->getOutput(0), (*one_const)->getOutput(0)); + TRT_ENSURE_PTR_OK(numerator); + return FloorDiv((*numerator)->getOutput(0), (*rhs_abs)->getOutput(0)); + } + + // Adds an elementwise multiplication operation to the network. + StatusOr Mul(nvinfer1::ITensor* lhs, + nvinfer1::ITensor* rhs) noexcept { + TRT_ENSURE(lhs); + TRT_ENSURE(rhs); + nvinfer1::IElementWiseLayer* layer = network_->addElementWise( + *lhs, *rhs, nvinfer1::ElementWiseOperation::kPROD); + TRT_ENSURE(layer); + return layer; + } + + // Adds a sequence of elementwise multiplication operations to the network. + // The returned layer's output contains the cumulative elementwise product of + // all tensors in the input. + StatusOr CumulativeProd( + absl::Span inputs) noexcept { + TRT_ENSURE(!absl::c_any_of( + inputs, [](nvinfer1::ITensor* x) { return x == nullptr; })); + nvinfer1::ILayer* out = nullptr; + if (inputs.size() == 1) { + out = network_->addIdentity(*inputs[0]); + TRT_ENSURE(out != nullptr); + return out; + } + nvinfer1::ITensor* last = inputs[0]; + for (int i = 1; i < inputs.size(); i++) { + StatusOr mul = this->Mul(last, inputs[i]); + TRT_ENSURE_PTR_OK(mul); + out = *mul; + last = (*mul)->getOutput(0); + } + return out; + } + + // Adds a Constant layer whose output is a TensorRT shape tensor. The shape + // tensor's size and values correspond to dim's nbDims and d[], respectively. + StatusOr ConstantShape( + const DimsAdapter& shape_data) noexcept { + TRT_ENSURE(shape_data.NumDims() > 0); + nvinfer1::Dims shape_dims; + shape_dims.nbDims = 1; + shape_dims.d[0] = shape_data.NumDims(); + StatusOr const_weights = + weight_store_->GetTempWeights(nvinfer1::DataType::kINT32, shape_dims); + TRT_ENSURE_OK(const_weights); + absl::c_copy(shape_data, const_weights->GetPointer()); + StatusOr trt_dims = const_weights->Shape().AsTrtDims(); + TRT_ENSURE_OK(trt_dims); + nvinfer1::IConstantLayer* const_layer = + network_->addConstant(*trt_dims, const_weights->GetTrtWeights()); + TRT_ENSURE(const_layer); + nvinfer1::ITensor* output = const_layer->getOutput(0); + TRT_ENSURE(output); + TRT_ENSURE(output->getType() == nvinfer1::DataType::kINT32); + return const_layer; + } + + // Adds a Constant layer whose output is a TensorRT shape tensor. The shape + // tensor's size and values correspond to dim's nbDims and d[], respectively. + StatusOr Constant( + const std::vector& data) noexcept { + nvinfer1::Dims shape_dims; + shape_dims.nbDims = 1; + shape_dims.d[0] = data.size(); + StatusOr const_weights = + weight_store_->GetTempWeights(nvinfer1::DataType::kINT32, shape_dims); + TRT_ENSURE_OK(const_weights); + int32* values = const_weights->GetPointer(); + for (int i = 0; i < data.size(); i++) { + values[i] = static_cast(data[i]); + } + StatusOr trt_dims = const_weights->Shape().AsTrtDims(); + TRT_ENSURE_OK(trt_dims); + nvinfer1::IConstantLayer* const_layer = + network_->addConstant(*trt_dims, const_weights->GetTrtWeights()); + TRT_ENSURE(const_layer); + nvinfer1::ITensor* output = const_layer->getOutput(0); + TRT_ENSURE(output); + TRT_ENSURE(output->getType() == nvinfer1::DataType::kINT32); + TRT_ENSURE(const_layer); + return const_layer; + } + + // Adds a Constant layer that produces a tensor of shape "shape", + // type "data_type" and filled with value "scalar". + template + StatusOr Constant( + const T value, nvinfer1::Dims shape, + nvinfer1::DataType data_type) noexcept { + StatusOr const_weights = + weight_store_->GetTempWeights(data_type, shape); + TRT_ENSURE_OK(const_weights); + TRT_ENSURE(const_weights->SetValues(value).ok()); + nvinfer1::IConstantLayer* const_layer = + network_->addConstant(shape, const_weights->GetTrtWeights()); + TRT_ENSURE(const_layer); + return const_layer; + } + + // Adds a Constant layer that produces a tensor with a single value "scalar". + // The tensor has "nb_dims" dimensions and each dimension has only one + // element. The data type of the tensor is determined by the data type of + // "scalar". + template ::value>::type* = nullptr> + StatusOr Constant(const T scalar, + const int nb_dims) noexcept { + TRT_ENSURE(nb_dims <= nvinfer1::Dims::MAX_DIMS); + auto data_type = nvinfer1::DataType::kINT32; + if (std::is_floating_point::value) { + data_type = nvinfer1::DataType::kFLOAT; + } + nvinfer1::Dims zero_shape; + zero_shape.nbDims = nb_dims; + std::fill_n(zero_shape.d, nb_dims, 1); + return Constant(scalar, zero_shape, data_type); + } + + // Adds a Constant layer from a TRT_ShapedWeights object. + StatusOr WeightsToConstant( + const nvinfer1::Weights& weights, const DimsAdapter& dims) noexcept { + StatusOr vol = dims.Volume(); + TRT_ENSURE_OK(vol); + TRT_ENSURE(*vol == weights.count); + StatusOr trt_dims = dims.AsTrtDims(); + TRT_ENSURE_OK(trt_dims); + nvinfer1::IConstantLayer* const_layer = + network_->addConstant(*trt_dims, weights); + TRT_ENSURE(const_layer); + return const_layer; + } + + Status get_tensor4TensorOrWeights(const TRT_TensorOrWeights& input, + ITensorProxyPtr* pTensor) { + if (input.is_weights()) { + StatusOr const_layer = WeightsToConstant( + input.weights().GetTrtWeights(), input.GetTrtDims()); + if (!const_layer.status().ok()) return const_layer.status(); + *pTensor = (*const_layer)->getOutput(0); + } else { + *pTensor = input.tensor(); + } + return OkStatus(); + } + + // Creates a nvinfer1::Weights object containing a single scalar. + template ::value>::type* = nullptr> + StatusOr ScalarWeights(const T scalar, + const int nb_dims) noexcept { + TRT_ENSURE(nb_dims <= nvinfer1::Dims::MAX_DIMS); + auto data_type = nvinfer1::DataType::kINT32; + if (std::is_floating_point::value) { + data_type = nvinfer1::DataType::kFLOAT; + } + nvinfer1::Dims weights_shape; + weights_shape.nbDims = nb_dims; + std::fill_n(weights_shape.d, nb_dims, 1); + StatusOr const_weights = + weight_store_->GetTempWeights(data_type, weights_shape); + TRT_ENSURE_OK(const_weights); + const_weights->GetPointer()[0] = scalar; + return const_weights->GetTrtWeights(); + } + + // Adds a TensorRT Slice operation to the network. + StatusOr Slice( + nvinfer1::ITensor* input, const nvinfer1::Dims& begin, + const nvinfer1::Dims& size, const nvinfer1::Dims& stride) noexcept { + nvinfer1::ISliceLayer* layer = + network_->addSlice(*input, begin, size, stride); + TRT_ENSURE(layer); + return layer; + } + + // Adds a TensorRT Concatenate operation to the network. + StatusOr Concat( + absl::Span inputs, const int axis) { + for (nvinfer1::ITensor* input : inputs) { + TRT_ENSURE(input); + } + nvinfer1::IConcatenationLayer* layer = network_->addConcatenation( + inputs.data(), static_cast(inputs.size())); + TRT_ENSURE(layer); + layer->setAxis(axis); + return layer; + } + + // Adds a TensorRT Concatenate operation to the network. + StatusOr Concat( + const std::vector& inputs, const int axis) { + return this->Concat(absl::MakeSpan(inputs), axis); + } + + // Adds a TensorRT Shape operation, which determines the runtime shape of the + // input tensor, to the network. + StatusOr Shape(nvinfer1::ITensor* input) { + TRT_ENSURE(input); + nvinfer1::IShapeLayer* layer = network_->addShape(*input); + TRT_ENSURE(layer); + return layer; + } + + // Creates a Gather operation on the shape of the input tensor. The output of + // the gather operation is a 1D shape tensor where output[i] = (!sub_one ? + // input_shape[i] : input_shape[i] -1) if i is in "indices", otherwise zero. + StatusOr GetPartialShapeOf( + nvinfer1::ITensor* input, absl::InlinedVector indices, + bool sub_one = false) { + TRT_ENSURE(input); + TRT_ENSURE(indices.size() <= nvinfer1::Dims::MAX_DIMS); + + // Get the runtime shape of input; + StatusOr shape_layer = this->Shape(input); + TRT_ENSURE_PTR_OK(shape_layer); + nvinfer1::ITensor* runtime_shape = (*shape_layer)->getOutput(0); + + if (sub_one) { + StatusOr ones = this->Constant(1, 1); + TRT_ENSURE_PTR_OK(ones); + StatusOr sub = + this->Sub(runtime_shape, (*ones)->getOutput(0)); + TRT_ENSURE_PTR_OK(sub); + runtime_shape = (*sub)->getOutput(0); + } + + // Create a constant tensor containing the gather indices. + // For any dim not in "indices", we mark it size to gather a zero. + const int input_nb_dims = input->getDimensions().nbDims; + std::vector indices_all(input_nb_dims, input_nb_dims); + for (auto idx : indices) { + TRT_ENSURE(idx < input_nb_dims); + indices_all[idx] = idx; + } + + StatusOr indices_result = + this->Constant(indices_all); + TRT_ENSURE_PTR_OK(indices_result); + nvinfer1::ITensor* gather_indices = (*indices_result)->getOutput(0); + TRT_ENSURE(gather_indices->getDimensions().nbDims == 1); + TRT_ENSURE(gather_indices->getType() == nvinfer1::DataType::kINT32); + + // Append a zero to the shape tensor. + StatusOr zero_result = + this->Constant(std::vector{0}); + TRT_ENSURE_PTR_OK(zero_result); + std::array cat_inputs = { + runtime_shape, (*zero_result)->getOutput(0)}; + nvinfer1::IConcatenationLayer* cat_layer = + network_->addConcatenation(cat_inputs.data(), cat_inputs.size()); + TRT_ENSURE(cat_layer); + nvinfer1::ITensor* gather_input = cat_layer->getOutput(0); + TRT_ENSURE(gather_input); + + // Finally, gather the indices from the input. + nvinfer1::IGatherLayer* gather = + network_->addGather(*gather_input, *gather_indices, 0); + TRT_ENSURE(gather); + return gather; + } + + // Adds a scale layer that uniformly scales the input tensor by the specified + // amount. + StatusOr AddUniformScale(nvinfer1::ITensor* input, + float scale, + const std::string& name) { + TRT_ENSURE(input); + TRT_ENSURE(!name.empty()); + StatusOr weight = this->ScalarWeights(scale, 1); + TRT_ENSURE_OK(weight); + const nvinfer1::Weights empty_weights = + nvinfer1::Weights{nvinfer1::DataType::kFLOAT, nullptr, 0}; + nvinfer1::IScaleLayer* scale_layer = + network_->addScale(*input, nvinfer1::ScaleMode::kUNIFORM, empty_weights, + (*weight), empty_weights); + TRT_ENSURE(scale_layer != nullptr); + scale_layer->setName(name.c_str()); + TRT_ENSURE((*scale_layer).getPower().count == 0); + TRT_ENSURE((*scale_layer).getShift().count == 0); + TRT_ENSURE((*scale_layer).getScale().count == 1); + return scale_layer; + } + + StatusOr AddFill(const TRT_TensorOrWeights& value_input, + const TRT_TensorOrWeights& dims_input, + bool is_value_static, bool is_dims_static, + int nbDims, + const nvinfer1::Dims& trt_dims, + ITensorProxyPtr scalar_tensor = nullptr, + ITensorProxyPtr beta_tensor = nullptr, + const float delta = 0) { + // TensorRT IFillLayer requires a rank 0 scalar. + nvinfer1::Dims scalar_dims; + scalar_dims.nbDims = 0; + if (is_value_static) { + StatusOr const_layer = + WeightsToConstant(value_input.weights().GetTrtWeights(), scalar_dims); + if (!const_layer.status().ok()) return const_layer.status(); + scalar_tensor = (*const_layer)->getOutput(0); + } else { + if (scalar_tensor == nullptr) { + StatusOr shuffler_layer = + Reshape(value_input.tensor()->trt_tensor(), scalar_dims); + if (!shuffler_layer.status().ok()) return shuffler_layer.status(); + scalar_tensor = (*shuffler_layer)->getOutput(0); + } + } + + if (beta_tensor == nullptr) { + nvinfer1::Dims beta_shape{1, {nbDims}}; + StatusOr const_layer = + Constant(delta, beta_shape, value_input.TrtDType()); + TF_RETURN_IF_ERROR(const_layer.status()); + beta_tensor = (*const_layer)->getOutput(0); + } + + nvinfer1::IFillLayer* layer = + network_->addFill(trt_dims, nvinfer1::FillOperation::kLINSPACE); + TRT_ENSURE(layer); + if (!is_dims_static) { + layer->setInput(0, *dims_input.tensor()->trt_tensor()); + } + layer->setInput(1, *scalar_tensor->trt_tensor()); + layer->setInput(2, *beta_tensor->trt_tensor()); + return layer; + } + + // Adds a quantization layer that uniformly scales the input tensor + // by the given multiplicative "scaling_factor", then rounds + // (round-to-nearest-ties-to-even) to the nearest integer and clamps in the + // range of [-128, 127]. + StatusOr Quantize(nvinfer1::ITensor* input, + const float scaling_factor, + const std::string& name) { + TRT_ENSURE(input); + TRT_ENSURE(!name.empty()); + // Preprocessor usage here is unavoidable because TRT8 API is new. +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + // The TensorRT IQuantizeLayer divides by the scale factor rather than + // multiplies. To be consistent, in this function we expect a multiplicative + // scale factor, so we take the reciprical. + StatusOr scaling_const = + this->Constant(1.0f / scaling_factor, 1); + TRT_ENSURE_PTR_OK(scaling_const); + (*scaling_const)->setDimensions(nvinfer1::Dims{0, {}}); + nvinfer1::IQuantizeLayer* quant_layer = + network_->addQuantize(*input, *(*scaling_const)->getOutput(0)); + TRT_ENSURE(quant_layer); + quant_layer->setAxis(1); + return quant_layer; +#else + StatusOr result = + this->AddUniformScale(input, scaling_factor, name); + TRT_ENSURE_PTR_OK(result); + (*result)->setOutputType(0, nvinfer1::DataType::kINT8); + (*result)->setPrecision(nvinfer1::DataType::kFLOAT); + return result; +#endif + } + + // Adds a dequantize layer that casts the input tensor to TensorRT float type + // and scales it uniformly by the given multiplicative "scaling_factor". + StatusOr Dequantize(nvinfer1::ITensor* input, + const float scaling_factor, + const std::string& name) { + TRT_ENSURE(input); + TRT_ENSURE(!name.empty()); +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + StatusOr scaling_const = + this->Constant(scaling_factor, 1); + TRT_ENSURE_PTR_OK(scaling_const); + (*scaling_const)->setDimensions(nvinfer1::Dims{0, {}}); + nvinfer1::IDequantizeLayer* dequant_layer = + network_->addDequantize(*input, *(*scaling_const)->getOutput(0)); + dequant_layer->setAxis(1); + TRT_ENSURE(dequant_layer); + return dequant_layer; +#else + StatusOr result = + this->AddUniformScale(input, scaling_factor, name); + TRT_ENSURE_PTR_OK(result); + (*result)->setOutputType(0, nvinfer1::DataType::kFLOAT); + (*result)->setPrecision(nvinfer1::DataType::kINT8); + return result; +#endif + } + + // Adds TensorRT Q/DQ operations. This is for explicit precision mode. + StatusOr UniformQuantizeDequantizeExplicit( + nvinfer1::ITensor* input, float quantize_scale, float dequantize_scale, + const std::string& name) { + TRT_ENSURE(input); + if (!IS_TRT_VERSION_GE(8, 0, 0, 0)) { + TRT_ENSURE(network_->hasExplicitPrecision()); + } + TRT_ENSURE(IS_TRT_VERSION_GE(7, 1, 0, 0)); + + static int count = 0; + TRT_ENSURE(input->getType() == nvinfer1::DataType::kFLOAT); + std::string quant_name = absl::StrCat(input->getName(), "_quant_", count); + + StatusOr quant = + this->Quantize(input, quantize_scale, quant_name); + TRT_ENSURE_PTR_OK(quant); + + std::string dequant_name = + absl::StrCat(input->getName(), "_dequant_", count); + StatusOr dequant = this->Dequantize( + (*quant)->getOutput(0), dequantize_scale, dequant_name); + TRT_ENSURE_PTR_OK(dequant); + + count++; + return dequant; + } + + StatusOr Reshape(nvinfer1::ITensor* input, + const nvinfer1::Dims& new_shape) { + TRT_ENSURE(input); + nvinfer1::IShuffleLayer* layer = network_->addShuffle(*input); + TRT_ENSURE(layer); + layer->setReshapeDimensions(new_shape); + return layer; + } + + StatusOr FindProducerOf(const nvinfer1::ITensor* tensor) { + const char* name = tensor->getName(); + const int num_layers = network_->getNbLayers(); + for (int i = 0; i < num_layers; i++) { + nvinfer1::ILayer* layer = network_->getLayer(i); + const int num_outputs = layer->getNbOutputs(); + for (int j = 0; j < num_outputs; j++) { + nvinfer1::ITensor* t = layer->getOutput(j); + if (std::string(t->getName()) == name) { + return layer; + } + } + } + return errors::NotFound("could not find producing layer of ", name); + } + + StatusOr UniqueParentOf(const nvinfer1::ILayer* layer, + int input_idx = 0) { + return FindProducerOf(layer->getInput(input_idx)); + } + + nvinfer1::INetworkDefinition* Network() { return network_; } + + private: + nvinfer1::INetworkDefinition* network_; + TrtWeightStore* weight_store_; +}; + +class ShuffleBuilder { + private: + explicit ShuffleBuilder(TRTNetworkBuilder* builder, nvinfer1::ITensor* input) + : builder_(builder) { + layer_ = builder->Network()->addShuffle(*input); + } + + public: + static StatusOr Create(TRTNetworkBuilder* builder, + nvinfer1::ITensor* input) { + TRT_ENSURE(builder != nullptr); + TRT_ENSURE(input != nullptr); + return ShuffleBuilder(builder, input); + } + + ShuffleBuilder& SetReshape(const nvinfer1::Dims& dims) { + layer_->setReshapeDimensions(dims); + return *this; + } + + ShuffleBuilder& SetReshape(nvinfer1::ITensor* shape) { + layer_->setInput(1, *shape); + return *this; + } + + ShuffleBuilder& SetFirstTranspose(const nvinfer1::Permutation& perm) { + layer_->setFirstTranspose(perm); + return *this; + } + + ShuffleBuilder& SetSecondTranspose(const nvinfer1::Permutation& perm) { + layer_->setSecondTranspose(perm); + return *this; + } + + StatusOr Output() { + TRT_ENSURE(layer_ != nullptr); + TRT_ENSURE(layer_->getOutput(0) != nullptr); + return layer_->getOutput(0); + } + + private: + TRTNetworkBuilder* builder_; + nvinfer1::IShuffleLayer* layer_; +}; + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_LAYER_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/like_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/like_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..7435ea511e8414bfc49d464d9ff6ae2698e434e5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/like_ops.cc @@ -0,0 +1,94 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + +template +class ConvertLikeOps : public OpConverterBase> { + public: + explicit ConvertLikeOps(const OpConverterParams *params) + : OpConverterBase>( + params, + {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32}) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("input", TrtInputArg::kBoth), + }; + } + Status Validate() { return ConvertLikeOps::NotSupportedInImplicitBatch(); } + + Status Convert() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + auto *network = params.converter->network(); + + const TRT_TensorOrWeights &input = inputs.at(0); + nvinfer1::Dims dims(input.GetTrtDims()); + + const std::vector value_input_dims_data = {1}; + const DimsAdapter value_input_dims(value_input_dims_data); + StatusOr value_weights = + params.weight_store->GetTempWeights(input.TrtDType(), value_input_dims); + TF_RETURN_IF_ERROR(value_weights.status()); + TF_RETURN_IF_ERROR(value_weights->SetValues(V)); + TRT_TensorOrWeights value_input(value_weights.value()); + + const auto is_dims_static = HasStaticShape(dims); + auto builder = TRTNetworkBuilder::Create(network, params.weight_store); + ITensorProxyPtr dims_input_tensor; + if (!is_dims_static) { + StatusOr shape_layer = + builder->Shape(input.tensor()->trt_tensor()); + TF_RETURN_IF_ERROR(shape_layer.status()); + dims_input_tensor = (*shape_layer)->getOutput(0); + dims.nbDims = 0; + } + + TRT_TensorOrWeights dims_input(dims_input_tensor); + StatusOr layer = + builder->AddFill(value_input, dims_input, true, is_dims_static, + input.GetTrtDims().nbDims, dims); + ITensorProxyPtr output_tensor = (*layer)->getOutput(0); + this->AddOutput(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } +}; + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction>(), + "zeros_like"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction>(), + "ones_like"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction>(), + "ZerosLike"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction>(), + "OnesLike"); + +#endif // IS_TRT_VERSION_GE(8, 2, 0, 0) + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/log_softmax.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/log_softmax.cc new file mode 100644 index 0000000000000000000000000000000000000000..3ea431814b8dbc73415026819702af44be83012c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/log_softmax.cc @@ -0,0 +1,104 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class ConvertLogSoftmax : public OpConverterBase { + public: + explicit ConvertLogSoftmax(const OpConverterParams *params) + : OpConverterBase(params) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("logits", TrtInputArg::kTensor)}; + } + + Status Validate() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + + ITensorProxyPtr logits_tensor = inputs.at(0).tensor(); + + const int num_trt_dims = logits_tensor->getDimensions().nbDims; + if (!num_trt_dims && params.use_implicit_batch) { + return errors::InvalidArgument( + "TensorRT LogSoftmax cannot apply on the batch dimension"); + } + + return OkStatus(); + } + + Status Convert() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + const auto &node_def = params.node_def; + + // Perform LogSoftmax operation: + // `logsoftmax = logits - log(reduce_sum(exp(logits), axis))` + + // Get the logits tensor. + ITensorProxyPtr logits_tensor = inputs.at(0).tensor(); + const int num_trt_dims = logits_tensor->getDimensions().nbDims; + + // Exponent of logits. + nvinfer1::IUnaryLayer *exp = params.converter->network()->addUnary( + *logits_tensor->trt_tensor(), nvinfer1::UnaryOperation::kEXP); + TFTRT_RETURN_ERROR_IF_NULLPTR(exp, node_def.name()); + params.converter->SetLayerName(exp, node_def, "exp"); + + // Reduce-sum operation across the final dimension. + nvinfer1::IReduceLayer *reduced_sum = + params.converter->network()->addReduce( + *exp->getOutput(0), nvinfer1::ReduceOperation::kSUM, + (1 << (num_trt_dims - 1)), /*Reduce across final dimension*/ + true /*Keep reduced dims*/); + params.converter->SetLayerName(reduced_sum, node_def, "reduced_sum"); + + // Logarithm of reduced_sum. + nvinfer1::IUnaryLayer *log_reduced_sum = + params.converter->network()->addUnary(*reduced_sum->getOutput(0), + nvinfer1::UnaryOperation::kLOG); + TFTRT_RETURN_ERROR_IF_NULLPTR(log_reduced_sum, node_def.name()); + params.converter->SetLayerName(log_reduced_sum, node_def, + "log_reduced_sum"); + + // Finally, get the output by subtracting log_reduced_sum from logits. + nvinfer1::IElementWiseLayer *sub = + params.converter->network()->addElementWise( + *logits_tensor->trt_tensor(), *log_reduced_sum->getOutput(0), + nvinfer1::ElementWiseOperation::kSUB); + TFTRT_RETURN_ERROR_IF_NULLPTR(sub, node_def.name()); + params.converter->SetLayerName(sub, node_def, "sub"); + + params.outputs->push_back(TRT_TensorOrWeights(sub->getOutput(0))); + return OkStatus(); + } +}; + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + "LogSoftmax"); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..9e6a334c2e3f76cc0f24b3ea0b2b7b919bca6d9e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.cc @@ -0,0 +1,421 @@ +/* Copyright 2021 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h" + +#include "absl/strings/str_format.h" +#include "tensorflow/cc/ops//array_ops.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/weights.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +bool IsQuantizeAndDequantizeOp(const Node* node) { + return absl::c_find(kQuantizationOpNames, node->def().op()) != + kQuantizationOpNames.end(); +} + +namespace { + +// Provides quantizing and dequantizing tensor scales for a given dynamic range. +// Borrowed from TF quantization kernel logic. +template +QuantizationScales ComputeQuantizationRange(bool signed_input, + int num_bits, + bool narrow_range, + T* min_range, T* max_range) { + // Calculate the range for the simulated integer quantization: + // e.g. [-127,127] for signed = true, narrow_range = true, num_bits = 8, + // or [-128,127] for signed = true, narrow_range = false, num_bits = 8, + // or [0, 255] for signed = false, num_bits = 8. + const int64_t min_quantized = + signed_input ? narrow_range ? -(1ULL << (num_bits - 1)) + 1 + : -(1ULL << (num_bits - 1)) + : 0; + const int64_t max_quantized = + signed_input ? (1ULL << (num_bits - 1)) - 1 : (1ULL << num_bits) - 1; + // Determine the maximum scaling factor that would scale + // [min_range, max_range] to not exceed [min_quantized, max_quantized], + // while keeping 0 unchanged. + const T scale_from_min_side = (min_quantized * *min_range > 0) + ? min_quantized / *min_range + : std::numeric_limits::max(); + const T scale_from_max_side = (max_quantized * *max_range > 0) + ? max_quantized / *max_range + : std::numeric_limits::max(); + + QuantizationScales scales; + // Note: Avoids changing the side of the range that determines scale. + if (scale_from_min_side < scale_from_max_side) { + scales.quantize_scale[0] = scale_from_min_side; + scales.dequantize_scale[0] = *min_range / min_quantized; + *max_range = max_quantized * scales.dequantize_scale[0]; + } else { + scales.quantize_scale[0] = scale_from_max_side; + scales.dequantize_scale[0] = *max_range / max_quantized; + *min_range = min_quantized * scales.dequantize_scale[0]; + } + return scales; +} + +// Prepares the input for a QDQ node in explicit precision mode, returning a +// ITensor pointer. If the input is weights, we convert it to a ITensor by +// adding a constant layer. +StatusOr ExlicitQDQInputToTensor( + TRTNetworkBuilder* builder, const OpConverterParams* params, + const TRT_TensorOrWeights& input) { + if (input.is_tensor()) { + return input.tensor()->trt_tensor(); + } + if (!IS_TRT_VERSION_GE(8, 0, 0, 0) && input.weights().count() > 1) { + LOG(WARNING) << absl::StrCat( + "QDQ per-channel for weights not " + "implemented, assuming uniform scaling"); + } + TRT_ShapedWeights trt_weights = input.weights(); + StatusOr weights_const = + builder->WeightsToConstant(trt_weights.GetTrtWeights(), + trt_weights.Shape()); + TRT_ENSURE_PTR_OK(weights_const); + params->converter->SetLayerName(*weights_const, params->node_def, "const"); + nvinfer1::ITensor* qdq_input = (*weights_const)->getOutput(0); + std::string name = absl::StrCat((*weights_const)->getName(), "_output"); + qdq_input->setName(name.c_str()); + return qdq_input; +} + +} // namespace + +// Carries traits for each specific quantization op type for conversion. +// Specialization for template parameter T should be given for each TF C++ +// quantization op. +template +struct QDQOpSpec {}; + +template <> +struct QDQOpSpec { + static constexpr std::array InputSpec() { + return { + InputArgSpec::Create("input", TrtInputArg::kBoth), + InputArgSpec::Create("input_min", TrtInputArg::kWeight), + InputArgSpec::Create("input_max", TrtInputArg::kWeight), + }; + } + + struct Attrs { + float min_range; + float max_range; + bool narrow_range; + std::string round_mode; + UniformQuantizationScales scales; + }; + + static Status ValidateQDQForExplicitPrecision( + const std::vector& inputs, const NodeDef& node_def, + Attrs* args) { + AttrSlice attrs(node_def); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "round_mode", &args->round_mode)); + if (args->round_mode != "HALF_TO_EVEN") { + LOG(WARNING) << node_def.op() << ": " << node_def.name() + << " has round_mode=" << args->round_mode + << ", but for TensorRT conversion, " + "round_mode=HALF_TO_EVEN is recommended."; + } + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "narrow_range", &args->narrow_range)); + if (args->narrow_range) { + LOG(WARNING) << node_def.op() << ": " << node_def.name() + << " has narrow_range=true, but for TensorRT conversion, " + "narrow_range=false is recommended."; + } + args->min_range = inputs.at(1).weights().template GetPointer()[0]; + args->max_range = inputs.at(2).weights().template GetPointer()[0]; + const int num_bits = 8; + args->scales = ComputeQuantizationRange( + /*signed_input=*/true, num_bits, args->narrow_range, &args->min_range, + &args->max_range); + TRT_ENSURE(args->scales.dequantize_scale[0] != 0); + TRT_ENSURE(args->scales.quantize_scale[0] != 0); + return OkStatus(); + } + + // Converts in explicit precision mode. In this mode, QDQ operations are + // directly converted into TensorRT quantizing and dequantizing scale + // operations. + static Status ConvertExplicit(const OpConverterParams* params, + const Attrs& args) { + const auto& node_def = params->node_def; + + StatusOr builder = TRTNetworkBuilder::Create( + params->converter->network(), params->weight_store); + + StatusOr qdq_input = + ExlicitQDQInputToTensor(&*builder, params, params->inputs.at(0)); + TRT_ENSURE_PTR_OK(qdq_input); + + // TODO(cbate): check this condition exists for TRT8? Outline this block to + // a "reshape policy". + const int required_dims = params->use_implicit_batch ? 3 : 4; + const nvinfer1::Dims idims = (*qdq_input)->getDimensions(); + nvinfer1::Dims intermediate_dims = idims; + TRT_ENSURE(idims.nbDims > 0); + if (idims.nbDims < required_dims) { + const int nb_extra_dims = required_dims - idims.nbDims; + intermediate_dims.nbDims = required_dims; + std::vector ones(nb_extra_dims, 1); + TRT_ENSURE(ones.size() == nb_extra_dims && nb_extra_dims > 0); + + if (!params->use_implicit_batch) { + intermediate_dims.d[0] = idims.d[0]; + std::copy(ones.begin(), ones.end(), intermediate_dims.d + 1); + std::copy_n(idims.d + 1, idims.nbDims - 1, + intermediate_dims.d + ones.size() + 1); + } else { + std::copy(ones.begin(), ones.end(), intermediate_dims.d); + std::copy_n(idims.d, idims.nbDims, intermediate_dims.d + ones.size()); + } + + LOG(WARNING) << absl::StrCat( + node_def.name(), ":", node_def.op(), ": tensor ", + (*qdq_input)->getName(), " has shape ", DebugString(idims), + " but TRT scale layer requires at least 3 dims excluding batch dim, " + "trying to recover by inserting 1's to create shape ", + DebugString(intermediate_dims)); + StatusOr reshape = + builder->Reshape(*qdq_input, intermediate_dims); + TRT_ENSURE_PTR_OK(reshape); + *qdq_input = (*reshape)->getOutput(0); + } + + VLOG(1) << "[ExplicitPrecision]" << node_def.op() << ": " << node_def.name() + << " computed scales: " << args.scales << " from min/max ranges " + << args.min_range << "/" << args.max_range; + + StatusOr qdq = + builder->UniformQuantizeDequantizeExplicit( + *qdq_input, args.scales.quantize_scale[0], + args.scales.dequantize_scale[0], node_def.name()); + TRT_ENSURE_PTR_OK(qdq); + ITensorProxyPtr final_output = (*qdq)->getOutput(0); + if (idims.nbDims != intermediate_dims.nbDims) { + StatusOr undo_reshape = + builder->Reshape(*qdq_input, idims); + TRT_ENSURE_PTR_OK(undo_reshape); + final_output = (*undo_reshape)->getOutput(0); + } + params->outputs->push_back(final_output); + return OkStatus(); + } +}; + +template <> + +struct QDQOpSpec { + static constexpr std::array InputSpec() { + return { + InputArgSpec::Create("input", TrtInputArg::kBoth), + InputArgSpec::Create("min", TrtInputArg::kWeight), + InputArgSpec::Create("max", TrtInputArg::kWeight), + InputArgSpec::Create("num_bits", TrtInputArg::kWeight), + }; + } + // Use same attributes and conversion functions as QDQV2. + using Attrs = QDQOpSpec::Attrs; + + static Status ValidateQDQForExplicitPrecision( + const std::vector& inputs, const NodeDef& node_def, + Attrs* args) { + return QDQOpSpec< + ops::QuantizeAndDequantizeV2>::ValidateQDQForExplicitPrecision(inputs, + node_def, + args); + } + + static Status ConvertExplicit(const OpConverterParams* params, + const Attrs& args) { + return QDQOpSpec::ConvertExplicit(params, + args); + } +}; + +template <> + +struct QDQOpSpec { + static constexpr std::array InputSpec() { + return { + InputArgSpec::Create("input", TrtInputArg::kBoth), + InputArgSpec::Create("min", TrtInputArg::kWeight), + InputArgSpec::Create("max", TrtInputArg::kWeight), + }; + } + struct Attrs { + int num_bits; + bool narrow_range; + }; + + static Status ValidateQDQForExplicitPrecision( + const std::vector& inputs, const NodeDef& node_def, + Attrs* args) { + return errors::Unimplemented(""); + } + + static Status ConvertExplicit(const OpConverterParams* params, + const Attrs& args) { + return errors::Unimplemented(""); + } +}; + +template <> + +struct QDQOpSpec { + static constexpr std::array InputSpec() { + return { + InputArgSpec::Create("input", TrtInputArg::kBoth), + }; + } + + struct Attrs { + float min; + float max; + int num_bits; + bool narrow_range; + }; + + static Status ValidateQDQForExplicitPrecision( + const std::vector& inputs, const NodeDef& node_def, + Attrs* args) { + return errors::Unimplemented(""); + } + + static Status ConvertExplicit(const OpConverterParams* params, + const Attrs& args) { + return errors::Unimplemented(""); + } +}; + +// Converts QDQ operations in non-explicit precision mode. This is the original +// "ConvertQuantize" function. In this mode, Q/DQ operations are no-ops and are +// instead used to set the dynamic range of the input tensor. +Status ConvertDynamicRangeMode(const OpConverterParams* params) { + const auto& inputs = params->inputs; + const auto& node_def = params->node_def; + float min_range = 0.0f; + float max_range = 0.0f; + const auto& op_name = node_def.op(); + if (op_name == "FakeQuantWithMinMaxArgs") { + AttrSlice attrs(node_def); + // Get ranges via node attributes. + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "min", &min_range)); + TF_RETURN_IF_ERROR(GetNodeAttr(attrs, "max", &max_range)); + } else if (op_name == "FakeQuantWithMinMaxVars" || + op_name == "QuantizeAndDequantizeV2" || + op_name == "QuantizeAndDequantizeV3") { + // Get ranges via inputs. + auto get_weights_value = [&inputs](int index) { + const auto* raw_weights = inputs.at(index).weights().GetPointer(); + return raw_weights[0]; + }; + min_range = get_weights_value(1); + max_range = get_weights_value(2); + } else { + return errors::InvalidArgument("Unknown quantization op ", op_name, ", at ", + node_def.name()); + } + if (params->validation_only) { + return OkStatus(); + } + + // Store ranges for tensor + ITensorProxyPtr input0 = inputs.at(0).tensor(); + params->converter->ProvideQuantizationRange(&input0, min_range, max_range); + // Sometimes, TRT may not quantize a tensor, either because it chooses to + // execute a higher precision kernel or because of op fusion. In these + // cases, accuracy will suffer if the model was trained to expect + // quantization at that tensor. We should consider adding a clip(tensor, + // min_range, max_range) operation here to ensure that any arbitrarily + // placed quantize node will execute as expected. However, this will + // negatively affect performance. If users train their models in a way which + // models inference as close as possible (i.e. not quantizing in place where + // fusion will occur), then there is no problem with the current + // implementation. + params->outputs->push_back(inputs.at(0)); + return OkStatus(); +} + +template +class ConvertQDQ : public OpConverterBase> { + public: + explicit ConvertQDQ(const OpConverterParams* params) + : OpConverterBase>(params) {} + + static constexpr auto InputSpec() { return QDQOpSpec::InputSpec(); } + + // Disable the non-applicable data type check by providing empty string. + static constexpr const char* NodeDefDataTypeAttributeName() { return ""; } + + Status ValidateDynamicRangeINT8Mode() { + // The condition ensures we only call the conversion once. We should break + // this function up into validation and conversion. + if (this->params_->validation_only) { + return ConvertDynamicRangeMode(this->params_); + } + return OkStatus(); + } + + Status Validate() { + if (!this->params_->use_explicit_precision) { + return ValidateDynamicRangeINT8Mode(); + } + return OpSpec::ValidateQDQForExplicitPrecision( + this->params_->inputs, this->params_->node_def, &attrs_); + } + + Status Convert() { + if (!this->params_->use_explicit_precision) { + return ConvertDynamicRangeMode(this->params_); + } + return OpSpec::ConvertExplicit(this->params_, attrs_); + } + + using OpSpec = QDQOpSpec; + using OpSpecAttrs = typename QDQOpSpec::Attrs; + OpSpecAttrs attrs_; +}; + +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction>(), + "QuantizeAndDequantizeV2"); +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction>(), + "QuantizeAndDequantizeV3"); +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction>(), + "FakeQuantWithMinMaxVars"); +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction>(), + "FakeQuantWithMinMaxArgs"); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..41be78d2174de1cacd083f19c42f1b017605f24f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h @@ -0,0 +1,76 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_OPS_QUANTIZATION_OPS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_QUANTIZATION_OPS_H_ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "absl/strings/str_format.h" +#include "absl/strings/str_join.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +constexpr std::array kQuantizationOpNames = { + "QuantizeAndDequantizeV2", + "QuantizeAndDequantizeV3", + "FakeQuantWithMinMaxVars", + "FakeQuantWithMinMaxArgs", +}; + +// Operations with supported conversion to Q/DQ ops in TensorRT explicit +// precision mode. +constexpr std::array kExplicitQuantizationOpNames = { + "QuantizeAndDequantizeV2", +}; + +// Contains two scaling factors for quantization and dequantization +// respectively. A shift factor is omitted as TensorRT only supports symmetric +// quantization. +template +struct QuantizationScales { + std::array quantize_scale; + std::array dequantize_scale; +}; + +// In TensorRT 7 and 8, only uniform tensor scaling is supported for +// activations. +using UniformQuantizationScales = QuantizationScales; + +// Per-channel scaling is supported for weights in TensorRT version >= 8.0. +template +using PerChannelQuantizationScales = QuantizationScales; + +template +std::ostream& operator<<(std::ostream& os, + const QuantizationScales& scales) { + os << absl::StrFormat("QuantizationScales[quantize={%s},dequantize={%s}]", + absl::StrJoin(scales.quantize_scale, ","), + absl::StrJoin(scales.dequantize_scale, ",")); + return os; +} + +// Returns true if the Tensorflow node is a quantize and dequantize operation. +bool IsQuantizeAndDequantizeOp(const Node*); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_QUANTIZATION_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9b7e7a93e575ec64a8d484b95982526203b01368 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops_test.cc @@ -0,0 +1,618 @@ +/* Copyright 2021 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h" + +#include +#include +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/array_ops.h" +#include "tensorflow/cc/ops/const_op.h" +#include "tensorflow/cc/ops/linalg_ops.h" +#include "tensorflow/cc/ops/math_ops.h" +#include "tensorflow/cc/ops/nn_ops.h" +#include "tensorflow/compiler/jit/shape_inference.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/trt_convert_api.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/platform/status_matchers.h" +#include "tensorflow/core/protobuf/error_codes.pb.h" + +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +namespace ops = ::tensorflow::ops; +using ::tensorflow::testing::StatusIs; + +// This anonymous namespace contains helper functions for instantiating small TF +// building blocks. These are used below to construct specific graph patterns +// which test end-to-end conversion of the TF graph to an explciit-precision +// enabled TensorRT network. +namespace { + +enum class ConvEpilogueType { + kNone, + kReLU, + kBatchNorm, + kReLUBatchnorm, + kBatchnormReLU +}; + +std::ostream& operator<<(std::ostream& os, ConvEpilogueType epilogue) { + switch (epilogue) { + case ConvEpilogueType::kNone: + return os << "None"; + case ConvEpilogueType::kReLU: + return os << "ReLU only"; + case ConvEpilogueType::kBatchNorm: + return os << "BatchNorm Only"; + case ConvEpilogueType::kReLUBatchnorm: + return os << "ReLU+Batchnorm"; + case ConvEpilogueType::kBatchnormReLU: + return os << "BatchNorm+ReLU"; + } +} + +std::string DebugString(ConvEpilogueType epilogue) { + std::stringstream ss; + ss << epilogue; + return ss.str(); +} + +// Adds a 2D 3x3, single channel input with specified data_format. data_format +// must be NHWC,NCHW or NHW. +ops::Placeholder AddInput(Scope scope, int input_idx, + const std::string data_format, + std::array size_chw = {1, 3, 3}) { + PartialTensorShape input_shape; + if (data_format == "NCHW") { + input_shape = + PartialTensorShape({1, size_chw[0], size_chw[1], size_chw[2]}); + } else if (data_format == "NHWC") { + input_shape = + PartialTensorShape({1, size_chw[1], size_chw[2], size_chw[0]}); + } else if (data_format == "NHW") { + input_shape = PartialTensorShape({1, size_chw[1], size_chw[2]}); + } else { + LOG(FATAL) << "Unknown input shape type " << data_format; + } + auto input_attrs = ops::Placeholder::Attrs().Shape(input_shape); + return ops::Placeholder(scope.WithOpName(absl::StrCat("input_", input_idx)), + DT_FLOAT, input_attrs); +} + +// Adds QDQ op with min = -1.0f, max = 1.0f. +Output AddQDQV2(Scope scope, Input input) { + // Create scaling factors. + auto input_min = + ops::Const(scope.WithOpName("in_min"), -1.0f, TensorShape{}); + auto input_max = + ops::Const(scope.WithOpName("in_max"), 1.0f, TensorShape{}); + return ops::QuantizeAndDequantizeV2(scope.WithOpName("qdq"), input, input_min, + input_max); +} + +Output AddOutput(Scope scope, Output input, int idx, bool add_qdq) { + Output out = input; + if (add_qdq) { + out = AddQDQV2(scope, input); + } + return ops::Identity(scope.WithOpName(StrCat("output_", idx)), out); +} + +// Adds a 3x3x1x1 Conv2D op and optional bias weights, followed by ReLU +// activation. Puts QDQ between (weights, op). Puts QDQ between (input, op) +// when qdq_on_output=false. Otherwise, puts QDQ between (op, output). +Output AddConv2D(Scope scope, Input input, int in_channels, int out_channels, + std::array filter_size = {1, 1}, + std::array stride = {1, 1}, + const std::string& data_format = "NCHW", bool with_bias = true, + ConvEpilogueType epilogue = ConvEpilogueType::kBatchnormReLU, + bool qdq_on_output = false) { + // Create 3x3 non-quantized weights weights. + auto weights_const = ops::Const( + scope.WithOpName("weights"), 1.0f, + TensorShape({filter_size[0], filter_size[1], in_channels, out_channels})); + + // Add QDQ to input if we don't add QDQ to output. + auto conv_input = + !qdq_on_output ? AddQDQV2(scope.WithOpName("qdq_input"), input) : input; + + Output result = ops::Conv2D( + scope.WithOpName("conv2d"), conv_input, AddQDQV2(scope, weights_const), + /*strides=*/{1, 1, 1, 1}, + /*padding=*/"SAME", ops::Conv2D::Attrs().DataFormat(data_format)); + + if (with_bias) { + auto bias_const = ops::Const(scope.WithOpName("bias_weights"), 1.0f, + TensorShape({ + out_channels, + })); + result = ops::BiasAdd(scope.WithOpName("bias"), result, bias_const, + ops::BiasAdd::Attrs().DataFormat(data_format)); + } + + auto add_bn = [scope, data_format](Input input, + const int channels) -> Output { + TensorShape constant_shape = TensorShape({channels}); + auto bn_scale = + ops::Const(scope.WithOpName("bn_scale"), 1.0f, constant_shape); + auto bn_offset = + ops::Const(scope.WithOpName("bn_offset"), 1.0f, constant_shape); + auto bn_mean = + ops::Const(scope.WithOpName("bn_mean"), 0.1f, TensorShape({channels})); + auto bn_var = + ops::Const(scope.WithOpName("bn_var"), 1.0f, TensorShape({channels})); + Input conv_bn_input = IS_TRT_VERSION_GE(8, 0, 1, 0) + ? input + : AddQDQV2(scope.WithOpName("qdq_input"), input); + return ops::FusedBatchNormV3( + scope.WithOpName("bn"), conv_bn_input, bn_scale, bn_offset, + bn_mean, bn_var, + ops::FusedBatchNormV3::Attrs().IsTraining(false).DataFormat( + data_format)) + .y; + }; + + switch (epilogue) { + case ConvEpilogueType::kBatchNorm: { + result = add_bn(result, out_channels); + break; + } + case ConvEpilogueType::kReLU: { + result = ops::Relu(scope.WithOpName("relu"), result); + break; + } + case ConvEpilogueType::kReLUBatchnorm: { + result = ops::Relu(scope.WithOpName("relu"), result); + result = add_bn(result, out_channels); + break; + } + case ConvEpilogueType::kBatchnormReLU: { + result = add_bn(result, out_channels); + result = ops::Relu(scope.WithOpName("relu"), result); + break; + } + case ConvEpilogueType::kNone: + break; + } + + if (qdq_on_output) { + result = AddQDQV2(scope.WithOpName("qdq_out"), result); + } + return result; +} + +// Adds a batch matrix multiplication V2 operation, which commonly appears in +// fully connected layers. Puts QDQ between (input, op) as well as between +// (weights, op). +ops::BatchMatMulV2 AddMatMul(Scope scope, const std::string& name, + Input input) { + // Add QDQ to input. + auto input_qdq = AddQDQV2(scope, input); + + // Add 3x3 weights with QDQ. + auto weights_const = + ops::Const(scope.WithOpName(name + "_weights"), + {1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f}, + TensorShape({3, 3})); + auto weights_qdq = AddQDQV2(scope.WithOpName("weights_qdq"), weights_const); + return ops::BatchMatMulV2(scope.WithOpName(name), input_qdq, weights_qdq); +} +} // namespace + +struct QDQTestOptions { + bool conv_has_bias{true}; + + // TRT7 may have issues with optimizing redundant transpose operations between + // QDQ and Op introduced by TF-TRT when format is not "NCHW". This allows to + // test both cases as well as WAR feasibility. + std::string data_format{"NCHW"}; + + // Tests whether placing QDQ on outputs rather than inputs is handled + // correctly. + bool qdq_on_output{false}; + + // Option for testing whether TRT build succeeds without a final QDQ before + // the output. + bool final_qdq{true}; + + // Whether to add activations (relu) to conv operations + ConvEpilogueType conv_epilogue; + + // TF-TRT API Options + TfTrtConversionParams conversion_params{}; +}; + +std::ostream& operator<<(std::ostream& os, const QDQTestOptions opts) { + return os << absl::StrCat( + "QDQTestOptions(conv_has_bias=", + static_cast(opts.conv_has_bias), + ", qdq_on_output=", static_cast(opts.qdq_on_output), + ", data_format=", opts.data_format, + ", conv_epilogue=", DebugString(opts.conv_epilogue), + ", final_qdq=", opts.final_qdq, ")"); +} + +std::vector EnumerateQDQTestOptions() { + std::vector result; + for (const absl::string_view data_format : {"NCHW", "NHWC"}) { + for (auto use_bias : {true, false}) { + for (auto qdq_on_output : {false, true}) { + // For now, always append a QDQ before output. For small single-op tests + // (besides QDQ), TensorRT7 sometimes has trouble. + for (auto final_qdq : {true, false}) { + for (auto conv_epilogue : + {ConvEpilogueType::kReLU, ConvEpilogueType::kNone, + ConvEpilogueType::kBatchnormReLU}) { + // Currently batch norm converter only supports NHWC. + if (data_format == "NHWC" && + (conv_epilogue == ConvEpilogueType::kBatchnormReLU || + conv_epilogue == ConvEpilogueType::kBatchNorm || + conv_epilogue == ConvEpilogueType::kBatchnormReLU)) { + continue; + } + QDQTestOptions opts{}; + opts.conv_has_bias = use_bias; + opts.data_format = data_format; + opts.qdq_on_output = qdq_on_output; + opts.final_qdq = final_qdq; + opts.conv_epilogue = conv_epilogue; + result.push_back(opts); + } + } + } + } + } + return result; +} + +// This class is a test fixture for running graph conversion and evaluating +// numerical results. +class QDQExplicitTest : public ::testing::Test, + public ::testing::WithParamInterface { + public: + static StatusOr GetShape(const std::string& name, + const GraphShapeInfo& shapes) { + TRT_ENSURE(shapes.find(name) != shapes.end()); + TRT_ENSURE(shapes.at(name).size() == 1); + return shapes.at(name)[0].shape; + } + + StatusOr GetModel(const GraphDef& graph_def, + const std::vector& inputs, + const std::vector& outputs, + const GraphShapeInfo& shapes) { + TRT_ENSURE(!inputs.empty()); + TRT_ENSURE(!outputs.empty()); + + MetaGraphDef out; + out.mutable_graph_def()->CopyFrom(graph_def); + + SignatureDef signature_def; + auto& mutable_inputs = *signature_def.mutable_inputs(); + for (int i = 0; i < inputs.size(); i++) { + std::string input_name = inputs[i]->name(); + auto& input = mutable_inputs[input_name]; + input.set_name(input_name); + input.set_dtype(DT_FLOAT); + TRT_ENSURE(shapes.find(input_name) != shapes.end()); + TRT_ENSURE(shapes.at(input_name).size() == 1); + PartialTensorShape input_shape = shapes.at(input_name)[0].shape; + input_shape.AsProto(input.mutable_tensor_shape()); + } + + auto& mutable_outputs = *signature_def.mutable_outputs(); + for (int i = 0; i < outputs.size(); i++) { + std::string output_name = outputs[i]->name(); + auto& output = mutable_outputs[output_name]; + output.set_name(output_name); + output.set_dtype(DT_FLOAT); + TRT_ENSURE(shapes.find(output_name) != shapes.end()); + TRT_ENSURE(shapes.at(output_name).size() == 1); + PartialTensorShape output_shape = shapes.at(output_name)[0].shape; + output_shape.AsProto(output.mutable_tensor_shape()); + } + + (*out.mutable_signature_def())["serving_default"] = signature_def; + return out; + } + + // Confirms that we have a TRT node with the correct attributes. + static Status CheckTrtNode(const GraphDef& converted_graph_def) { + int n_trt_ops = 0; + string op_name{"TRTEngineOp"}; + for (const auto& node : converted_graph_def.node()) { + if (op_name == node.op()) { + n_trt_ops++; + const auto& attr = node.attr(); + TRT_ENSURE(attr.at("static_engine").b()); + VLOG(2) << "Found serialized segment with size " + << attr.at("serialized_segment").s().size(); + TRT_ENSURE(!attr.at("serialized_segment").s().empty()); + } + } + TRT_ENSURE(n_trt_ops == 1); + return OkStatus(); + } + + Status ConvertAndRun(Scope* scope) { + std::vector inputs; + std::vector outputs; + + GraphDef gdef; + TF_RETURN_IF_ERROR(scope->ToGraphDef(&gdef)); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_RETURN_IF_ERROR(scope->ToGraph(graph.get())); + + GraphShapeInfo shape_info; + TF_RETURN_IF_ERROR(InferShapes(graph.get(), /*arg_shapes=*/{}, + /*fnlib_def=*/nullptr, &shape_info)); + + for (const NodeDef& node : gdef.node()) { + if (absl::StartsWith(node.name(), "input_")) { + inputs.push_back(&node); + } else if (absl::StartsWith(node.name(), "output_")) { + outputs.push_back(&node); + } + } + + StatusOr meta_graph_def = + GetModel(gdef, inputs, outputs, shape_info); + TRT_ENSURE_OK(meta_graph_def); + + // Create a list of input tensors, they will be used to build the engines. + std::vector input_tensors; + std::vector input_names; + for (const auto& input : inputs) { + input_names.push_back(input->name()); + + StatusOr input_shape = + GetShape(input->name(), shape_info); + TRT_ENSURE_OK(input_shape); + + TensorShape shape; + input_shape->AsTensorShape(&shape); + Tensor tensor(DT_FLOAT, shape); + test::FillIota(&tensor, 1.0f); + input_tensors.push_back(tensor); + } + + std::vector output_names; + for (const auto& output : outputs) { + output_names.push_back(output->name()); + } + + TfTrtConversionParams conversion_params; + conversion_params.allow_build_at_runtime = true; + conversion_params.precision_mode = TrtPrecisionMode::INT8; + conversion_params.use_calibration = false; + conversion_params.convert_to_static_engine = true; + TRT_ENSURE(input_names.size() == input_tensors.size()); + StatusOr converted_gdef = tensorrt::ConvertAndBuild( + meta_graph_def->graph_def(), input_names, output_names, {input_tensors}, + conversion_params); + TRT_ENSURE_OK(converted_gdef); + return CheckTrtNode(*converted_gdef); + } + + protected: + TfTrtConversionParams params_; + TrtUniquePtrType engine_; +}; + +class TestQDQSuite : public QDQExplicitTest {}; + +#define EXPECT_QDQ_ON_OUTPUT_FAILURE(params, scope) \ + if ((params).qdq_on_output) { \ + EXPECT_THAT(ConvertAndRun(&(scope)), StatusIs(error::INTERNAL)); \ + return; \ + } +#define EXPECT_NO_FINAL_QDQ_FAILURE(params, scope) \ + if (!(params).final_qdq) { \ + EXPECT_THAT(ConvertAndRun(&(scope)), StatusIs(error::INTERNAL)); \ + return; \ + } + +#define EXPECT_BUILD_OK(scope) TF_EXPECT_OK(ConvertAndRun(&(scope))) + +#define POLICY_TRT7(params, scope) \ + if (!IS_TRT_VERSION_GE(8, 0, 0, 0)) { \ + EXPECT_QDQ_ON_OUTPUT_FAILURE(params, scope); \ + EXPECT_NO_FINAL_QDQ_FAILURE(params, scope); \ + EXPECT_BUILD_OK(scope); \ + } + +#define POLICY_TRT8(params, scope) \ + if (IS_TRT_VERSION_GE(8, 0, 0, 0)) { \ + if (((params).conv_epilogue == ConvEpilogueType::kBatchNorm || \ + (params).conv_epilogue == ConvEpilogueType::kBatchnormReLU || \ + (params).conv_epilogue == ConvEpilogueType::kReLUBatchnorm) && \ + (params).data_format == "NHWC") { \ + EXPECT_THAT(ConvertAndRun(&(scope)), StatusIs(error::UNIMPLEMENTED)); \ + return; \ + } \ + EXPECT_BUILD_OK(scope); \ + } + +#define SKIP_TRT7(x) \ + if (!IS_TRT_VERSION_GE(8, 0, 0, 0) && (x)) { \ + GTEST_SKIP(); \ + } + +// Tests single convolution operation conversion. +TEST_P(TestQDQSuite, TestConv2DBasic) { + SKIP_TRT7(GetParam().qdq_on_output); + SKIP_TRT7(GetParam().data_format != "NCHW"); + SKIP_TRT7(!GetParam().final_qdq); + + Scope scope = Scope::NewRootScope(); + auto input = AddInput(scope, 0, GetParam().data_format, {3, 28, 28}); + + Output out = input; + const int num_conv = 1; + std::array in_channels = {3, 16}; + std::array out_channels = {16, 32}; + for (int i = 0; i < num_conv; i++) { + out = AddConv2D(scope.WithOpName(absl::StrCat("conv_", i)), out, + in_channels[i], out_channels[i], /*filter_size=*/{3, 3}, + /*stride=*/{1, 1}, GetParam().data_format, + GetParam().conv_has_bias, GetParam().conv_epilogue, + GetParam().qdq_on_output); + } + out = AddOutput(scope, out, 0, GetParam().final_qdq); + POLICY_TRT7(GetParam(), scope); + POLICY_TRT8(GetParam(), scope); +} + +// Tests single convolution operation conversion. +TEST_P(TestQDQSuite, TestMatMulBasic) { + // Some param's don't apply, so pick one combination and skip otherwise. + if (GetParam().data_format != "NCHW" || !GetParam().conv_has_bias || + GetParam().qdq_on_output || + GetParam().conv_epilogue != ConvEpilogueType::kReLU) { + GTEST_SKIP(); + } + Scope scope = Scope::NewRootScope(); + auto input = AddInput(scope, 0, "NHW"); + auto matmul_op = AddMatMul(scope, "matmul", input); + auto out = AddOutput(scope, matmul_op, 0, GetParam().final_qdq); + + TF_EXPECT_OK(ConvertAndRun(&scope)); +} + +// A single input goes through two different Conv2D. Outputs of Conv2D are +// added together, with QQQ on both branches of ADD. +TEST_P(TestQDQSuite, AddBothBranchesQDQConvSingleInput) { + SKIP_TRT7(!GetParam().final_qdq); + SKIP_TRT7(GetParam().data_format != "NCHW"); + + Scope scope = Scope::NewRootScope(); + auto input1 = AddInput(scope, 0, GetParam().data_format, + /*size_chw=*/{3, 28, 28}); + + auto conv1 = + AddConv2D(scope, input1, 3, 16, /*filter_size=*/{3, 3}, /*stride=*/{1, 1}, + GetParam().data_format, GetParam().conv_has_bias, + GetParam().conv_epilogue, GetParam().qdq_on_output); + + auto conv2 = + AddConv2D(scope, input1, 3, 16, /*filter_size=*/{3, 3}, /*stride=*/ + {1, 1}, GetParam().data_format, GetParam().conv_has_bias, + GetParam().conv_epilogue, GetParam().qdq_on_output); + + // In the case of "qdq on output", we don't need to add QDQ. + auto add = + ops::Add(scope.WithOpName("add"), + !GetParam().qdq_on_output ? AddQDQV2(scope, conv1) : conv1, + !GetParam().qdq_on_output ? AddQDQV2(scope, conv2) : conv2); + + auto conv3 = + AddConv2D(scope.WithOpName("conv3"), conv2, 16, 16, {1, 1}, {1, 1}, + GetParam().data_format, GetParam().conv_has_bias, + GetParam().conv_epilogue, GetParam().qdq_on_output); + + auto out = + AddOutput(scope.WithOpName("output"), conv3, 0, GetParam().final_qdq); + + POLICY_TRT7(GetParam(), scope); + POLICY_TRT8(GetParam(), scope); +} + +// Tests adding a single tensor to itself, with QQQ on both branches of ADD. +TEST_P(TestQDQSuite, AddBothBranchesQDQMultipleInput) { + // TRT7 QDQ optimizer makes single-input restriction. + SKIP_TRT7(true); + + Scope scope = Scope::NewRootScope(); + auto input1 = AddInput(scope, 0, GetParam().data_format); + auto input2 = AddInput(scope, 1, GetParam().data_format); + auto add = + ops::Add(scope.WithOpName("add"), + !GetParam().qdq_on_output ? AddQDQV2(scope, input1) : input1, + !GetParam().qdq_on_output ? AddQDQV2(scope, input2) : input2); + auto output = AddOutput(scope, add, 0, true); + TF_EXPECT_OK(ConvertAndRun(&scope)); +} + +// Tests Conv-MaxPool combination +TEST_P(TestQDQSuite, TestConvMaxpool) { + SKIP_TRT7(!GetParam().final_qdq); + SKIP_TRT7(GetParam().data_format != "NCHW"); + + Scope scope = Scope::NewRootScope(); + auto input = AddInput(scope, 0, GetParam().data_format, + /*size_chw=*/{3, 28, 28}); + auto conv1 = + AddConv2D(scope, input, 3, 16, /*filter_size=*/{3, 3}, /*stride=*/{1, 1}, + GetParam().data_format, GetParam().conv_has_bias, + GetParam().conv_epilogue, GetParam().qdq_on_output); + ops::MaxPool maxpool = + ops::MaxPool(scope.WithOpName("maxpool"), + AddQDQV2(scope.WithOpName("mp_qdq_in"), conv1), {1, 1, 1, 1}, + {1, 1, 1, 1}, "SAME", + ops::MaxPool::Attrs().DataFormat(GetParam().data_format)); + auto output = + AddOutput(scope.WithOpName("output"), maxpool, 0, GetParam().final_qdq); + POLICY_TRT7(GetParam(), scope); + POLICY_TRT8(GetParam(), scope); +} + +// Tests QDQ(Conv(QDQ(MaxPool(Conv(QDQ(x)))))) +TEST_P(TestQDQSuite, TestConvMaxpoolConv) { + SKIP_TRT7(!GetParam().final_qdq); + SKIP_TRT7(GetParam().data_format != "NCHW"); + + Scope scope = Scope::NewRootScope(); + auto input = AddInput(scope, 0, GetParam().data_format, + /*size_chw=*/{3, 28, 28}); + auto conv1 = + AddConv2D(scope, input, 3, 16, /*filter_size=*/{3, 3}, /*stride=*/{1, 1}, + GetParam().data_format, GetParam().conv_has_bias, + GetParam().conv_epilogue, GetParam().qdq_on_output); + ops::MaxPool maxpool = + ops::MaxPool(scope.WithOpName("maxpool"), + AddQDQV2(scope.WithOpName("mp_qdq_in"), conv1), {1, 1, 1, 1}, + {1, 1, 1, 1}, "SAME", + ops::MaxPool::Attrs().DataFormat(GetParam().data_format)); + auto conv2 = AddConv2D(scope, maxpool, 16, 16, {3, 3}, {1, 1}, + GetParam().data_format, GetParam().conv_has_bias, + GetParam().conv_epilogue, GetParam().qdq_on_output); + auto output = + AddOutput(scope.WithOpName("out"), conv2, 0, GetParam().final_qdq); + POLICY_TRT7(GetParam(), scope); + POLICY_TRT8(GetParam(), scope); +} + +INSTANTIATE_TEST_SUITE_P(TestQDQSuiteInst, TestQDQSuite, + ::testing::ValuesIn(EnumerateQDQTestOptions())); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // IS_TRT_VERSION_GE(8, 0, 0, 0) +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/selectv2.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/selectv2.cc new file mode 100644 index 0000000000000000000000000000000000000000..e84b25a5b69f5678add6df65d302a294b33285ad --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/selectv2.cc @@ -0,0 +1,220 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +#if IS_TRT_VERSION_GE(8, 2, 0, 0) +/* The ConvertSelectV2 is working only for cond_input passed as a boolean + * tensor, which could be created only for TRT >= 8.2. + */ +class ConvertSelectBase : public OpConverterBase { + public: + explicit ConvertSelectBase(const OpConverterParams* params, + const std::string& layer_name) + : OpConverterBase( + params, + {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32}), + layer_name_(layer_name) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("cond", TrtInputArg::kBoth), + InputArgSpec::Create("then", TrtInputArg::kBoth), + InputArgSpec::Create("else", TrtInputArg::kBoth)}; + } + + Status Validate() { + TF_RETURN_IF_ERROR(NotSupportedInImplicitBatch()); + + const auto& params = *this->params_; + const auto& inputs = params.inputs; + const auto& i_cond = inputs.at(0); + const auto& node = params.node_def; + TF_RETURN_IF_ERROR( + check_type(i_cond.TrtDType(), nvinfer1::DataType::kBOOL, node)); + + if (i_cond.is_weights()) { + // According to + // https://docs.nvidia.com/deeplearning/tensorrt/developer-guide/index.html#constant-layer + // Boolean weights are not supported in TRT version 8.4. + return errors::InvalidArgument(bool_weight_error_msg(node)); + } + + const auto& i_then = inputs.at(1); + const auto& i_else = inputs.at(2); + const auto type_then = i_then.TrtDType(); + const auto type_else = i_else.TrtDType(); + if (type_then != type_else && (type_then == nvinfer1::DataType::kINT32 || + type_else == nvinfer1::DataType::kINT32)) { + // Both or none of (type_then, type_else) should be equal to kINT32. + return errors::InvalidArgument( + then_else_dtypes_error_msg(type_then, type_else, node)); + } + + bool cond_is_vector = false; + const auto& shape_cond = i_cond.GetTrtDims(); + if (layer_name_ == "select") { + const auto& shape_then = i_then.GetTrtDims(); + const auto& shape_else = i_else.GetTrtDims(); + TF_RETURN_IF_ERROR(compare_shapes(shape_then, shape_else)); + TF_RETURN_IF_ERROR( + compare_shapes(shape_cond, shape_then, &cond_is_vector)); + } + + nvinfer1::Dims cond_dims(shape_cond); + if (cond_is_vector) { + cond_dims.nbDims = i_then.GetTrtDims().nbDims; + const std::vector ones(cond_dims.d[0], 1); + std::copy(ones.begin(), ones.end(), cond_dims.d + 1); + } + + const TRT_TensorOrWeights new_cond(nvinfer1::DataType::kBOOL, cond_dims, + i_cond.batch_size()); + nvinfer1::Dims broadcasted_dims[3]; + for (int i = 1; i < 3; i++) { + TF_RETURN_IF_ERROR(GetTrtBroadcastShape(new_cond, inputs.at(i), true, + false, broadcasted_dims, + broadcasted_dims + i)); + } + + for (int i = 0; i < tensor_.size(); i++) { + // This will also convert constants to tensors. + tensor_[i] = std::make_unique(inputs.at(i)); + TF_RETURN_IF_ERROR( + ApplyBroadcast(tensor_[i], broadcasted_dims[i], this->params_, 0)); + } + + return OkStatus(); + } + + Status Convert() { + const auto& params = *this->params_; + auto* converter = params.converter; + + nvinfer1::ISelectLayer* select_layer = converter->network()->addSelect( + *tensor_[0].get()->as_tensor(params_)->trt_tensor(), // cond_tensor + *tensor_[1].get()->as_tensor(params_)->trt_tensor(), // then_tensor + *tensor_[2].get()->as_tensor(params_)->trt_tensor() // else_tensor + ); + + converter->SetLayerName(select_layer, params.node_def.name(), layer_name_); + AddOutput(TRT_TensorOrWeights(select_layer->getOutput(0))); + return OkStatus(); + } + + private: + Status compare_shapes(const nvinfer1::Dims& shape1, + const nvinfer1::Dims& shape2, + bool* cond_is_vector = nullptr) const { + const bool then_vs_else = cond_is_vector == nullptr; + bool same_shapes = shape1 == shape2; + if (!same_shapes && shape1.nbDims == shape2.nbDims) { + // We can't check size equivalent when dynamic shapes are involved. + // In this case, the two shapes should be equal at runtime. Therefore, + // the shapes still should be considered as equal if at least one of + // them is a tensor with dynamic shape, + same_shapes = DynamicShapeInput(this->params_->inputs, then_vs_else); + } + if (!same_shapes) { + if (then_vs_else || !(*cond_is_vector = (shape1.nbDims == 1 && + shape1.d[0] == shape2.d[0]))) { + const auto err = input_shapes_error_msg( + shape1, shape2, this->params_->node_def, then_vs_else); + return errors::InvalidArgument(err); + } + } + return OkStatus(); + } + + bool DynamicShapeInput(const std::vector& inputs, + bool then_vs_else) const { + const int idx = then_vs_else ? 1 : 0; + for (int i = 0; i < 2; ++i) { + const auto& input = inputs.at(i + idx); + if (input.is_tensor() && !HasStaticShape(input.GetTrtDims())) { + return true; + } + } + return false; + } + + std::array, 3> tensor_; + const std::string layer_name_; +}; + +class ConvertSelect : public ConvertSelectBase { + public: + explicit ConvertSelect(const OpConverterParams* params) + : ConvertSelectBase(params, "select") {} +}; + +class ConvertSelectV2 : public ConvertSelectBase { + public: + explicit ConvertSelectV2(const OpConverterParams* params) + : ConvertSelectBase(params, "selectv2") {} +}; + +std::string op_node_info(const NodeDef& node) { + return " of the '" + node.op() + "' operation at the node '" + node.name() + + "' "; +} + +std::string bool_weight_error_msg(const NodeDef& node) { + return "The boolean parameter '" + node.input(0) + "'" + op_node_info(node) + + "cannot be passed as a weight in TRT version 8.4."; +} + +std::string then_else_dtypes_error_msg(nvinfer1::DataType type_then, + nvinfer1::DataType type_else, + const NodeDef& node) { + return "DataTypes (" + DebugString(type_then) + ", " + + DebugString(type_else) + ") of parameters (" + node.input(1) + ", " + + node.input(2) + ")" + op_node_info(node) + "are incompatible."; +} + +std::string input_shapes_error_msg(const nvinfer1::Dims& shape1, + const nvinfer1::Dims& shape2, + const NodeDef& node, bool then_vs_else) { + const std::string& param_names = + then_vs_else ? "'then' and 'else'" : "'cond' and 'then'"; + std::string error_msg = "The shapes of the " + param_names + " parameters" + + op_node_info(node) + "must be the same"; + if (!then_vs_else) { + error_msg += + " OR 'cond' must be a vector with N elements, " + "where N is a batch size (the first shape dimension for 'then')"; + } + return error_msg + ", got " + DebugString(shape1) + " vs. " + + DebugString(shape2) + "."; +} + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + "Select"); +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + "SelectV2"); +#endif + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..dba708e4e03ae9f3373d1d00ad77d3a68d099b3f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.cc @@ -0,0 +1,300 @@ +/* Copyright 2021 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/tf2tensorrt/convert/ops/slice_ops.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" +#include "absl/types/optional.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/strided_slice_op.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +// Adds a set of operations to the network which set the parameters for the +// given "slice_layer" in order to handle dynamic input shape. +Status HandleDynamicStridedSliceInput( + TRTNetworkBuilder* builder, nvinfer1::ISliceLayer* slice_layer, + const StridedSliceShapeSpec& strided_slice_spec, + const absl::InlinedVector& dynamic_input_size_indices, + nvinfer1::Dims begin_dims, nvinfer1::Dims stride_dims, + nvinfer1::Dims end_dims); + +Status ConvertStridedSliceHelper( + const OpConverterParams* params, const TRT_TensorOrWeights& input, + const PartialTensorShape& input_dims, const SliceDims& begin, + const SliceDims& stride, const SliceDims& end, + std::optional final_shape, std::optional op_instance, + std::optional strided_slice_spec) { + const auto& node_def = params->node_def; + + auto begin_dims = DimsAdapter::Create(begin, params->use_implicit_batch); + auto stride_dims = DimsAdapter::Create(stride, params->use_implicit_batch); + auto end_dims = DimsAdapter::Create(end, params->use_implicit_batch); + TRT_ENSURE_OK(begin_dims); + TRT_ENSURE_OK(stride_dims); + TRT_ENSURE_OK(end_dims); + + // For each dimension, gather information about static vs dynamic dimension + // and slice size. + nvinfer1::Dims size_dims = begin_dims->AsTrtDims(); + absl::InlinedVector static_input_size_indices; + absl::InlinedVector dynamic_input_size_indices; + for (int i = 0; i < begin_dims->NumDims(); i++) { + size_dims.d[i] = (std::abs(end_dims->dim(i) - begin_dims->dim(i)) + + std::abs(stride_dims->dim(i)) - 1) / + std::abs(stride_dims->dim(i)); + // When begin tensor has negative values, currently range can't be computed. + if (begin_dims->dim(i) < 0) { + return errors::Unimplemented( + "Negative values in begin weight tensor are unsupported"); + } + if (input_dims.dim_size(i) < 0) { + // end_dims and begin_dims do not have valid information yet. + dynamic_input_size_indices.push_back(i); + } else { + static_input_size_indices.push_back(i); + if (end_dims->dim(i) < begin_dims->dim(i) && stride_dims->dim(i) > 0) { + return errors::InvalidArgument( + "\"size\" cannot be negative for StridedSlice"); + } + } + } + + if (!dynamic_input_size_indices.empty()) { + if (strided_slice_spec == std::nullopt) { + return errors::InvalidArgument( + "The argument `strided_slice_spec` is " + "`std::nullopt` with `dynamic_input_size_indices` non empty."); + } + if (params->use_implicit_batch) { + return errors::InvalidArgument( + "In implicit batch mode, dynamic input size is not supported."); + } + } + + if (params->validation_only) return OkStatus(); + + StatusOr builder = TRTNetworkBuilder::Create( + params->converter->network(), params->weight_store); + TRT_ENSURE_OK(builder); + + // Create the slice operation. For dynamic dims, the inputs of the operations + // may be reassigned later. + StatusOr slice = + builder->Slice(input.tensor()->trt_tensor(), begin_dims->AsTrtDims(), + size_dims, stride_dims->AsTrtDims()); + TRT_ENSURE_PTR_OK(slice); + + // Handle dynamic input shapes. + if (!dynamic_input_size_indices.empty()) { + TF_RETURN_IF_ERROR(HandleDynamicStridedSliceInput( + &*builder, *slice, *strided_slice_spec, dynamic_input_size_indices, + begin_dims->AsTrtDims(), stride_dims->AsTrtDims(), + end_dims->AsTrtDims())); + } + + params->converter->SetLayerName(*slice, params->node_def, "slice", + op_instance); + ITensorProxyPtr tensor = (*slice)->getOutput(0); + + // Reshape for shrink axis, ellipsis masks based on the shape computed by + // ValidateStridedSliceOp or HandleDynamicStridedSliceInput. + nvinfer1::Dims dims = tensor->trt_tensor()->getDimensions(); + std::vector slice_input_dims(dims.d, dims.d + dims.nbDims); + StridedSliceShapeSpec empty_spec; + empty_spec.shrink_axis_dense_mask = 0; + auto shrink_axis_mask = + strided_slice_spec.value_or(empty_spec).shrink_axis_dense_mask; + if (final_shape) { + if (shrink_axis_mask) { + int shrink_idx = params->use_implicit_batch ? 1 : 0; + const auto bShrink_axis_mask = std::bitset<32>(shrink_axis_mask); + for (int idx = 0; idx < slice_input_dims.size(); ++idx, ++shrink_idx) { + const bool shrink_axis = bShrink_axis_mask[shrink_idx]; + if (shrink_axis) { + slice_input_dims[idx] = 0; + } + } + TF_RETURN_IF_ERROR(params->converter->SqueezeTensor( + tensor, &slice_input_dims, params, &tensor, op_instance)); + } else { + /* To do: pmajety: + Remove the else condition when shrink_axis_mask is always defined */ + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params->converter, TRT_TensorOrWeights(tensor), *final_shape, + /*validation_only=*/false, &tensor, node_def, op_instance)); + } + } + params->outputs->push_back(TRT_TensorOrWeights(tensor)); + return OkStatus(); +} + +Status HandleDynamicStridedSliceInput( + TRTNetworkBuilder* builder, nvinfer1::ISliceLayer* slice_layer, + const StridedSliceShapeSpec& strided_slice_spec, + const absl::InlinedVector& dynamic_input_size_indices, + nvinfer1::Dims begin_dims, nvinfer1::Dims stride_dims, + nvinfer1::Dims end_dims) { + TRT_ENSURE(builder); + TRT_ENSURE(slice_layer); + + nvinfer1::ITensor* input_tensor = slice_layer->getInput(0); + TRT_ENSURE(input_tensor); + + // When begin_mask or end_mask are set, we have to disregard the begin_tensor + // and end_tensor values. In static indices cases, ValidateStridedSliceOp + // returns the correct begin_tensor and end_tensor values, however with + // dynamic indices the correct shape has to be computed. + + VLOG(3) << "begin_dims before: " << DebugString(begin_dims); + VLOG(3) << "end_dims before: " << DebugString(end_dims); + const auto begin_mask = std::bitset<32>(strided_slice_spec.begin_dense_mask); + const auto end_mask = std::bitset<32>(strided_slice_spec.end_dense_mask); + const auto shrink_axis_mask = + std::bitset<32>(strided_slice_spec.shrink_axis_dense_mask); + nvinfer1::Dims dims = input_tensor->getDimensions(); + + for (int idx = 0; idx < dims.nbDims; ++idx) { + VLOG(3) << "begin_mask[" << idx << "]: " << begin_mask[idx]; + VLOG(3) << "end_mask[" << idx << "]: " << end_mask[idx]; + VLOG(3) << "shrink_mask[" << idx << "]: " << shrink_axis_mask[idx]; + if (begin_mask[idx]) { + begin_dims.d[idx] = 0; + } + if (end_mask[idx]) { + end_dims.d[idx] = dims.d[idx]; + } + if (shrink_axis_mask[idx]) { + end_dims.d[idx] = begin_dims.d[idx] + 1; + } + } + + VLOG(2) << "begin_dims after shrink_axis_mask correction: " + << DebugString(begin_dims); + VLOG(2) << "end_dims after shrink_axis_mask correction: " + << DebugString(end_dims); + + // For each dynamic input dimension of the input, do some preprocessing based + // on whether this dimension is set in "begin_mask" or "end_mask" and the sign + // of the dimension's stride value. + // When stride is negative: + // - If "begin_mask[dynamic_idx]" is set, then we need to adjust the slice + // start of dimension[i] to the dynamic size. + // - If "end_mask[dynamic_idx]" is set, it suffices to set + // end_dims[dynamic_idx] to -1. + // When stride is positive: + // - If "begin_mask[dynamic_idx]" is set, it suffices to set + // begin_dims[dynamic_idx] to zero. + // - If "end_mask[dynamic_idx]" is set, we need to adjust slice end to the + // dynamic size of dimension "dynamic_idx". + absl::InlinedVector dynamic_begin_indices; + absl::InlinedVector dynamic_end_indices; + + for (int i = 0; i < dynamic_input_size_indices.size(); i++) { + auto dynamic_idx = dynamic_input_size_indices[i]; + if (begin_mask[dynamic_idx]) { + begin_dims.d[dynamic_idx] = 0; + if (stride_dims.d[dynamic_idx] < 0) { + dynamic_begin_indices.push_back(dynamic_idx); + } + } + if (end_mask[dynamic_idx] && !shrink_axis_mask[dynamic_idx]) { + end_dims.d[dynamic_idx] = stride_dims.d[dynamic_idx] > 0 ? 0 : -1; + if (stride_dims.d[dynamic_idx] > 0) { + dynamic_end_indices.push_back(dynamic_idx); + } + } + } + + VLOG(2) << " Dynamic begin indices: " << DebugString(dynamic_begin_indices) + << " Dynamic end indices: " << DebugString(dynamic_end_indices); + + // Create ITensors for each of the begin/stride/end constants. + StatusOr begin_const = builder->Constant( + std::vector(begin_dims.d, begin_dims.d + begin_dims.nbDims)); + TRT_ENSURE_PTR_OK(begin_const); + nvinfer1::ITensor* begin_tensor = (*begin_const)->getOutput(0); + StatusOr stride_const = builder->Constant( + std::vector(stride_dims.d, stride_dims.d + stride_dims.nbDims)); + TRT_ENSURE_PTR_OK(stride_const); + StatusOr end_const = builder->Constant( + std::vector(end_dims.d, end_dims.d + end_dims.nbDims)); + TRT_ENSURE_PTR_OK(end_const); + nvinfer1::ITensor* end_tensor = (*end_const)->getOutput(0); + + // Make corrections based on the begin_mask/end_mask values. + if (dynamic_end_indices.size() > 0) { + StatusOr dynamic_end_masked_tensor = + builder->GetPartialShapeOf(input_tensor, dynamic_end_indices, + /*sub_one=*/false); + TRT_ENSURE_PTR_OK(dynamic_end_masked_tensor); + StatusOr end_corrected = + builder->Add((*dynamic_end_masked_tensor)->getOutput(0), end_tensor); + TRT_ENSURE_PTR_OK(end_corrected); + end_tensor = (*end_corrected)->getOutput(0); + } + if (dynamic_begin_indices.size() > 0) { + StatusOr dynamic_begin_masked_tensor = + builder->GetPartialShapeOf(input_tensor, dynamic_begin_indices, + /*sub_one=*/true); + TRT_ENSURE_PTR_OK(dynamic_begin_masked_tensor); + + // Add back the original "begin" values for static dimensions. + StatusOr begin_corrected = builder->Add( + (*dynamic_begin_masked_tensor)->getOutput(0), begin_tensor); + TRT_ENSURE_PTR_OK(begin_corrected); + begin_tensor = (*begin_corrected)->getOutput(0); + } + + // Calculate the final size of the slice dynamically. + nvinfer1::ITensor* size_tensor; + { + StatusOr num = + builder->Sub(end_tensor, begin_tensor); + TRT_ENSURE_PTR_OK(num); + StatusOr ceil_div = builder->AbsCeilDivInt( + (*num)->getOutput(0), (*stride_const)->getOutput(0)); + TRT_ENSURE_PTR_OK(ceil_div); + size_tensor = (*ceil_div)->getOutput(0); + } + + slice_layer->setInput(1, *begin_tensor); + slice_layer->setInput(2, *size_tensor); + slice_layer->setInput(3, *(*stride_const)->getOutput(0)); + + return OkStatus(); +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..56012deee93c304b94a66b08aa287eb4ede1770e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/slice_ops.h @@ -0,0 +1,70 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_OPS_SLICE_OPS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_SLICE_OPS_H_ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/util/strided_slice_op.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { +using SliceDims = absl::InlinedVector; + +// Creates a strided slice operation using the given information. This function +// expects that the begin, stride, and end vectors have already been validated. +// This function converts the [begin:stride:end] specification to the TensorRT +// [begin:stride:size] ISliceLayer specification. The following algorithm is +// used to perform this conversion: 1) The given (input_dims, +// [begin:stride:end]) specification is dividied into +// "static dimensions" and "dynamic dimensions". "Dynamic dimensions" +// includes all dimensions of the slice where input_dims[i] == -1. +// 2a) If there are no dynamic dimensions, then the "begin", "stride", and +// "size" variables are passed to the ISLiceLayer creation as build-time +// constants in the form of nvinfer1::Dims objects. +// 2b) If there are any dynamic dimensions, then the "begin", "stride", and +// "size" variables are treated as runtime dynamic shape Tensors in the +// TensorRT graph. In this case, we must calculate "size" at runtime for all +// dynamic dimensions, while static dimensions use the constant values. +// +// Note that when any dynamic indices are present (2b), the "strided_slice_spec" +// must be specified. This structure can be obtained through the +// "tensorflow::ValidateStridedSliceOp" function, or it can be constructed +// directly. When the ValidateStridedSliceOp helper function is used, it will +// also return the "begin", "stride", and "end" vectors. When all dimensions are +// static (2a), the "strided_slice_spec" variable is not required. +// +// If the "final_shape" variable is specified, then a reshape operation will be +// added to the graph to achieve this shape. The shape must be fully specified. +// +// "op_instance" is only required if the caller needs to pass this variable +// through to the Converter functions optionally accept it (SetLayerName, +// PrepareTensorForShape). +Status ConvertStridedSliceHelper( + const OpConverterParams* params, const TRT_TensorOrWeights& input, + const PartialTensorShape& input_dims, const SliceDims& begin, + const SliceDims& stride, const SliceDims& end, + std::optional final_shape = std::nullopt, + std::optional op_instance = std::nullopt, + std::optional strided_slice_spec = std::nullopt); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_OPS_SLICE_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/softmax.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/softmax.cc new file mode 100644 index 0000000000000000000000000000000000000000..fec218a9737b603e731ce145da5fcee54db9e34d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/softmax.cc @@ -0,0 +1,81 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class ConvertSoftmax : public OpConverterBase { + public: + explicit ConvertSoftmax(const OpConverterParams *params) + : OpConverterBase(params) {} + + static constexpr std::array AllowedDataTypes() { + return {DataType::DT_FLOAT, DataType::DT_HALF}; + } + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("logits", TrtInputArg::kTensor)}; + } + + Status Validate() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + + ITensorProxyPtr logits_tensor = inputs.at(0).tensor(); + const int num_trt_dims = logits_tensor->getDimensions().nbDims; + if (!num_trt_dims && params.use_implicit_batch) { + return errors::InvalidArgument( + "TensorRT Softmax cannot apply on the batch dimension"); + } + return OkStatus(); + } + + Status Convert() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + const auto &node_def = params.node_def; + + ITensorProxyPtr logits_tensor = inputs.at(0).tensor(); + const int num_trt_dims = logits_tensor->getDimensions().nbDims; + + // Perform Softmax operation: + nvinfer1::ISoftMaxLayer *layer = + params.converter->network()->addSoftMax(*logits_tensor->trt_tensor()); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + params.converter->SetLayerName(layer, node_def); + // Tensorflow SoftMax applies softmax operation over the last dimension. + layer->setAxes(1 << (num_trt_dims - 1)); + + ITensorProxyPtr output_tensor = layer->getOutput(0); + params.outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } +}; + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + "Softmax"); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/tile.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/tile.cc new file mode 100644 index 0000000000000000000000000000000000000000..fcf612f1c9c26afbbad9015d5f5861b51a9c76f8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/tile.cc @@ -0,0 +1,207 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class ConvertTile : public OpConverterBase { + public: + explicit ConvertTile(const OpConverterParams *params) + : OpConverterBase( + params, + {DataType::DT_FLOAT, DataType::DT_HALF, DataType::DT_INT32}) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("input_tensor", TrtInputArg::kBoth), + InputArgSpec::Create("weight", TrtInputArg::kBoth)}; + } + + Status Validate() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + + const auto &repl = inputs.at(1); + if (params.use_implicit_batch && repl.is_tensor()) { + return errors::InvalidArgument( + "Conversion for Tile is not implemented for multipliers " + "passed as a tensor in implicit batch mode."); + } + + nvinfer1::DataType dtype; + const int *multiplies; + if (repl.is_weights()) { + TFTRT_CHECK_SHAPE_TENSOR(repl.weights().GetTensor()); + dtype = repl.weights().TrtDType(); + multiplies = repl.weights().GetPointer(); + } else { + dtype = repl.tensor()->getType(); + multiplies = nullptr; + } + + const auto &node = params.node_def; + TF_RETURN_IF_ERROR(check_type(dtype, nvinfer1::DataType::kINT32, node, 1)); + + const auto dims = inputs.at(0).GetTrtDims(); + const auto nb_dims = + dims.nbDims + + (params.use_implicit_batch && inputs.at(0).is_tensor() ? 1 : 0); + if (multiplies) { + const int mult_numb = repl.weights().count(); + if (mult_numb != nb_dims) { + return errors::InvalidArgument( + "The length of the replication vector (", mult_numb, + ") of the Tile operation in '", node.name(), + "' is expected to be equal to the rank of the input vector (", + nb_dims, ")."); + } + + if (std::any_of(multiplies, multiplies + nb_dims, + [](int i) { return i <= 0; })) { + const auto &mul = absl::StrJoin(multiplies, multiplies + nb_dims, ", "); + return errors::InvalidArgument( + "All replications of the Tile operation in '", node.name(), + "' should be positive, got (", mul, ")."); + } + + if (params.use_implicit_batch && multiplies[0] > 1) { + return errors::Unimplemented( + "The Tile operation along the batch dimension in '", node.name(), + "' is not implemented."); + } + } else { + const auto &repl_dims = repl.GetTrtDims(); + if (repl_dims.nbDims != 1) { + return errors::InvalidArgument( + "When replications are defined as a tensor, that tensor must be " + "1-dimensional. Got ", + repl_dims.nbDims, "-dimensional tensor."); + } + + // Check the number of elements in multiplyer for tensors with non-dynamic + // shape + if (repl_dims.d[0] >= 0 && repl_dims.d[0] != nb_dims) { + return errors::InvalidArgument( + "When replications are defined as a tensor, " + "the number of its elements (", + repl_dims.d[0], ") must be equal to the rank of the input tensor (", + nb_dims, ")."); + } + } + + return OkStatus(); + } + + Status Convert() { + const auto ¶ms = *this->params_; + const auto &inputs = params.inputs; + auto *converter = params.converter; + auto *network = converter->network(); + const auto &tensor = inputs.at(0); + const auto &replics = inputs.at(1); + const auto dims = tensor.GetTrtDims(); + const auto nb_dims = dims.nbDims; + + nvinfer1::Dims output_size{nb_dims, {1}}; + bool dynamic_flag = replics.is_tensor() || !HasStaticShape(dims); + + if (!dynamic_flag) { + // If input0 is a tensor, and we're in implicit batch mode, then we need + // dim_offset. + const auto dim_offset = + params.use_implicit_batch && tensor.is_tensor() ? 1 : 0; + const auto *input_size = dims.d; + const int *pReplics = replics.weights().GetPointer() + dim_offset; + for (int i = 0; i < nb_dims; i++) + output_size.d[i] = pReplics[i] * input_size[i]; + } + + StatusOr builder; + if (tensor.is_weights() || (dynamic_flag && replics.is_weights())) { + builder = + TRTNetworkBuilder::Create(converter->network(), params.weight_store); + TRT_ENSURE_OK(builder); + } + + ITensorProxyPtr input_tensor; + if (tensor.is_weights()) { + StatusOr weights_const = + builder->WeightsToConstant(tensor.weights().GetTrtWeights(), dims); + TRT_ENSURE_PTR_OK(weights_const); + input_tensor = (*weights_const)->getOutput(0); + } else { + input_tensor = tensor.tensor(); + } + + auto &input_trt_tensor = *input_tensor->trt_tensor(); + nvinfer1::ITensor *target_shape = nullptr; + if (dynamic_flag) { + nvinfer1::ITensor *mult; + if (replics.is_weights()) { + StatusOr weights_const = + builder->WeightsToConstant(replics.weights().GetTrtWeights(), + replics.GetTrtDims()); + TRT_ENSURE_PTR_OK(weights_const); + mult = (*weights_const)->getOutput(0); + } else { + const ITensorProxyPtr multiplies = replics.tensor()->trt_tensor(); + mult = multiplies->trt_tensor(); + } + + nvinfer1::ITensor *shape = + network->addShape(input_trt_tensor)->getOutput(0); + target_shape = network + ->addElementWise(*shape, *mult, + nvinfer1::ElementWiseOperation::kPROD) + ->getOutput(0); + } + + nvinfer1::Dims start{nb_dims, {}}; + DimsAdapter stride(std::vector(nb_dims, 1)); + auto layer = network->addSlice(input_trt_tensor, start, output_size, + stride.AsTrtDims()); + layer->setMode(nvinfer1::SliceMode::kWRAP); + if (target_shape) layer->setInput(2, *target_shape); + + converter->SetLayerName(layer, params.node_def.name(), "to_tile"); + ITensorProxyPtr output_tensor = layer->getOutput(0); + if (tensor.is_weights() && params.use_implicit_batch) { + // Reshape output tensor by removing first dimension. + DimsAdapter adap(output_tensor->getDimensions()); + TF_RETURN_IF_ERROR(adap.RemoveBatchDimension()); + + TF_RETURN_IF_ERROR(PrepareTensorForShape( + params.converter, TRT_TensorOrWeights(output_tensor), + adap.AsTrtDims(), false, &output_tensor, params.node_def)); + } + + AddOutput(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } +}; + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), "Tile"); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/unary_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/unary_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..b25afda81a1fa01ef17b87ae70031d9858a230cf --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/unary_ops.cc @@ -0,0 +1,251 @@ +/* Copyright 2022 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/layer_utils.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +const UnaryOperationMapType* UnaryOperationMap() { + static auto* const m = new UnaryOperationMapType({ + {"Exp", nvinfer1::UnaryOperation::kEXP}, + {"Log", nvinfer1::UnaryOperation::kLOG}, + {"Sqrt", nvinfer1::UnaryOperation::kSQRT}, + {"Rsqrt", nvinfer1::UnaryOperation::kSQRT}, + {"Reciprocal", nvinfer1::UnaryOperation::kRECIP}, + {"Abs", nvinfer1::UnaryOperation::kABS}, + {"Neg", nvinfer1::UnaryOperation::kNEG}, + {"Sin", nvinfer1::UnaryOperation::kSIN}, + {"Cos", nvinfer1::UnaryOperation::kCOS}, + {"Tan", nvinfer1::UnaryOperation::kTAN}, + {"Sinh", nvinfer1::UnaryOperation::kSINH}, + {"Cosh", nvinfer1::UnaryOperation::kCOSH}, + {"Asin", nvinfer1::UnaryOperation::kASIN}, + {"Acos", nvinfer1::UnaryOperation::kACOS}, + {"Atan", nvinfer1::UnaryOperation::kATAN}, + {"Asinh", nvinfer1::UnaryOperation::kASINH}, + {"Acosh", nvinfer1::UnaryOperation::kACOSH}, + {"Atanh", nvinfer1::UnaryOperation::kATANH}, + {"Ceil", nvinfer1::UnaryOperation::kCEIL}, + {"Floor", nvinfer1::UnaryOperation::kFLOOR}, + {"Erf", nvinfer1::UnaryOperation::kERF}, +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + {"Round", nvinfer1::UnaryOperation::kROUND}, + {"Sign", nvinfer1::UnaryOperation::kSIGN}, +#endif + }); + return m; +} + +const UnaryOperationMapType* UnaryBooleanOperationMap() { + static auto* const m = new UnaryOperationMapType({ + {"LogicalNot", nvinfer1::UnaryOperation::kNOT}, + }); + return m; +} + +const ActivationTypeMapType* ActivationTypeMap() { + static auto* const m = new ActivationTypeMapType({ + {"LeakyRelu", nvinfer1::ActivationType::kLEAKY_RELU}, + {"Relu", nvinfer1::ActivationType::kRELU}, + {"Relu6", nvinfer1::ActivationType::kCLIP}, + {"Sigmoid", nvinfer1::ActivationType::kSIGMOID}, + {"Tanh", nvinfer1::ActivationType::kTANH}, + {"Elu", nvinfer1::ActivationType::kELU}, + {"Selu", nvinfer1::ActivationType::kSELU}, + {"Softsign", nvinfer1::ActivationType::kSOFTSIGN}, + {"Softplus", nvinfer1::ActivationType::kSOFTPLUS}, + }); + return m; +} + +template +class ConvertUnaryImpl { + protected: + ConvertUnaryImpl(const OperationMap* pOperMap) : pOperMap_(pOperMap) {} + + Status ValidateImpl(const OpConverterParams& params, + const std::vector& not_supported_ops = {}) { + const auto& node = params.node_def; + const auto& op = node.op(); + if (pOperMap_->find(op) == pOperMap_->end()) { + return errors::Unimplemented("Unary op: ", op, " not supported"); + } + DimsAdapter input_dims(params.inputs.at(0).GetTrtDims()); + if (!input_dims.NumDims()) { + return errors::InvalidArgument( + "At least 1 dimension is required for UNARY operation '", op, "'"); + } + + if (!not_supported_ops.empty() && params.use_implicit_batch) { + const auto& end = not_supported_ops.end(); + if (std::find(not_supported_ops.begin(), end, op) != end) { + const auto& err = + convert_not_supported_implicit(op, node.name(), "Unary"); + return errors::Unimplemented(err); + } + } + + return OkStatus(); + } + + Status ConvertImpl(const OpConverterParams& params) { + const auto& node_def = params.node_def; + auto* converter = params.converter; + const auto op_pair = pOperMap_->find(node_def.op()); + ITensorProxyPtr tensor = params.inputs.at(0).tensor(); + nvinfer1::IUnaryLayer* layer = + converter->network()->addUnary(*tensor->trt_tensor(), op_pair->second); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + converter->SetLayerName(layer, node_def); + if (node_def.op() == "Rsqrt") { + layer = converter->network()->addUnary(*layer->getOutput(0), + nvinfer1::UnaryOperation::kRECIP); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + converter->SetLayerName(layer, node_def, "recip"); + } + params.outputs->push_back(TRT_TensorOrWeights(layer->getOutput(0))); + return OkStatus(); + } + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("x", TrtInputArg::kTensor)}; + } + + protected: + const OperationMap* pOperMap_; +}; + +class ConvertUnary : public OpConverterBase, + protected ConvertUnaryImpl { + public: + explicit ConvertUnary(const OpConverterParams* params) + : OpConverterBase( + params, + params->node_def.op() == "Sign" + ? std::vector{DataType::DT_FLOAT, DataType::DT_HALF, + DataType::DT_INT8, DT_INT32} + : std::vector{DataType::DT_FLOAT, DataType::DT_HALF, + DataType::DT_INT8}), + ConvertUnaryImpl(UnaryOperationMap()) {} + + static constexpr std::array InputSpec() { + return ConvertUnaryImpl::InputSpec(); + } + + Status Validate() { return ValidateImpl(*params_, {"Sign", "Round"}); } + Status Convert() { return ConvertImpl(*params_); } +}; + +class ConvertBooleanUnary : public OpConverterBase, + public ConvertUnaryImpl { + public: + explicit ConvertBooleanUnary(const OpConverterParams* params) + : OpConverterBase(params, {DataType::DT_BOOL}), + ConvertUnaryImpl(UnaryBooleanOperationMap()) {} + + static constexpr std::array InputSpec() { + return ConvertUnaryImpl::InputSpec(); + } + + static constexpr const char* NodeDefDataTypeAttributeName() { + /* + node { + name: "..." + op: "LogicalNot" + input: "..." + } + */ + return ""; + } + Status Validate() { +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + return ValidateImpl(*params_, {"LogicalNot"}); +#else + return errors::Unimplemented("Boolean op: ", params_->node_def.op(), + " is not supported in TRT version < 8.2"); +#endif + } + Status Convert() { return ConvertImpl(*params_); } +}; + +class ConvertActivation : public OpConverterBase, + protected ConvertUnaryImpl { + public: + explicit ConvertActivation(const OpConverterParams* params) + : OpConverterBase(params), + ConvertUnaryImpl(ActivationTypeMap()) {} + + static constexpr std::array InputSpec() { + return std::array{ + InputArgSpec::Create("input", TrtInputArg::kTensor)}; + } + + Status Validate() { + TF_RETURN_IF_ERROR(ValidateImpl(*params_)); + const auto& node_def = params_->node_def; + if (node_def.op() == "LeakyRelu") { + return GetNodeAttr(AttrSlice(node_def), "alpha", &alpha_); + } + alpha_ = 1.0f; + return OkStatus(); + } + Status Convert() { + auto* converter = params_->converter; + const auto& inputs = params_->inputs; + const auto& node_def = params_->node_def; + const auto& op = node_def.op(); + const auto op_pair = pOperMap_->find(op); + nvinfer1::IActivationLayer* layer = converter->network()->addActivation( + *inputs.at(0).tensor()->trt_tensor(), op_pair->second); + TFTRT_RETURN_ERROR_IF_NULLPTR(layer, node_def.name()); + converter->SetLayerName(layer, node_def, "activation"); + ITensorProxyPtr output_tensor = layer->getOutput(0); + // Set parameters. + if (op == "Selu") { + // From tensorflow/core/kernels/relu_op_functor.h + alpha_ = 1.7580993408473768599402175208123f; + layer->setBeta(1.0507009873554804934193349852946f); + } else if (op == "Softplus") { + layer->setBeta(1.0f); + } else if (op == "Relu6") { + layer->setBeta(6.0f); + converter->ProvideQuantizationRange(&output_tensor, alpha_ = 0.0f, 6.0f); + } + layer->setAlpha(alpha_); + params_->outputs->push_back(TRT_TensorOrWeights(output_tensor)); + return OkStatus(); + } + + private: + float alpha_ = 0.f; +}; + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + GetOperationNames(*UnaryOperationMap())); +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction(), + GetOperationNames(*UnaryBooleanOperationMap())); + +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + GetOperationNames(*ActivationTypeMap())); +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/variable_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/variable_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..2a8da0ea8ac2a4d8d7dc12b2ea2ffa76b3e66715 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/ops/variable_ops.cc @@ -0,0 +1,356 @@ +/* Copyright 2022 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "third_party/tensorrt/NvInfer.h" +#include "third_party/tensorrt/NvInferRuntimeCommon.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +struct VarAttributes { + TensorShapeProto shape_proto; + TensorShape shape; + string name; + DataType dtype; + string shared_name; + string container; +}; + +template +Status ReadVariableHelper(const OpConverterParams* params, + const VarAttributes& attrs, + TRT_ShapedWeights* weights) { + Tensor tensor(attrs.dtype, attrs.shape); + auto ctx = params->converter->context(); + TRT_ENSURE(ctx != nullptr); + auto tensor_flat = tensor.flat(); + + // Clone function library runtime in order to get a mutable library + // definition to add and run a function with the variable operation. + auto lib = ctx->function_library(); + std::unique_ptr lib_def; + std::unique_ptr lib_pflr; + FunctionLibraryRuntime* lib_clone; // Not owned. + TF_RETURN_IF_ERROR(lib->Clone(&lib_def, &lib_pflr, &lib_clone)); + + // Create function definition. + FunctionDef fdef; + std::vector args; + string func_name = attrs.name + "/func"; + if (is_resource) { + // Create input tensor with the resource handle. + const auto& inputs = params->inputs; + const TRT_TensorOrWeights& handle = inputs.at(0); + args.emplace_back(handle.resource()); + + fdef = FunctionDefHelper::Define( + func_name, // Name + {"in: resource"}, // Args + {absl::StrCat("out: ", DataTypeString(attrs.dtype))}, // Returns + {}, // Attr def + // Nodes + {{{attrs.name}, + "ReadVariableOp", + {"in"}, // Name of the Placeholder or VarHandleOp + {{"dtype", attrs.dtype}}}, + {{"out"}, "Identity", {attrs.name}, {{"T", attrs.dtype}}}}); + } else { + fdef = FunctionDefHelper::Define( + func_name, // Name + {}, // Args + {absl::StrCat("out: ", DataTypeString(attrs.dtype))}, // Returns + {}, // Attr def + // Nodes + {{{attrs.name}, + "VariableV2", + {}, + {{"dtype", attrs.dtype}, + {"shape", attrs.shape_proto}, + {"container", attrs.container}, + {"shared_name", attrs.shared_name}}}, + {{"out"}, "Identity", {attrs.name}, {{"T", attrs.dtype}}}}); + } + + // Add function definition to the library. + TF_RETURN_IF_ERROR(lib_def->AddFunctionDef(fdef)); + + // Instantiate function. + FunctionLibraryRuntime::Handle func_handle; + FunctionLibraryRuntime::InstantiateOptions inst_ops; + inst_ops.state_handle = ""; + inst_ops.target = ctx->device()->name(); + AttrValueMap attr_list; + TF_RETURN_IF_ERROR(lib_clone->Instantiate(func_name, AttrSlice(&attr_list), + inst_ops, &func_handle)); + + FunctionLibraryRuntime::Options opts; + opts.rendezvous = ctx->rendezvous(); + opts.cancellation_manager = ctx->cancellation_manager(); + opts.runner = ctx->runner(); + + std::vector* rets = new std::vector(); + std::unique_ptr> outputs_wrapper(rets); + + // Run the new function synchronously. + TF_RETURN_IF_ERROR(lib_clone->RunSync(opts, func_handle, args, rets)); + + TRT_ENSURE(ctx->op_device_context() != nullptr); + TRT_ENSURE(ctx->op_device_context()->stream() != nullptr); + + // Copy tensor. + cudaStream_t stream = reinterpret_cast(CHECK_NOTNULL( + ctx->op_device_context()->stream()->platform_specific_handle().stream)); + + auto ret = cudaMemcpyAsync(tensor_flat.data(), rets->at(0).flat().data(), + rets->at(0).NumElements() * sizeof(T), + cudaMemcpyDeviceToHost, stream); + if (ret != 0) { + return errors::Internal("Could not copy the variable ", attrs.name); + } + cudaStreamSynchronize(stream); + + TF_RETURN_IF_ERROR( + TfTensorToTrtWeights(tensor, params->weight_store, weights)); + + return OkStatus(); +} + +class ConvertVariableV2 : public OpConverterBase { + public: + ConvertVariableV2(const OpConverterParams* params) + : OpConverterBase(params) {} + + static constexpr std::array InputSpec() { return {}; } + + static constexpr const char* NodeDefDataTypeAttributeName() { + /* + node { + name: "..." + op: "VariableV2" + ... + attr { + key: "dtype" + value { + type: DT_FLOAT + } + } + ... + } + */ + return "dtype"; + } + + template + Status ValidateImpl() { + const auto& node_def = params_->node_def; + + // Verify and consume node attributes. + StatusOr shape_proto = + GetAttrValue("shape"); + StatusOr shared_name = GetAttrValue("shared_name"); + StatusOr container = GetAttrValue("container"); + TRT_ENSURE_OK(shape_proto); + TRT_ENSURE_OK(shared_name); + TRT_ENSURE_OK(container); + + attrs_.shape_proto = *shape_proto; + attrs_.shape = TensorShape(*shape_proto); + attrs_.name = node_def.name(); + attrs_.shared_name = *shared_name; + attrs_.container = *container; + + Tensor tensor(attrs_.dtype, attrs_.shape); + auto tensor_flat = tensor.flat(); + for (int64_t i = 0; i < tensor_flat.size(); i++) { + tensor_flat(i) = T(0.0f); + } + + TRT_ShapedWeights weights; + TF_RETURN_IF_ERROR( + TfTensorToTrtWeights(tensor, params_->weight_store, &weights)); + + // Only push outputs during validation and when outputs are expected. + if (params_->validation_only && params_->outputs != nullptr) { + AddOutput(TRT_TensorOrWeights(weights)); + } + return OkStatus(); + } + + Status Validate() { + const auto& node_def = params_->node_def; + StatusOr dtype = GetAttrValue("dtype"); + TRT_ENSURE_OK(dtype); + attrs_.dtype = *dtype; + + switch (attrs_.dtype) { + case DT_FLOAT: + return ValidateImpl(); + case DT_HALF: + return ValidateImpl(); + default: + // Note: this should have been caught by ValidateNodeDefDataType, but + // the compiler expects that all paths be handled in switch. + return errors::Unimplemented("Data type ", DataTypeString(attrs_.dtype), + " is not supported for ", node_def.op(), + ", at ", node_def.name()); + } + } + + template + Status ConvertImpl() { + TRT_ShapedWeights weights; + TF_RETURN_IF_ERROR(ReadVariableHelper(params_, attrs_, &weights)); + AddOutput(TRT_TensorOrWeights(weights)); + return OkStatus(); + } + + Status Convert() { + const auto& node_def = params_->node_def; + + switch (attrs_.dtype) { + case DT_FLOAT: + return ConvertImpl(); + case DT_HALF: + return ConvertImpl(); + default: + // Note: this should have been caught by ValidateNodeDefDataType, but + // the compiler expects that all paths be handled in switch. + return errors::Unimplemented("Data type ", DataTypeString(attrs_.dtype), + " is not supported for ", node_def.op(), + ", at ", node_def.name()); + } + } + + private: + VarAttributes attrs_{}; +}; +REGISTER_DEFAULT_TRT_OP_CONVERTER(MakeConverterFunction(), + {"VariableV2"}); + +class ConvertReadVariableOp : public OpConverterBase { + public: + ConvertReadVariableOp(const OpConverterParams* params) + : OpConverterBase(params) {} + + static constexpr std::array InputSpec() { + return {InputArgSpec::Create("resource", TrtInputArg::kResource)}; + } + + static constexpr const char* NodeDefDataTypeAttributeName() { + return "dtype"; + } + + template + Status ValidateImpl() { + const auto& node_def = params_->node_def; + + // Verify and consume node attributes. + StatusOr shape_proto = + GetAttrValue("_shape"); + TRT_ENSURE_OK(shape_proto); + + attrs_.shape_proto = *shape_proto; + attrs_.shape = TensorShape(*shape_proto); + attrs_.name = node_def.name(); + + Tensor tensor(attrs_.dtype, attrs_.shape); + auto tensor_flat = tensor.flat(); + for (int64_t i = 0; i < tensor_flat.size(); i++) { + tensor_flat(i) = T(0.0f); + } + + TRT_ShapedWeights weights; + TF_RETURN_IF_ERROR( + TfTensorToTrtWeights(tensor, params_->weight_store, &weights)); + + // Only push outputs during validation and when outputs are expected. + if (params_->validation_only && params_->outputs != nullptr) { + AddOutput(TRT_TensorOrWeights(weights)); + } + return OkStatus(); + } + + Status Validate() { + const auto& node_def = params_->node_def; + if (params_->use_implicit_batch) { + return errors::Unimplemented("Implicit batch mode not supported, at ", + node_def.name()); + } + + StatusOr dtype = GetAttrValue("dtype"); + TRT_ENSURE_OK(dtype); + attrs_.dtype = *dtype; + + switch (attrs_.dtype) { + case DT_FLOAT: + return ValidateImpl(); + case DT_HALF: + return ValidateImpl(); + default: + // Note: this should have been caught by ValidateNodeDefDataType, but + // the compiler expects that all paths be handled in switch. + return errors::Unimplemented("Data type ", DataTypeString(attrs_.dtype), + " is not supported for ", node_def.op(), + ", at ", node_def.name()); + } + } + + template + Status ConvertImpl() { + TRT_ShapedWeights weights; + TF_RETURN_IF_ERROR(ReadVariableHelper(params_, attrs_, &weights)); + AddOutput(TRT_TensorOrWeights(weights)); + return OkStatus(); + } + + Status Convert() { + const auto& node_def = params_->node_def; + + switch (attrs_.dtype) { + case DT_FLOAT: + return ConvertImpl(); + case DT_HALF: + return ConvertImpl(); + default: + // Note: this should have been caught by ValidateNodeDefDataType, but + // the compiler expects that all paths be handled in switch. + return errors::Unimplemented("Data type ", DataTypeString(attrs_.dtype), + " is not supported for ", node_def.op(), + ", at ", node_def.name()); + } + } + + private: + VarAttributes attrs_{}; +}; +REGISTER_DEFAULT_TRT_OP_CONVERTER( + MakeConverterFunction(), {"ReadVariableOp"}); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/timing_cache.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/timing_cache.cc new file mode 100644 index 0000000000000000000000000000000000000000..feff2d783a97ba3c2b39dc75f49bfc67644a25e3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/timing_cache.cc @@ -0,0 +1,86 @@ +/* Copyright 2022 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/convert/timing_cache.h" + +#include + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/core/platform/errors.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +StatusOr TimingCacheRegistry::LookUp( + const string& name, nvinfer1::IBuilderConfig* builder_config) { +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + TRT_ENSURE(builder_config != nullptr); + mutex_lock scoped_lock(mu_); + if (map_.find(name) != map_.end()) { + const std::vector& data = map_[name]; + return std::unique_ptr( + builder_config->createTimingCache(data.data(), data.size())); + } + + // If no such timing cache exists, create a new timing cache. + return std::unique_ptr( + builder_config->createTimingCache(nullptr, 0)); +#endif // IS_TRT_VERSION_GE(8, 0, 0, 0) + return errors::Unimplemented( + "serializable timing cache does not exist in TensorRT versions < 8.0"); +} + +void TimingCacheRegistry::Upsert(const string& name, TimingCache* cache) { +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + nvinfer1::IHostMemory* memory = cache->serialize(); + if (memory == nullptr) { + return; + } + + if (map_.find(name) == map_.end()) { + // If the timing cache with the given name does not exist, emplace the + // serialized buffer. + std::vector mem(memory->size()); + std::copy_n(static_cast(memory->data()), memory->size(), + mem.begin()); + { + mutex_lock scoped_lock(mu_); + map_.emplace(name, std::move(mem)); + } + } else { + // If the timing cache does exist, use the existing buffer. + mutex_lock scoped_lock(mu_); + std::vector& mem = map_[name]; + mem.resize(memory->size()); + std::copy_n(static_cast(memory->data()), memory->size(), + mem.begin()); + } + memory->destroy(); +#endif // IS_TRT_VERSION_GE(8, 0, 0, 0) +} + +TimingCacheRegistry* GetTimingCacheRegistry() { + static TimingCacheRegistry* registry = new TimingCacheRegistry(); + return registry; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/timing_cache.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/timing_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..bba940da9e83f002198880e2620386c3ab2fe09f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/timing_cache.h @@ -0,0 +1,70 @@ +/* Copyright 2022 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_TF2TENSORRT_CONVERT_TIMING_CACHE_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TIMING_CACHE_H_ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/core/framework/registration/registration.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/statusor.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +// A registry for holding serialized TensorRT autotuner timing caches. +// For TensorRT versions < 8.0, the timing cache is not serializable, so these +// operations become no-ops. +class TimingCacheRegistry { + public: + TimingCacheRegistry() = default; + ~TimingCacheRegistry() = default; + +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + using TimingCache = nvinfer1::ITimingCache; + using TimingCachePtr = std::unique_ptr; +#else + struct TimingCache {}; + using TimingCachePtr = std::unique_ptr; +#endif + + // Insert or update a registry into the map using the given name. The cache + // will be serialized before being placed into the map. + void Upsert(const string& name, TimingCache* cache); + + // Find a timing cache using the given name. The provided BuilderConfig is + // used to deserialize the cache. If no timing cache is found, a new timing + // cache is returned. + StatusOr LookUp(const string& name, + nvinfer1::IBuilderConfig* builder_config); + + private: + using SerializedTimingCache = std::vector; + + mutex mu_; + std::unordered_map map_; +}; + +TimingCacheRegistry* GetTimingCacheRegistry(); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TIMING_CACHE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..04d774ce3fc3e36a484762bfe57ad1c0b72f0a6e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.cc @@ -0,0 +1,97 @@ +/* Copyright 2021 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/tf2tensorrt/convert/trt_layout_optimization_pass.h" + +#include "absl/strings/ascii.h" +#include "absl/strings/escaping.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_graph.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/grappler/clusters/cluster.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h" +#include "tensorflow/core/grappler/utils/functions.h" +#include "tensorflow/core/lib/strings/numbers.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/casts.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/stacktrace.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +namespace tensorflow { +namespace tensorrt { +namespace convert { + +using absl::AsciiStrToUpper; +using absl::StrAppend; +using absl::StrCat; + +TRTLayoutOptimizationPass::TRTLayoutOptimizationPass(const string& name) + : name_(name), + trt_logger_name_("DefaultLogger"), + minimum_segment_size_(3), + is_dynamic_op_(false), + max_cached_batches_(1), + max_workspace_size_bytes_(256LL << 20) { + VLOG(1) << "Constructing " << name_; +} + +Status TRTLayoutOptimizationPass::Optimize(grappler::Cluster* cluster, + const grappler::GrapplerItem& item, + GraphDef* optimized_graph) { + GraphDef modified_graph_def = item.graph; + + // Construct a GrapplerItem using the modified graph_def and the input + // grappler_item. + grappler::GrapplerItem grappler_item = + grappler_item.WithGraph(std::move(modified_graph_def)); + const GraphDef& graph_def = grappler_item.graph; + + // Convert graphdef to graph. + FunctionLibraryDefinition flib(OpRegistry::Global(), graph_def.library()); + Graph graph(flib); + TF_RETURN_IF_ERROR( + ConvertGraphDefToGraph(GraphConstructorOptions(), graph_def, &graph)); + + // Algorithm steps: + // 1. We iterate over the graph to find any Conv (or other layout sensitive + // op) + // 2. If found, we continue, else we return + // 3. We iterate over the nodes and replace the layout-sensitive params + // 3. We add Transpose before the inputs and after the outputs + + grappler::GraphProperties static_graph_properties(grappler_item); + + std::cout << "TRTLayoutOptimizationPass: reading nodes..." << std::endl; + for (Node* node : graph.nodes()) { + std::cout << node->name() << std::endl; + } + + // TODO: assign output *optimized_graph =; +} + +Status TRTLayoutOptimizationPass::Init( + const RewriterConfig_CustomGraphOptimizer* config) { + std::cout << "Do nothing for now" << std::endl; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..9715cd6359d38ac56023c0d614c4c39d7a32c741 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_layout_optimization_pass.h @@ -0,0 +1,69 @@ +/* Copyright 20121 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_TF2TENSORRT_CONVERT_TRT_LAYOUT_OPTIMIZATION_PASS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TRT_LAYOUT_OPTIMIZATION_PASS_H_ + +#include + +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer.h" +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#if !IS_TRT_VERSION_GE(7, 0, 0, 0) +#error From version 2.6, we only support NVIDIA TensorRT version 7 or newer. +#error Please update your environment and relaunch the compilation. +#endif + +namespace tensorflow { +namespace tensorrt { +namespace convert { +class TRTLayoutOptimizationPass : public grappler::CustomGraphOptimizer { + public: + TRTLayoutOptimizationPass(const string& name = "TRTLayoutOptimizationPass"); + + string name() const override { return name_; }; + + bool UsesFunctionLibrary() const override { return true; } + + Status Init( + const RewriterConfig_CustomGraphOptimizer* config = nullptr) override; + + Status Optimize(grappler::Cluster* cluster, + const grappler::GrapplerItem& item, + GraphDef* optimized_graph) override; + + /* void PrintDebugInfo(grappler::Cluster* cluster, + const grappler::GrapplerItem& item); + */ + + private: + const string name_; + string trt_logger_name_; + int minimum_segment_size_; + bool is_dynamic_op_; + int max_cached_batches_; + int64_t max_workspace_size_bytes_; +}; + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TRT_LAYOUT_OPTIMIZATION_PASS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..bb12d66cd048e1f37b90c15dd3368059c64d85f2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.cc @@ -0,0 +1,251 @@ +/* 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/tf2tensorrt/convert/trt_optimization_pass.h" + +#include + +#include "absl/strings/ascii.h" +#include "absl/strings/escaping.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_graph.h" +#include "tensorflow/compiler/tf2tensorrt/convert/ops/quantization_ops.h" +#include "tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/grappler/clusters/cluster.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/grappler/op_types.h" +#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer_registry.h" +#include "tensorflow/core/grappler/utils/functions.h" +#include "tensorflow/core/grappler/utils/topological_sort.h" +#include "tensorflow/core/lib/strings/numbers.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/casts.h" +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +namespace tensorflow { +namespace tensorrt { +namespace convert { +using absl::AsciiStrToUpper; +using absl::StrAppend; +using absl::StrCat; + +namespace { + +bool ShouldUseExplicitPrecision(const GraphDef& gdef) { + if (!IS_TRT_VERSION_GE(8, 0, 0, 0)) { + return false; + } + return absl::c_any_of(gdef.node(), [](const auto& node) { + return (absl::c_find(kExplicitQuantizationOpNames, node.op()) != + kExplicitQuantizationOpNames.end()); + }); +} + +StatusOr ShouldConvertFunction(const grappler::GrapplerItem& item) { + if (item.id == "tf_graph") { + return false; + } + const auto& func_item = + tensorflow::down_cast(item); + const AttrSlice& attr = func_item.func_attr(); + const AttrValue* attr_value = attr.FindByString("_tftrt_convert_function"); + if (attr_value != nullptr) { + bool result = false; + TF_RETURN_IF_ERROR(GetNodeAttr(attr, "_tftrt_convert_function", &result)); + return result; + } + VLOG(1) << "Attribute _tftrt_convert_function was not found."; + return false; +} + +// Converts function conversion attributes to conversion parameters. +Status UpdateFunctionSpecificConversionParams( + TRTOptimizationPass::ConversionParams& cp, + const tensorflow::AttrSlice& attr) { + auto get_size_attr = [](const AttrSlice& attr, absl::string_view name, + size_t* dst) -> Status { + int tmp = 0; + TF_RETURN_IF_ERROR(GetNodeAttr(attr, name, &tmp)); + *dst = static_cast(tmp); + return OkStatus(); + }; + + TF_RETURN_IF_ERROR( + GetNodeAttr(attr, "_tftrt_trt_logger_name", &cp.trt_logger_name)); + TF_RETURN_IF_ERROR( + get_size_attr(attr, "_tftrt_max_batch_size", &cp.max_batch_size)); + TF_RETURN_IF_ERROR(get_size_attr(attr, "_tftrt_max_workspace_size_bytes", + &cp.max_workspace_size_bytes)); + std::string precision_mode; + TF_RETURN_IF_ERROR( + GetNodeAttr(attr, "_tftrt_precision_mode", &precision_mode)); + TF_RETURN_IF_ERROR( + TrtPrecisionModeFromName(precision_mode, &cp.precision_mode)); + TF_RETURN_IF_ERROR(GetNodeAttr(attr, "_tftrt_minimum_segment_size", + &cp.minimum_segment_size)); + TF_RETURN_IF_ERROR(GetNodeAttr(attr, "_tftrt_is_dyn_op", &cp.is_dynamic_op)); + TF_RETURN_IF_ERROR( + GetNodeAttr(attr, "_tftrt_max_cached_engines", &cp.max_cached_engines)); + TF_RETURN_IF_ERROR( + GetNodeAttr(attr, "_tftrt_use_calibration", &cp.use_calibration)); + TF_RETURN_IF_ERROR( + GetNodeAttr(attr, "_tftrt_use_implicit_batch", &cp.use_implicit_batch)); + std::string profile_strategy; + TF_RETURN_IF_ERROR( + GetNodeAttr(attr, "_tftrt_profile_strategy", &profile_strategy)); + TF_RETURN_IF_ERROR( + ProfileStrategyFromName(profile_strategy, &cp.profile_strategy)); + TF_RETURN_IF_ERROR(GetNodeAttr(attr, "_tftrt_allow_build_at_runtime", + &cp.allow_build_at_runtime)); + return OkStatus(); +} +} // namespace + +Status TRTOptimizationPass::Init( + const RewriterConfig_CustomGraphOptimizer* config) { + if (config == nullptr) { + return OkStatus(); + } + const auto params = config->parameter_map(); + if (params.count("minimum_segment_size")) { + params_.minimum_segment_size = params.at("minimum_segment_size").i(); + } + if (params.count("max_batch_size")) { + params_.max_batch_size = params.at("max_batch_size").i(); + } + if (params.count("is_dynamic_op")) { + params_.is_dynamic_op = params.at("is_dynamic_op").b(); + } + if (params.count("maximum_cached_engines")) { + params_.max_cached_engines = params.at("maximum_cached_engines").i(); + } + if (params.count("max_workspace_size_bytes")) { + params_.max_workspace_size_bytes = + params.at("max_workspace_size_bytes").i(); + } + if (params.count("precision_mode")) { + TF_RETURN_IF_ERROR(TrtPrecisionModeFromName( + AsciiStrToUpper(params.at("precision_mode").s()), + ¶ms_.precision_mode)); + } + if (params.count("use_calibration")) { + params_.use_calibration = params.at("use_calibration").b(); + } + if (params.count("trt_logger")) { + params_.trt_logger_name = params.at("trt_logger").s(); + } + if (params.count("allow_build_at_runtime")) { + params_.allow_build_at_runtime = params.at("allow_build_at_runtime").b(); + } + if (params.count("use_implicit_batch")) { + params_.use_implicit_batch = params.at("use_implicit_batch").b(); + } + if (params.count("profile_strategy")) { + TF_RETURN_IF_ERROR(ProfileStrategyFromName( + params.at("profile_strategy").s(), ¶ms_.profile_strategy)); + } + return OkStatus(); +} + +static bool ExplicitPrecisionModePolicy() { + return IS_TRT_VERSION_GE(8, 0, 0, 0); +} + +Status TRTOptimizationPass::Optimize(grappler::Cluster* cluster, + const grappler::GrapplerItem& item, + GraphDef* optimized_graph) { + VLOG(1) << "Called TRTOptimization Pass " << name_ + << " on a grappler item with id=" << item.id; + TF_ASSIGN_OR_RETURN(bool do_function_conversion, ShouldConvertFunction(item)); + // Optimizing the main graph(identified with `item.id == "tf_graph"`) with + // `minimim_segment_size == -1` indicates skipping main graph conversion. + if ((params_.minimum_segment_size == -1 && item.id == "tf_graph") || + (item.id != "tf_graph" && !do_function_conversion)) { + VLOG(1) << "Not optimizing this grappler item: " << item.id; + *optimized_graph = item.graph; + return OkStatus(); + } + + if (params_.use_calibration && + params_.precision_mode != TrtPrecisionMode::INT8) { + LOG(WARNING) << "Calibration with FP32 or FP16 is not implemented. " + << "Falling back to use_calibration = False." + << "Note that the default value of use_calibration is True."; + params_.use_calibration = false; + } + + params_.use_explicit_precision = ShouldUseExplicitPrecision(item.graph); + if (params_.use_explicit_precision) { + LOG(INFO) << "[TF-TRT] Using explicit QDQ mode"; + if (params_.precision_mode != TrtPrecisionMode::INT8 || + params_.use_calibration) { + LOG(WARNING) + << "Explicit precision mode with calibration or FP32/FP16 mode is " + "not supported." + << " Setting precision mode to INT8 and calibration to false."; + params_.precision_mode = TrtPrecisionMode::INT8; + params_.use_calibration = false; + } + } + + // Create a copy of the graph to optimize. + grappler::GrapplerItem optimized_item(item); + + std::vector nodes_to_preserve; + const auto& old_nodes_to_preserve = item.NodesToPreserve(); + nodes_to_preserve.reserve(old_nodes_to_preserve.size()); + for (const auto& n : old_nodes_to_preserve) { + auto tokens = str_util::Split(n, ":"); + string s = tokens.at(0); + for (int i = 1; i < tokens.size() - 1; ++i) { + StrAppend(&s, ":", tokens.at(i)); + } + int dumm_port = -1; + // If the last token is not an integer, it must be part of the name. + // Otherwise it is port number. + if (tokens.size() > 1 && + !strings::safe_strto32(tokens.back(), &dumm_port)) { // non-absl ok + StrAppend(&s, ":", tokens.back()); + } + nodes_to_preserve.push_back(s); + } + + if (item.id != "tf_graph" && do_function_conversion) { + const grappler::GrapplerFunctionItem& func_item = + tensorflow::down_cast(item); + TF_RETURN_IF_ERROR( + UpdateFunctionSpecificConversionParams(params_, func_item.func_attr())); + } + + return ConvertGraph(params_, optimized_item, nodes_to_preserve, cluster, + optimized_graph); +} + +static grappler::CustomGraphOptimizerRegistrar TRTOptimizationPass_Registrar( + []() { + VLOG(1) + << "Instantiating CustomOptimizationPass object TensorRTOptimizer"; + return new TRTOptimizationPass("TensorRTOptimizer"); + }, + ("TensorRTOptimizer")); + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..2bc3e0bd5e12fd9a93186799d259147db2cf0903 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_optimization_pass.h @@ -0,0 +1,87 @@ +/* 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_TF2TENSORRT_CONVERT_TRT_OPTIMIZATION_PASS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TRT_OPTIMIZATION_PASS_H_ + +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/grappler/costs/graph_properties.h" +#include "tensorflow/core/grappler/optimizers/custom_graph_optimizer.h" +#include "tensorflow/core/grappler/utils.h" +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#if !IS_TRT_VERSION_GE(7, 0, 0, 0) +#error From version 2.6, we only support NVIDIA TensorRT version 7 or newer. +#error Please update your environment and relaunch the compilation. +#endif + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +class TRTOptimizationPass : public grappler::CustomGraphOptimizer { + public: + struct ConversionParams { + string trt_logger_name = "DefaultLogger"; + size_t max_batch_size = -1; + size_t max_workspace_size_bytes = 1 << 30; + TrtPrecisionMode precision_mode = TrtPrecisionMode::FP32; + int minimum_segment_size = 3; + // Whether to create engine on conversion or execution time + bool is_dynamic_op = false; + // maximum number of cached engines + int max_cached_engines = 1; + bool use_calibration = true; + bool use_implicit_batch = true; + ProfileStrategy profile_strategy = ProfileStrategy::kRange; + bool allow_build_at_runtime = true; + bool use_explicit_precision = false; + }; + + TRTOptimizationPass(const string& name = "TRTOptimizationPass") + : name_(name) {} + + string name() const override { return name_; }; + + bool UsesFunctionLibrary() const override { return true; } + + Status Init( + const RewriterConfig_CustomGraphOptimizer* config = nullptr) override; + + Status Optimize(grappler::Cluster* cluster, + const grappler::GrapplerItem& item, + GraphDef* optimized_graph) override; + + private: + const string name_; + + ConversionParams params_; + + std::vector batches_; +}; + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TRT_OPTIMIZATION_PASS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.cc new file mode 100644 index 0000000000000000000000000000000000000000..bc0e2d73480b083db16362688fb1bcdfd3a463b7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.cc @@ -0,0 +1,102 @@ +/* Copyright 2021 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/tf2tensorrt/convert/trt_parameters.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include + +#include "absl/strings/str_cat.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace tensorrt { + +Status TrtPrecisionModeToName(const TrtPrecisionMode mode, string* name) { + const char* kUnknown = "UNKNOWN"; + *name = *kUnknown; + switch (mode) { + case TrtPrecisionMode::FP32: + *name = "FP32"; + break; + case TrtPrecisionMode::FP16: + *name = "FP16"; + break; + case TrtPrecisionMode::INT8: + *name = "INT8"; + break; + } + if (name->compare(kUnknown) == 0) + return errors::OutOfRange("Unknown precision mode"); + return OkStatus(); +} + +Status TrtPrecisionModeFromName(const string& name, TrtPrecisionMode* mode) { + if (name == "FP32") { + *mode = TrtPrecisionMode::FP32; + } else if (name == "FP16") { + *mode = TrtPrecisionMode::FP16; + } else if (name == "INT8") { + *mode = TrtPrecisionMode::INT8; + } else { + return errors::InvalidArgument("Invalid precision mode name: ", name); + } + return OkStatus(); +} + +string DebugString(const TrtPrecisionMode mode) { + string mode_str; + TF_CHECK_OK(TrtPrecisionModeToName(mode, &mode_str)); + return absl::StrCat("TrtPrecisionMode::", mode_str); +} + +string ProfileStrategyToName(const ProfileStrategy strategy) { + switch (strategy) { + case ProfileStrategy::kRange: + return "Range"; + case ProfileStrategy::kOptimal: + return "Optimal"; + case ProfileStrategy::kRangeOptimal: + return "Range+Optimal"; + case ProfileStrategy::kImplicitBatchModeCompatible: + return "ImplicitBatchModeCompatible"; + } + return "Unknown"; +} + +Status ProfileStrategyFromName(const string& name, ProfileStrategy* strategy) { + std::string name_lowercase = absl::AsciiStrToLower(name); + if (name_lowercase == "range") { + *strategy = ProfileStrategy::kRange; + } else if (name_lowercase == "optimal") { + *strategy = ProfileStrategy::kOptimal; + } else if (name_lowercase == "range+optimal") { + *strategy = ProfileStrategy::kRangeOptimal; + } else if (name_lowercase == "implicitbatchmodecompatible") { + *strategy = ProfileStrategy::kImplicitBatchModeCompatible; + } else { + return errors::InvalidArgument("Invalid profile strategy: ", name); + } + return OkStatus(); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h new file mode 100644 index 0000000000000000000000000000000000000000..f4f8833bb45c0290ee1650ee9ef50750f46a752f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h @@ -0,0 +1,72 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_TRT_PARAMETERS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TRT_PARAMETERS_H_ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace tensorrt { + +// The PrecisionMode controls the precision used in TRT converted parts of the +// model. Setting PrecisionMode other than FP32 enables TensorRT to select +// lower-precision implementations when searching for the fastest kernels. +// +// For regularized models whose input dynamic range is approximately one, this +// typically produces significant speedups with negligible change in accuracy. +// There is additional complexity when working with INT8, see Calibration. +// +// - FP32 +// - FP16 Enable FP16 layer selection, with FP32 fallback. +// - INT8 Enable Int8 layer selection, with FP32 and FP16 fallback. +// +// Note that TensorRT will still choose a higher-precision kernel if it results +// in overall lower runtime, or if no low-precision implementation exists. +enum class TrtPrecisionMode { FP32, FP16, INT8 }; + +Status TrtPrecisionModeToName(const TrtPrecisionMode mode, string* name); + +Status TrtPrecisionModeFromName(const string& name, TrtPrecisionMode* mode); + +string DebugString(const TrtPrecisionMode mode); + +// Optimization profile generation strategies. +// - `kRange`: create one profile that works for inputs with dimension values +// in the range of [min_dims, max_dims] where min_dims and max_dims are +// derived from the provided inputs. +// - `kOptimal`: create one profile for each input. The profile only works for +// inputs with the same dimensions as the input it is created for. The GPU +// engine will be run with optimal performance with such inputs. +// - `kRangeOptimal`: create the profiles for both `Range` and `Optimal`. +// - `kImplicitBatchModeCompatible`: create the profiles that will produce the +// same GPU engines as the implicit_batch_mode would produce. +enum class ProfileStrategy { + kRange, + kOptimal, + kRangeOptimal, + kImplicitBatchModeCompatible, +}; + +string ProfileStrategyToName(const ProfileStrategy strategy); +Status ProfileStrategyFromName(const string& name, ProfileStrategy* strategy); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_TRT_PARAMETERS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..a58149c601b8f1a793afc1c2d1c8adf7a6973687 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/utils.cc @@ -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. +==============================================================================*/ + +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "absl/strings/ascii.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace tensorrt { + +string DebugString(const nvinfer1::Dims& dims) { + string out = StrCat("nvinfer1::Dims(nbDims=", dims.nbDims, ", d="); + for (int i = 0; i < std::max(dims.nbDims, 0); ++i) { + StrAppend(&out, dims.d[i]); + StrAppend(&out, ","); + } + StrAppend(&out, ")"); + return out; +} + +string DebugString(const DataType tf_type) { + switch (tf_type) { + case DT_FLOAT: + return "DT_FLOAT"; + case DT_HALF: + return "DT_HALF"; + case DT_INT32: + return "DT_INT32"; + case DT_INT8: + return "DT_INT8"; + case DT_BOOL: + return "DT_BOOL"; + case DT_UINT8: + return "DT_UINT8"; + default: + return "Unknow TF DataType"; + } +} + +string DebugString(const nvinfer1::DataType trt_dtype) { + switch (trt_dtype) { + case nvinfer1::DataType::kFLOAT: + return "kFLOAT"; + case nvinfer1::DataType::kHALF: + return "kHALF"; + case nvinfer1::DataType::kINT8: + return "kINT8"; + case nvinfer1::DataType::kINT32: + return "kINT32"; + case nvinfer1::DataType::kBOOL: + return "kBOOL"; +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + case nvinfer1::DataType::kUINT8: + return "kUINT8"; +#endif +#if IS_TRT_VERSION_GE(8, 6, 0, 0) + case nvinfer1::DataType::kFP8: + return "kFP8"; +#endif + default: + return "Invalid TRT data type"; + } +} + +string DebugString(const nvinfer1::Permutation& permutation, int len) { + string out = "nvinfer1::Permutation("; + for (int i = 0; i < len; ++i) { + StrAppend(&out, permutation.order[i], ","); + } + StrAppend(&out, ")"); + return out; +} + +string DebugString(const ITensorProxyPtr& tensor) { + return StrCat( + tensor->is_trt_tensor() ? "nvinfer1::ITensor(@" : "SimpleItensor(@", + reinterpret_cast(&tensor), ", name=", tensor->getName(), + ", dtype=", DebugString(tensor->getType()), + ", dims=", DebugString(tensor->getDimensions()), ")"); +} + +string DebugString(const nvinfer1::ITensor& tensor) { + return StrCat("nvinfer1::ITensor(@", reinterpret_cast(&tensor), + ", name=", tensor.getName(), + ", dtype=", DebugString(tensor.getType()), + ", dims=", DebugString(tensor.getDimensions()), ")"); +} + +string DebugString(const std::vector& dimvec) { + return absl::StrCat("[", + absl::StrJoin(dimvec, ",", + [](std::string* out, nvinfer1::Dims in) { + out->append(DebugString(in)); + }), + "]"); +} + +string DebugString(const std::vector& shapes) { + return TensorShapeUtils::ShapeListString(shapes); +} + +string DebugString(const std::vector& shapes) { + return PartialTensorShapeUtils::PartialShapeListString(shapes); +} + +// Checks whether actual_shapes are compatible with cached_shapes. This should +// only be used in implicit batch mode (in explicit batch mode one needs to +// check the profile ranges). Therefore implicit batch mode is assumed. +// It is also assumed that both actual_shapes and cached_shapes have been +// verified by TRTEngineOp::VerifyInputShapes, which ensures that the batch size +// for all tensors are the same. +bool AreShapesCompatible(const std::vector& actual_shapes, + const std::vector& cached_shapes) { + auto match_shape = [](const TensorShape& actual_shape, + const TensorShape& cached_shape) { + // Match the rank. + if (actual_shape.dims() != cached_shape.dims()) return false; + // Match the batch size. In implicit batch mode cached_shape.dim_size(0) is + // the max batch size, which can be larger than the actual batch size. + if (actual_shape.dim_size(0) > cached_shape.dim_size(0)) return false; + // Match remaining dimensions. + for (int i = 1; i < actual_shape.dims(); ++i) { + if (actual_shape.dim_size(i) != cached_shape.dim_size(i)) return false; + } + return true; + }; + for (int i = 0; i < actual_shapes.size(); ++i) { + if (!match_shape(actual_shapes[i], cached_shapes[i])) { + return false; + } + } + return true; +} +Status GetNetworkInputShapes(const nvinfer1::INetworkDefinition* network, + std::vector* input_shapes) { + const int n_inputs = network->getNbInputs(); + input_shapes->resize(n_inputs); + for (int i = 0; i < n_inputs; i++) { + const ITensorProxyPtr input = network->getInput(i); + TF_RETURN_IF_ERROR(DimsAdapter(input->getDimensions()) + .PartialTensorShape(&input_shapes->at(i))); + } + return OkStatus(); +} + +Status TfTypeToTrtType(DataType tf_type, nvinfer1::DataType* trt_type) { + switch (tf_type) { + case DT_FLOAT: + *trt_type = nvinfer1::DataType::kFLOAT; + break; + case DT_HALF: + *trt_type = nvinfer1::DataType::kHALF; + break; + case DT_INT32: + *trt_type = nvinfer1::DataType::kINT32; + break; +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + case DT_BOOL: + *trt_type = nvinfer1::DataType::kBOOL; + break; +#endif +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + case DT_UINT8: + *trt_type = nvinfer1::DataType::kUINT8; + break; +#endif + default: + return errors::InvalidArgument("Unsupported tensorflow data type ", + DataTypeString(tf_type)); + } + return OkStatus(); +} + +Status TrtTypeToTfType(nvinfer1::DataType trt_type, DataType* tf_type) { + switch (trt_type) { + case nvinfer1::DataType::kFLOAT: + *tf_type = DT_FLOAT; + break; + case nvinfer1::DataType::kHALF: + *tf_type = DT_HALF; + break; + case nvinfer1::DataType::kINT32: + *tf_type = DT_INT32; + break; +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + case nvinfer1::DataType::kBOOL: + *tf_type = DT_BOOL; + break; +#endif +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + case nvinfer1::DataType::kUINT8: + *tf_type = DT_UINT8; + break; +#endif +#if IS_TRT_VERSION_GE(8, 6, 0, 0) + case nvinfer1::DataType::kFP8: + *tf_type = DT_FLOAT8_E4M3FN; + break; +#endif + default: + return errors::InvalidArgument("Invalid TRT data type"); + } + return OkStatus(); +} + +int GetNumberOfEngineInputs(const nvinfer1::ICudaEngine* engine) { + int n_bindings = engine->getNbBindings(); + int n_input = 0; + for (int i = 0; i < n_bindings; i++) { + if (engine->bindingIsInput(i)) n_input++; + } + // According to TensorRT 7 doc: "If the engine has been built for K profiles, + // the first getNbBindings() / K bindings are used by profile number 0, the + // following getNbBindings() / K bindings are used by profile number 1 etc." + // Therefore, to get the number of input tensors, we need to divide by the + // the number of profiles. + int n_profiles = engine->getNbOptimizationProfiles(); + return n_input / n_profiles; +} + +absl::string_view GetDeviceName(const Node* node) { + if (node->has_assigned_device_name()) { + return node->assigned_device_name(); + } + return node->requested_device(); +} + +std::optional GetDeviceParsedName( + const Node* node) { + absl::string_view device_name = GetDeviceName(node); + DeviceNameUtils::ParsedName parsed_name; + if (!DeviceNameUtils::ParseFullName(device_name, &parsed_name)) { + return std::nullopt; + } + return parsed_name; +} + +std::optional MergeIfCompatible( + const DeviceNameUtils::ParsedName& a, + const DeviceNameUtils::ParsedName& b) { + DeviceNameUtils::ParsedName merged_name = a; + if (!DeviceNameUtils::MergeDevNames(&merged_name, b, + /*allow_soft_placement=*/false) + .ok()) { + return std::nullopt; + } + return merged_name; +} + +std::optional MergeIfCompatible( + const DeviceNameUtils::ParsedName& a, absl::string_view b) { + DeviceNameUtils::ParsedName b_parsed_name; + if (!DeviceNameUtils::ParseFullName(b, &b_parsed_name)) { + return std::nullopt; + } + + return MergeIfCompatible(a, b_parsed_name); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/utils.h new file mode 100644 index 0000000000000000000000000000000000000000..afe39872eb0023e69fadad5d54f10da371434b4e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/utils.h @@ -0,0 +1,399 @@ +/* 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_TF2TENSORRT_CONVERT_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_UTILS_H_ + +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/util/env_var.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +#define TFTRT_ERROR(func, ...) \ + do { \ + return func("TFTRT::", __FUNCTION__, ":", __LINE__, ": ", __VA_ARGS__); \ + } while (0) + +#define TFTRT_CHECK_SHAPE_TENSOR(tensor) \ + if (!IsTrtShapeTensorCompatible(tensor)) { \ + TFTRT_ERROR(errors::InvalidArgument, "Tensor of type ", \ + DebugString(tensor.dtype()), " having shape ", \ + tensor.shape().DebugString(), " is not TRT compatible"); \ + } + +namespace tensorflow { +namespace tensorrt { + +static constexpr char kCastOutputTypeAttrName[] = "DstT"; + +#if !IS_TRT_VERSION_GE(8, 2, 0, 0) +template +struct TrtDestroyer { + void operator()(T* t) { + if (t) t->destroy(); + } +}; +template +using TrtUniquePtrType = std::unique_ptr>; +#else +template +using TrtUniquePtrType = std::unique_ptr; +#endif + +// Define a hash function for vector because it is used as the key +// for the engine cache. +struct VectorTensorShapeHasher { + std::size_t operator()(const std::vector& key) const { + return std::hash()(TensorShapeUtils::ShapeListString(key)); + } +}; + +using absl::StrAppend; +using absl::StrCat; + +// This utility template converts an arithmetic type to a string. This function +// is necessary to allow the following function to behave recursively: +// `string DebugString(const std::vector&)`. +template ::value, CType>::type> +string DebugString(const CType& el) { + string el_str = std::to_string(el); + // Prettify std::to_string which can sometimes returns 1.50000 instead of 1.5. + // In short it removes trailing 0s in a string-formatted number. + el_str.erase(el_str.find_last_not_of('0') + 1, std::string::npos); + return el_str; +} +// This utility template converts nested vectors to a string for debug purposes. +template +string DebugString(const std::vector& vector) { + string tmp_s = ""; + for (const auto el : vector) { + StrAppend(&tmp_s, StrCat(DebugString(el), ", ")); + } + return StrCat("{", tmp_s.substr(0, tmp_s.length() - 2), "}"); +} +string DebugString(const nvinfer1::Dims& dims); +string DebugString(const nvinfer1::DataType trt_dtype); +string DebugString(const DataType tf_type); +string DebugString(const nvinfer1::Permutation& permutation, int len); +string DebugString(const ITensorProxyPtr& tensor); +string DebugString(const nvinfer1::ITensor& tensor); +string DebugString(const std::vector& dimvec); +string DebugString(const std::vector& shapes); +string DebugString(const std::vector& shapes); + +template +string DebugString(const absl::InlinedVector& data) { + return absl::StrCat("[", absl::StrJoin(data, ","), "]"); +} + +inline bool HasStaticShape(const nvinfer1::Dims& dims) { + if (dims.nbDims < 0) return false; + for (int d = 0; d < dims.nbDims; ++d) { + if (dims.d[d] < 0) return false; + } + return true; +} + +template +bool HasStaticShape(const T& dims) { + return !absl::c_any_of(dims, [](int i) { return i < 0; }); +} + +// Returns whether a shape is compatible with a TRT shape tensor. +template +inline bool IsTrtShapeTensorCompatible(const TensorShapeType& shape) { + return ( + shape.dims() == 0 || + (shape.dims() == 1 && shape.num_elements() <= nvinfer1::Dims::MAX_DIMS)); +} + +// Returns whether a TF tensor could be interpreted as a TRT shape tensor. +inline bool IsTrtShapeTensorCompatible(const Tensor& tensor) { + return tensor.dtype() == DT_INT32 && + IsTrtShapeTensorCompatible(tensor.shape()); +} + +// Adapts various representations of shape (TF Shape, TRT Dims, plain +// containers) and provides methods for properties (length, volume) and +// conversion between types. Note that unlike TF's TensorShape, the underlying +// storage will only contain active dimensions. In the case of scalar shapes, +// `NumDims` is allowed to return 0 or 1, but the `storage_` vector will contain +// 1 element in both cases. In the non-scalar case, `NumDims() == +// storage_.size()`. +class DimsAdapter { + public: + using StorageType = absl::InlinedVector; + + private: + template + using EnableIfNotTensorShapeType = + std::enable_if_t, T>::value>; + + template + using EnableIfInt = std::enable_if_t::value && + std::is_integral::value>; + + public: + //----- Constructors ------ + + // Constructs from an absl::Span. + template + explicit DimsAdapter(absl::Span shape) + : num_dims_(static_cast(shape.size())) { + absl::c_copy(shape, std::back_inserter(storage_)); + } + + // Constructs from an absl::Span. + template + explicit DimsAdapter(const std::vector& shape) + : num_dims_(static_cast(shape.size())) { + absl::c_copy(shape, std::back_inserter(storage_)); + } + + // Constructs from a TRT dims object. + DimsAdapter(const nvinfer1::Dims& dims) : num_dims_(dims.nbDims) { + absl::c_copy(absl::MakeSpan(dims.d, dims.d + std::max(dims.nbDims, 0)), + std::back_inserter(storage_)); + } + + // Constructs explicitly specifying num_dims and storage data. + DimsAdapter(int32_t num_dims, StorageType data) + : num_dims_(num_dims), storage_(std::forward(data)) {} + + // Constructs from a TensorShape or PartialTensorShape. + template + static StatusOr Create(const TensorShapeBase& shape, + bool ignore_first_dim = false) { + if (shape.dims() > nvinfer1::Dims::MAX_DIMS) + return errors::InvalidArgument("dims of TensorShape exceed MAX_DIMS"); + if (ignore_first_dim && shape.dims() <= 0) + return errors::InvalidArgument( + "removing first dim requires explicit batch dimension"); + if (shape.dims() == -1) { + return DimsAdapter(-1, StorageType{}); + } + if (shape.dims() == 0) { + return DimsAdapter(0, StorageType{1}); + } + auto offt = (ignore_first_dim ? 1 : 0); + return DimsAdapter( + absl::MakeSpan(shape.dim_sizes().begin() + offt, shape.dims() - offt)); + } + + // Constructs from a container. + template > + static StatusOr Create(const InputSequence& shape, + bool ignore_first_dim = false) { + if (ignore_first_dim && shape.size() <= 0) { + return errors::InvalidArgument( + "removing first dim requires explicit batch dimension"); + } + return DimsAdapter( + absl::MakeSpan(shape).subspan(ignore_first_dim ? 1 : 0, shape.size())); + } + + //----- Conversion Utilities ------ + + // Converts to an nvinfers::Dims and assign the result to the object passed + // in via the result pointer. + void TrtDims(nvinfer1::Dims* result) const { + result->nbDims = num_dims_; + absl::c_copy(storage_, static_cast(result->d)); + } + + // Converts to an nvinfer1::Dims and return by value. + nvinfer1::Dims AsTrtDims() const { + nvinfer1::Dims result; + TrtDims(&result); + return result; + } + + // Converts to a TensorShape and assigns the result to the object passed in + // via the shape pointer. + Status TensorShape(TensorShape* shape, + std::optional batch_size = std::nullopt) const { + TF_RETURN_IF_ERROR(TensorShapeUtils::MakeShape( + static_cast(storage_.data()), storage_.size(), shape)); + if (batch_size) shape->InsertDim(0, *batch_size); + return OkStatus(); + } + + // Converts to a PartialTensorShape and assigns the result to the object + // passed in via the shape pointer. + Status PartialTensorShape( + PartialTensorShape* shape, + std::optional batch_size = std::nullopt) const { + TF_RETURN_IF_ERROR(TensorShapeUtils::MakeShape( + static_cast(storage_.data()), storage_.size(), shape)); + if (batch_size) shape->InsertDim(0, *batch_size); + return OkStatus(); + } + + // Copies the dimension values to the vector passed in via the shape pointer. + template > + Status Vector(std::vector* shape) const { + shape->clear(); + absl::c_copy(storage_, std::back_inserter(*shape)); + return OkStatus(); + } + + //----- Property Accessors ------ + + // Returns true if the shape has no dynamic dimensions. + bool IsStatic() const { + return !absl::c_any_of(storage_, [](auto i) { return i < 0; }); + } + + // Returns product of all dimensions. + int64_t Volume() const { + return absl::c_accumulate(storage_, static_cast(1), + std::multiplies<>()); + } + + int32_t NumDims() const { return num_dims_; } + + // Returns true if the shape should be interpreted as a scalar. This follows + // TensorRT conversions: a scalar shape can have NumDims()==1 or NumDims()==0, + // but the underlying storage_ container has a single dimension of size 1. + bool IsScalar() const { + return (num_dims_ == 0 || num_dims_ == 1) && storage_.size() == 1 && + storage_[0] == 1; + } + + // Returns true if the dimension storage is empty. This indicates an empty + // shape in both the scalar and non-scalar case. + bool IsEmpty() const { return storage_.empty(); } + + string DebugString() const { + auto vol = absl::c_accumulate(storage_, static_cast(1), + std::multiplies<>()); + return absl::StrCat("DimsAdapter(num_dims=", num_dims_, ",shape=[", + absl::StrJoin(storage_, ","), "],", "vol=", vol, ")"); + } + + // Returns beginning iterator for the underlying storage. + StorageType::const_iterator begin() const { return storage_.begin(); } + + // Returns ending iterator for the underlying storage. + StorageType::const_iterator end() const { return storage_.end(); } + + // Returns the size of the dimension at `idx`. + StorageType::value_type dim(size_t idx) const { return storage_[idx]; } + + // Returns a references to the dimension at `idx`. + StorageType::value_type& dim(size_t idx) { return storage_[idx]; } + + //----- Non-Const Operators ------ + + DimsAdapter& Append(int32_t dim) { + StatusOr is_scalar = IsScalar(); + if (!is_scalar.ok()) return *this; + num_dims_ = *is_scalar ? 2 : num_dims_ + 1; + storage_.push_back(dim); + return *this; + } + + DimsAdapter& Prepend(std::optional dim) { + if (dim) { + num_dims_ = IsScalar() ? 2 : num_dims_ + 1; + storage_.insert(storage_.begin(), *dim); + } + return *this; + } + + Status RemoveBatchDimension() { + if (storage_.empty()) + return errors::InvalidArgument( + "attempted to remove batch dim from scalar"); + num_dims_ -= 1; + storage_.erase(storage_.begin()); + return OkStatus(); + } + + //----- Comparison Operators ------ + + bool operator==(const DimsAdapter& rhs) const { + if (rhs.num_dims_ != num_dims_) return false; + for (int i = 0; i < num_dims_; i++) { + if (rhs.storage_[i] != storage_[i]) return false; + } + return true; + } + + bool operator!=(const DimsAdapter& rhs) const { return !(*this == rhs); } + + private: + int32_t num_dims_{0}; + StorageType storage_{}; +}; + +Status GetNetworkInputShapes(const nvinfer1::INetworkDefinition* network, + std::vector* input_shapes); + +Status TfTypeToTrtType(DataType tf_type, nvinfer1::DataType* trt_type); +Status TrtTypeToTfType(nvinfer1::DataType trt_type, DataType* tf_type); + +// Returns true if an engine built for cached_shapes can also run actual_shapes. +bool AreShapesCompatible(const std::vector& actual_shapes, + const std::vector& cached_shapes); + +// Returns the number of inputs for the engine, which also correspends to the +// number of input tensors for the network. This can differ from the number of +// input bindings, because the number of total input bindings equals the number +// of profiles times the number of engine inputs. +int GetNumberOfEngineInputs(const nvinfer1::ICudaEngine* engine); + +// Returns the string representation for the assigned device or the requested +// device of the given node. +absl::string_view GetDeviceName(const Node* node); + +// Returns the ParsedName representation for the assigned device or the +// requested device string of the given node. If the device string is invalid, +// returns std::nullopt. +std::optional GetDeviceParsedName( + const Node* node); + +// If the given two device assignments as compatible, returns the merge of the +// two assignments. Otherwise, returns std::nullopt. +std::optional MergeIfCompatible( + const DeviceNameUtils::ParsedName& a, const DeviceNameUtils::ParsedName& b); +// Similar to the above, except that the second device assignment is represented +// by a string_view. +std::optional MergeIfCompatible( + const DeviceNameUtils::ParsedName& a, absl::string_view b); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/weights.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/weights.cc new file mode 100644 index 0000000000000000000000000000000000000000..f599c102757edd40907ab6f9008c9ed42229546a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/weights.cc @@ -0,0 +1,214 @@ +/* Copyright 2021 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/tf2tensorrt/convert/weights.h" + +#include +#include + +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +namespace convert { + +TRT_ShapedWeights::TRT_ShapedWeights(nvinfer1::DataType type) + : shape_(0, DimsAdapter::StorageType{}), type_(type), volume_(0) {} + +StatusOr TRT_ShapedWeights::CreateWithTensor( + nvinfer1::DataType type, DimsAdapter dims, Tensor tensor) { + TRT_ShapedWeights weights(type); + weights.shape_ = dims; + weights.tensor_ = std::forward(tensor); + weights.volume_ = weights.shape_.Volume(); + if (weights.shape_.NumDims() == 0) { + DCHECK(weights.shape_.IsEmpty() || weights.shape_.IsScalar()); + } + return weights; +} + +nvinfer1::Weights TRT_ShapedWeights::GetTrtWeights() const { + return nvinfer1::Weights{type_, GetPointer(), volume_}; +} + +Status TRT_ShapedWeights::SetShape(DimsAdapter dims) { + if (volume_ != dims.Volume()) { + VLOG(2) << "Changing shape from " << shape_.DebugString() << ", to " + << dims.DebugString(); + return errors::Internal("SetShape would change number of elements"); + } + shape_ = std::move(dims); + return OkStatus(); +} + +size_t TRT_ShapedWeights::size_bytes() const { + size_t data_type_size = -1; + switch (type_) { + case nvinfer1::DataType::kFLOAT: + case nvinfer1::DataType::kINT32: + data_type_size = 4; + break; + case nvinfer1::DataType::kHALF: + data_type_size = 2; + break; +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + case nvinfer1::DataType::kUINT8: +#endif +#if IS_TRT_VERSION_GE(8, 6, 0, 0) + case nvinfer1::DataType::kFP8: +#endif + case nvinfer1::DataType::kINT8: + case nvinfer1::DataType::kBOOL: + data_type_size = 1; + break; + } + return volume_ * data_type_size; +} + +string TRT_ShapedWeights::DebugString() const { + return absl::StrCat( + "TRT_ShapedWeights(shape=", shape_.DebugString(), + ", type=", tensorflow::tensorrt::DebugString(type_), + ", values=", reinterpret_cast(GetPointer()), ")"); +} + +TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor) + : tensor_proxy_ptr_(tensor), + initialized_(true), + arg_type_(TRT_ArgumentType::TENSOR) {} + +TRT_TensorOrWeights::TRT_TensorOrWeights(ITensorProxyPtr tensor, int batch_size) + : tensor_proxy_ptr_(tensor), + batch_size_(batch_size), + initialized_(true), + arg_type_(TRT_ArgumentType::TENSOR) {} + +TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::ITensor* tensor, + int batch_size) + : tensor_proxy_ptr_(tensor), + batch_size_(batch_size), + initialized_(true), + arg_type_(TRT_ArgumentType::TENSOR) {} + +TRT_TensorOrWeights::TRT_TensorOrWeights(nvinfer1::DataType trt_dtype, + const nvinfer1::Dims& trt_dims, + int batch_size) + : tensor_proxy_ptr_(new SimpleITensor(trt_dtype, trt_dims)), + batch_size_(batch_size), + initialized_(true), + arg_type_(TRT_ArgumentType::TENSOR) {} + +TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_ShapedWeights& weights) + : weights_(weights), + initialized_(true), + arg_type_(TRT_ArgumentType::WEIGHTS) {} + +TRT_TensorOrWeights::TRT_TensorOrWeights(const ResourceHandle& resource) + : resource_(resource), + initialized_(true), + arg_type_(TRT_ArgumentType::RESOURCE) {} + +TRT_TensorOrWeights::TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs) + : tensor_proxy_ptr_(rhs.tensor_proxy_ptr_), + batch_size_(rhs.batch_size_), + resource_(rhs.resource_), + weights_(rhs.weights_), + initialized_(rhs.initialized_), + arg_type_(rhs.arg_type_) {} + +void TRT_TensorOrWeights::operator=(const TRT_TensorOrWeights& rhs) { + tensor_proxy_ptr_ = rhs.tensor_proxy_ptr_; + batch_size_ = rhs.batch_size_; + weights_ = rhs.weights_; + resource_ = rhs.resource_; + initialized_ = rhs.initialized_; + arg_type_ = rhs.arg_type_; +} + +ITensorProxyPtr TRT_TensorOrWeights::tensor() const { + DCHECK(is_tensor()); + return tensor_proxy_ptr_; +} + +ResourceHandle TRT_TensorOrWeights::resource() const { + DCHECK(is_resource()); + return resource_; +} + +nvinfer1::Dims TRT_TensorOrWeights::GetTrtDims() const { + switch (arg_type_) { + case TRT_ArgumentType::TENSOR: + return tensor()->getDimensions(); + case TRT_ArgumentType::WEIGHTS: + return weights().Shape().AsTrtDims(); + case TRT_ArgumentType::RESOURCE: + return {0, {}}; // Scalar. + } +} + +Status TRT_TensorOrWeights::GetTfType(DataType* tf_type) const { + if (!initialized_) { + return errors::Internal("The object is not initialized"); + } + switch (arg_type_) { + case TRT_ArgumentType::TENSOR: { + nvinfer1::DataType trt_type = tensor()->getType(); + return TrtTypeToTfType(trt_type, tf_type); + } + case TRT_ArgumentType::WEIGHTS: + *tf_type = weights().GetTensor().dtype(); + return OkStatus(); + case TRT_ArgumentType::RESOURCE: + *tf_type = DataType::DT_RESOURCE; + return OkStatus(); + } +} + +string TRT_TensorOrWeights::DebugString() const { + string output = "TRT_TensorOrWeights(type="; + if (is_tensor()) { + absl::StrAppend(&output, + "tensor=", tensorflow::tensorrt::DebugString(tensor()), + ", batch_size=", batch_size_); + } else { + absl::StrAppend(&output, "weights=", weights_.DebugString()); + } + absl::StrAppend(&output, ")"); + return output; +} + +StatusOr TrtWeightStore::GetTempWeights( + nvinfer1::DataType trt_dtype, const DimsAdapter& dims) { + DataType tf_dtype; + TF_RETURN_IF_ERROR(TrtTypeToTfType(trt_dtype, &tf_dtype)); + TensorShape shape; + TF_RETURN_IF_ERROR(dims.TensorShape(&shape)); + // TODO(jie): check weights size_bytes. 0 means type error + Tensor tensor(tf_dtype, shape); + StatusOr weights = + TRT_ShapedWeights::CreateWithTensor(trt_dtype, dims, tensor); + TRT_ENSURE_OK(weights); + store_.emplace_back(std::move(tensor)); + return weights; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/weights.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/weights.h new file mode 100644 index 0000000000000000000000000000000000000000..a84b95313a28461432632ccaf6d06594830e8b65 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/convert/weights.h @@ -0,0 +1,295 @@ +/* Copyright 2021 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_TF2TENSORRT_CONVERT_WEIGHTS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_WEIGHTS_H_ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include + +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +// Class to convert TF compile-time constants (e.g. Const nodes) to TRT weight. +class TRT_ShapedWeights { + public: + explicit TRT_ShapedWeights( + nvinfer1::DataType type = nvinfer1::DataType::kFLOAT); + + // Constructs a weights from another weights. + // + // NOTE: this does not copy the underlying buffer but only increase its + // reference count. + TRT_ShapedWeights(const TRT_ShapedWeights& rhs) = default; + + nvinfer1::Weights GetTrtWeights() const; + + const Tensor& GetTensor() const { return tensor_; } + + // Returns a pointer of type const T to the underlying buffer of the tensor. + template + const T* GetPointer() const { + int64 num_elem = + (tensor_.NumElements() * DataTypeSize(tensor_.dtype())) / sizeof(T); + return tensor_.bit_casted_shaped({num_elem}).data(); + } + + // Returns a pointer of type T to the underlying buffer of the tensor. + template + T* GetPointer() { + int64 num_elem = + (tensor_.NumElements() * DataTypeSize(tensor_.dtype())) / sizeof(T); + return tensor_.bit_casted_shaped({num_elem}).data(); + } + + // Fills all the weight values with value. + template + Status SetValues(T value) { + switch (type_) { + case nvinfer1::DataType::kFLOAT: { + float* ptr = tensor_.flat().data(); + std::fill(ptr, ptr + volume_, value); + break; + } + case nvinfer1::DataType::kHALF: { + Eigen::half* ptr = tensor_.flat().data(); + std::fill(ptr, ptr + volume_, Eigen::half(value)); + break; + } + case nvinfer1::DataType::kINT32: { + int32* ptr = tensor_.flat().data(); + std::fill(ptr, ptr + volume_, value); + break; + } + default: + return errors::InvalidArgument( + "Unsupported data type ", tensorflow::tensorrt::DebugString(type_)); + } + return OkStatus(); + } + + Status SetShape(DimsAdapter dims); + void SetShapeUnsafe(DimsAdapter dims) { shape_ = std::move(dims); } + + // Returns total number of elements. Returning 0 means either some dim is 0 + // or the number of dims is 0. Note that a TF scalar constant is marked as + // Dims{0, {1}}, and has a count() == 1. + int64_t count() const { return volume_; } + + size_t size_bytes() const; + + string DebugString() const; + + template + absl::Span GetSpan() const { + return absl::Span(tensor_.flat().data(), volume_); + } + + template + std::vector ToVector() const { + auto span = GetSpan(); + return std::vector(span.data(), span.data() + span.size()); + } + + nvinfer1::DataType TrtDType() const { return type_; } + + const DimsAdapter& Shape() const { return shape_; } + DimsAdapter& Shape() { return shape_; } + + private: + // The shape of the weights. Defaults to the empty shape. + DimsAdapter shape_; + + // This creation method is only used by TrtWeightStore, which creates the + // underlying buffer. + static StatusOr CreateWithTensor(nvinfer1::DataType type, + DimsAdapter dims, + Tensor tensor); + + nvinfer1::DataType type_; + + // All weights should be stored inside TrtWeightStore to make sure lifetime of + // all the underlying tensors are available until the engine is built. For + // this reason, tensor_ should never be reassigned to a different value that + // is not already present in the TrtWeightStore. + Tensor tensor_; + // Contains the volume of the weight's shape. + int64_t volume_; + + friend class TrtWeightStore; +}; + +// Container for TRT_ShapedWeights. We need this container because TRT does not +// manage the lifetime of the weights buffer, it only keeps a pointer to it and +// requires that the data referenced by the pointer be available until the +// building of engine is complete. For more information see +// https://docs.nvidia.com/deeplearning/sdk/tensorrt-api/c_api/classnvinfer1_1_1_weights.html +// +// TODO(laigd): consider adding garbage collection to the unused weights. +class TrtWeightStore { + public: + // Gets a TRT_ShapedWeights with 'type' and 'dims'. + StatusOr GetTempWeights(nvinfer1::DataType trt_type, + const DimsAdapter& dims); + + // Gets a TRT_ShapedWeights with the same data type and dimensions as + // 'weights'. + StatusOr GetTempWeights(const TRT_ShapedWeights& weights) { + return GetTempWeights(weights.TrtDType(), weights.Shape()); + } + + private: + // The backend storage of the TRT_ShapedWeights. + std::vector store_; +}; + +// Enumerates the possible types of arguments of a converter. This determines +// what object is contained in TRT_TensorOrWeights, and converters can require +// a specific type for each of their arguments. +enum class TRT_ArgumentType { + TENSOR = 0, + WEIGHTS = 1, + RESOURCE = 2, +}; + +struct OpConverterParams; + +// Represents a TRT-style input to a TF node, it can be either a +// ITensorProxyPtr (representing nvinfer1::ITensor* or SimpleITensor), +// or TRT_ShapedWeights which is compile-time constant. +// +// TODO(laigd): maybe rename it to TrtArgument, or mimic XlaCompiler::Argument. +class TRT_TensorOrWeights { + public: + TRT_TensorOrWeights() {} + TRT_TensorOrWeights(ITensorProxyPtr); + TRT_TensorOrWeights(ITensorProxyPtr tensor, int batch_size); + + // Constructs a wrapper for the given ITensor. + // This is used by Converter when building the TRT network, where the ITensor + // is owned by the TRT network being built. See comment for 'trt_tensor_' + // in trt_proxy_tensor.h. + explicit TRT_TensorOrWeights(nvinfer1::ITensor* tensor, int batch_size = -1); + + // Creates a SimpleITensor for trt_dtype and trt_dims and takes ownership of + // the object. Constructs a wrapper for the SimpleITensor. This is used by + // TrtNodeValidator to encapsulate the type and shape information for + // validation of graph nodes, and the created ITensor is fake and temporary, + // and should not be used to build any TRT network. See comment for + // 'simple_tensor_' in trt_proxy_tensor.h. + explicit TRT_TensorOrWeights(nvinfer1::DataType trt_dtype, + const nvinfer1::Dims& trt_dims, int batch_size); + + // Constructs a wrapper for the given weights. + explicit TRT_TensorOrWeights(const TRT_ShapedWeights& weights); + + // Constructs a wrapper for the given resource handle. + explicit TRT_TensorOrWeights(const ResourceHandle& resource); + + TRT_TensorOrWeights(const TRT_TensorOrWeights& rhs); + + void operator=(const TRT_TensorOrWeights& rhs); + + bool is_tensor() const { + return initialized_ && arg_type_ == TRT_ArgumentType::TENSOR; + } + bool is_weights() const { + return initialized_ && arg_type_ == TRT_ArgumentType::WEIGHTS; + } + bool is_resource() const { + return initialized_ && arg_type_ == TRT_ArgumentType::RESOURCE; + } + + ITensorProxyPtr tensor() const; + + ResourceHandle resource() const; + + ITensorProxyPtr as_tensor(const OpConverterParams* params); + + TRT_ShapedWeights& weights() { + DCHECK(is_weights()); + return weights_; + } + + const TRT_ShapedWeights& weights() const { + DCHECK(is_weights()); + return weights_; + } + + nvinfer1::Dims GetTrtDims() const; + + Status GetTfType(DataType* tf_type) const; + + int batch_size() const { return batch_size_; } + + string DebugString() const; + + nvinfer1::DataType TrtDType() const { + if (arg_type_ == TRT_ArgumentType::RESOURCE) { + VLOG(0) << "Calling TrtDType() with a RESOURCE argument is undefined " + "behavior."; + } + return arg_type_ == TRT_ArgumentType::TENSOR ? tensor_proxy_ptr_->getType() + : weights_.TrtDType(); + } + + private: + void set_batch_size(int batch_size) { batch_size_ = batch_size; } + + // First dimension of the TF tensor (NOT tensor_) that is represented by + // tensor_ is treated as the "batch dimension" by TRT, and tensor_'s + // dimensions (obtained via tensor_->getDimensions()) do not contain the batch + // dimension. For example, when a TF tensor with shape (A,B,C) is represented + // in TRT, tensor_->getDimensions() will be (B,C) and batch_size_ will be A. + // + // This requires that all tensors in the subgraph that is converted to a TRT + // engine have the same batch size are represented by the first dimension of + // their shape, and Converter will verify this during conversion. The drawback + // is that currently it cannot convert a graph that doesn't have the batch + // size represented in the shapes or the batch sizes are different. See + // b/118387490 for more details. + // + // If use_implicit_batch is false, batch_size_ is unused and + // tensor_->getDimensions() will contain the entire shape (A,B,C). + // + // tensor_proxy_ptr_ is used when arg_type_ == TENSOR. + ITensorProxyPtr tensor_proxy_ptr_ = nullptr; + int batch_size_ = -1; + + // For DT_RESOURCE arguments (there is no corresponding type in TRT). + // resource_ is used when arg_type_ == RESOURCE. + ResourceHandle resource_; + + // weights_ is used when arg_type_ == WEIGHTS. + TRT_ShapedWeights weights_; + bool initialized_ = false; + TRT_ArgumentType arg_type_ = TRT_ArgumentType::WEIGHTS; + + friend class Converter; +}; +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_CONVERT_WEIGHTS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/get_calibration_data_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/get_calibration_data_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..d02be9218eeb442e89bee777cc705a474b8720f4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/get_calibration_data_op.cc @@ -0,0 +1,69 @@ +/* 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 +#include + +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/lib/core/refcount.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +class GetCalibrationDataOp : public OpKernel { + public: + explicit GetCalibrationDataOp(OpKernelConstruction* context) + : OpKernel(context) {} + + ~GetCalibrationDataOp() override {} + + void Compute(OpKernelContext* context) override { + // TODO(laigd): it will allocate the tensor on the device and copy the + // serialized string to that tensor, and later sess.run() will copy it back + // to host. We need to optimize this. + + const string& resource_name = context->input(0).scalar()(); + // Get the resource. + TRTEngineCacheResource* resource = nullptr; + OP_REQUIRES_OK(context, context->resource_manager()->Lookup( + std::string(kTfTrtContainerName), resource_name, + &resource)); + core::ScopedUnref sc(resource); + + // Serialize the resource as output. + string serialized_resource = resource->calib_ctx_->TerminateCalibration(); + OP_REQUIRES(context, !serialized_resource.empty(), + errors::Unknown("Calibration table is empty.")); + + Tensor* output = nullptr; + OP_REQUIRES_OK(context, + context->allocate_output(0, TensorShape({}), &output)); + + output->scalar()() = serialized_resource; + } +}; + +REGISTER_KERNEL_BUILDER(Name("GetCalibrationDataOp").Device(DEVICE_GPU), + GetCalibrationDataOp); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f5c2743a75818d52beef5f64bdbca9b0e1b28609 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_op.cc @@ -0,0 +1,1448 @@ +/* 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 +#include +#include + +#include "absl/memory/memory.h" +#include "absl/strings/ascii.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/common_runtime/graph_optimizer.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#include "tensorflow/core/framework/node_def_builder.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/grappler/clusters/utils.h" +#include "tensorflow/core/grappler/clusters/virtual_cluster.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/profiler/lib/traceme.h" +#include "tensorflow/core/util/env_var.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace { +Logger& logger = *Logger::GetLogger(); +using absl::StrAppend; +using absl::StrCat; +using ::nvinfer1::IRuntime; + +#define LOG_FIRST_FEW_WARNING_WITH_PREFIX \ + LOG_FIRST_N(WARNING, 5) << "TF-TRT Warning: " + +// Allocates device memory for an execution context to execute a TensorRT +// engine and records the relevant information for deallocating the memory when +// the engine finishes execution. +class ContextDeviceMemory { + public: + ContextDeviceMemory() + : execution_context_(nullptr), + device_memory_allocator_(nullptr), + device_memory_(nullptr) {} + + ~ContextDeviceMemory() { + if (device_memory_) { + device_memory_allocator_->free(device_memory_); + } + } + + Status AllocateDeviceMemory(nvinfer1::IExecutionContext* execution_context, + TRTBaseAllocator* device_memory_allocator, + size_t device_memory_size) { + execution_context_ = execution_context; + device_memory_allocator_ = device_memory_allocator; + device_memory_ = nullptr; + VLOG(2) << "Device memory size for TensorRT engine " << device_memory_size; + if (device_memory_size > 0) { + device_memory_ = device_memory_allocator_->allocate( + device_memory_size, + /*unused alignment=*/0, /*flags=*/0); + if (device_memory_ == nullptr) { + return errors::InvalidArgument( + "Out of GPU memory for execution context"); + } + } + { + tensorflow::profiler::TraceMe activity( + "setDeviceMemory", tensorflow::profiler::TraceMeLevel::kInfo); + execution_context_->setDeviceMemory(device_memory_); + } + return OkStatus(); + } + + private: + nvinfer1::IExecutionContext* execution_context_; + TRTBaseAllocator* device_memory_allocator_; + void* device_memory_; +}; + +// Macros for asynchronous execution, such as OP_REQUIRES_OK_ASYNC requires an +// object with operator (). Provides such an object with a noop operator() +// because we don't need such macros to invoke the DoneCallback for the +// TRTEngineOp. +struct DummyAsyncHelper { + void operator()() {} +}; + +// A helper class to call the DoneCallback for the TRTEngineOp when the object +// is destructed to support asynchronous of the native segment and TRT engines +// for the TRTEngineOp. +class AsyncHelper : public core::RefCounted { + public: + AsyncHelper(AsyncOpKernel::DoneCallback done) : done_(done) {} + + ~AsyncHelper() override { done_(); } + + private: + AsyncOpKernel::DoneCallback done_; +}; + +} // end anonymous namespace + +// This OP can construct TRTEngine on the fly and if construction of engine +// fails, executes equivalent subgraph as a TensorFlow function. +class TRTEngineOp : public AsyncOpKernel { + public: + explicit TRTEngineOp(OpKernelConstruction* context); + + void ComputeAsync(OpKernelContext* context, + AsyncOpKernel::DoneCallback done) override; + + private: + // Executes calibration asynchronously. + void ExecuteCalibration(OpKernelContext* ctx, + TRTEngineCacheResource* cache_res, + AsyncHelper* async_helper); + + // Constructs a function handle for the segment of the TRTEngineOp. + StatusOr ConstructFunctionHandle( + FunctionLibraryRuntime* lib, const string& device_name, + bool allow_soft_placement = false, size_t num_inputs = 0, + size_t num_outputs = 0); + + // Imports the GraphDef for the segment of the TRTEngineOp to + // segment_graph_def_. + Status ImportSegmentGraphDef(FunctionLibraryRuntime* lib, + const string& device_name); + + // Executes the native segment as function Op asynchronously. + void ExecuteNativeSegment(OpKernelContext* ctx, AsyncHelper* async_helper); + + // Allocates the device memory for the execution context and enqueues the + // TensorRT engine for execution. Also deallocates the device memory. Returns + // whether we need to retry by running the native segment. + Status ExecuteTrtEngine(OpKernelContext* ctx, EngineContext* engine_context, + int trt_context_idx, + const TrtShapeOptimizationProfile& profiles, + TRTBaseAllocator* allocator); + + // Allocates necessary resources for calibration. + Status AllocateCalibrationResources(OpKernelContext* ctx, + TRTEngineCacheResource* cache_res); + + Status GetEngineCacheResource(OpKernelContext* ctx, + TRTEngineCacheResource** cache_res); + + // Returns a pair of 1) An EngineContext object that is compatible with the + // input and 2) The index of the IExecutionContext compatible with the input. + // If a cuda engine for the given input shapes can't be found, returns + // (nullptr, 0) to allow native engine execution. Returns an error code for + // any problem that would prevent both TensorRT engine exceution and native + // segment execution. + StatusOr> GetEngine( + const std::vector& input_concrete_shapes, + OpKernelContext* ctx, TRTEngineCacheResource* cache_resource); + + // Builds and returns a cuda engine for the input shapes. If building the + // engine fails, enters a dummy entry into the cache_resource cache so we + // don't continually try to build the same failing engine. + StatusOr> BuildEngine( + const std::vector& input_concrete_shapes, int batch_size, + bool use_calibration, TRTInt8Calibrator* calibrator, + TRTEngineCacheResource* cache_resource, OpKernelContext* ctx); + + // Verify that the input shapes are consistent and can be handled by this op. + Status VerifyInputShapes(const std::vector& shapes); + + std::vector input_nodes_; + std::vector output_nodes_; + + // serialized protobuf segment or trt engine depending on static_engine_ flag. + string serialized_segment_; + + // The function for TF native execution of the segment. + NameAttrList func_; + + // GraphDef representation of the segment. + GraphDef segment_graph_def_; + + // Engine Precision mode. + TrtPrecisionMode precision_mode_; + + // Whether engine is constructed during the conversion or needs to be + // constructed from protobuf segment. + bool static_engine_; + + // Whether to calibrate INT8 engine. + bool calibration_mode_; + + // Whether to use implicit batch dimension for TensorRT. + bool use_implicit_batch_; + + // Whether to collect optimization profiles for TensorRT, only used when + // use_implicit_batch_=false. + bool profile_generation_mode_; + + // Optimization profile generation strategy. + ProfileStrategy profile_strategy_; + + // Whether the TRTEngineOp has any input with unknown dimensions. + bool has_dynamic_shape_input_; + + // Whether to build TensorRT engines at runtime. + bool allow_build_at_runtime_; + + // Whether to allow soft placement when the graph is executed with native + // TensorFlow. + bool allow_soft_placement_; + + // Maximum number of cached engines. + int max_cached_engines_; + + // Flag to detect whether native segment nodes have been deleted from graph + bool native_segment_absent_; + + int64 workspace_size_; + mutex engine_mutex_; + FunctionLibraryRuntime::Handle native_execution_func_handle_; + + // The finalized calibrator for inference. + std::unique_ptr calibrator_; + + // If true, create calibration graph for INT8 mode. Otherwise, we are using + // user-provided quantization ranges. + bool use_calibration_; + + tensorflow::grappler::Cluster* cluster_; + + // Array of all input shapes, collected from the input_shapes attribute when + // constructing the TRTEngineOp. The input_shapes attribute is set during + // graph conversion time. This data is used to retrieve which input dimensions + // could be unknown. During inference time this information is not available + // otherwise (all shapes are known (concrete) shapes when we run inference). + std::vector input_partial_shapes_; + // Shapes, excluding resource inputs. + std::vector input_partial_shapes_filtered_; + + // The TF node can have more inputs than the TRT engine: resource inputs are + // saved as weight in the engine, instead of passing that as engine input. + // Input mask is true for those TF input that are TRT engine inputs. + std::vector input_mask_; + + // Whether to use explicit precision (QDQ) mode. + bool use_explicit_precision_; +}; + +#define TYPECASE(dt, X) \ + case dt: { \ + return (void*)X->flat::Type>().data(); \ + } + +void* GetTensorAddress(const Tensor* tensor_ptr) { + const auto tensor_type = tensor_ptr->dtype(); + switch (tensor_type) { + TYPECASE(DT_FLOAT, tensor_ptr); + TYPECASE(DT_HALF, tensor_ptr); + TYPECASE(DT_INT8, tensor_ptr); + TYPECASE(DT_INT32, tensor_ptr); +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + TYPECASE(DT_BOOL, tensor_ptr); +#endif +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + TYPECASE(DT_UINT8, tensor_ptr); +#endif + default: { + LOG(ERROR) << "Unsupported Data type " << DataTypeString(tensor_type); + return nullptr; + } + } +} + +static Status FunctionDefToGraphDef(FunctionLibraryRuntime::Handle handle, + FunctionLibraryRuntime* flib_runtime, + GraphDef* graph_def) { + const FunctionLibraryDefinition* flib_def = + flib_runtime->GetFunctionLibraryDefinition(); + const FunctionBody* fbody; + fbody = flib_runtime->GetFunctionBody(handle); + if (!fbody) { + return errors::Internal( + "Function body is null when converting from FuncDef to GraphDef."); + } + std::unique_ptr graph(new Graph(flib_def)); + CopyGraph(*fbody->graph, graph.get()); + + auto replace_name = [](const char* const prefix, string* name) { + if (absl::StartsWith(*name, absl::AsciiStrToLower(prefix))) { + name->replace(0, strlen(prefix), prefix); + return true; + } + return false; + }; + graph->ToGraphDef(graph_def); + // GraphToFunctionDef() will convert all the node names to lowercase. + for (auto& node : *graph_def->mutable_node()) { + if (!replace_name(IONamePrefixes::kInputPHName, node.mutable_name())) { + if (replace_name(IONamePrefixes::kOutputPHName, node.mutable_name())) { + // Instantiation of the function will append _RetVal to the node name, + // need to remove it for backward compatibility. + const char* const suffix_to_remove = "_RetVal"; + if (absl::EndsWith(node.name(), suffix_to_remove)) { + node.mutable_name()->erase(node.name().size() - + strlen(suffix_to_remove)); + } + } + } + for (auto& input : *node.mutable_input()) { + if (!replace_name(IONamePrefixes::kInputPHName, &input)) { + replace_name(IONamePrefixes::kOutputPHName, &input); + } + } + } + return OkStatus(); +} + +StatusOr TRTEngineOp::ConstructFunctionHandle( + FunctionLibraryRuntime* lib, const string& device_name, + bool allow_soft_placement, size_t num_inputs, size_t num_outputs) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::ConstructFunctionHandle", + tensorflow::profiler::TraceMeLevel::kInfo); + VLOG(1) << "Constructing function handle"; + if (lib == nullptr) { + return errors::Internal("Context function library is null"); + } + FunctionLibraryRuntime::InstantiateOptions inst_ops; + inst_ops.state_handle = ""; + inst_ops.target = device_name; + if (!native_segment_absent_ && allow_soft_placement) { + const FunctionDef* fdef = + lib->GetFunctionLibraryDefinition()->Find(func_.name()); + if (!fdef) { + return errors::Internal( + StrCat("Can't find FunctionDef for ", func_.name())); + } + bool ints_on_device = + fdef->attr().count(FunctionLibraryDefinition::kIntsOnDeviceAttr) != 0 && + fdef->attr().at(FunctionLibraryDefinition::kIntsOnDeviceAttr).b(); + // kIntsOnDeviceAttr is not compatible with is_multi_device_function which + // is needed to support allow_soft_placement. + if (ints_on_device) { + LOG_FIRST_FEW_WARNING_WITH_PREFIX + << "Function " << name() + << " has attribute kIntsOnDeviceAttr=true " + "and will be executed natively with allow_soft_placement=false. " + "If this is a problem, please re-generate your SavedModel with " + "the TF-TRT runtime you are using."; + } else { + inst_ops.is_multi_device_function = true; + inst_ops.input_devices.resize(num_inputs, device_name); + inst_ops.output_devices.resize(num_outputs, device_name); + inst_ops.config_proto.set_allow_soft_placement(true); + } + } + FunctionLibraryRuntime::Handle func_handle; + Status status = lib->Instantiate(func_.name(), AttrSlice(&func_.attr()), + inst_ops, &func_handle); + if (status.ok()) { + return func_handle; + } + return status; +} + +Status TRTEngineOp::ImportSegmentGraphDef(FunctionLibraryRuntime* lib, + const string& device_name) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::ImportSegmentGraphDef", + tensorflow::profiler::TraceMeLevel::kInfo); + TF_ASSIGN_OR_RETURN(FunctionLibraryRuntime::Handle func_handle, + ConstructFunctionHandle(lib, device_name)); + return FunctionDefToGraphDef(func_handle, lib, &segment_graph_def_); +} + +TRTEngineOp::TRTEngineOp(OpKernelConstruction* context) + : AsyncOpKernel(context) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::TRTEngineOp", tensorflow::profiler::TraceMeLevel::kInfo); + // read serialized_engine + OP_REQUIRES_OK(context, + context->GetAttr("serialized_segment", &serialized_segment_)); + OP_REQUIRES_OK(context, + context->GetAttr("workspace_size_bytes", &workspace_size_)); + OP_REQUIRES_OK(context, context->GetAttr("static_engine", &static_engine_)); + + VLOG(1) << "Constructing " << name(); + string precision_string; + OP_REQUIRES_OK(context, + context->GetAttr("precision_mode", &precision_string)); + string calibration_data; + OP_REQUIRES_OK(context, + context->GetAttr("calibration_data", &calibration_data)); + OP_REQUIRES_OK(context, context->GetAttr("segment_func", &func_)); + OP_REQUIRES_OK(context, + TrtPrecisionModeFromName(precision_string, &precision_mode_)); + OP_REQUIRES_OK(context, + context->GetAttr("use_calibration", &use_calibration_)); + OP_REQUIRES_OK(context, + context->GetAttr("input_shapes", &input_partial_shapes_)); + auto status = + context->GetAttr("_allow_build_at_runtime", &allow_build_at_runtime_); + if (status.code() == tensorflow::error::NOT_FOUND) { + VLOG(2) << "Not found _allow_build_at_runtime in " + << context->device()->name() + << ", thus setting _allow_build_at_runtime=true"; + allow_build_at_runtime_ = true; + } else { + OP_REQUIRES_OK(context, status); + } + + // Get a mask of non-resource inputs. + std::vector in_types; + input_mask_.resize(input_partial_shapes_.size()); + OP_REQUIRES_OK(context, context->GetAttr("InT", &in_types)); + for (int i = 0; i < input_mask_.size(); i++) { + input_mask_[i] = (in_types[i] != DataType::DT_RESOURCE); + } + + // Filter the shapes to exclude resources. + for (int i = 0; i < input_partial_shapes_.size(); i++) { + if (input_mask_[i]) { + input_partial_shapes_filtered_.push_back(input_partial_shapes_[i]); + } + } + + status = context->GetAttr("_allow_soft_placement", &allow_soft_placement_); + if (status.code() == tensorflow::error::NOT_FOUND) { + allow_soft_placement_ = true; + } else { + OP_REQUIRES_OK(context, status); + } + + status = context->GetAttr("use_explicit_precision", &use_explicit_precision_); + if (!status.ok()) { + use_explicit_precision_ = false; + } + + // When a TF-TRT converted model without native segments is loaded, + // func_ can be empty. + native_segment_absent_ = (func_.name() == ""); + native_execution_func_handle_ = kInvalidHandle; + if (!native_segment_absent_) { + if (!static_engine_) { + OP_REQUIRES_OK(context, ImportSegmentGraphDef(context->function_library(), + context->device()->name())); + } + } + + // TODO(laigd): calibration_data is used in TF v1.x and we keep it only for + // backward compatibility reasons. Remove it once all known users switch to + // 2.0. + calibration_mode_ = + (use_calibration_ && precision_mode_ == TrtPrecisionMode::INT8 && + calibration_data.empty()); + if (!calibration_data.empty()) { + calibrator_.reset(new TRTInt8Calibrator(calibration_data)); + calibration_data.resize(0); + } + OP_REQUIRES_OK(context, context->GetAttr("max_cached_engines_count", + &max_cached_engines_)); + + status = context->GetAttr("_use_implicit_batch", &use_implicit_batch_); + if (status.code() == tensorflow::error::NOT_FOUND) { + VLOG(2) << "Not found _use_implicit_batch in " << context->device()->name() + << ", thus setting _use_implicit_batch=true"; + use_implicit_batch_ = true; + } + + status = + context->GetAttr("_profile_generation_mode", &profile_generation_mode_); + if (status.code() == tensorflow::error::NOT_FOUND) { + VLOG(2) << "Not found _profile_generation_mode in " + << context->device()->name() + << ", thus setting _profile_generation_mode=false"; + profile_generation_mode_ = false; + } + if (static_engine_) { + if (profile_generation_mode_) profile_generation_mode_ = false; + } + if (use_implicit_batch_) { + OP_REQUIRES(context, !profile_generation_mode_, + errors::InvalidArgument( + "profile_generation_mode_=true is only supported if " + "use_implicit_batch=false")); + if (input_partial_shapes_.empty()) { + VLOG(1) << "Attribute input_shapes is not set. This happens probably " + << "because you are using a model that is already converted " + << "to TensorRT with a previous version of TF-TRT (i.e. includes " + << "TRTEngineOp in graph). This is not an error. If you convert " + << "the original model again to TensorRT, the attributes " + << "input_shapes will be set automatically."; + } + } else { + OP_REQUIRES( + context, !input_partial_shapes_.empty(), + errors::InvalidArgument( + "Explicit batch mode requires attribute input_shapes to be set." + "If you are using a model that was converted to TensorRT by a " + "previous version of TF-TRT, (i.e. includes TRTEngineOp in graph " + "without the input_shapes attribute), then you need to convert the " + "original model again to TensorRT in order to set the attribute " + "input_shapes.")); + + string profile_strategy_name; + status = context->GetAttr("profile_strategy", &profile_strategy_name); + if (status.code() == tensorflow::error::NOT_FOUND) { + VLOG(2) << "Not found strategy in " << context->device()->name() + << ", thus setting profile_strategy='Range'"; + profile_strategy_ = ProfileStrategy::kRange; + } else { + OP_REQUIRES_OK(context, ProfileStrategyFromName(profile_strategy_name, + &profile_strategy_)); + } + } + has_dynamic_shape_input_ = absl::c_any_of( + input_partial_shapes_filtered_, + [](PartialTensorShape shape) { return !shape.IsFullyDefined(); }); + VLOG(2) << "TRTEngineOp has_dynamic_shape_input_: " + << has_dynamic_shape_input_; +} + +// Copies input tensor ctx->input(i) (which is in device memory) to the host, +// and place the resulting host tensor to the back of native_inputs. +Status CopyToHostAsync(OpKernelContext* ctx, std::vector* native_inputs, + int i, const cudaStream_t stream) { + // The TRTEngineOp has all ctx->inputs on the device. In contrast, the + // native segment expects to find int32 inputs on the host. We copy int32 + // inputs from device to host. + + AllocatorAttributes allocator_attr; + allocator_attr.set_on_host(true); + Tensor t; + TF_RETURN_IF_ERROR(ctx->allocate_temp( + ctx->input_dtype(i), ctx->input(i).shape(), &t, allocator_attr)); + native_inputs->push_back(t); + const Tensor& gpu_tensor = ctx->input(i); + auto ret = cudaMemcpyAsync( + t.flat().data(), gpu_tensor.flat().data(), + t.NumElements() * sizeof(int32), cudaMemcpyDeviceToHost, stream); + if (ret != 0) { + return errors::Internal("Could not copy tensor for native segment input"); + } + return OkStatus(); +} + +// Copies native_tensor, which is in host memory to ctx->output(t), which is in +// device memory. +Status CopyToDeviceAsync(OpKernelContext* ctx, const Tensor& native_tensor, + int t, cudaStream_t stream) { + Tensor* gpu_tensor; + TF_RETURN_IF_ERROR( + ctx->allocate_output(t, native_tensor.shape(), &gpu_tensor)); + auto ret = cudaMemcpyAsync(gpu_tensor->flat().data(), + native_tensor.flat().data(), + native_tensor.NumElements() * sizeof(int32), + cudaMemcpyHostToDevice, stream); + if (ret != 0) { + return errors::Internal("Could not copy tensor for native segment output"); + } + return OkStatus(); +} + +void TRTEngineOp::ExecuteNativeSegment(OpKernelContext* ctx, + AsyncHelper* async_helper) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::ExecuteNativeSegment", + tensorflow::profiler::TraceMeLevel::kInfo); + std::vector native_inputs; + std::vector* native_outputs = new std::vector(); + DummyAsyncHelper dummy_async_helper; + if (native_execution_func_handle_ == kInvalidHandle) { + StatusOr status_or_handle = + ConstructFunctionHandle(ctx->function_library(), ctx->device()->name(), + allow_soft_placement_, ctx->num_inputs(), + ctx->num_outputs()); + OP_REQUIRES_OK_ASYNC(ctx, status_or_handle.status(), dummy_async_helper); + native_execution_func_handle_ = *status_or_handle; + } + + auto lib = ctx->function_library(); + FunctionLibraryRuntime::Options opts; + opts.rendezvous = ctx->rendezvous(); + opts.cancellation_manager = ctx->cancellation_manager(); + opts.runner = ctx->runner(); + native_inputs.reserve(ctx->num_inputs()); + int n_copies = 0; + cudaStream_t stream = reinterpret_cast(CHECK_NOTNULL( + ctx->op_device_context()->stream()->platform_specific_handle().stream)); + for (int i = 0; i < ctx->num_inputs(); i++) { + if (ctx->input_dtype(i) != DT_INT32) { + native_inputs.push_back(ctx->input(i)); + } else { + OP_REQUIRES_OK_ASYNC(ctx, CopyToHostAsync(ctx, &native_inputs, i, stream), + dummy_async_helper); + n_copies++; + } + } + if (n_copies > 0) { + // If we have any int32 tensors, then wait until data is copied to host. + cudaStreamSynchronize(stream); + } + VLOG(1) << "Executing native segment: " << name(); + // Increment the reference count of the async_helper by 1. When the native + // segment finishes execution asynchronously, we decrement the reference + // count of the object. + async_helper->Ref(); + lib->Run( + opts, native_execution_func_handle_, native_inputs, native_outputs, + [this, ctx, native_outputs, async_helper, stream](const Status& s) { + core::ScopedUnref sc(async_helper); + DummyAsyncHelper dummy_async_helper; + std::unique_ptr> outputs_wrapper(native_outputs); + OP_REQUIRES_OK_ASYNC(ctx, s, dummy_async_helper); + VLOG(1) << "Native Segment completed"; + int n_copies = 0; + for (size_t t = 0; t < native_outputs->size(); ++t) { + if (native_outputs->at(t).dtype() == DT_INT32) { + OP_REQUIRES_OK_ASYNC( + ctx, CopyToDeviceAsync(ctx, native_outputs->at(t), t, stream), + dummy_async_helper); + n_copies++; + } else { + ctx->set_output(t, native_outputs->at(t)); + } + } + if (n_copies > 0) { + cudaStreamSynchronize(stream); + } + }); +} + +void TRTEngineOp::ExecuteCalibration(OpKernelContext* ctx, + TRTEngineCacheResource* cache_res, + AsyncHelper* async_helper) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::ExecuteCalibration", + tensorflow::profiler::TraceMeLevel::kInfo); + VLOG(1) << "Executing TRT calibration: " << name(); + DummyAsyncHelper dummy_async_helper; + + CalibrationContext* calib_ctx = cache_res->calib_ctx_.get(); + const int num_inputs = ctx->num_inputs(); + // TODO(laigd): need to check that input shape matches. + // Pass input data to calibrator + std::unordered_map input_data; + bool input_size_ok = true; + for (int i = 0; i < num_inputs; i++) { + const Tensor& t = ctx->input(i); + void* data_address = GetTensorAddress(&t); + OP_REQUIRES_ASYNC(ctx, data_address, + errors::InvalidArgument( + "Unsupported data type encountered in input ", i), + dummy_async_helper); + // Check the allocated buffer is sufficient for input + const auto device_tensor = &calib_ctx->device_tensors_.at(i); + if (t.TotalBytes() != device_tensor->TotalBytes()) { + // This can happen if the network has data dependent shapes. + input_size_ok = false; + VLOG(2) << "Size differs for input " << i + << ", skipping calibration for this input."; + break; + } + input_data.emplace(StrCat(IONamePrefixes::kInputPHName, i), data_address); + } + if (input_size_ok) { + VLOG(2) << "Filled map for sending"; + // Copied from gpu_kernel_helper.h as the header can only be used in *.cu.cc + // files. + cudaStream_t stream = reinterpret_cast(CHECK_NOTNULL( + ctx->op_device_context()->stream()->platform_specific_handle().stream)); + // TRTInt8Calibrator::setBatch will wait until TRTInt8Calibrator::getBatch + // is called before proceeding with feeding the calibration data to the + // calibrator. It returns true if the calibration data is accepted and + // returns false if calibration is terminated due to errors. + // + // If TRTInt8Calibrator::getBatch is never called, which could happen if + // there is any problem in building the cuda engine for calibration inside + // TensorRT, then the TRTInt8Calibrator::setBatch call here will hang until + // TRTInt8Calibrator::setDone is called by the calibration thread in + // AllocateCalibrationResources. + // + // In both of the above cases, setBatch here returns a boolean value to + // indicate the result of the calibration process. + if (!calib_ctx->calibrator_->setBatch(input_data, stream)) { + VLOG(2) << "Failed to feed calibration data"; + } else { + VLOG(2) << "Passed calibration data"; + } + } + if (!native_segment_absent_) { + ExecuteNativeSegment(ctx, async_helper); + } else { + LOG(ERROR) << "Calibration requires native segment, but is not found in " + "the graph."; + } +} + +Status TRTEngineOp::VerifyInputShapes( + const std::vector& input_concrete_shapes) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::VerifyInputShapes", + tensorflow::profiler::TraceMeLevel::kInfo); + if (input_concrete_shapes.empty()) { + return errors::InvalidArgument("Input shapes are empty, for ", name()); + } + + if (input_partial_shapes_filtered_.empty()) { + if (!use_implicit_batch_) { + return errors::InvalidArgument( + "Explicit batch mode requires input_partial_shapes_ ", + "to contain the dynamic input shapes to TRTEngineOp"); + } + // If the graph was converted with an earlier version of TF-TRT, it can + // happen that the input_partial_shapes_ vector is not set (see + // input_shapes attribute handling in the TRTEngineOp constructor). + // In implicit batch mode it is allowed to have empty input_partial_shapes_, + // since it is only required in explicit batch mode (see the input_shapes + // attribute of ConvertGraphDefToEngine in TRTEngineOp::GetEngine. + } else { + // Additional consistency checks if input_partial_shapes_ is present. + const string error_msg = StrCat( + "Input shapes do not match input partial shapes stored in graph, for ", + name(), ": ", DebugString(input_concrete_shapes), + " != ", DebugString(input_partial_shapes_filtered_)); + if (input_concrete_shapes.size() != input_partial_shapes_filtered_.size()) { + return errors::InvalidArgument(error_msg); + } + for (int i = 0; i < input_concrete_shapes.size(); i++) { + if (input_concrete_shapes[i].dims() != + input_partial_shapes_filtered_[i].dims()) { + return errors::InvalidArgument(error_msg); + } + } + for (int i = 0; i < input_concrete_shapes.size(); i++) { + for (int d = 0; d < input_concrete_shapes[i].dims(); d++) { + if (input_partial_shapes_filtered_[i].dim_size(d) != -1) { + if (input_concrete_shapes[i].dim_size(d) != + input_partial_shapes_filtered_[i].dim_size(d)) { + return errors::InvalidArgument(error_msg); + } + } + } + } + } + + if (use_implicit_batch_) { + if (input_concrete_shapes[0].dims() < 1) { + return errors::InvalidArgument( + "Input shapes contain scalar, for ", name(), ": ", + TensorShapeUtils::ShapeListString(input_concrete_shapes)); + } + const int batch_size = input_concrete_shapes[0].dim_size(0); + if (batch_size < 1) { + return errors::InvalidArgument( + "Incorrect batch dimension, for ", name(), ": ", + TensorShapeUtils::ShapeListString(input_concrete_shapes)); + } + for (const TensorShape& shape : input_concrete_shapes) { + if (batch_size != shape.dim_size(0)) { + return errors::InvalidArgument( + "Input shapes are inconsistent on the batch dimension, for ", + name(), ": ", + TensorShapeUtils::ShapeListString(input_concrete_shapes)); + } + } + } + return OkStatus(); +} + +static bool AllowEngineNativeSegmentExecution() { + bool value; + Status status = + ReadBoolFromEnvVar("TF_TRT_ALLOW_ENGINE_NATIVE_SEGMENT_EXECUTION", + /*default_val=*/true, &value); + if (!status.ok()) { + LOG(ERROR) << status; + } + return value; +} + +void TRTEngineOp::ComputeAsync(OpKernelContext* ctx, + AsyncOpKernel::DoneCallback done) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::ComputeAsync", tensorflow::profiler::TraceMeLevel::kInfo); + + // Invoke DoneCallback when this object is destructed, which could be after + // this routine finishes execution, in particular, when native segment is + // executed. + auto async_helper = new AsyncHelper(done); + core::ScopedUnref sc(async_helper); + + // For all async execution macros, use this object as there is no need to call + // DoneCallback from those macros. + DummyAsyncHelper dummy_async_helper; + + // Get TRT resource. + TRTEngineCacheResource* cache_res = nullptr; + OP_REQUIRES_OK_ASYNC(ctx, GetEngineCacheResource(ctx, &cache_res), + dummy_async_helper); + core::ScopedUnref unref_cache_res(cache_res); + + // Get shapes of inputs to engine. + std::vector input_concrete_shapes; + input_concrete_shapes.reserve(ctx->num_inputs()); + std::vector input_concrete_shapes_filtered; + for (int i = 0; i < ctx->num_inputs(); ++i) { + input_concrete_shapes.push_back(ctx->input(i).shape()); + if (ctx->input(i).dtype() != DataType::DT_RESOURCE) { + input_concrete_shapes_filtered.push_back(ctx->input(i).shape()); + } + } + + /// TODO(lsugy): fix case of engine with only resource inputs. + Status verify_input_shape_status = + VerifyInputShapes(input_concrete_shapes_filtered); + // TODO(bixia): Fix the segmentation. + if (!verify_input_shape_status.ok() && !native_segment_absent_) { + LOG_FIRST_FEW_WARNING_WITH_PREFIX + << "Running native segment for" << name() + << " due to failure in verifying input shapes: " + << verify_input_shape_status.message(); + ExecuteNativeSegment(ctx, async_helper); + return; + } + + if (!use_implicit_batch_ && + (has_dynamic_shape_input_ || cache_res->profiles_.HasShapeTensor())) { + OP_REQUIRES_OK_ASYNC(ctx, cache_res->profiles_.CollectShapeValues(ctx), + dummy_async_helper); + cache_res->profiles_.SetInputMask(input_mask_); + if (profile_generation_mode_) { + // Collecting new shapes for profiles can be only done once. After the + // shapes are converted to TRT profiles, no shapes can be collected + // anymore. + OP_REQUIRES_ASYNC(ctx, cache_res->profiles_.GetNumProfiles() == 0, + errors::Unimplemented("Cannot collect new shapes when " + "profiles are already created."), + dummy_async_helper); + // Just collect the input shape info and return. The shapes are used to + // generate optimization profiles during engine creation. + cache_res->profiles_.AddShape(input_concrete_shapes); + VLOG(1) + << "Native segment is used during collecting shapes for profiles."; + if (!native_segment_absent_) { + ExecuteNativeSegment(ctx, async_helper); + } else { + LOG(ERROR) << "Native segment is required for profile generation, " + "but is not found in the graph."; + } + return; + } else if (cache_res->profiles_.GetNumProfiles() == 0 && !static_engine_) { + // Add current shape if we did not collect any shapes so far. + if (!cache_res->profiles_.HasShape()) { + cache_res->profiles_.AddShape(input_concrete_shapes); + } + // Create profiles out of collected shapes during profile generation. + cache_res->profiles_.InitProfiles(input_partial_shapes_, + profile_strategy_); + } + } + + // Run calibration if in int8+calibration mode. + // * Logic in TF 1.x: + // - During conversion: calibration_mode_ is true and cache size is 0, so it + // will run calibration. + // - During inference: calibration_data will be set, so calibration_mode_ + // is false and it won't trigger calibration. + // * Logic in TF 2.0: + // - During conversion: similar to 1.x. + // - During inference: calibration_data will still be empty, but cache will + // contain the calibrated engine, so it won't trigger calibration. + // + // TODO(laigd): consider the following alternatives: + // 1. Serialize the state (calibration or inference) using + // TRTEngineInstance proto (or a new proto), so we know which mode we're + // in and don't run calibration during inference (which is invalid). + // 2. Reuse the calibration_data attribute or use a new attribute in the + // NodeDef to indicate whether it's in calibration mode. + if (calibration_mode_ && cache_res->cache_.size() == 0) { + if (!cache_res->calib_ctx_) { + // TODO(laigd): better encapsulation. + mutex_lock lock(engine_mutex_); + if (!cache_res->calib_ctx_) { + // Add profiles if we are in dynamic shape mode. + if (!use_implicit_batch_ && (has_dynamic_shape_input_ || + cache_res->profiles_.HasShapeTensor())) { + cache_res->profiles_.InitCalibProfile(input_concrete_shapes); + } + OP_REQUIRES_OK_ASYNC(ctx, AllocateCalibrationResources(ctx, cache_res), + dummy_async_helper); + } + } + // TODO(laigd): check that the input shapes match the shapes of the + // persistent tensor in the calibration resource. + ExecuteCalibration(ctx, cache_res, async_helper); + return; + } + + StatusOr> status = + GetEngine(input_concrete_shapes, ctx, cache_res); + OP_REQUIRES_OK_ASYNC(ctx, status.status(), dummy_async_helper); + + EngineContext* engine_context = status.value().first; + int trt_context_idx = status.value().second; + auto may_execute_native_segment = [&] { + if (!native_segment_absent_ && !AllowEngineNativeSegmentExecution()) { + ctx->CtxFailure( + errors::Aborted("User disallowed engine native segment execution.")); + return false; + } else if (native_segment_absent_) { + ctx->CtxFailure( + errors::Aborted("Native segment execution is enabled but " + " native segment is not found in the graph.")); + return false; + } + return true; + }; + if (!engine_context->GetCudaEngine()) { + LOG_FIRST_FEW_WARNING_WITH_PREFIX + << "Engine retrieval for input shapes: " + << TensorShapeUtils::ShapeListString(input_concrete_shapes) + << " failed. Running native segment for " << name(); + if (may_execute_native_segment()) { + ExecuteNativeSegment(ctx, async_helper); + } + return; + } + Status stat = + ExecuteTrtEngine(ctx, engine_context, trt_context_idx, + cache_res->profiles_, cache_res->allocator_.get()); + if (stat.ok()) return; + + LOG_FIRST_FEW_WARNING_WITH_PREFIX << "Failed to execute engine: " << stat + << " Retrying with native segment for " + << name(); + if (!may_execute_native_segment()) { + return; + } + // When Native Segment execution is enabled, release any outputs that + // are allocated. ExecuteNativeSegment will re-allocate them and + // fail if they are currently allocated. + // The Tensor pointer in the returned TensorValue must be explicitly + // deleted. + for (int i = 0; i < ctx->num_outputs(); i++) { + delete ctx->release_output(i).tensor; + } + if (!native_segment_absent_) { + ExecuteNativeSegment(ctx, async_helper); + } else { + LOG(ERROR) << "Native segment execution is enabled, " + "but native segment is not found in the graph."; + } +} + +Status TRTEngineOp::ExecuteTrtEngine( + OpKernelContext* ctx, EngineContext* engine_context, int trt_context_idx, + const TrtShapeOptimizationProfile& profiles, TRTBaseAllocator* allocator) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::ExecuteTrtEngine", + tensorflow::profiler::TraceMeLevel::kInfo); + VLOG(1) << "Executing TRT engine: " << name(); + nvinfer1::ICudaEngine* cuda_engine = engine_context->GetCudaEngine(); + + if (VLOG_IS_ON(2)) { + VLOG(2) << " Network name: " << cuda_engine->getName(); + VLOG(2) << " Activation size: " << engine_context->GetDeviceMemorySize() + << " bytes"; +#if !IS_TRT_VERSION_GE(8, 0, 0, 0) + // getWorkspaceSize() is deprecated as of TRT 8 + VLOG(2) << " Workspace size: " << cuda_engine->getWorkspaceSize() + << " bytes"; +#endif // #if !IS_TRT_VERSION_GE(8, 0, 0, 0) + VLOG(2) << " Datatype of " << cuda_engine->getNbBindings() + << " inputs/outputs"; + string binding_types = ""; + for (int i = 0; i < cuda_engine->getNbBindings(); i++) { + binding_types += " " + string(cuda_engine->getBindingName(i)) + ": " + + DebugString(cuda_engine->getBindingDataType(i)) + "\n"; + } + VLOG(2) << binding_types; + } + + const int num_binding = cuda_engine->getNbBindings(); + std::vector buffers(num_binding); + + // nvinfer1::IExecutionContext::enqueue is not thread safe and we need a mutex + // for it. + mutex_lock lock(engine_context->mu); + nvinfer1::IExecutionContext* execution_context; + bool has_device_memory; + TF_RETURN_IF_ERROR(engine_context->GetExecutionContext( + trt_context_idx, &execution_context, &has_device_memory)); + + if (VLOG_IS_ON(2)) { + VLOG(2) << "Selected execution context: " << trt_context_idx; + } + const int num_batch = + use_implicit_batch_ ? ctx->input(0).shape().dim_size(0) : 0; + + TF_RETURN_IF_ERROR(SetTrtEngineInputs( + cuda_engine, execution_context, trt_context_idx, buffers, + use_implicit_batch_, num_batch, profiles, ctx)); + + TF_RETURN_IF_ERROR(SetTrtEngineOutputs(cuda_engine, execution_context, + trt_context_idx, buffers, + use_implicit_batch_, num_batch, ctx)); + + // Copied from gpu_kernel_helper.h as the header can only be used in *.cu.cc + // files. + cudaStream_t stream = reinterpret_cast(CHECK_NOTNULL( + ctx->op_device_context()->stream()->platform_specific_handle().stream)); + + ContextDeviceMemory context_device_memory; + if (!has_device_memory) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::AllocateDeviceMemory", + tensorflow::profiler::TraceMeLevel::kInfo); + // Allocate device memory for the TensorRT engine execution. The device + // memory will be released when context_device_memory goes out of scope. + TF_RETURN_IF_ERROR(context_device_memory.AllocateDeviceMemory( + execution_context, allocator, engine_context->GetDeviceMemorySize())); + } + // Enqueue the TensorRT engine for execution. + return TrtEnqueue(execution_context, buffers, stream, use_implicit_batch_, + num_batch); +} + +Status TRTEngineOp::GetEngineCacheResource(OpKernelContext* ctx, + TRTEngineCacheResource** cache_res) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::GetEngineCachResource", + tensorflow::profiler::TraceMeLevel::kInfo); + // Canonicalize the op name by removing the scopes if any. This is mainly + // because in TFv2, the function graph can be instantiated in various ways and + // it'll insert scope names to the name of the TRTEngineOps, which will result + // in many different engine caches if we use the instantiated op name + // directly, but we still want all of them share the same cache (if they were + // representing the same subgraph). + absl::string_view resource_name = name(); + size_t last_slash = resource_name.find_last_of('/'); + if (last_slash != absl::string_view::npos) { + resource_name.remove_prefix(last_slash + 1); + } + + // Get engine cache. + return ctx->resource_manager()->LookupOrCreate( + std::string(kTfTrtContainerName), std::string(resource_name), cache_res, + {[this, ctx](TRTEngineCacheResource** cr) -> Status { + *cr = new TRTEngineCacheResource(ctx, this->max_cached_engines_); + return OkStatus(); + }}); +} + +StatusOr> TRTEngineOp::BuildEngine( + const std::vector& input_concrete_shapes, int batch_size, + bool use_calibration, TRTInt8Calibrator* calibrator, + TRTEngineCacheResource* cache_resource, OpKernelContext* ctx) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::BuildEngine", tensorflow::profiler::TraceMeLevel::kInfo); + TRT_ENSURE(cache_resource); + TRT_ENSURE(ctx); + // Use concrete shapes for implicit batch mode and partial shapes for + // explicit batch mode. + bool use_concrete_shapes = + use_implicit_batch_ || cache_resource->profiles_.IsStaticCompatible(); + const std::vector& conversion_input_shapes = + use_concrete_shapes + ? std::vector(input_concrete_shapes.begin(), + input_concrete_shapes.end()) + : input_partial_shapes_; + + VLOG(1) << "Building a new TensorRT engine for " << name() + << " with input shapes: " << DebugString(conversion_input_shapes); + + std::unordered_map device_map; + DeviceNameUtils::ParsedName full_parsed_name; + DeviceNameUtils::ParseFullName(ctx->device()->name(), &full_parsed_name); + device_map.emplace(ctx->device()->name(), + grappler::GetDeviceInfo(full_parsed_name)); + tensorflow::grappler::VirtualCluster cluster(device_map); + + TrtUniquePtrType engine; + auto status = convert::ConvertGraphDefToEngine( + segment_graph_def_, ctx, precision_mode_, batch_size, workspace_size_, + conversion_input_shapes, &logger, cache_resource->allocator_.get(), + calibrator, &engine, use_calibration, use_implicit_batch_, nullptr, + &cache_resource->profiles_, name(), use_explicit_precision_, &cluster, + ctx->device()->name()); + if (!status.ok()) { + LOG_FIRST_FEW_WARNING_WITH_PREFIX + << "Engine creation for " << name() << " failed. " + << "The native segment will be used instead. " + << "Reason: " << status; + // Store an empty engine in the cache for these input shapes so we don't try + // to build the same failing engine again. + cache_resource->cache_.emplace(input_concrete_shapes, + std::make_unique()); + return status; + } + return engine; +} + +StatusOr> TRTEngineOp::GetEngine( + const std::vector& input_concrete_shapes, OpKernelContext* ctx, + TRTEngineCacheResource* cache_res) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::GetEngine", tensorflow::profiler::TraceMeLevel::kInfo); + static EngineContext empty_context; + mutex_lock lock(engine_mutex_); + // Using first input to get batch size is reliable - VerifyInputShapes() + // guarantees that the first input is not a scalar. As such we can always use + // the first input to get the batch size for implicit batch mode. For explicit + // batch mode, this value is not used. + const int batch_size = input_concrete_shapes[0].dim_size(0); + // TODO(Tamas): remove the need for batch_size in explicit_batch mode + auto& cache = cache_res->cache_; + auto allocator = cache_res->allocator_.get(); + if (allocator == nullptr) { + return std::pair(&empty_context, 0); + } + + // Handle the static engine case. For static engines, the cache will have a + // single element containing the only engine. + if (static_engine_) { + if (cache.size()) { + // TODO(laigd): need a better shape compatibility check for the case where + // implicit batch is disabled. + if (!use_implicit_batch_ || + AreShapesCompatible(input_concrete_shapes, cache.begin()->first)) { + int profile_id = 0; + if (!use_implicit_batch_) + profile_id = + cache_res->profiles_.GetProfileNumber(input_concrete_shapes); + if (profile_id != -1) { + return std::pair(cache.begin()->second.get(), + profile_id); + } + } + return std::pair(&empty_context, 0); + } + + TrtUniquePtrType infer(nvinfer1::createInferRuntime(logger)); + infer->setGpuAllocator(allocator); + // Need to initialize plugins in order to deserialize engines that contain + // plugins. + MaybeInitializeTrtPlugins(&logger); + TrtUniquePtrType static_engine( + infer->deserializeCudaEngine(serialized_segment_.c_str(), + serialized_segment_.size(), nullptr)); + int profile_id = 0; + if (static_engine && !use_implicit_batch_) { + // load profiles + std::vector exec_contexts; + TF_RETURN_IF_ERROR(cache_res->profiles_.RestoreProfiles( + static_engine.get(), ctx->num_inputs())); + TF_RETURN_IF_ERROR(cache_res->profiles_.CreateExecutionContexts( + static_engine.get(), &exec_contexts)); + cache.emplace(input_concrete_shapes, + std::make_unique(std::move(static_engine), + std::move(exec_contexts))); + VLOG(1) << "Added new engine to cache of " << name() + << ". Cache size: " << cache.size(); + // Query which profile of the new engine matches the actual input. + profile_id = cache_res->profiles_.GetProfileNumber(input_concrete_shapes); + if (profile_id == -1) { + return std::pair(&empty_context, 0); + } + EngineContext* engine_context = cache_res->GetEngineContext(profile_id); + return std::pair(engine_context, profile_id); + } + + if (!static_engine) { + if (!allow_build_at_runtime_) { + // Store an empty engine in the cache so we don't try to load the same + // failing engine again. + cache.emplace(input_concrete_shapes, std::make_unique()); + return std::pair(&empty_context, 0); + } + if (segment_graph_def_.node().empty()) { + Status status = ImportSegmentGraphDef(ctx->function_library(), + ctx->device()->name()); + if (!status.ok()) { + LOG_FIRST_FEW_WARNING_WITH_PREFIX << "Getting segment graph for " + << name() << " failed. " + << "Reason: " << status; + } + } + auto result = BuildEngine(input_concrete_shapes, batch_size, + /*use_calibration=*/false, + /*calibrator=*/nullptr, cache_res, ctx); + if (!result.ok()) { + return std::pair(&empty_context, 0); + } + static_engine = std::move(result.value()); + } + + auto raw_static_engine = static_engine.get(); + std::vector engine_input_shapes(input_concrete_shapes); + + int max_batch_size = 1; + if (use_implicit_batch_) { + max_batch_size = raw_static_engine->getMaxBatchSize(); + // Static engine will have max_batch_size for batch size so that all + // inputs will map to this single engine. + for (int i = 0; i < engine_input_shapes.size(); i++) { + engine_input_shapes[i].set_dim(0, max_batch_size); + } + } + + ExecutionContext context = ExecutionContext::Create(raw_static_engine); + // TODO(laigd): here we assume engine_input_shapes matches the actual input + // shapes of the engine, we should verify that. + cache.emplace(engine_input_shapes, + std::make_unique(std::move(static_engine), + std::move(context))); + // Runtime is safe to delete after engine creation + VLOG(1) << "Size of serialized TRT engine: " + << serialized_segment_.capacity(); + string tmp; + // Swap with temporary empty string to deallocate the CPU memory. + serialized_segment_.swap(tmp); + if (use_implicit_batch_ && (max_batch_size < batch_size)) { + return std::pair(&empty_context, 0); + } + return std::pair(cache.at(engine_input_shapes).get(), + 0); + } // static_engine_ + + int profile_id = -1; + if (!use_implicit_batch_) { + profile_id = cache_res->profiles_.GetProfileNumber(input_concrete_shapes); + // Since all profiles are already created at this point, finding no + // compatible profiles results in falling back to native TF. + if (profile_id == -1) { + return std::pair(&empty_context, 0); + } + } + + EngineContext* engine_contexts; + if (use_implicit_batch_) { + engine_contexts = cache_res->GetEngineContext(input_concrete_shapes); + } else { + engine_contexts = cache_res->GetEngineContext(profile_id); + } + + // If cache does not have a compatible engine then create a new engine. + if (engine_contexts == nullptr) { + if (!allow_build_at_runtime_) { + LOG_FIRST_FEW_WARNING_WITH_PREFIX + << "Found no engine in cache matching input shapes. " + << "Not building a new engine because " + << "allow_build_at_runtime=False. " + << "The native segment will be used instead."; + // Store an empty engine in the cache for these input shapes so we don't + // try to build the same failing engine again. + cache.emplace(input_concrete_shapes, std::make_unique()); + return std::pair(&empty_context, 0); + } + + // Up to this point, calibrator_ can never be empty, since otherwise it + // means calibration_mode_ is true and this path won't get executed. + auto result = + BuildEngine(input_concrete_shapes, batch_size, use_calibration_, + calibrator_.get(), cache_res, ctx); + if (!result.ok()) { + return std::pair(&empty_context, 0); + } + TrtUniquePtrType engine = std::move(result.value()); + std::vector exec_contexts; + TF_RETURN_IF_ERROR(cache_res->profiles_.CreateExecutionContexts( + engine.get(), &exec_contexts)); + cache.emplace(input_concrete_shapes, + std::make_unique(std::move(engine), + std::move(exec_contexts))); + VLOG(1) << "Added new engine to cache of " << name() + << ". Cache size: " << cache.size(); + engine_contexts = cache.at(input_concrete_shapes).get(); + // Query which profile of the new engine matches the actual input. + profile_id = cache_res->profiles_.GetProfileNumber(input_concrete_shapes); + } + return std::pair(engine_contexts, + use_implicit_batch_ ? 0 : profile_id); +} + +// TODO(hinsu): Move this allocation to CalibrationContext constructor, if +// possible. +Status TRTEngineOp::AllocateCalibrationResources( + OpKernelContext* ctx, TRTEngineCacheResource* cache_res) { + tensorflow::profiler::TraceMe activity( + "TRTEngineOp::AllocateCalibrationResources", + tensorflow::profiler::TraceMeLevel::kInfo); + cache_res->calib_ctx_ = std::make_unique(); + auto* cres = cache_res->calib_ctx_.get(); + + // Get the input shapes. + /// TODO(lsugy): support INT8 calibration in non-frozen mode. + const int batch_size = ctx->input(0).dim_size(0); + const int num_inputs = ctx->num_inputs(); + std::vector shapes; + cres->device_tensors_.resize(num_inputs); + VLOG(1) << "Constructing calibrator"; + for (int i = 0; i < num_inputs; i++) { + // allocate workspace on device for inputs + auto* input = &cres->device_tensors_.at(i); + const Tensor& t = ctx->input(i); + shapes.emplace_back(t.shape()); + TF_RETURN_IF_ERROR(ctx->allocate_temp(t.dtype(), t.shape(), input)); + CHECK_EQ(t.TotalBytes(), input->TotalBytes()); // Crash OK + + void* device_address = GetTensorAddress(input); + if (device_address == nullptr) { + return errors::InvalidArgument("Unsupported data type [", + DebugString(t.dtype()), + "] encountered in input ", i); + } + cres->device_buffers_.emplace( + StrCat(IONamePrefixes::kInputPHName, i), + std::pair(device_address, input->TotalBytes())); + } + cres->calibrator_.reset( + new TRTInt8Calibrator(cres->device_buffers_, batch_size, name())); + const int platform_device_id = + ctx->device()->tensorflow_accelerator_device_info()->gpu_id; + if (platform_device_id < 0) { + LOG(ERROR) << "Can't get gpu_device_info from context->device()"; + return errors::InvalidArgument( + "Context->device doesn't contain device info!"); + } + + bool use_concrete_shapes = + use_implicit_batch_ || cache_res->profiles_.IsStaticCompatible(); + const std::vector& conversion_input_shapes = + use_concrete_shapes + ? std::vector(shapes.begin(), shapes.end()) + : input_partial_shapes_; + + cache_res->Ref(); + string platform_device_name = ctx->device()->name(); + cres->thr_.reset(new std::thread([this, cres, shapes, conversion_input_shapes, + platform_device_id, platform_device_name, + cache_res, ctx]() { + core::ScopedUnref sc(cache_res); + + VLOG(1) << "Starting calibration thread on device " << platform_device_id + << ", Calibration Resource @ " << cres; + auto err = cudaSetDevice(platform_device_id); + if (err != cudaSuccess) { + // TODO(aaroey): should return error here. + LOG(ERROR) << "Couldn't set cuda device to " << platform_device_id + << " in calibration thread"; + } + + std::unordered_map device_map; + DeviceNameUtils::ParsedName full_parsed_name; + DeviceNameUtils::ParseFullName(platform_device_name, &full_parsed_name); + device_map.emplace(platform_device_name, + grappler::GetDeviceInfo(full_parsed_name)); + tensorflow::grappler::VirtualCluster cluster(device_map); + + // ConvertGraphDefToEngine() will try to build the engine. This thread + // will loop inside buildCudaEngine() consuming the calibration data + // that is set by the TF op, and drive the builder until calibrator + // returns false. Engine is discarded after calibration table is + // generated + // + // TODO(aaroey): maybe setting the max batch size using the python + // calibration wrapper class. + auto s = convert::ConvertGraphDefToEngine( + this->segment_graph_def_, ctx, TrtPrecisionMode::INT8, + cres->calibrator_->getBatchSize(), this->workspace_size_, + conversion_input_shapes, &cache_res->GetLogger(), + cache_res->allocator_.get(), cres->calibrator_.get(), &cres->engine_, + /*use_calibration=*/true, this->use_implicit_batch_, + /*convert_successfully=*/nullptr, + /*profiles=*/&cache_res->profiles_, name(), + /*use_explicit_precision=*/use_explicit_precision_, + /*cluster=*/&cluster, platform_device_name); + if (!s.ok()) { + LOG(ERROR) << "Calibration failed: " << s; + cres->calibrator_->setDone(); // Ignore further pushes + cache_res->cache_.emplace(shapes, std::make_unique()); + } else { + // Transfer the ownership of the engine to the engine cache, so we can + // dump it out during conversion for TF 2.0. + mutex_lock lock(this->engine_mutex_); + this->calibrator_ = std::move(cres->calibrator_); + if (!use_implicit_batch_ && + (has_dynamic_shape_input_ || cache_res->profiles_.HasShapeTensor())) { + std::vector exec_contexts; + auto calib_result = cache_res->profiles_.CreateExecutionContexts( + cres->engine_.get(), &exec_contexts); + cache_res->cache_.emplace( + shapes, std::make_unique(std::move(cres->engine_), + std::move(exec_contexts))); + } else { + ExecutionContext context = + ExecutionContext::Create(cres->engine_.get()); + cache_res->cache_.emplace( + shapes, std::make_unique(std::move(cres->engine_), + std::move(context))); + } + } + + VLOG(1) << "Calibration loop terminated " << this->name(); + })); + VLOG(1) << "initialized calibrator resource"; + return OkStatus(); +} + +REGISTER_KERNEL_BUILDER(Name("TRTEngineOp").Device(DEVICE_GPU), TRTEngineOp); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_op_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_op_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a687045cb27368de64321b0108204b84f8d1f3ff --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_op_test.cc @@ -0,0 +1,377 @@ +/* Copyright 2019 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 +#include +#include +#include + +#include +#include +#include "absl/container/inlined_vector.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/function_ops.h" +#include "tensorflow/cc/ops/math_ops.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_graph.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "xla/tsl/framework/fixedpoint/FixedPoint.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/fake_input.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/node_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/kernels/ops_testutil.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/public/version.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +using ::absl::StrCat; +using ::testing::ElementsAre; + +struct TestParam { + bool static_engine; +}; + +class TRTEngineOpTestBase : public OpsTestBase { + public: + void AddSimpleTrtOp(DataType dtype, int max_cached_engines_count = 1, + PartialTensorShape shape = PartialTensorShape({-1, -1}), + bool use_implicit_batch = true, + bool allow_build_at_runtime = true, + bool static_engine = false) { + // Create the GPU device. + std::unique_ptr device( + DeviceFactory::NewDevice("GPU", {}, "/job:worker/replica:0/task:0")); + + // Create simple TF graph. + Scope s = Scope::NewRootScope(); + auto feed = ops::_Arg(s.WithOpName("TensorRTInputPH_0"), dtype, 0); + auto add = ops::Add(s.WithOpName("add"), feed, feed); + ops::_Retval give_me_a_name(s.WithOpName("TensorRTOutputPH_0"), add, 0); + + // Serialize the graph. TRTEngineOp will convert it using dynamic mode. + GraphDef graph_def; + TF_ASSERT_OK(s.ToGraphDef(&graph_def)); + Graph* graph = s.graph(); + TF_ASSERT_OK(convert::RegisterGraphToFunctionLibrary(graph_def, graph, + std::string(kOpName))); + TF_ASSERT_OK(flib_def_->AddLibrary(graph->flib_def())); + + string segment_string; + if (static_engine) { + convert::TRTOptimizationPass::ConversionParams params; + convert::EngineInfo info; + info.segment_graph_def.CopyFrom(graph_def); + info.precision_mode = TrtPrecisionMode::FP32; + info.max_workspace_size_bytes = 1 << 20; + info.engine_name = "TRTEngineOP_000_000"; + params.use_implicit_batch = use_implicit_batch; + params.trt_logger_name = "DefaultLogger"; + + TrtShapeOptimizationProfile profile; + // We set the input mask to true (no resource inputs) + std::vector input_mask = {true}; + profile.SetInputMask(input_mask); + // We set profile 0 to be incompatible with the input used in the test. + // This way we ensure that profile selection is tested. + TensorShape my_shape; + TF_CHECK_OK( + TensorShapeUtils::MakeShape(std::vector{4, 2}, &my_shape)); + profile.AddShape({my_shape, {}}); + TF_CHECK_OK( + TensorShapeUtils::MakeShape(std::vector{1, 2}, &my_shape)); + profile.AddShape({my_shape, {}}); + + profile.InitProfiles({shape}, ProfileStrategy::kOptimal); + std::vector shape_vec{shape, {}}; + TF_CHECK_OK(convert::CreateStaticEngine( + params, info, 1, shape_vec, &profile, &segment_string, nullptr)); + } + + // Create the op. + // In implicit batch mode, the input shapes that we specify here are not + // used for engine creation, we use the concrete shapes during inference + // time for creating the engine. + // In explicit batch mode, the input shapes attribute is used to define + // the network for the TensorRT engine. + OpsTestBase::SetDevice(DEVICE_GPU, std::move(device)); + NameAttrList function; + function.set_name(StrCat(std::string(kOpName), "_native_segment")); + // We disable allow_soft_placement when executing the native segment of the + // TRTEngineOp for the following reasons: + // OpsTestBase only allow one device in the device manager. + // We need to define the GPU device to test TRTEngineOp. + // When allow_soft_placement is true, the TensorFlow runtime produces an + // error if a CPU device is not defined + // (see ProcessFunctionLibraryRuntime::InstantiateMultiDevice). + TF_ASSERT_OK(NodeDefBuilder(std::string(kOpName), "TRTEngineOp") + .Input(FakeInput(1, dtype)) + .Attr("input_shapes", {shape}) + .Attr("output_shapes", {shape}) + .Attr("static_engine", static_engine) + .Attr("segment_func", function) + .Attr("serialized_segment", segment_string) + .Attr("calibration_data", "") + .Attr("max_cached_engines_count", max_cached_engines_count) + .Attr("workspace_size_bytes", 1 << 20) + .Attr("precision_mode", "FP32") + .Attr("use_calibration", false) + .Attr("profile_strategy", "optimal") + .Attr("_use_implicit_batch", use_implicit_batch) + .Attr("_allow_build_at_runtime", allow_build_at_runtime) + .Attr("_allow_soft_placement", false) + .Attr("OutT", {dtype}) + .Finalize(OpsTestBase::node_def())); + TF_ASSERT_OK(InitOpWithFunctionLibrary()); + } + + static const absl::string_view kOpName; + + template + void AddSimpleInput(const TensorShape& shape) { + std::vector input(shape.num_elements()); + std::iota(input.begin(), input.end(), T(0)); + OpsTestBase::AddInputFromArray(shape, input); + } + + void ResetInputs() { + inputs_.clear(); + for (auto& temp : tensors_) { + delete temp; + } + tensors_.clear(); + } + + private: + Status InitOpWithFunctionLibrary() { + OpKernel* kernel = nullptr; + auto flr = pflr_->GetFLR(device_->name()); + std::shared_ptr props; + Status status = NodeProperties::CreateFromNodeDef( + node_def_, flr->GetFunctionLibraryDefinition(), &props); + if (status.ok()) { + status.Update(CreateOpKernel(device_type_, device_, allocator(), flr, + props, TF_GRAPH_DEF_VERSION, &kernel)); + } + kernel_ = std::unique_ptr(kernel); + if (kernel_ != nullptr) input_types_ = kernel_->input_types(); + return status; + } +}; + +class TRTEngineOpTestWithParam + : public TRTEngineOpTestBase, + public ::testing::WithParamInterface { + public: + TRTEngineOpTestWithParam() : param_(GetParam()) {} + + protected: + TestParam param_; +}; + +const absl::string_view TRTEngineOpTestBase::kOpName = "myop"; + +constexpr std::array TestParameters{TestParam{false}, + TestParam{true}}; + +INSTANTIATE_TEST_CASE_P(TRTEngineOpTestInstantiation, TRTEngineOpTestWithParam, + ::testing::ValuesIn(TestParameters)); + +TEST_F(TRTEngineOpTestBase, DynamicEngines) { + // Test dynamic engine creation during inference time + TRTEngineOpTestBase::AddSimpleTrtOp(DT_FLOAT, /*max_cached_engines_count=*/4); + + // Execute the op with batch size > 1. + TRTEngineOpTestBase::AddSimpleInput(TensorShape({2, 2})); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + + // Get the engine cache. + TRTEngineCacheResource* cache_resource = nullptr; + TF_ASSERT_OK(device_->resource_manager()->Lookup( + std::string(kTfTrtContainerName), std::string(kOpName), &cache_resource)); + core::ScopedUnref sc(cache_resource); + + // It should contain only one engine. + auto cache = &cache_resource->cache_; + EXPECT_EQ(1, cache->size()); + EXPECT_EQ(1, cache->count({TensorShape({2, 2})})); + + // Execute the op with batch size 1. It should reuse existing engine to + // execute. + ResetInputs(); + TRTEngineOpTestBase::AddSimpleInput(TensorShape({1, 2})); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + EXPECT_EQ(1, cache->size()); + EXPECT_EQ(1, cache->count({TensorShape({2, 2})})); + + // Execute the op with a larger batch size. + ResetInputs(); + TRTEngineOpTestBase::AddSimpleInput(TensorShape({3, 2})); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + EXPECT_EQ(2, cache->size()); + EXPECT_EQ(1, cache->count({TensorShape({2, 2})})); + EXPECT_EQ(1, cache->count({TensorShape({3, 2})})); + + // Execute the op with an input that has different non-batch dimension. + ResetInputs(); + TRTEngineOpTestBase::AddSimpleInput(TensorShape({10, 10})); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + // Execute it again with an input that has the same non-batch dimension but + // smallest batch size. It should find the correct engine to use. + ResetInputs(); + TRTEngineOpTestBase::AddSimpleInput(TensorShape({1, 10})); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + EXPECT_EQ(3, cache->size()); // Should only create 3 engines in total. + EXPECT_EQ(1, cache->count({TensorShape({2, 2})})); + EXPECT_EQ(1, cache->count({TensorShape({3, 2})})); + EXPECT_EQ(1, cache->count({TensorShape({10, 10})})); +} + +TEST_F(TRTEngineOpTestBase, AllowBuildAtRuntime) { + TRTEngineOpTestBase::AddSimpleTrtOp(DT_FLOAT, /*max_cached_engines_count=*/1, + PartialTensorShape({-1, -1}), + /*use_implicit_batch=*/true, + /*allow_build_at_runtime=*/false); + + // Execute the op + TensorShape input_shape({2, 2}); + TRTEngineOpTestBase::AddSimpleInput(input_shape); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + + // Get the engine cache. + TRTEngineCacheResource* cache_resource = nullptr; + TF_ASSERT_OK(device_->resource_manager()->Lookup( + std::string(kTfTrtContainerName), std::string(kOpName), &cache_resource)); + core::ScopedUnref sc(cache_resource); + + // It should contain a placeholder with an empty cuda_engine (to mark that + // engine creation was not successful for the given input shape). + auto cache = &cache_resource->cache_; + EXPECT_EQ(1, cache->size()); + ASSERT_EQ(1, cache->count({input_shape})); + EngineContext* ectx = cache->at({input_shape}).get(); + EXPECT_EQ(ectx->GetCudaEngine(), nullptr); +} + +TEST_P(TRTEngineOpTestWithParam, ExplicitBatch) { + // Test inference in explicit batch mode with static input shapes. Static + // shapes in this context means that the TensorRT knows all the input shapes + // during engine creation time. + TRTEngineOpTestBase::AddSimpleTrtOp(DT_FLOAT, /*max_cached_engines_count=*/1, + /*shape=*/PartialTensorShape({1, 2}), + /*use_implicit_batch=*/false, + /*allow_build_at_runtime=*/true, + /*static_engine=*/param_.static_engine); + + TensorShape input_shape({1, 2}); + TRTEngineOpTestBase::AddSimpleInput(input_shape); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + + // Get the engine cache. + TRTEngineCacheResource* cache_resource = nullptr; + TF_ASSERT_OK(device_->resource_manager()->Lookup( + std::string(kTfTrtContainerName), std::string(kOpName), &cache_resource)); + core::ScopedUnref sc(cache_resource); + + auto cache = &cache_resource->cache_; + EXPECT_EQ(1, cache->size()); + ASSERT_EQ(1, cache->count({input_shape})); + EngineContext* ectx = cache->at({input_shape}).get(); + EXPECT_NE(ectx->GetCudaEngine(), nullptr); +} + +TEST_P(TRTEngineOpTestWithParam, DynamicShapes) { + // Test inference in explicit batch mode with dynamic input shapes. Dynamic + // shapes in this context means that some input shapes for TensorRT are + // unknown during engine creation time. When we create the network, the + // unknow shapes are repsesented as -1. Before we run inference, these shapes + // have to be specified by calling setBindingDimensions. + TRTEngineOpTestBase::AddSimpleTrtOp(DT_FLOAT, /*max_cached_engines_count=*/1, + /*shape=*/PartialTensorShape({-1, -1}), + /*use_implicit_batch=*/false, + /*allow_build_at_runtime=*/true, + param_.static_engine); + + TensorShape input_shape({1, 2}); + TRTEngineOpTestBase::AddSimpleInput(input_shape); + + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + + // Get the engine cache. + TRTEngineCacheResource* cache_resource = nullptr; + TF_ASSERT_OK(device_->resource_manager()->Lookup( + std::string(kTfTrtContainerName), std::string(kOpName), &cache_resource)); + core::ScopedUnref sc(cache_resource); + + auto cache = &cache_resource->cache_; + EXPECT_EQ(1, cache->size()); + ASSERT_EQ(1, cache->count({input_shape})); + EngineContext* ectx = cache->at({input_shape}).get(); + EXPECT_NE(ectx->GetCudaEngine(), nullptr); + + // Execute the op with an incompatible shape. + ResetInputs(); + TRTEngineOpTestBase::AddSimpleInput(TensorShape({1, 37})); + // Test that the op runs. This should fall back to native segment. + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + // We should still have a single engine that is not compatible with the input. + EXPECT_EQ(1, cache->size()); + EXPECT_EQ(0, cache->count({TensorShape({1, 37})})); +} + +template +class TRTEngineOpTest : public TRTEngineOpTestBase {}; + +using TypeList = ::testing::Types; +TYPED_TEST_SUITE(TRTEngineOpTest, TypeList); + +TYPED_TEST(TRTEngineOpTest, Basic) { + TRTEngineOpTestBase::AddSimpleTrtOp(DataTypeToEnum::v()); + + // Execute the op. + OpsTestBase::AddInputFromArray(TensorShape({1, 2}), + {TypeParam(0.0f), TypeParam(1.0f)}); + TF_ASSERT_OK(OpsTestBase::RunOpKernel()); + + // Verify the result. + Tensor* output = OpsTestBase::GetOutput(0); + EXPECT_THAT( + absl::Span(output->template flat().data(), + output->NumElements()), + ElementsAre(TypeParam(0.0f), TypeParam(2.0f))); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_resource_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_resource_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8d04574c7f83addc526c000c73f917a2a847ce3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_resource_ops.cc @@ -0,0 +1,310 @@ +/* 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 +#include +#include + +#include "absl/memory/memory.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_engine_instance.pb.h" // NOLINT +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/refcount.h" +#include "tensorflow/core/lib/io/record_reader.h" +#include "tensorflow/core/lib/io/record_writer.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/profiler/lib/traceme.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +using ::nvinfer1::IRuntime; + +class CreateTRTResourceHandle : public OpKernel { + public: + explicit CreateTRTResourceHandle(OpKernelConstruction* ctx) : OpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("resource_name", &resource_name_)); + } + + void Compute(OpKernelContext* ctx) override { + tensorflow::profiler::TraceMe activity( + "CreateTRTResourceHandle::Compute", + tensorflow::profiler::TraceMeLevel::kInfo); + { + mutex_lock l(mutex_); + if (!initialized_) { + AllocatorAttributes attr; + attr.set_on_host(true); + OP_REQUIRES_OK(ctx, ctx->allocate_temp(DT_RESOURCE, TensorShape({}), + &handle_, attr)); + + VLOG(1) << "Creating TRT engine cache resource handle for op " + << resource_name_ << " on device " << ctx->device()->name(); + handle_.scalar()() = + MakeResourceHandle( + ctx, std::string(kTfTrtContainerName), resource_name_); + initialized_ = true; + } + } + ctx->set_output(0, handle_); + } + + private: + string resource_name_; + Tensor handle_; + mutex mutex_; + bool initialized_ TF_GUARDED_BY(mutex_) = false; + + CreateTRTResourceHandle(const CreateTRTResourceHandle&) = delete; + void operator=(const CreateTRTResourceHandle&) = delete; +}; + +REGISTER_KERNEL_BUILDER(Name("CreateTRTResourceHandle") + .Device(DEVICE_GPU) + .HostMemory("resource_handle"), + CreateTRTResourceHandle); + +class InitializeTRTResource : public OpKernel { + public: + explicit InitializeTRTResource(OpKernelConstruction* ctx) : OpKernel(ctx) { + OP_REQUIRES_OK( + ctx, ctx->GetAttr("max_cached_engines_count", &max_cached_engines_)); + } + + void Compute(OpKernelContext* ctx) override { + tensorflow::profiler::TraceMe activity( + "InitializeTRTResource::Compute", + tensorflow::profiler::TraceMeLevel::kInfo); + ResourceHandle handle = HandleFromInput(ctx, 0); + core::RefCountPtr resource; + OP_REQUIRES_OK( + ctx, LookupOrCreateResource( + ctx, handle, &resource, + [this, ctx](TRTEngineCacheResource** resource) -> Status { + *resource = new TRTEngineCacheResource( + ctx, this->max_cached_engines_); + return OkStatus(); + })); + + auto allocator = resource->allocator_.get(); + OP_REQUIRES(ctx, allocator != nullptr, + errors::Internal("Not able to initialize TRT engine cache when " + "GPU allocator is empty.")); + OP_REQUIRES(ctx, resource->cache_.size() == 0, + errors::Internal("Expect engine cache to be empty, but got ", + resource->cache_.size(), " entries.")); + + // Get the file name. + const string& filename = ctx->input(1).scalar()(); + OP_REQUIRES(ctx, !filename.empty(), + errors::InvalidArgument("filename cannot be empty.")); + + // Parse the serialized engines and add them to the cache. + std::unique_ptr file; + OP_REQUIRES_OK(ctx, ctx->env()->NewRandomAccessFile(filename, &file)); + auto reader = std::make_unique(file.get()); + + uint64 offset = 0; + int num_loaded_engine = 0; + do { + tstring record; + Status status = reader->ReadRecord(&offset, &record); + if (absl::IsOutOfRange(status)) break; + + TRTEngineInstance engine_instance; + engine_instance.ParseFromString(record); + std::vector engine_input_shapes; + const auto& input_shapes = engine_instance.input_shapes(); + engine_input_shapes.reserve(input_shapes.size()); + for (const TensorShapeProto& shape : input_shapes) { + engine_input_shapes.emplace_back(shape); + } + + TrtUniquePtrType infer( + nvinfer1::createInferRuntime(TRTEngineCacheResource::GetLogger())); + infer->setGpuAllocator(allocator); + TrtUniquePtrType engine( + infer->deserializeCudaEngine( + engine_instance.serialized_engine().c_str(), + engine_instance.serialized_engine().size(), nullptr)); + auto raw_engine = engine.get(); + std::vector ctx_vec; + if (num_loaded_engine == 0) { + // Restore profiles if there are any. Currently only 1 engine is allowed + // in dynamic mode therefore we call this only for the 0th engine. + // it is a no-op in implicit batch mode. + OP_REQUIRES_OK(ctx, resource->profiles_.RestoreProfiles( + raw_engine, engine_input_shapes.size())); + OP_REQUIRES_OK(ctx, resource->profiles_.CreateExecutionContexts( + raw_engine, &ctx_vec)); + } else { + // Multiple engines are only available in static mode. For each engine + // we have only a single execution context. + ctx_vec.push_back(ExecutionContext::Create(raw_engine)); + } + resource->cache_.emplace(engine_input_shapes, + std::make_unique( + std::move(engine), std::move(ctx_vec))); + ++num_loaded_engine; + } while (1); + VLOG(1) << "Loaded " << num_loaded_engine << " TRT engines for op " + << handle.name() << " on device " << ctx->device()->name() + << " from file " << filename; + } + + private: + // Maximum number of cached engines + int max_cached_engines_; + + InitializeTRTResource(const InitializeTRTResource&) = delete; + void operator=(const InitializeTRTResource&) = delete; +}; + +REGISTER_KERNEL_BUILDER(Name("InitializeTRTResource") + .Device(DEVICE_GPU) + .HostMemory("resource_handle"), + InitializeTRTResource); + +class SerializeTRTResource : public OpKernel { + public: + explicit SerializeTRTResource(OpKernelConstruction* ctx) : OpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("delete_resource", &delete_resource_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("save_gpu_specific_engines", + &save_gpu_specific_engines_)); + } + + void Compute(OpKernelContext* ctx) override { + tensorflow::profiler::TraceMe activity( + "SerializeTRTResource::Compute", + tensorflow::profiler::TraceMeLevel::kInfo); + const string& resource_name = ctx->input(0).scalar()(); + const string& filename = ctx->input(1).scalar()(); + OP_REQUIRES(ctx, !filename.empty(), + errors::InvalidArgument("filename cannot be empty.")); + + // Lookup engine cache resource. + TRTEngineCacheResource* resource = nullptr; + OP_REQUIRES( + ctx, + ctx->resource_manager() + ->Lookup(std::string(kTfTrtContainerName), resource_name, &resource) + .ok(), + errors::NotFound("TRTEngineCacheResource not yet created")); + core::ScopedUnref unref_me(resource); + + // Terminate the calibration if any. + if (resource->calib_ctx_) resource->calib_ctx_->TerminateCalibration(); + + // Serialize the engines and write them to file. + std::unique_ptr file; + OP_REQUIRES_OK(ctx, ctx->env()->NewWritableFile(filename, &file)); + auto writer = std::make_unique(file.get()); + + int num_serialized_engines = 0; + if (save_gpu_specific_engines_) { + // If user requests TRT engines export, recursively create + // requisite directories. + const char* export_trt_engines_env = + getenv("TF_TRT_EXPORT_TRT_ENGINES_PATH"); + if (export_trt_engines_env) { + VLOG(1) << "Exporting TRT engines to directory: " + << export_trt_engines_env; + OP_REQUIRES_OK( + ctx, ctx->env()->RecursivelyCreateDir(export_trt_engines_env)); + } + + for (const auto& pair : resource->cache_) { + // Ignore engines that failed to build. + const std::unique_ptr& engine = pair.second; + if (!engine || !engine->GetCudaEngine()) continue; + + TRTEngineInstance engine_instance; + // Add input shapes. + const std::vector& engine_input_shapes = pair.first; + for (const TensorShape& shape : engine_input_shapes) { + shape.AsProto(engine_instance.add_input_shapes()); + } + // Add the serialized engine. + TrtUniquePtrType engine_data( + engine->GetCudaEngine()->serialize()); + engine_instance.set_serialized_engine(engine_data->data(), + engine_data->size()); + + if (export_trt_engines_env) { + const std::string engine_filename = + std::string(export_trt_engines_env) + "/" + resource_name; + std::unique_ptr engine_file; + OP_REQUIRES_OK( + ctx, ctx->env()->NewWritableFile(engine_filename, &engine_file)); + OP_REQUIRES_OK(ctx, engine_file->Append(StringPiece( + static_cast(engine_data->data()), + engine_data->size()))); + + const std::string dims_filename = + std::string(export_trt_engines_env) + "/dims-" + resource_name; + std::unique_ptr dims_file; + OP_REQUIRES_OK( + ctx, ctx->env()->NewWritableFile(dims_filename, &dims_file)); + + for (const TensorShape& shape : engine_input_shapes) { + OP_REQUIRES_OK(ctx, + dims_file->Append(StringPiece(shape.DebugString()))); + } + } + + OP_REQUIRES_OK( + ctx, writer->WriteRecord(engine_instance.SerializeAsString())); + ++num_serialized_engines; + } + } else { + VLOG(1) << "TRT Engines are not serialized for op: " << resource_name; + } + VLOG(1) << "Serialized " << num_serialized_engines << " TRT engines for op " + << resource_name << " on device " << ctx->device()->name() + << " to file " << filename; + + if (delete_resource_) { + VLOG(1) << "Destroying TRT engine cache resource for op " << resource_name + << " on device " << ctx->device()->name(); + OP_REQUIRES_OK(ctx, + ctx->resource_manager()->Delete( + std::string(kTfTrtContainerName), resource_name)); + } + } + + private: + bool delete_resource_ = false; + bool save_gpu_specific_engines_ = true; + + SerializeTRTResource(const SerializeTRTResource&) = delete; + void operator=(const SerializeTRTResource&) = delete; +}; + +REGISTER_KERNEL_BUILDER(Name("SerializeTRTResource").Device(DEVICE_GPU), + SerializeTRTResource); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_resource_ops_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_resource_ops_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..0059f369edbe6d847acb8fdc68ec0e95aead919e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/kernels/trt_engine_resource_ops_test.cc @@ -0,0 +1,412 @@ +/* Copyright 2019 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 +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/memory/memory.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2tensorrt/common/datavec.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_engine_instance.pb.h" // NOLINT +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_factory.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/resource_mgr.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/kernels/ops_testutil.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/lib/io/record_reader.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/file_system.h" +#include "tensorflow/core/platform/path.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/tstring.h" +#include "tensorflow/core/platform/types.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +struct TestParam { + nvinfer1::Dims dims; + bool dynamic_shape; + int n_inputs; +}; + +class TRTEngineResourceOpsTest + : public OpsTestBase, + public ::testing::WithParamInterface { + public: + TRTEngineResourceOpsTest() : param_(GetParam()) {} + + protected: + void Reset() { + for (auto& temp : tensors_) { + delete temp; + } + for (auto& temp : managed_outputs_) { + delete temp; + } + tensors_.clear(); + managed_outputs_.clear(); + inputs_.clear(); + } + + ITensorProxyPtr NetworkWith1Input(nvinfer1::INetworkDefinition* network, + ITensorProxyPtr input) { + // Add a unary layer. + nvinfer1::IUnaryLayer* layer = + network->addUnary(*input->trt_tensor(), nvinfer1::UnaryOperation::kEXP); + EXPECT_NE(nullptr, layer); + return layer->getOutput(0); + } + + // Constructs a network with two inputs, where the second input is a shape + // tensor. We take a slice of the first input with the size of the slice + // specified by the second input, assuming the first input is a 2D tensor. + // We then add the slice to itself to produce the output of the network. + ITensorProxyPtr NetworkWith2Inputs(nvinfer1::INetworkDefinition* network, + ITensorProxyPtr input) { + nvinfer1::Dims dims2{1, {2}}; + ITensorProxyPtr input2 = + network->addInput(absl::StrCat(IONamePrefixes::kInputPHName, 1).c_str(), + nvinfer1::DataType::kINT32, dims2); + EXPECT_NE(nullptr, input2->trt_tensor()); + + nvinfer1::Dims start{2, {0, 0}}; + nvinfer1::Dims stride{2, {1, 1}}; + auto slice_layer = + network->addSlice(*input->trt_tensor(), start, stride, stride); + EXPECT_NE(nullptr, slice_layer); + + slice_layer->setInput(2, *input2->trt_tensor()); + ITensorProxyPtr sliced_input = slice_layer->getOutput(0); + EXPECT_NE(nullptr, sliced_input->trt_tensor()); + + auto layer = network->addElementWise(*sliced_input->trt_tensor(), + *sliced_input->trt_tensor(), + nvinfer1::ElementWiseOperation::kSUM); + EXPECT_NE(nullptr, layer); + return layer->getOutput(0); + } + + TrtUniquePtrType CreateTRTEngine() { + TrtUniquePtrType builder( + nvinfer1::createInferBuilder(logger_)); + TrtUniquePtrType network; +#if IS_TRT_VERSION_GE(8, 0, 0, 0) + network = + TrtUniquePtrType(builder->createNetworkV2( + 1U << static_cast( + nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH))); +#else + network = + TrtUniquePtrType(builder->createNetworkV2( + 1U << static_cast( + nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH))); +#endif + + // Add the input. + nvinfer1::Dims dims = this->param_.dims; + if (this->param_.dynamic_shape) { + std::fill(dims.d, dims.d + dims.nbDims, -1); + } + const std::string in_name = StrCat(IONamePrefixes::kInputPHName, 0); + ITensorProxyPtr input = + network->addInput(in_name.c_str(), nvinfer1::DataType::kFLOAT, dims); + EXPECT_NE(nullptr, input->trt_tensor()); + // Mark the output. + ITensorProxyPtr output = + this->param_.n_inputs == 1 + ? this->NetworkWith1Input(network.get(), input) + : this->NetworkWith2Inputs(network.get(), input); + output->setName("output"); + network->markOutput(*output->trt_tensor()); + + // Build the engine + TrtUniquePtrType builder_config( + builder->createBuilderConfig()); + builder_config->setMaxWorkspaceSize(1 << 10); + builder->setMaxBatchSize(1); + + if (this->param_.dynamic_shape) { + TrtShapeOptimizationProfile profile; + profile.SetShapeTensorMask(network.get()); + const int n_input = param_.n_inputs; + // Set the input mask to true (no resource input) + std::vector input_mask(n_input, true); + profile.SetInputMask(input_mask); + // The for loop defines three optimization profiles for the network. + for (int i = 1; i <= 3; i++) { + std::vector shape_vec(n_input); + // Define a shape with all dimensions set to 3*i. + std::vector dimvec(this->param_.dims.nbDims, 3 * i); + TensorShape shape; + TF_CHECK_OK( + TensorShapeUtils::MakeShape(dimvec.data(), dimvec.size(), &shape)); + + const ITensorProxyPtr input = network->getInput(0); + const char* name = input->getName(); + VLOG(2) << "Defining profile for input " << name; + shape_vec[0] = shape; + if (this->param_.n_inputs == 2) { + // The shape of the shape tensor. + TF_CHECK_OK(TensorShapeUtils::MakeShape( + std::vector{param_.dims.nbDims}, &shape)); + shape_vec[1] = shape; + // Values of the shape tensor + Tensor shape_tensor(DT_INT32, shape); + // Define shape values {1, i}, where 1 is the value of the first dim, + // and i is the value of the second dimension. + std::vector vals{1, i}; + std::copy_n(vals.data(), vals.size(), + shape_tensor.flat().data()); + DataVec shape_values{{"one", {}}, {"two", shape_tensor}}; + TF_CHECK_OK(profile.CollectShapeValues(shape_values)); + } else { + TF_CHECK_OK(profile.CollectShapeValues({{"one", {}}})); + } + profile.AddShape(shape_vec); + } + std::vector input_partial_shapes; + TF_CHECK_OK(GetNetworkInputShapes(network.get(), &input_partial_shapes)); + profile.InitProfiles(input_partial_shapes, ProfileStrategy::kOptimal); + // Configure and build engine + TF_CHECK_OK(profile.ConfigureBuilder(builder.get(), builder_config.get(), + network.get())); + } + VLOG(2) << "ConfigureBuilder Finished"; + TrtUniquePtrType engine( + builder->buildEngineWithConfig(*network, *builder_config)); + VLOG(2) << "Engine constructed"; + EXPECT_NE(nullptr, engine); + return engine; + } + Logger& logger_ = *Logger::GetLogger(); + TestParam param_; +}; + +#if IS_TRT_VERSION_GE(7, 1, 3, 0) +constexpr std::array TestParameters = { + TestParam{nvinfer1::Dims{1, {1}}, false, 1}, + TestParam{nvinfer1::Dims{1, {1}}, true, 1}, + TestParam{nvinfer1::Dims{2, {3, 3}}, true, 2}}; +#else +constexpr std::array TestParameters = { + TestParam{nvinfer1::Dims{1, {1}}, false, 1}, + TestParam{nvinfer1::Dims{1, {1}}, true, 1}}; +#endif + +INSTANTIATE_TEST_CASE_P(EngineResourceOpsTestInstantiation, + TRTEngineResourceOpsTest, + ::testing::ValuesIn(TestParameters)); + +TEST_P(TRTEngineResourceOpsTest, Basic) { + // Create the GPU device. + std::unique_ptr device( + DeviceFactory::NewDevice("GPU", {}, "/job:worker/replica:0/task:0")); + ResourceMgr* rm = device->resource_manager(); + SetDevice(DEVICE_GPU, std::move(device)); + + // Create a resource handle. + const string container(kTfTrtContainerName); + const string resource_name = "myresource"; + Reset(); + TF_ASSERT_OK(NodeDefBuilder("op", "CreateTRTResourceHandle") + .Attr("resource_name", resource_name) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + TF_ASSERT_OK(RunOpKernel()); + ResourceHandle handle = + context_->mutable_output(0)->scalar()(); + + // Check that a resource hasn't been created yet. + TRTEngineCacheResource* resource = nullptr; + EXPECT_TRUE( + errors::IsNotFound(rm->Lookup(container, resource_name, &resource))); + + // Create a resource and use an empty file to initialize the resource. + Reset(); + Env* env = Env::Default(); + const string filename = io::JoinPath(testing::TmpDir(), "trt_engine_file"); + { + std::unique_ptr file; + TF_ASSERT_OK(env->NewWritableFile(filename, &file)); + } + TF_ASSERT_OK(NodeDefBuilder("op", "InitializeTRTResource") + .Input(FakeInput(DT_RESOURCE)) + .Input(FakeInput(DT_STRING)) + .Attr("max_cached_engines_count", 1) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + AddInputFromArray(TensorShape({}), {handle}); + AddInputFromArray(TensorShape({}), {filename}); + TF_ASSERT_OK(RunOpKernel()); + + // Check that the resource is registered with the resource manager and the + // cache of the resource is empty. + EXPECT_TRUE(rm->Lookup(container, resource_name, &resource).ok()); + EXPECT_EQ(0, resource->cache_.size()); + + // Create an engine and add it to the cache of the resource. + TrtUniquePtrType engine = CreateTRTEngine(); + ExecutionContext context = ExecutionContext::Create(engine.get()); + + std::vector engine_input_shape(1); + TF_ASSERT_OK(DimsAdapter(param_.dims).TensorShape(&(engine_input_shape[0]))); + if (param_.n_inputs > 1) { + engine_input_shape.push_back(TensorShape({1, 1})); + } + resource->cache_.emplace( + engine_input_shape, + std::make_unique(std::move(engine), std::move(context))); + // Check that the resource has multiple references before it is unregistered + // from the resource manager. + EXPECT_FALSE(resource->RefCountIsOne()); + + // Serialize the engine to a file and unregistered the resource from the + // resource manager. + Reset(); + TF_ASSERT_OK(NodeDefBuilder("op", "SerializeTRTResource") + .Attr("delete_resource", true) + .Input(FakeInput(DT_STRING)) + .Input(FakeInput(DT_STRING)) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + AddInputFromArray(TensorShape({}), {resource_name}); + AddInputFromArray(TensorShape({}), {filename}); + TF_ASSERT_OK(RunOpKernel()); + // Check that the resource now has only one reference. Detach the reference + // to the resource to destroy the resource. + EXPECT_TRUE(resource->RefCountIsOne()); + resource->Unref(); + + // Check that unregistering the resource from the resource manager returns + // an error as the resource has already been unregistered. + Reset(); + TF_ASSERT_OK(NodeDefBuilder("op", "DestroyResourceOp") + .Attr("ignore_lookup_error", false) + .Input(FakeInput(DT_RESOURCE)) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + AddInputFromArray(TensorShape({}), {handle}); + EXPECT_TRUE(errors::IsNotFound(RunOpKernel())); + + // Verify the file for the serialized engine. + std::unique_ptr file; + TF_ASSERT_OK(env->NewRandomAccessFile(filename, &file)); + auto reader = std::make_unique(file.get()); + uint64 offset = 0; + tstring record; + TF_ASSERT_OK(reader->ReadRecord(&offset, &record)); + TRTEngineInstance engine_instance; + engine_instance.ParseFromString(record); + EXPECT_EQ(param_.n_inputs, engine_instance.input_shapes_size()); + EXPECT_EQ(param_.dims.nbDims, engine_instance.input_shapes(0).dim_size()); + for (int i = 0; i < param_.dims.nbDims; i++) { + EXPECT_EQ(param_.dims.d[i], engine_instance.input_shapes(0).dim(i).size()); + } + EXPECT_TRUE(errors::IsOutOfRange(reader->ReadRecord(&offset, &record))); + + // Recreate the resource and use the file with the serialized engine to + // initialize the resource. + Reset(); + TF_ASSERT_OK(NodeDefBuilder("op", "InitializeTRTResource") + .Input(FakeInput(DT_RESOURCE)) + .Input(FakeInput(DT_STRING)) + .Attr("max_cached_engines_count", 1) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + AddInputFromArray(TensorShape({}), {handle}); + AddInputFromArray(TensorShape({}), {filename}); + TF_ASSERT_OK(RunOpKernel()); + + // Check that the resource is registered with the resource manager again and + // the cache of the resource is not empty. + EXPECT_TRUE(rm->Lookup(container, resource_name, &resource).ok()); + EXPECT_EQ(1, resource->cache_.size()); + if (this->param_.dynamic_shape) { + EXPECT_EQ(3, resource->profiles_.GetNumProfiles()); + EXPECT_EQ(3, resource->cache_.begin()->second->GetNumContexts()); + + if (this->param_.n_inputs == 1) { + // Check if profiles are restored correctly. + std::vector shapes(1); + // We create a shape vector that matches only profile 1. + TF_CHECK_OK( + TensorShapeUtils::MakeShape(std::vector{6}, &shapes[0])); + EXPECT_EQ(1, resource->profiles_.GetProfileNumber(shapes)); + } else { + // Check if shape values are restored correctly. + std::vector shapes(2); + // We create a shape vector that matches only profile 2. + TF_CHECK_OK( + TensorShapeUtils::MakeShape(std::vector{9, 9}, &shapes[0])); + TF_CHECK_OK( + TensorShapeUtils::MakeShape(std::vector{2}, &shapes[1])); + Tensor shape_tensor(DT_INT32, shapes[1]); + std::vector vals{1, 3}; + std::copy_n(vals.data(), vals.size(), + shape_tensor.flat().data()); + // DataVec names are not in used CollectShapeValues, only the order + // matters. + DataVec shape_values{{"one", {}}, {"two", shape_tensor}}; + TF_CHECK_OK(resource->profiles_.CollectShapeValues(shape_values)); + EXPECT_EQ(2, resource->profiles_.GetProfileNumber(shapes)); + } + } + // Check that the resource has multiple references before it is unregistered + // from the resource manager. + EXPECT_FALSE(resource->RefCountIsOne()); + + // Unregister the resource from the resource manager two times, expect that + // the second time produces an error. + Reset(); + TF_ASSERT_OK(NodeDefBuilder("op", "DestroyResourceOp") + .Attr("ignore_lookup_error", false) + .Input(FakeInput(DT_RESOURCE)) + .Finalize(node_def())); + TF_ASSERT_OK(InitOp()); + AddInputFromArray(TensorShape({}), {handle}); + TF_ASSERT_OK(RunOpKernel()); + EXPECT_TRUE(errors::IsNotFound(RunOpKernel())); + + // Check that the resource now has only one reference. Detach the reference + // to the resource to destroy resource. + EXPECT_TRUE(resource->RefCountIsOne()); + resource->Unref(); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/get_calibration_data_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/get_calibration_data_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..d66b0a21becd9a14959483446730343e8780e97c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/get_calibration_data_op.cc @@ -0,0 +1,36 @@ +/* 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/core/framework/common_shape_fns.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace tensorflow { + +REGISTER_OP("GetCalibrationDataOp") + .Input("resource_name: string") + .Output("serialized_resource: string") + .SetShapeFn(shape_inference::ScalarShape) + .SetIsStateful() + .Doc(R"doc( +Returns calibration data for the given resource name +)doc"); + +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/trt_engine_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/trt_engine_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..6ba67ab7a7fa38be203ae739508ced78761908ae --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/trt_engine_op.cc @@ -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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/core/framework/common_shape_fns.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace tensorflow { + +// NOTE: when making changes please follow +// https://www.tensorflow.org/guide/extend/op#backwards_compatibility to not +// break backward compatibility. +// +// TODO(laigd): consider making this op stateful. The only problem is it uses TF +// function which has to be stateless, but we can use function library as the +// key to cache the instantiated functions for different executor subgraphs. +REGISTER_OP("TRTEngineOp") + .Attr("serialized_segment: string") + .Attr("segment_func: func = {}") + .Attr("InT: list({bool,int8,float16,float32,int32,resource})") + .Attr("OutT: list({bool,int8,float16,float32,int32})") + .Attr("input_shapes: list(shape) = []") + .Attr("output_shapes: list(shape) = []") + .Attr("max_cached_engines_count: int = 1") + .Attr("max_batch_size: int = 1") + .Attr("workspace_size_bytes: int") + .Attr("precision_mode: {'FP32', 'FP16', 'INT8'}") + .Attr("calibration_data: string = ''") + .Attr("use_calibration: bool = true") + .Input("in_tensor: InT") + .Output("out_tensor: OutT") + .SetShapeFn([](::tensorflow::shape_inference::InferenceContext* c) { + std::vector output_shapes; + TF_RETURN_IF_ERROR(c->GetAttr("output_shapes", &output_shapes)); + + for (int i = 0; i < output_shapes.size(); i++) { + ::tensorflow::shape_inference::ShapeHandle shape; + shape_inference::ShapeHandle output_shape_handle; + TF_RETURN_IF_ERROR(c->MakeShapeFromPartialTensorShape( + output_shapes[i], &output_shape_handle)); + c->set_output(i, output_shape_handle); + } + + return OkStatus(); + }) + // Deprecated attributes. + .Attr("segment_funcdef_name: string = ''") + .Attr("cached_engine_batches: list(int) >= 0 = []") + .Attr("fixed_input_size: bool = true") + .Attr("static_engine: bool = true") + .Attr("profile_strategy: string = ''") + .Attr("use_explicit_precision: bool = false"); +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/trt_engine_resource_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/trt_engine_resource_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..0890b6e596653fbbaea40b03071b4d814526365d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/ops/trt_engine_resource_ops.cc @@ -0,0 +1,49 @@ +/* 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/core/framework/common_shape_fns.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace tensorflow { + +REGISTER_OP("CreateTRTResourceHandle") + .Attr("resource_name: string") + .Output("resource_handle: resource") + .SetIsStateful() + .SetShapeFn(shape_inference::ScalarShape); + +REGISTER_OP("InitializeTRTResource") + .Attr("max_cached_engines_count: int = 1") + .Input("resource_handle: resource") + .Input("filename: string") + .SetIsStateful() + .SetShapeFn(shape_inference::NoOutputs); + +REGISTER_OP("SerializeTRTResource") + .Attr("delete_resource: bool = false") + .Attr("save_gpu_specific_engines: bool = True") + .Input("resource_name: string") + .Input("filename: string") + .SetIsStateful() + .SetShapeFn(shape_inference::NoOutputs); + +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.cc new file mode 100644 index 0000000000000000000000000000000000000000..e78ed9b64bbd95758d8a69c1d16e2e66996ea2af --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.cc @@ -0,0 +1,30 @@ +/* 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 + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +const char* kTfTrtPluginVersion = "1"; + +const char* kTfTrtPluginNamespace = "TF"; + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.h new file mode 100644 index 0000000000000000000000000000000000000000..ad0e8196f7d538168ee72e77f56e3ea8bbbba4bb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/plugin/trt_plugin.h @@ -0,0 +1,94 @@ +/* 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_TF2TENSORRT_PLUGIN_TRT_PLUGIN_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_PLUGIN_TRT_PLUGIN_H_ + +#include + +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +extern const char* kTfTrtPluginVersion; +extern const char* kTfTrtPluginNamespace; + +// A wrapper class for TensorRT plugin. User application should inherit from +// this class to write custom kernels. +class TrtPlugin : public nvinfer1::IPluginV2Ext { + public: + TrtPlugin() { setPluginNamespace(kTfTrtPluginNamespace); } + + TrtPlugin(const void* serialized_data, size_t length) {} + + TrtPlugin(const TrtPlugin& rhs) : namespace_(rhs.namespace_) {} + + int initialize() noexcept override { return 0; } + + void terminate() noexcept override {} + + void destroy() noexcept override { delete this; } + + void setPluginNamespace(const char* plugin_namespace) noexcept override { + namespace_ = plugin_namespace; + } + + const char* getPluginNamespace() const noexcept override { + return namespace_.c_str(); + } + + protected: + template + void WriteToBuffer(const T& val, char** buffer) const { + *reinterpret_cast(*buffer) = val; + *buffer += sizeof(T); + } + + template + T ReadFromBuffer(const char** buffer) { + T val = *reinterpret_cast(*buffer); + *buffer += sizeof(T); + return val; + } + + private: + std::string namespace_; +}; + +template +class TrtPluginRegistrar { + public: + TrtPluginRegistrar() { + getPluginRegistry()->registerCreator(creator, kTfTrtPluginNamespace); + } + + private: + T creator; +}; + +#define REGISTER_TFTRT_PLUGIN(name) \ + static ::tensorflow::tensorrt::TrtPluginRegistrar \ + plugin_registrar_##name {} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_PLUGIN_TRT_PLUGIN_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a7506af31f6ce904094a9f44b315e264b6f8cb1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment.cc @@ -0,0 +1,1311 @@ +/* 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/tf2tensorrt/segment/segment.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/profiler/lib/traceme.h" +#include "tensorflow/core/util/env_var.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace segment { +namespace { +using absl::StrAppend; +using absl::StrAppendFormat; +using absl::StrCat; +using absl::StrJoin; + +// A simple graph representation to mirror Graph. This structure +// helps saving memory since segmenter modifies the graph in place, preventing +// the need to create a copy of the graph. It is composed of edges and nodes. +// Nodes keep pointers to original TF nodes. +class SimpleNode; +class SimpleGraph; +class SimpleEdge { + public: + SimpleEdge(int id, SimpleNode* src, int src_port, SimpleNode* dst, + int dst_port, bool is_control = false) + : id_(id), + src_(src), + src_port_(src_port), + dst_(dst), + dst_port_(dst_port), + control_(is_control) {} + ~SimpleEdge() {} + + SimpleNode* src() const { return src_; } + SimpleNode* dst() const { return dst_; } + int src_output() const { return src_port_; } + int dst_input() const { return dst_port_; } + int id() const { return id_; } + bool IsControlEdge() const { return control_; } + + private: + int id_; + SimpleNode* src_; + int src_port_; + SimpleNode* dst_; + int dst_port_; + bool control_; +}; + +class SimpleNode { + public: + SimpleNode(const Node* node, const int id); + + const std::vector& in_edges() const { return in_edges_; } + const std::vector& out_edges() const { return out_edges_; } + + std::vector in_nodes() const { + std::vector res; + res.reserve(in_edges_.size()); + for (const auto e : in_edges_) { + if (e) res.push_back(e->src()); + } + return res; + } + + std::vector out_nodes() const { + std::vector 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 Node* tf_node() const { return node_; } + int id() const { return id_; } + + private: + const Node* node_; + std::vector in_edges_; + std::vector out_edges_; + int id_; + + friend class SimpleGraph; +}; + +class SimpleGraph { + public: + explicit SimpleGraph(const Graph* g); + ~SimpleGraph(); + + void AddControlEdge(SimpleNode* src, SimpleNode* dst); + void AddEdge(SimpleNode* src, int out_port, SimpleNode* dst, int in_port); + void RemoveEdge(const SimpleEdge*); + SimpleNode* FindNodeId(int node_id) { + if (node_id < 0 || node_id > static_cast(nodes_.size())) { + return nullptr; + } + return nodes_[node_id]; + } + int num_node_ids() const { return nodes_.size(); } + const SimpleNode* source_node() const { return nodes_[Graph::kSourceId]; } + const SimpleNode* sink_node() const { return nodes_[Graph::kSinkId]; } + + private: + const Graph* g_; + std::vector nodes_; + std::vector edges_; + // free_edge_ids_ and free_node_ids_ contain freed indices. + std::set free_edge_ids_; + std::set free_node_ids_; +}; + +SimpleNode::SimpleNode(const Node* node, const int id) : node_(node), id_(id) { + if (node_) { + in_edges_.reserve(node_->in_edges().size()); + out_edges_.reserve(node_->out_edges().size()); + } +} + +SimpleGraph::SimpleGraph(const Graph* g) : g_(g) { + int n_nodes = g_->num_node_ids(); + nodes_.resize(n_nodes, nullptr); + nodes_[g->kSourceId] = new SimpleNode(g->source_node(), g->kSourceId); + nodes_[g->kSinkId] = new SimpleNode(g->sink_node(), g->kSinkId); + int n_edges = g->num_edge_ids(); + edges_.resize(n_edges, nullptr); + for (int i = 2; i < n_nodes; i++) { + const auto n = g->FindNodeId(i); + if (n) { + nodes_[i] = new SimpleNode(n, i); + } else { + free_node_ids_.insert(i); + } + } + for (int i = 0; i < n_edges; i++) { + const auto e = g->FindEdgeId(i); + if (e) { + const auto tfsrc = e->src(); + const auto tfdst = e->dst(); + bool is_control = e->IsControlEdge(); + auto src = nodes_[tfsrc->id()]; + auto dst = nodes_[tfdst->id()]; + auto edge = new SimpleEdge(i, src, e->src_output(), dst, e->dst_input(), + is_control); + edges_[i] = edge; + src->out_edges_.push_back(edge); + dst->in_edges_.push_back(edge); + } else { + free_edge_ids_.insert(i); + } + } +} + +void SimpleGraph::AddEdge(SimpleNode* src, int out_port, SimpleNode* dst, + int in_port) { + int i = edges_.size(); + if (!free_edge_ids_.empty()) { + auto it = free_edge_ids_.begin(); + i = *it; + free_edge_ids_.erase(it); + } else { + edges_.push_back(nullptr); + } + bool is_control = (out_port == Graph::kControlSlot); + is_control |= (in_port == Graph::kControlSlot); + auto edge = new SimpleEdge(i, src, out_port, dst, in_port, is_control); + edges_[i] = edge; + src->out_edges_.push_back(edge); + dst->in_edges_.push_back(edge); +} + +void SimpleGraph::AddControlEdge(SimpleNode* src, SimpleNode* dst) { + AddEdge(src, Graph::kControlSlot, dst, Graph::kControlSlot); +} + +void SimpleGraph::RemoveEdge(const SimpleEdge* edge) { + auto src = edge->src(); + auto dst = edge->dst(); + for (auto it = src->out_edges_.begin(); it != src->out_edges_.end(); ++it) { + if (*it == edge) { + src->out_edges_.erase(it); + break; + } + } + for (auto it = dst->in_edges_.begin(); it != dst->in_edges_.end(); ++it) { + if (*it == edge) { + dst->in_edges_.erase(it); + break; + } + } +} + +SimpleGraph::~SimpleGraph() { + for (auto x : nodes_) delete x; + for (auto x : edges_) delete x; +} + +// Define comparison functions for std::set with pointer keys so that behavior +// is deterministic. When using std::set with pointer key types, the items are +// sorted by pointer address which is non-deterministic. This can cause issues +// for INT8 mode because the graph is converted twice and non-determinism may +// cause a mismatch between the calibration tables of the conversions. +struct SimpleEdgePtrCompare { + bool operator()(const SimpleEdge* lhs, const SimpleEdge* rhs) const { + return lhs->id() < rhs->id(); + } +}; + +// Copied from TF ReverseDFS, which only works for Graph. +void StableDFS(const SimpleGraph& g, bool reverse, + const std::vector& start, + const std::function& enter, + const std::function& leave) { + // Stack of work to do. + struct Work { + const SimpleNode* node; + bool leave; // Are we entering or leaving n? + }; + std::vector stack(start.size()); + for (int i = 0; i < start.size(); ++i) { + stack[i] = Work{start[i], false}; + } + + auto get_nodes = [reverse](const SimpleNode* n) { + return reverse ? n->in_nodes() : n->out_nodes(); + }; + std::vector visited(g.num_node_ids(), false); + while (!stack.empty()) { + Work w = stack.back(); + stack.pop_back(); + + auto n = w.node; + if (w.leave) { + if (leave && !leave(n)) return; + continue; + } + + if (visited[n->id()]) continue; + visited[n->id()] = true; + if (enter && !enter(n)) return; + + // 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 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}); + } + } + } +} + +bool CanContractEdge(const SimpleEdge* edge, + const std::unique_ptr& graph) { + const auto src = edge->src(); + const auto dst = edge->dst(); + + // Can't contract edge if doing so would cause a cycle in the + // graph. So, if there is a directed path from 'src' to 'dst', other + // than 'edge' (or any other direct edge from 'src' to 'dst'), then + // combining 'src' and 'dst' will cause a cycle along that path. + // + // In practice, to avoid modifying the graph and to take advantage + // of existing graph functions, we perform an equivalent. + // 1. Get all nodes incoming to 'dst', excluding 'src' + // 2. Reverse DFS from those nodes + // 3. If reverse DFS reaches 'src' then we have a cycle + // + // TODO(aaroey): there are several problems with the current approach: + // 1. src->dst->src, this is not detected but it should be; + // 2. src->dst->...(any node sequence that doesn't contain src)...->dst, this + // is detected but it should not be. + // + // Note that it's fine that dst connects back to src indirectly (i.e. through + // a path with length > 1 that consists of intermedia nodes other than src). + // While loops is one example. + // + // The goal is to make sure that the trt subgraph: + // 1. has no loops (i.e. is a DAG), and + // 2. if there is a path in the subgraph from X to Y (X and Y are both nodes + // in the subgraph), then all paths from X to Y are in the subgraph. + // + // 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 dfs_start_nodes; + for (const SimpleNode* node : dst->in_nodes()) { + if (node != src) { + dfs_start_nodes.push_back(node); + } + } + 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; +} + +// TODO(bixia): put this to a common utility file. +string TensorPropertiesToString(const OpInfo::TensorProperties& prop) { + string s = StrCat(DataTypeString(prop.dtype()), ": "); + StrAppend(&s, "["); + if (prop.shape().unknown_rank()) { + StrAppend(&s, "?"); + } else { + StrAppend(&s, StrJoin(prop.shape().dim(), ",", + [](string* out, const TensorShapeProto_Dim& d) { + StrAppendFormat(out, "%d", d.size()); + })); + } + StrAppend(&s, "]"); + return s; +} + +string TensorPropertiesToString( + const std::vector& properties) { + return StrJoin(properties, "; ", + [](string* out, const OpInfo::TensorProperties& prop) { + StrAppend(out, TensorPropertiesToString(prop)); + }); +} + +// From the given list of input properties, returns the leading shape, which is +// the shape that determines the batch size of the operation. The leading shape +// is selected from the group of input shapes with the highest rank as follows: +// . If all of those shapes have non-negative values for the batch dimension, +// the leading shape is the one with the largest value for the batch +// dimension. +// . If some or all of those shapes have negative values for the batch +// dimension, and the rest of those shapes have 1 for the batch dimension, +// the leading shape is the first of those shapes with a negative value for +// the batch dimension. +// . Otherwise, we can't determine the leading shape for the operation and +// have to exclude the operation from TRT. +// +// Examples: +// case-1: a[1,3,4] + b[2,3,4] => leading shape [2,3,4] +// case-2: a[2,3,4] + b[scalar] => leading shape [2,3,4] +// case-3: a[-1,3,4] + b[1,3,4] => leading shape [-1,3,4] +// case-4: a[-1,3,4] + b[2,3,4] => no leading shape +// +// We have to return "no leading shape" for case-4 to exclude such operation +// from being translated for this reason: +// The actually input for "a" have to be in the shape of [2,3,4] for the +// operation to be valid. On the other hand, if we translate the operation +// to implicit batch mode, it will becomes a[3,4]+b[3,4] which is valid for +// any input shape of "a". +// +// This routine assumes the input program is valid. For example, we shouldn't +// see invalid operation like a[2,3,4] + b[3,3,4]. It also assumes the input +// properties is not empty and all input have known shapes. +// +// TODO(bixia): find a way to share this knowledge with the converter. +// TODO(bixia): investigate the use of symbolic shape analysis to improve +// segmentation, such as by requiring the dynamic dimensions to have the same +// negative value. +std::optional FindLeadingShape( + absl::Span properties) { + DCHECK(!properties.empty()); + const TensorShapeProto* result; + int max_batch_dim_value; + auto choose_shape_with_higher_rank = [&](const TensorShapeProto* s) { + result = s; + max_batch_dim_value = s->dim_size() < 1 ? 1 : s->dim(0).size(); + }; + + DCHECK(!properties[0].shape().unknown_rank()); + choose_shape_with_higher_rank(&properties[0].shape()); + + for (const OpInfo::TensorProperties& p : properties.subspan(1)) { + DCHECK(!p.shape().unknown_rank()); + if (p.shape().dim_size() < result->dim_size()) continue; + + if (p.shape().dim_size() > result->dim_size()) { + choose_shape_with_higher_rank(&p.shape()); + continue; + } + + // Among the shapes with the same rank, choose the one with a dynamic batch + // size. If no shapes have a dynamic batch size, choose the one with the + // largest size. + if (result->dim_size() < 1) continue; + + if (p.shape().dim(0).size() < 0 || result->dim(0).size() < 0) { + if (p.shape().dim(0).size() < 0 && result->dim(0).size() >= 0) { + result = &p.shape(); + } else { + max_batch_dim_value = + std::max(max_batch_dim_value, p.shape().dim(0).size()); + } + + continue; + } + + if (p.shape().dim(0).size() > result->dim(0).size()) { + result = &p.shape(); + max_batch_dim_value = result->dim(0).size(); + } + } + + if (result->dim_size() > 0 && result->dim(0).size() < 0) { + // dynamic batch size + if (max_batch_dim_value <= 1) { + return result; + } else { + return std::nullopt; + } + } + + return result; +} + +// Returns the inputs that are relevant to determinate the batch size of the +// operation. This routine handles the following cases: +// . Operations that support implicit broadcasting, such as operation mul. +// In this case, we need to inspect all the inputs in order to determine the +// batch size of the operation. +// . Special cases. Such as "Conv2DBackpropInput", "Conv3DBackpropInputV2". +// . The batch size of a operation is determined by the first input of the +// operation. +absl::Span GetInputsToDeterminateBatchSize( + const Node* node, const std::vector& all_inputs) { + // TODO(bixia): Find a way to share this knowledge with the converter. + static std::set broadcast_supporting_ops = { + // ops corresponding to ConvertBinary in the converter + "Add", + "AddV2", + "Mul", + "Sub", + "Div", + "FloorDiv", + "RealDiv", + "Minimum", + "Maximum", + "Pow", + // other ops that need to need GetTrtBroadcastShape to convert + "BiasAdd", + "SquaredDifference", + "BatchMatMul", + "BatchMatMulV2", + }; + const string& op = node->def().op(); + + if (op == "Conv2DBackpropInput" || op == "Conv3DBackpropInputV2") { + DCHECK_EQ(all_inputs.size(), 3); + return absl::MakeSpan(all_inputs).subspan(2, 1); + } + + if (broadcast_supporting_ops.count(op)) { + return absl::MakeSpan(all_inputs); + } + + // This is the common case for the operations that don't support implicit + // broadcasting: the first operand determines its batch size. All otherwise + // cases are handled before reaching here. + return absl::MakeSpan(all_inputs).subspan(0, 1); +} + +// Returns true if the operation we can remove the implicit batch of the +// operation. +// +// In particular, if the input shape has dynamic rank or the input shape rank +// is less than 2, we can't remove the implicit batch dimension and generate +// a new operation for TRT translation. +bool OperationCanBeTranslatedToImplicitBatch( + const grappler::GraphProperties* graph_properties, const Node* node) { + VLOG(3) << "process node " << node->name(); + if (node->num_inputs() == 0) return true; + if (!graph_properties || !graph_properties->HasInputProperties(node->name())) + return false; + + VLOG(3) << "input shapes " + << TensorPropertiesToString( + graph_properties->GetInputProperties(node->name())); + + const std::vector& all_input_properties = + graph_properties->GetInputProperties(node->name()); + absl::Span input_properties = + GetInputsToDeterminateBatchSize(node, all_input_properties); + if (absl::c_any_of(input_properties, [](const OpInfo::TensorProperties& p) { + return p.shape().unknown_rank(); + })) { + return false; + } + + std::optional leading_shape = + FindLeadingShape(input_properties); + return leading_shape.has_value() && leading_shape.value()->dim_size() >= 2; +} + +// Returns true if we can't be sure that the operand with the given properties +// won't have negative values for non-batch dimensions. +// +bool HasDynamicNonBatchDimension(const OpInfo::TensorProperties& prop) { + const TensorShapeProto& shape = prop.shape(); + if (shape.unknown_rank()) return true; + + // Scalar is a well specified shape, and TRT supports implicit broadcasting + // from scalar to other shapes. + if (shape.dim_size() == 0) return false; + for (int i = 1; i < shape.dim_size(); ++i) { + // The value of a dynamic dimension can be other negative values besides + // -1, representing the symbolic group of the dimension. + if (shape.dim(i).size() <= -1) { + return true; + } + } + return false; +} + +// Returns true if we can't be sure that the operation won't have dynamic +// non-batch dimension involved. We only check the shape of the first output +// assuming shape inference already propagates the shapes. +bool OperationHasDynamicNonBatchDimension( + const grappler::GraphProperties* graph_properties, const Node* node) { + VLOG(3) << "process node " << node->name(); + // If the node doesn't have any input or output, not computation is involved. + if (node->num_inputs() == 0 || node->num_outputs() == 0) return false; + + // If the node doesn't have output properties, return true to be conservative. + if (!graph_properties->HasOutputProperties(node->name())) return true; + VLOG(3) << "output shapes " + << TensorPropertiesToString( + graph_properties->GetOutputProperties(node->name())); + return HasDynamicNonBatchDimension( + graph_properties->GetOutputProperties(node->name()).at(0)); +} + +void ContractEdge(SimpleEdge* edge, SimpleGraph* graph, + std::vector* remove_edges) { + // Transfer all inputs and outputs of 'dst' to 'src' except edges + // connecting the two. + auto src = edge->src(); + auto dst = edge->dst(); + + // We can use '0' for input/output index because we don't need them + // to be accurate for the way we are using the graph. + std::vector in_edges(dst->in_edges().begin(), + dst->in_edges().end()); + for (const SimpleEdge* in_edge : in_edges) { + if (in_edge->IsControlEdge()) { + if (in_edge->src() != src) { + SimpleEdge* e = const_cast(in_edge); + graph->AddControlEdge(e->src(), src); + } + } else { + if (in_edge->src() != src) { + SimpleEdge* e = const_cast(in_edge); + if (e->src() == graph->source_node()) { + graph->AddEdge(e->src(), e->src_output(), src, Graph::kControlSlot); + } else { + graph->AddEdge(e->src(), e->src_output(), src, 0 /* input index */); + } + } + } + } + + std::vector out_edges(dst->out_edges().begin(), + dst->out_edges().end()); + for (const SimpleEdge* out_edge : out_edges) { + if (out_edge->IsControlEdge()) { + SimpleEdge* e = const_cast(out_edge); + graph->AddControlEdge(src, e->dst()); + } else { + SimpleEdge* e = const_cast(out_edge); + if (e->dst() == graph->sink_node()) { + VLOG(1) << " edge to sink node " << src->name() << " -> " + << e->dst()->name(); + graph->AddEdge(src, Graph::kControlSlot, e->dst(), e->dst_input()); + } else { + graph->AddEdge(src, 0 /* output index */, e->dst(), e->dst_input()); + } + } + } + + // Return the edges that must be removed to disconnect 'dst' from + // the graph. We don't actually remove 'dst' since the caller holds + // references to all the nodes. + for (const auto& in_edge : dst->in_edges()) { + remove_edges->push_back(in_edge); + } + for (const auto& out_edge : dst->out_edges()) { + remove_edges->push_back(out_edge); + } +} + +// Returns a batch size representation for a segment that only contains the +// given node. +ClusterBatchSize GetClusterBatchSizeForNode( + const grappler::GraphProperties* graph_properties, const Node* node, + bool use_implicit_batch) { + ClusterBatchSize cluster_batch_size; + if (!use_implicit_batch || !node || node->num_inputs() == 0) { + return cluster_batch_size; + } + + const NodeDef& node_def = node->def(); + if (node_def.attr().count(kTftrtOpMaxBatchSizeAttr)) { + cluster_batch_size.SetMaxBatchSize( + node_def.attr().at(kTftrtOpMaxBatchSizeAttr).i()); + } + + // As shape inference cannot provide any useful information about the batch + // size, we keep it as missing. + if (!graph_properties || + !graph_properties->HasInputProperties(node->name())) { + VLOG(3) << "doesn't have input property"; + return cluster_batch_size; + } + + const std::vector& input_properties = + graph_properties->GetInputProperties(node->name()); + std::optional optional_leading_shape = + FindLeadingShape(GetInputsToDeterminateBatchSize(node, input_properties)); + DCHECK(optional_leading_shape.has_value()); + const TensorShapeProto* leading_shape = optional_leading_shape.value(); + DCHECK(!leading_shape->unknown_rank() && leading_shape->dim_size() >= 2); + VLOG(3) << "set batch size as " << leading_shape->dim(0).size(); + return cluster_batch_size.SetBatchSize(leading_shape->dim(0).size()); +} + +void AddSegmentForNode(const grappler::GraphProperties* graph_properties, + std::vector>* segments, + SimpleNode* node, + const DeviceNameUtils::ParsedName& device_name, + bool use_implicit_batch) { + tensorflow::profiler::TraceMe activity( + "AddSegmentForNode", tensorflow::profiler::TraceMeLevel::kInfo); + ClusterProperty property( + GetClusterBatchSizeForNode(graph_properties, + node == nullptr ? nullptr : node->tf_node(), + use_implicit_batch), + device_name); + segments->emplace_back(node, std::move(property)); +} + +} // namespace + +Status ExportNonConversionReportToCSV( + string filename, + std::map>& nonconverted_ops_map, + string sep = "|") { + tensorflow::profiler::TraceMe activity( + "ExportNonConversionReportToCSV", + tensorflow::profiler::TraceMeLevel::kInfo); + std::unique_ptr csv_file; + auto open_status = Env::Default()->NewWritableFile(filename, &csv_file); + + if (!open_status.ok()) { + return errors::Internal("Failed to open output file: `", filename, "`"); + } + + LOG(WARNING) << "TF-TRT Non-Conversion Report saved at: `" << filename << "`"; + + std::ostringstream sstream; + sstream << "OP Name" << sep << "Reason" << sep << "Count" << std::endl; + + for (auto& op_details : nonconverted_ops_map) { + auto op_name = op_details.first; + auto op_data = op_details.second; + + for (auto& reject_data : op_data) { + auto reason = reject_data.first; + auto count = reject_data.second; + sstream << op_name << sep << reason << sep << count << std::endl; + } + } + + auto append_status = csv_file->Append(sstream.str()); + + if (!append_status.ok()) { + return errors::Internal("Error writing to output file `", filename, "`."); + } + + auto close_status = csv_file->Close(); + + if (!close_status.ok()) { + return errors::Internal("Error closing the file `", filename, + "`. The file might be corrupted."); + } + + return OkStatus(); +} + +string GenerateNonConversionReport( + std::map>& nonconverted_ops_map) { + // Fetch whether to print a detailed version of the TF-TRT conversion report. + // TF_TRT_SHOW_DETAILED_REPORT triggers three possible behaviors: + // - If Number >= 1: Print detailed non-conversion report on stdout. + // Usage: TF_TRT_SHOW_DETAILED_REPORT=1 + // - If non empty string: Exports the non-conversion report in CSV format at + // the path defined by the environment variable. + // This will also print the detailed non-conversion + // report on stdout. + // Usage: TF_TRT_SHOW_DETAILED_REPORT=/path/to/file.csv + // - Else: Print normal (undetailed) non-conversion report on + // stdout. + tensorflow::profiler::TraceMe activity( + "GenerateNonConversionReport", tensorflow::profiler::TraceMeLevel::kInfo); + + string detailed_report_var; + TF_CHECK_OK(ReadStringFromEnvVar("TF_TRT_SHOW_DETAILED_REPORT", + /*default_value=*/"", &detailed_report_var)); + + bool show_detailed_conversion_report = false; + + if (detailed_report_var != "") { + // Checking if `TF_TRT_SHOW_DETAILED_REPORT` env var is a string or a number + if (detailed_report_var.find_first_not_of("-0123456789") != string::npos) { + const Status status = ExportNonConversionReportToCSV( + detailed_report_var, nonconverted_ops_map); + + if (!status.ok()) { + // Log the error in case of issue, however do not stop execution. + LOG(ERROR) << "Problem encountered while generating the TF-TRT " + << "Non-Conversion Report in CSV Format:\n" + << status.message(); + } + show_detailed_conversion_report = true; + } else if (std::stoi(detailed_report_var) >= 1) { + show_detailed_conversion_report = true; + } + } + + string unsupported_op_report = + StrCat("\n\n", string(80, '#'), "\n", + "TensorRT unsupported/non-converted OP Report:"); + int total_nonconverted_ops{0}; + + // + using ReasonCounterVector = std::vector>; + // >> + using NotConvertedOPTuple = std::tuple; + + std::vector nonconverted_ops_vec; + + // Populate the vector from the map + for (auto& nonconverted_op_data : nonconverted_ops_map) { + int total_nonconverted_op{0}; + ReasonCounterVector reason_occurances_vect; + + auto op_name = nonconverted_op_data.first; + auto op_data = nonconverted_op_data.second; + + for (auto& notconversion_reason_data : op_data) { + auto reason_count = notconversion_reason_data.second; + total_nonconverted_op += reason_count; + reason_occurances_vect.push_back(notconversion_reason_data); + } + + // Sort in descending number of occurances for the reasons why a given + // TensorFlow OP was not converted. + std::sort(reason_occurances_vect.begin(), reason_occurances_vect.end(), + [](const std::pair& a, + const std::pair& b) -> bool { + return a.second > b.second; + }); + + nonconverted_ops_vec.push_back(std::make_tuple( + op_name, total_nonconverted_op, reason_occurances_vect)); + } + + // Sort the vector by descending OP names. + std::sort(nonconverted_ops_vec.begin(), nonconverted_ops_vec.end(), + [](const NotConvertedOPTuple& a, const NotConvertedOPTuple& b) { + return std::get<1>(a) > std::get<1>(b); + }); + + for (auto& notconverted_op_detail : nonconverted_ops_vec) { + auto& op_name = std::get<0>(notconverted_op_detail); + auto& op_total_nonconverted = std::get<1>(notconverted_op_detail); + total_nonconverted_ops += op_total_nonconverted; + + unsupported_op_report = StrCat(unsupported_op_report, "\n\t- ", op_name, + " -> ", op_total_nonconverted, "x"); + + if (show_detailed_conversion_report) { + auto& nonconverted_ops_details = std::get<2>(notconverted_op_detail); + + for (auto& nonconversion_details : nonconverted_ops_details) { + auto& reason = nonconversion_details.first; + auto& reason_count = nonconversion_details.second; + if (reason_count == 0) { + continue; + } + + unsupported_op_report = StrCat(unsupported_op_report, "\n\t\t- ", + "[Count: ", reason_count, "x] ", reason); + } + unsupported_op_report = StrCat(unsupported_op_report, "\n"); + } + } + + unsupported_op_report = + StrCat(unsupported_op_report, "\n", string(80, '-'), + "\n\t- Total nonconverted OPs: ", total_nonconverted_ops, + "\n\t- Total nonconverted OP Types: ", nonconverted_ops_map.size(), + "\nFor more information see https://docs.nvidia.com/deeplearning", + "/frameworks/tf-trt-user-guide/index.html#supported-ops.", "\n", + string(80, '#'), "\n"); + + return unsupported_op_report; +} + +Status SegmentGraph(const Graph* tf_graph, + const grappler::GraphProperties* graph_properties, + const std::function& candidate_fn, + const std::function& input_candidate_fn, + const std::function& output_candidate_fn, + const SegmentOptions& options, SegmentVector* segments) { + tensorflow::profiler::TraceMe activity( + "SegmentGraph", tensorflow::profiler::TraceMeLevel::kInfo); + if (!options.use_implicit_batch && !options.allow_dynamic_non_batch_dim) { + return errors::Internal( + "Explicit batch mode should allow dynamic non-batch dimensions"); + } + + if (options.use_implicit_batch && !options.maximum_batch_size.has_value()) { + return errors::Internal("Implicit batch mode requires maximum_batch_size"); + } + + if (!options.allow_dynamic_non_batch_dim && !graph_properties) { + return errors::Internal( + "Need graph propertities to disallow dynamic non-batch dimensions"); + } + + // Steps: + // 1. run the segmentation algorithm to find all the segments, which uses + // candidate_fn to determine the candidates segment nodes; + // 2. for each segments, remove the nodes that are inputs/outputs of the + // segment but are not eligible, using input/output_candidate_fn to + // determine the eligibilities; + // 3. convert the segment into expected return format and return the result. + + // --------------------------------- Step 1 --------------------------------- + auto graph = std::unique_ptr(new SimpleGraph(tf_graph)); + + // Fetch the user-provide TF operations denylisted for conversion by TF-TRT. + const absl::flat_hash_set tftrt_op_denylist = [] { + string tftrt_op_denylist_str; + TF_CHECK_OK(ReadStringFromEnvVar("TF_TRT_OP_DENYLIST", /*default_value=*/"", + &tftrt_op_denylist_str)); + absl::flat_hash_set tftrt_op_denylist{}; + for (const auto& x : str_util::Split(tftrt_op_denylist_str, ",")) { + tftrt_op_denylist.insert(x); + } + // Force a rehash of the flat hash set + tftrt_op_denylist.rehash(0); + return tftrt_op_denylist; + }(); + + // Use a union-find to collect the nodes that belong to the same + // segment. A node value of nullptr indicates that the node is not a candidate + // for TRT. + + std::map> nonconverted_ops_map = {}; + + // Parsing each node of the graph + std::vector> node_segments; + for (int i = 0; i < graph->num_node_ids(); ++i) { + SimpleNode* node = graph->FindNodeId(i); + + if (!node) { + VLOG(3) << "Node " << i << " doesn't exist in the graph"; + continue; + } + + const string node_op_type{node->tf_node()->type_string()}; + + auto exclude_node = [&](absl::string_view reason) { + VLOG(1) << "Not a TF-TRT candidate, " << "(Op type: " << node_op_type + << "), " << "(Op name: " << node->name() << "), " + << "(Reason: " << reason << ")"; + nonconverted_ops_map[node_op_type][string(reason)]++; + node = nullptr; + }; + std::optional device_name = + GetDeviceParsedName(node->tf_node()); + // GetDeviceParseName capitalizes the device type. + if (!device_name.has_value() || + (device_name->has_type && device_name->type != "GPU")) { + exclude_node("node can't be placed on GPU"); + } else if (options.exclude_node_list.count(node->name()) != 0) { + exclude_node( + "excluded by segmenter option. Most likely an input or " + "output node."); + } else if (options.use_implicit_batch && + !OperationCanBeTranslatedToImplicitBatch(graph_properties, + node->tf_node())) { + exclude_node( + "implicit batch mode requires input shape with at least two " + "dimensions"); + } else if (!options.allow_dynamic_non_batch_dim && + OperationHasDynamicNonBatchDimension(graph_properties, + node->tf_node())) { + exclude_node("dynamic non-batch dimensions not allowed"); + } else { + const Status status = candidate_fn(node->tf_node()); + if (!status.ok()) { + exclude_node(status.message()); + } else if (tftrt_op_denylist.contains(node->tf_node()->type_string())) { + // WARNING verbosity since the user explicitly requests this behavior. + LOG_WARNING_WITH_PREFIX + << "Denylisted as TF-TRT candidate, " + << "(Op type: " << node->tf_node()->type_string() << "), " + << "(Op name: " << node->name() << ")"; + exclude_node("Denylisted with the env var TF_TRT_OP_DENYLIST"); + } else { + VLOG(2) << "Accepted as a TF-TRT candidate, " + << "(Op type: " << node->tf_node()->type_string() << "), " + << "(Op name: " << node->name(); + } + } + AddSegmentForNode(graph_properties, &node_segments, node, *device_name, + options.use_implicit_batch); + } + + LOG(WARNING) << GenerateNonConversionReport(nonconverted_ops_map); + + // The segmentation algorithm below visits nodes in reverse topological order + // and attempts to merge nodes along output edges. That means that subgraphs + // grow from the output-side of the network towards the inputs. + // + // In general this is not guaranteed to produce a globally optimal + // segmentation. For example, consider graph with node {A, B, C, D} and edges + // {A->B, A->C, B->D, C->D), where A, B, D are trt compatible but C is not, so + // in theory we can choose to contract either A, B or B, D but not both, but + // here it always choose to contract B, D. + // + // 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 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(); + // 'node' must be a TRT candidate. + if (node_segments[node->id()].Value() == nullptr) { + VLOG(3) << "... not a TRT candidate"; + continue; + } + // Contract output edges to combine 'node' with output nodes. Repeat this + // step until no output edges can be further contracted. This is because + // contracting an output edge may unblock new edges for contracting. + ClusterBatchSize expected_batch_size = + node_segments[node->id()].Property().BatchSize(); + DeviceNameUtils::ParsedName expected_device_name = + node_segments[node->id()].Property().DeviceName(); + VLOG(3) << "batch size " << expected_batch_size; + while (true) { + std::set contract_edges; + // TODO(bixia): consider merging the loop to find the edges and the loop + // to contract the edges. + for (const SimpleEdge* out_edge : node->out_edges()) { + VLOG(3) << "... out node " << out_edge->dst()->name() << " ( " + << out_edge->dst()->id() << " <- " << node->id() << " )"; + if (out_edge->IsControlEdge()) { + VLOG(3) << "... ... Control Edge, Skipping"; + continue; + } + UnionFind* out_cluster = + &node_segments[out_edge->dst()->id()]; + // Out node must be a TRT candidate. + if (out_cluster->Value() == nullptr) { + VLOG(3) << "... ... not a TRT candidate"; + continue; + } + // Out node must have compatible batch size. + ClusterBatchSize out_batch_size = out_cluster->Property().BatchSize(); + ClusterBatchSize merged_batch_size = expected_batch_size; + if (!merged_batch_size.MergeIfCompatible(out_batch_size)) { + VLOG(3) << "... ... incompatible batch sizes " + << expected_batch_size.ToString() << " " + << out_batch_size.ToString(); + continue; + } + + const DeviceNameUtils::ParsedName& out_device_name = + out_cluster->Property().DeviceName(); + std::optional merged_device_name = + MergeIfCompatible(expected_device_name, out_device_name); + if (!merged_device_name.has_value()) { + VLOG(3) << "... ... incompatible device names " + << expected_device_name << " " << out_device_name; + continue; + } + + if (CanContractEdge(out_edge, graph)) { + VLOG(3) << "... ... can contract. new batch size " + << merged_batch_size.ToString(); + contract_edges.insert(out_edge); + expected_batch_size = merged_batch_size; + expected_device_name = *merged_device_name; + } else { + VLOG(3) << "... ... cannot contract, would form cycle"; + } + } + if (contract_edges.empty()) { + break; + } + // Contract edges and collect the adjacent nodes into the same + // segment/subgraph. + while (!contract_edges.empty()) { + const SimpleEdge* contract_edge = *contract_edges.begin(); + const SimpleNode* src = contract_edge->src(); + const SimpleNode* dst = contract_edge->dst(); + + VLOG(3) << "Merge " << src->name() << " <- " << dst->name() << " (" + << src->id() << " <- " << dst->id(); + TF_RETURN_IF_ERROR( + node_segments[src->id()].Merge(&node_segments[dst->id()])); + + // Contracting the edge leaves disconnected graph edges. + // Remove these from the graph and from 'contract_edges' so we + // don't visit them again. + SimpleEdge* e = const_cast(contract_edge); + std::vector remove_edges; + ContractEdge(e, graph.get(), &remove_edges); + + for (const SimpleEdge* r : remove_edges) { + contract_edges.erase(r); + graph->RemoveEdge(r); + } + } + if (expected_batch_size != + node_segments[node->id()].Property().BatchSize()) { + return errors::Internal( + "expected batch size is not the same as the actual batch size"); + } + if (expected_device_name != + node_segments[node->id()].Property().DeviceName()) { + return errors::Internal( + "expected device name is not the same as the actual device name"); + } + } + } + + // Collect the segments/subgraphs. Each subgraph is represented by a + // set of the names of the nodes in that subgraph. + + // A map from the segment identifier (currently the name of the root node of + // the segment tree) to the segment nodes set. + std::map sg_map; + + for (auto& u : node_segments) { + if ((u.Value() != nullptr) && (u.ParentValue() != nullptr)) { + sg_map[u.ParentValue()->name()].nodes.insert(u.Value()->tf_node()); + } + if ((u.Value() != nullptr) && (u.ParentValue() == u.Value())) { + sg_map[u.Value()->name()].property = u.Property(); + } + } + + // --------------------------------- Step 2 --------------------------------- + // Remove ineligible input/output nodes. + for (auto& itr : sg_map) { + std::set& segment_nodes = itr.second.nodes; + VLOG(1) << "Segment original size: " << segment_nodes.size(); + while (true) { + std::deque in_nodes_que, out_nodes_que; + // Find an input node that is not eligible and add it to the queue. + // Nodes that has no incoming edges should not be treated as "input", + // as there are really no inputs to them. Similar for output nodes. + for (auto node : segment_nodes) { + bool added = false; + for (const Edge* edge : node->in_edges()) { + if (!edge->IsControlEdge() && !edge->src()->IsSource() && + !segment_nodes.count(edge->src())) { // 'node' is an input node. + if (!input_candidate_fn(edge)) { + in_nodes_que.push_back(node); + added = true; + break; + } + } + } + if (added) continue; // Only adding the node once to either queue. + for (const Edge* edge : node->out_edges()) { + if (!edge->dst()->IsSink() && !edge->IsControlEdge() && + !segment_nodes.count(edge->dst())) { // 'node' is an output node. + if (!output_candidate_fn(edge)) { + out_nodes_que.push_back(node); + break; + } + } + } + } + if (in_nodes_que.empty() && out_nodes_que.empty()) { + // No more ineligible input/output nodes. + break; + } + // Now for each ineligible node, remove all of its inputs or outputs from + // the subgraph. + // + // It can be proven that, if the original subgraph: + // 1. is a DAG, and + // 2. all paths between two nodes in the subgraph are all inside the + // subgraph + // then after doing this operation the resulting subgraph will keep the + // same properties 1 and 2. + // + // For simplicity we use heuristics: for input and const output nodes + // remove all their inputs, and for non-const output nodes remove all + // their outputs. In this way, for common cases the number of removed + // nodes should be minimum. + auto remove_nodes = [&segment_nodes](bool is_input_nodes, + std::deque* que) { + // Run a BFS on the queue to find all the input/output nodes. + std::set visited; + std::set logged(que->begin(), que->end()); + while (!que->empty()) { + auto node = que->front(); + que->pop_front(); + if (!visited.insert(node).second) continue; + segment_nodes.erase(node); + for (auto in : (is_input_nodes || node->type_string() == "Const") + ? node->in_nodes() + : node->out_nodes()) { + if (segment_nodes.count(in)) { + que->push_back(in); + if (VLOG_IS_ON(2)) { + if (!logged.count(in)) { + VLOG(2) << "----> Need to remove node " << in->name() + << " because one of its " + << (is_input_nodes ? "output" : "input") + << " nodes in the graph was removed: " + << node->name(); + logged.insert(in); + } + } + } + } + } + }; + remove_nodes(true, &in_nodes_que); + remove_nodes(false, &out_nodes_que); + } + VLOG(1) << "Segment new size: " << segment_nodes.size(); + } + + // --------------------------------- Step 3 --------------------------------- + // Convert the segments into the expected return format + std::vector effective_nodes_counts; + for (const auto& itr : sg_map) { + const string& segment_root = itr.first; + // Return format does not require set comparator. + std::set segment_nodes( + itr.second.nodes.begin(), itr.second.nodes.end()); + if (VLOG_IS_ON(1) && !segment_nodes.empty()) { + string s; + for (auto node : segment_nodes) { + StrAppend(&s, "\n[Op type: ", node->type_string(), "] ", node->name()); + } + VLOG(1) << "Nodes in segment " << segments->size() + << " with parent=" << segment_root << ":" << s; + } + + const int num_effective_nodes = std::count_if( + segment_nodes.begin(), segment_nodes.end(), [](const Node* node) { + static auto noops = + new std::set{"Identity", "Snapshot", "StopGradient"}; + return noops->count(node->type_string()) == 0; + }); + + // Don't use segments whose number of effective nodes is small. + if (num_effective_nodes == 0 || + num_effective_nodes < options.minimum_segment_size) { + VLOG(1) << "Segment " << segments->size() << " has only " + << num_effective_nodes << " effective nodes, dropping"; + continue; + } + segments->emplace_back(itr.second.property, segment_nodes); + effective_nodes_counts.push_back(num_effective_nodes); + } + + // --------------------------------- Step 4 --------------------------------- + // If the number of segments exceeds max_engines, prune the smallest ones. + + int64_t max_trt_engine_ops; + TF_CHECK_OK(ReadInt64FromEnvVar("TF_TRT_MAX_ALLOWED_ENGINES", + /*default_value=*/20, &max_trt_engine_ops)); + + if (max_trt_engine_ops <= 0) { + LOG(WARNING) << "The environment variable TF_TRT_MAX_ALLOWED_ENGINES is " + << "<= 0. TF-TRT did not limit the number of TensorRT engines " + << "created."; + + } else { + if (segments->size() > max_trt_engine_ops) { + LOG(WARNING) << "A total of " << segments->size() << " segments with at " + << "least minimum_segment_size=" + << options.minimum_segment_size << " nodes have been found. " + << "TF-TRT will only convert the " << max_trt_engine_ops + << " largest segments. You can change this behavior by " + << "modifying the environment variable " + << "TF_TRT_MAX_ALLOWED_ENGINES=" << max_trt_engine_ops; + + // Stable sort of the segment indices according to their effective sizes. + std::vector indices(segments->size()); + std::iota(indices.begin(), indices.end(), 0); + + std::stable_sort(indices.begin(), indices.end(), + [&effective_nodes_counts](int i1, int i2) { + return effective_nodes_counts[i1] > + effective_nodes_counts[i2]; + }); + + // Create a mask of segments to keep. + std::vector mask = std::vector(segments->size(), false); + + for (int i = 0; i < max_trt_engine_ops; i++) { + mask[indices[i]] = true; + } + + // Gather the masked elements at the start of the array, in place. + int j = 0; + VLOG(1) << "The following segments have been accepted by TF-TRT:"; + for (int i = 0; i < segments->size(); i++) { + if (mask[i]) { + VLOG(1) << "[*] Segment " << i + << " [node count: " << effective_nodes_counts[i] + << "] accepted. Re-assigned " << "segment id=" << j; + segments->at(j) = segments->at(i); + j++; + } + } + + VLOG(1) << "The following segments have been rejected by TF-TRT:"; + for (int i = 0; i < segments->size(); i++) { + if (!mask[i]) { + VLOG(1) << "[*] Segment " << i + << " [node count: " << effective_nodes_counts[i] + << "] rejected."; + } + } + + // Resize the array. + segments->resize(max_trt_engine_ops); + } else { + LOG(WARNING) << "The environment variable TF_TRT_MAX_ALLOWED_ENGINES=" + << max_trt_engine_ops << " has no effect since there are " + << "only " << segments->size() << " TRT Engines with at " + << "least minimum_segment_size=" + << options.minimum_segment_size << " nodes."; + } + } + + return OkStatus(); +} + +} // namespace segment +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment.h new file mode 100644 index 0000000000000000000000000000000000000000..5028b62a51c82d10bb7a2985e98f3162ab7bf5a8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment.h @@ -0,0 +1,94 @@ +/* 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_TF2TENSORRT_SEGMENT_SEGMENT_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_SEGMENT_H_ + +#include +#include + +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2tensorrt/segment/union_find.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/grappler/costs/graph_properties.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace segment { + +constexpr char kTftrtOpMaxBatchSizeAttr[] = "_tftrt_op_max_batch_size"; + +struct SegmentOptions { + // This struct holds per graph segmenting parameters. + // Segment must contain at least this many nodes. + int minimum_segment_size = 2; + bool use_implicit_batch = true; + // The maximum batch size used to build the engines in the graph, when + // use_implicit_batch is true. + std::optional maximum_batch_size = std::nullopt; + // When use_implicit_batch is false or when we are building dynamic engines, + // we allow dynamic non-batch dimensions. + bool allow_dynamic_non_batch_dim = false; + // The name of the device to put the segment on. + std::set exclude_node_list; +}; + +struct NodePtrCompare { + bool operator()(const Node* lhs, const Node* rhs) const { + return lhs->name() < rhs->name(); + } +}; + +struct Segment { + Segment() {} + Segment(const ClusterProperty& property, + const std::set& nodes) + : property(property), nodes(nodes) {} + ClusterProperty property; + std::set nodes; +}; + +// Vector of segments, each entry contains a set of node pointers. +using SegmentVector = std::vector; + +// Get the subgraphs of a graph that can be handled by TensorRT. +// +// @param tf_graph Graph of the network. +// @graph_properties is the static graph properties. +// @param candidate_fn A function that returns OK for a Node* if +// that node can be handled by TensorRT. +// @param segments Returns the TensorRT segments/subgraphs. Each entry +// in the vector describes a subgraph by giving a set of the names of +// all the NodeDefs in that subgraph. +// @return the status. +Status SegmentGraph(const Graph* tf_graph, + const grappler::GraphProperties* graph_properties, + const std::function& candidate_fn, + const std::function& input_candidate_fn, + const std::function& output_candidate_fn, + const SegmentOptions& options, SegmentVector* segments); + +} // namespace segment +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_SEGMENT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..2780f012ad2d127573719f525ff3b7d1a0b889bb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/segment_test.cc @@ -0,0 +1,593 @@ +/* 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/tf2tensorrt/segment/segment.h" + +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/core/graph/testlib.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace segment { +namespace test { + +class SegmentTest : public ::testing::Test { + protected: + std::function MakeCandidateFn( + const std::set& node_names) { + return [node_names](const Node* node) -> Status { + if (node_names.find(node->name()) != node_names.end()) { + return OkStatus(); + } + return errors::NotFound("Not a user specified candidate"); + }; + } + + std::function MakeInputEdgeCandidateFn( + const std::set& node_names) { + return [node_names](const Edge* in_edge) -> bool { + return node_names.find(in_edge->dst()->name()) != node_names.end(); + }; + } + + std::function MakeOutputEdgeCandidateFn( + const std::set& node_names) { + return [node_names](const Edge* out_edge) -> bool { + return node_names.find(out_edge->src()->name()) != node_names.end(); + }; + } + + void RunTest(const Graph* graph, + const grappler::GraphProperties* graph_properties, + const std::set& candidates, + const std::set& input_candidates, + const std::set& output_candidates, + const std::vector>& expected_segments) { + SegmentVector segments; + TF_EXPECT_OK(SegmentGraph(graph, graph_properties, + MakeCandidateFn(candidates), + MakeInputEdgeCandidateFn(input_candidates), + MakeOutputEdgeCandidateFn(output_candidates), + segment_options_, &segments)); + ValidateSegment(segments, expected_segments); + } + + void RunTest(const Graph* graph, const std::set& candidates, + const std::set& input_candidates, + const std::set& output_candidates, + const std::vector>& expected_segments) { + RunTest(graph, nullptr, candidates, input_candidates, output_candidates, + expected_segments); + } + + void ValidateSegment(const SegmentVector& segments, + const std::vector>& expected_segments) { + EXPECT_EQ(expected_segments.size(), segments.size()); + for (int i = 0; i < segments.size(); ++i) { + std::set segment_node_names; + for (const Node* node : segments[i].nodes) { + segment_node_names.insert(node->name()); + } + const auto& expected = expected_segments[i]; + for (const auto& name : expected) { + EXPECT_TRUE(segment_node_names.count(name)) + << "Segment " << i << " is missing expected node: " << name; + } + if (segment_node_names.size() == expected.size()) continue; + for (const auto& name : segment_node_names) { + EXPECT_TRUE(expected.count(name)) + << "Unexpected node found in segment " << i << ": " << name; + } + } + } + + void DisableImplicitBatchMode() { + segment_options_.use_implicit_batch = false; + segment_options_.allow_dynamic_non_batch_dim = true; + } + + void EnableImplicitBatchModeForStaticEngine(int maximum_batch_size = 1000) { + segment_options_.use_implicit_batch = true; + segment_options_.maximum_batch_size = maximum_batch_size; + segment_options_.allow_dynamic_non_batch_dim = false; + } + + SegmentOptions segment_options_; +}; + +std::set operator-(const std::set& lhs, const string& rhs) { + std::set result = lhs; + CHECK(result.erase(rhs)); + return result; +} + +TEST_F(SegmentTest, Empty) { + Scope s = Scope::NewRootScope(); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + // Expect no segments/subgraphs. + DisableImplicitBatchMode(); + RunTest(&g, {}, {}, {}, {}); +} + +TEST_F(SegmentTest, Simple) { + // feed + // // \\ + // add0 add1 + // | \ / + // | add2 + // | / \\ + // add3 add4 + // \ / + // + Scope s = Scope::NewRootScope(); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT); + auto add0 = ops::Add(s.WithOpName("add0"), feed, feed); + auto add1 = ops::Add(s.WithOpName("add1"), feed, feed); + auto add2 = ops::Add(s.WithOpName("add2"), add0, add1); + auto add3 = ops::Add(s.WithOpName("add3"), add0, add2); + auto add4 = ops::Add(s.WithOpName("add4"), add2, add2); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + + // All Add operations are candidates, and we expect all of them to be + // collapsed into a single segment + const std::set all_adds = {"add0", "add1", "add2", "add3", "add4"}; + DisableImplicitBatchMode(); + RunTest(&g, all_adds, all_adds, all_adds, {all_adds}); + + // Make add1 not a candidate, and we expect all other Add operations to be + // collapsed into a single segment + auto without_add1 = all_adds - "add1"; + RunTest(&g, without_add1, without_add1, without_add1, {without_add1}); + + // Make add1 not a candidate and add2 not an input candidate, and we expect + // add0 and add2 are removed from the segment. + auto without_add2 = all_adds - "add2"; + RunTest(&g, without_add1, without_add2, without_add1, {{"add3", "add4"}}); + + // Making add2 not an input candidate itself won't affect anything. + RunTest(&g, all_adds, without_add2, all_adds, {all_adds}); + + // Making add1 not an input candidate. + RunTest(&g, all_adds, without_add1, all_adds, {without_add1}); + + // Making add3 not an output candidate doesn't affect anything, since it's + // output is sink. + auto without_add3 = all_adds - "add3"; + RunTest(&g, all_adds, all_adds, without_add3, {all_adds}); +} + +TEST_F(SegmentTest, WithDeviceAssignments) { + // feed + // // \\ + // add0 add1 + // | \ / + // | add2 + // | / \\ + // add3 add4 + // \ / + // + Scope s = Scope::NewRootScope(); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT); + auto add0 = ops::Add(s.WithOpName("add0"), feed, feed); + auto add1 = ops::Add(s.WithOpName("add1"), feed, feed); + auto add2 = ops::Add(s.WithOpName("add2"), add0, add1); + auto add3 = ops::Add(s.WithOpName("add3"), add0, add2); + auto add4 = ops::Add(s.WithOpName("add4"), add2, add2); + + const std::set all_adds = {"add0", "add1", "add2", "add3", "add4"}; + DisableImplicitBatchMode(); + + { + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + RunTest(&g, all_adds, all_adds, all_adds, {all_adds}); + } + + { + // Assigning add1 to CPU to exclude it from the cluster. + add1.node()->set_assigned_device_name("/device:CPU:0"); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + RunTest(&g, all_adds, all_adds, all_adds, {all_adds - "add1"}); + add1.node()->set_assigned_device_name(""); + } + + { + // Assigning operations add3 and add4 to another GPU to exclude the + // operation from the cluster. + constexpr char kGpu0[] = "/device:GPU:0"; + add0.node()->set_assigned_device_name(kGpu0); + add1.node()->set_assigned_device_name(kGpu0); + add2.node()->set_assigned_device_name(kGpu0); + constexpr char kGpu1[] = "/device:GPU:1"; + add3.node()->set_assigned_device_name(kGpu1); + add4.node()->set_assigned_device_name(kGpu1); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + RunTest(&g, all_adds, all_adds, all_adds, {{"add0", "add1", "add2"}}); + } + + { + // Assigning the operations to two compatible GPU devices resulting in + // one cluster with all operations. + constexpr char kGpuAny[] = "/device:GPU:*"; + add3.node()->set_assigned_device_name(kGpuAny); + add4.node()->set_assigned_device_name(kGpuAny); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + RunTest(&g, all_adds, all_adds, all_adds, {all_adds}); + } +} + +TEST_F(SegmentTest, AvoidCycle) { + // feed + // // \\ + // add0 add1 + // | \ / + // | add2 + // | / \\ + // add3 add4 + // \ / + // + Scope s = Scope::NewRootScope(); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT); + auto add0 = ops::Add(s.WithOpName("add0"), feed, feed); + auto add1 = ops::Add(s.WithOpName("add1"), feed, feed); + auto add2 = ops::Add(s.WithOpName("add2"), add0, add1); + auto add3 = ops::Add(s.WithOpName("add3"), add0, add2); + auto add4 = ops::Add(s.WithOpName("add4"), add2, add2); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + + // add2 is not a TRT candidate so there should be no segments generated. + const std::set without_add2 = {"add0", "add1", "add3", "add4"}; + DisableImplicitBatchMode(); + RunTest(&g, without_add2, without_add2, without_add2, {}); +} + +TEST_F(SegmentTest, Multiple) { + // feed + // // || \\ + // add0 add1 add7 + // | \ / / \\ + // | add2 / \\ + // | || \ | || + // | || add5 add8 + // | / \ / \ / + // add3 add4 add6 + // \ | / + // + Scope s = Scope::NewRootScope(); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT); + auto add0 = ops::Add(s.WithOpName("add0"), feed, feed); + auto add1 = ops::Add(s.WithOpName("add1"), feed, feed); + auto add7 = ops::Add(s.WithOpName("add7"), feed, feed); + auto add2 = ops::Add(s.WithOpName("add2"), add0, add1); + auto add5 = ops::Add(s.WithOpName("add5"), add2, add7); + auto add8 = ops::Add(s.WithOpName("add8"), add7, add7); + auto add3 = ops::Add(s.WithOpName("add3"), add0, add2); + auto add4 = ops::Add(s.WithOpName("add4"), add2, add5); + auto add6 = ops::Add(s.WithOpName("add6"), add5, add8); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + + const std::set all_adds = {"add0", "add1", "add2", "add3", "add4", + "add5", "add6", "add7", "add8"}; + // Make add5 not a TRT candidate, and we expect two segments. + auto without_add5 = all_adds - "add5"; + DisableImplicitBatchMode(); + RunTest(&g, without_add5, without_add5, without_add5, + {{"add0", "add1", "add2", "add3"}, {"add6", "add8"}}); + + // Make add8 not a candidate and add6 not an input candidate, then all direct + // and indirect inputs of add6 will be removed from the segment. + auto without_add8 = all_adds - "add8"; + auto without_add6 = all_adds - "add6"; + RunTest(&g, without_add8, without_add6, all_adds, {{"add3", "add4"}}); + + // Make add3 not a candidate and add0 not an output candidate, then all + // direct and indirect outputs of add0 will be removed from the segment. + auto without_add3 = all_adds - "add3"; + auto without_add0 = all_adds - "add0"; + RunTest(&g, without_add3, all_adds, without_add0, {{"add1", "add7", "add8"}}); +} + +TEST_F(SegmentTest, BigIfElse) { + // feed + // || + // add0 + // // \\ + // add1 add4 + // || || + // add2 add5 + // || || + // add3 add6 + // \\ // + // add7 + // || + // + Scope s = Scope::NewRootScope(); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT); + auto add0 = ops::Add(s.WithOpName("add0"), feed, feed); + auto add1 = ops::Add(s.WithOpName("add1"), add0, add0); + auto add2 = ops::Add(s.WithOpName("add2"), add1, add1); + auto add3 = ops::Add(s.WithOpName("add3"), add2, add2); + auto add4 = ops::Add(s.WithOpName("add4"), add0, add0); + auto add5 = ops::Add(s.WithOpName("add5"), add4, add4); + auto add6 = ops::Add(s.WithOpName("add6"), add5, add5); + auto add7 = ops::Add(s.WithOpName("add7"), add3, add6); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + + // Make add2 not a TRT candidate, and we expect 2 segments. + const std::set all_adds = {"add0", "add1", "add2", "add3", + "add4", "add5", "add6", "add7"}; + DisableImplicitBatchMode(); + RunTest(&g, all_adds - "add2", all_adds, all_adds, + {{"add0", "add1"}, {"add3", "add4", "add5", "add6", "add7"}}); +} + +TEST_F(SegmentTest, IdentityOps) { + Scope s = Scope::NewRootScope(); + auto feed = ops::Placeholder(s.WithOpName("feed"), DT_FLOAT); + auto identity0 = ops::Identity(s.WithOpName("identity0"), feed); + auto identity1 = ops::Identity(s.WithOpName("identity1"), identity0); + auto identity2 = ops::Identity(s.WithOpName("identity2"), identity1); + auto identity3 = ops::Identity(s.WithOpName("identity3"), identity2); + Graph g(OpRegistry::Global()); + TF_EXPECT_OK(s.ToGraph(&g)); + + const std::set all_identities = {"identity0", "identity1", + "identity2", "identity3"}; + // Identity ops are not counted as effective ops in the segment, so no segment + // will be formed in this case. + DisableImplicitBatchMode(); + RunTest(&g, all_identities, all_identities, all_identities, {}); +} + +// Testing implicit batch mode segmentation: it excludes the add-2 operation +// with a dynamic non-batch dimension. +TEST_F(SegmentTest, ExcludeAddWithDynamicNonBatchDimension) { + Scope s = Scope::NewRootScope(); + auto feed_0_shape = ops::Placeholder::Shape(PartialTensorShape({-1, 2, 3})); + auto feed_1_shape = ops::Placeholder::Shape(PartialTensorShape({-1, -1, 3})); + auto const_val = ops::Const(s, {1.0}, {}); + auto feed_0 = + ops::Placeholder(s.WithOpName("feed-1"), DT_FLOAT, feed_0_shape); + auto feed_1 = + ops::Placeholder(s.WithOpName("feed-2"), DT_FLOAT, feed_1_shape); + auto add_0 = ops::Add(s.WithOpName("add-0"), feed_0, const_val); + auto add_1 = ops::Add(s.WithOpName("add-1"), add_0, feed_0); + auto add_2 = ops::Add(s.WithOpName("add-2"), const_val, feed_1); + + grappler::GrapplerItem item; + item.fetch.push_back("add-2"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"add-0", "add-1", "add-2"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, + {all_nodes - "add-2"}); +} + +// Testing implicit batch mode segmentation: It excludes the reshape operation +// with a dynamic non-batch output dimension. +// TODO(bixia): hoist the check for reshape should not change batch size from +// the converter to the segmenter and add another test case for excluding +// a reshape without dynamic dimensions involved. +TEST_F(SegmentTest, ExcludeReshapeWithDynamicNonBatchDimensionInOutput) { + Scope s = Scope::NewRootScope(); + auto feed_0_shape = ops::Placeholder::Shape(PartialTensorShape({-1, 2, 3})); + auto const_val = ops::Const(s, {1.0}, {}); + auto feed_0 = + ops::Placeholder(s.WithOpName("feed-1"), DT_FLOAT, feed_0_shape); + auto add_0 = ops::Add(s.WithOpName("add-0"), feed_0, const_val); + auto reshape = ops::Reshape(s.WithOpName("reshape"), add_0, Input({6, -1})); + auto add_1 = ops::Add(s.WithOpName("add-1"), reshape, const_val); + + grappler::GrapplerItem item; + item.fetch.push_back("add-1"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"add-0", "reshape", "add-1"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, {}); +} + +TEST_F(SegmentTest, RankOneCannotUseImplicitBatch) { + Scope s = Scope::NewRootScope(); + auto input_0_shape = ops::Placeholder::Shape(TensorShape({3})); + auto input_1_shape = ops::Placeholder::Shape(TensorShape({3})); + auto input_0 = + ops::Placeholder(s.WithOpName("input-0"), DT_FLOAT, input_0_shape); + auto input_1 = + ops::Placeholder(s.WithOpName("input-1"), DT_FLOAT, input_1_shape); + auto const_val = ops::Const(s.WithOpName("const-scalar"), 1.0f, {}); + auto output_0 = ops::Add(s.WithOpName("output-0"), input_0, const_val); + auto output_1 = ops::Add(s.WithOpName("output-1"), input_1, const_val); + + grappler::GrapplerItem item; + item.fetch.push_back("output-0"); + item.fetch.push_back("output-1"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"const-scalar", "output-0", "output-1"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, {}); +} + +TEST_F(SegmentTest, TwoChainsDiffBatchSizes) { + Scope s = Scope::NewRootScope(); + auto input_0_shape = ops::Placeholder::Shape(TensorShape({2, 3})); + auto input_1_shape = ops::Placeholder::Shape(TensorShape({5, 3})); + auto input_0 = + ops::Placeholder(s.WithOpName("input-0"), DT_FLOAT, input_0_shape); + auto input_1 = + ops::Placeholder(s.WithOpName("input-1"), DT_FLOAT, input_1_shape); + auto const_val = ops::Const(s.WithOpName("const-scalar"), 1.0f, {}); + auto output_0 = ops::Add(s.WithOpName("output-0"), input_0, const_val); + auto output_1 = ops::Add(s.WithOpName("output-1"), input_1, const_val); + + grappler::GrapplerItem item; + item.fetch.push_back("output-0"); + item.fetch.push_back("output-1"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"const-scalar", "output-0", "output-1"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, + /*expected_segments=*/{{"output-0", "const-scalar"}}); + + // Converter will create engines based on the static batch size + EnableImplicitBatchModeForStaticEngine(1); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, + /*expected_segments=*/{{"output-0", "const-scalar"}}); +} + +TEST_F(SegmentTest, SameRankImplicitBroadcastingStaticBatchSize) { + Scope s = Scope::NewRootScope(); + auto input_0_shape = ops::Placeholder::Shape(TensorShape({2, 3, 1})); + auto input_1_shape = ops::Placeholder::Shape(TensorShape({1, 3, 4})); + auto input_2_shape = ops::Placeholder::Shape(TensorShape({2, 3, 4})); + auto input_0 = + ops::Placeholder(s.WithOpName("input-0"), DT_FLOAT, input_0_shape); + auto input_1 = + ops::Placeholder(s.WithOpName("input-1"), DT_FLOAT, input_1_shape); + auto input_2 = + ops::Placeholder(s.WithOpName("input-2"), DT_FLOAT, input_2_shape); + auto multiple = ops::Mul(s.WithOpName("multiple"), input_2, input_2); + auto output_0 = ops::Add(s.WithOpName("output-0"), input_0, multiple); + auto output_1 = ops::Add(s.WithOpName("output-1"), input_1, multiple); + + grappler::GrapplerItem item; + item.fetch.push_back("output-0"); + item.fetch.push_back("output-1"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"multiple", "output-0", "output-1"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, + {all_nodes}); +} + +TEST_F(SegmentTest, SameRankImplicitBroadcastingDynamicBatchSize) { + Scope s = Scope::NewRootScope(); + auto input_0_shape = ops::Placeholder::Shape(PartialTensorShape({-1, 2})); + auto input_1_shape = ops::Placeholder::Shape(TensorShape({1, 2})); + auto input_0 = + ops::Placeholder(s.WithOpName("input-0"), DT_FLOAT, input_0_shape); + auto input_1 = + ops::Placeholder(s.WithOpName("input-1"), DT_FLOAT, input_1_shape); + auto const_val = ops::Const(s.WithOpName("const-val"), 1.0f, {1, 1}); + auto add_0 = ops::Add(s.WithOpName("add-0"), input_0, const_val); + auto output_0 = ops::Add(s.WithOpName("output-0"), input_0, add_0); + + grappler::GrapplerItem item; + item.fetch.push_back("output-0"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"const-val", "add-0", "output-0"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, + {{"const-val", "add-0", "output-0"}}); +} + +TEST_F(SegmentTest, IncompatibleBatchSizes) { + Scope s = Scope::NewRootScope(); + auto input_0_shape = ops::Placeholder::Shape(PartialTensorShape({-1, 2})); + auto input_1_shape = ops::Placeholder::Shape(TensorShape({2, 2})); + auto input_0 = + ops::Placeholder(s.WithOpName("input-0"), DT_FLOAT, input_0_shape); + auto input_1 = + ops::Placeholder(s.WithOpName("input-1"), DT_FLOAT, input_1_shape); + auto const_val = ops::Const(s.WithOpName("const-val"), 1.0f, {2, 2}); + auto add_0 = ops::Add(s.WithOpName("add-0"), input_0, const_val); + auto output_0 = ops::Add(s.WithOpName("output-0"), input_0, add_0); + + grappler::GrapplerItem item; + item.fetch.push_back("output-0"); + TF_EXPECT_OK(s.ToGraphDef(&item.graph)); + + grappler::GraphProperties static_graph_properties(item); + TF_EXPECT_OK(static_graph_properties.InferStatically(true)); + + Graph g(OpRegistry::Global()); + TF_CHECK_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), item.graph, &g)); + + const std::set all_nodes = {"const-val", "add-0", "output-0"}; + EnableImplicitBatchModeForStaticEngine(); + RunTest(&g, &static_graph_properties, all_nodes, all_nodes, all_nodes, {}); +} +} // namespace test +} // namespace segment +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/union_find.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/union_find.cc new file mode 100644 index 0000000000000000000000000000000000000000..029fd316a35fe186467cd31463700d03d57bb057 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/union_find.cc @@ -0,0 +1,154 @@ +/* Copyright 2020 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/tf2tensorrt/segment/union_find.h" + +#include "absl/strings/str_format.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace segment { + +namespace { +template +inline bool CheckIfCompatible(const std::optional& a, + const std::optional& b) { + if (a.has_value() && b.has_value()) { + return *a == *b; + } + return true; +} + +template +inline bool UnifyValues(std::optional& a, std::optional& b) { + if (a.has_value()) { + b = a; + } else { + a = b; + } + return true; +} + +template +inline std::optional MergeCompatible(const std::optional& a, + const std::optional& b) { + DCHECK(CheckIfCompatible(a, b)); + return a.has_value() ? a : b; +} + +} // namespace + +ClusterBatchSize::ClusterBatchSize() + : batch_size_(std::nullopt), max_batch_size_(std::nullopt) {} + +bool ClusterBatchSize::operator==(const ClusterBatchSize& other) { + return batch_size_ == other.batch_size_ && + max_batch_size_ == other.max_batch_size_; +} + +ClusterBatchSize& ClusterBatchSize::SetBatchSize(int batch_size) { + SetBatchSize(static_cast>(batch_size)); + return *this; +} + +ClusterBatchSize& ClusterBatchSize::SetBatchSize( + const std::optional& batch_size) { + batch_size_ = MergeCompatible(batch_size_, batch_size); + if (batch_size_.has_value() && batch_size_.value() >= 0) { + SetMaxBatchSize(batch_size_); + } + return *this; +} + +bool ClusterBatchSize::HasBatchSize() const { return batch_size_.has_value(); } + +int ClusterBatchSize::GetBatchSize() const { + DCHECK(HasBatchSize()); + return batch_size_.value(); +} + +ClusterBatchSize& ClusterBatchSize::SetMaxBatchSize(int max_batch_size) { + SetBatchSize(static_cast>(max_batch_size)); + return *this; +} + +ClusterBatchSize& ClusterBatchSize::SetMaxBatchSize( + const std::optional& max_batch_size) { + max_batch_size_ = MergeCompatible(max_batch_size_, max_batch_size); + return *this; +} + +std::optional ClusterBatchSize::GetOptionalMaxBatchSize() const { + return max_batch_size_; +} + +bool ClusterBatchSize::MergeIfCompatible(const ClusterBatchSize& other) { + if (!CheckIfCompatible(batch_size_, other.batch_size_) || + !CheckIfCompatible(max_batch_size_, other.max_batch_size_)) { + return false; + } + + SetBatchSize(other.batch_size_); + SetMaxBatchSize(other.max_batch_size_); + return true; +} + +string ClusterBatchSize::ToString() const { + string s; + const auto append_optional_num = [&](const std::optional& num) { + if (num.has_value()) { + absl::StrAppendFormat(&s, "%d", num.value()); + } else { + absl::StrAppendFormat(&s, "?"); + } + }; + absl::StrAppendFormat(&s, "batch_size="); + append_optional_num(batch_size_); + absl::StrAppendFormat(&s, ", max_batch_size="); + append_optional_num(max_batch_size_); + return s; +} + +ClusterProperty::ClusterProperty(const ClusterBatchSize& batch_size, + const DeviceNameUtils::ParsedName& device_name) + : batch_size_(batch_size), device_name_(device_name) {} + +Status ClusterProperty::Merge(const ClusterProperty& other) { + ClusterBatchSize merged_batch_size(batch_size_); + if (!merged_batch_size.MergeIfCompatible(other.batch_size_)) { + return errors::Internal( + "trying to merge clusters with incompatible batch sizes."); + } + + std::optional merged_device_name = + MergeIfCompatible(device_name_, other.device_name_); + if (!merged_device_name.has_value()) { + return errors::Internal( + "trying to merge clusters with incompatible device assignment."); + } + + batch_size_ = std::move(merged_batch_size); + device_name_ = std::move(merged_device_name.value()); + return OkStatus(); +} + +} // namespace segment +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/union_find.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/union_find.h new file mode 100644 index 0000000000000000000000000000000000000000..84a558e42858d73464e60ca39bcda9572602701e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/segment/union_find.h @@ -0,0 +1,218 @@ +/* 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_TF2TENSORRT_SEGMENT_UNION_FIND_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_ + +#include "absl/types/optional.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/util/device_name_utils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +namespace segment { + +// ClusterBatchSize is a data structure to record the batch size we have seen +// for a cluster during segmentation. +// +// With the help of shape inference, all the dynamic batch sizes are converted +// to a negative integer number. +// If the number is -1, then nothing is known about the dynamic batch size. +// Ideally, we should not put nodes with -1 batch size into the same cluster, +// as they will likely have different batch sizes at runtime. However, we +// currently treat -1 as an equivalent class for simple implementation. We may +// need to revise this if it causes performance issues. +// If the number is strictly less than -1, then it represents a equivalent +// class. It is inferred that all the nodes with the same equivalent class +// (strictly less than -1) shall have the same batch size at runtime. +// +// When constructing clusters for implicit batch mode, we support both +// dynamic batch sizes and static batch sizes. As all the nodes inside the same +// cluster shall have the same batch size at runtime, we restrict nodes inside a +// cluster to either have the same dynamic batch size equivalent class or the +// same static batch size value. +// +// Besides, all the nodes with an annotated max batch size inside the same +// cluster shall have the same annotated max batch size. (It is allowed if +// part or all the nodes inside the cluster doesn't have annotated max batch +// size). Static batch sizes are treated as max batch size annotations. The +// converter max batch size is used for an OP with a dynamic batch size and no +// annotated max batch size. +// +// cluster: a = a1[1,3] + a1[1,3] +// ClusterBatchSize: batch_size_ = 1 +// max_batch_size_ = 1 +// +// cluster: b = b1[-1,3] + b2[-1, 3] +// ClusterBatchSize: batch_size_ = -1 +// max_batch_size_ = null +// +// cluster: c = c1[-2,3] + c2[-2, 3](max_batch_size=100) +// ClusterBatchSize: batch_size_ = -2 +// max_batch_size_ = 100 +// +// When constructing cluster for explicit batch mode, all ClusterBatchSize is +// irrelevant. +// + +class ClusterBatchSize { + public: + ClusterBatchSize(); + + bool operator==(const ClusterBatchSize& other); + bool operator!=(const ClusterBatchSize& other) { return !(*this == other); } + + // Sets the batch size assuming that the object doesn't have a batch size yet: + // A non-negative input representing a static batch size value. + // A negative input representing a dynamic batch size equivalent class. + ClusterBatchSize& SetBatchSize(int batch_size); + bool HasBatchSize() const; + int GetBatchSize() const; + + // Sets the max batch size assuming that the object doesn't have a max batch + // size yet. + ClusterBatchSize& SetMaxBatchSize(int max_batch_size); + std::optional GetOptionalMaxBatchSize() const; + + // Merge `other` into the current ClusterBatchSize if the two are not + // conflicting. Two ClusterBatchSizes are conflicting iff they both have a + // value and their values are different. + bool MergeIfCompatible(const ClusterBatchSize& other); + + // Returns a string for the batch size and the annotated max batch size. + // For the batch size: + // If the object has a static batch size, return a string representing a + // non-negative integer. + // If the object has a dynamic batch size, return a string representing a + // negative integer as an equivalent class. + // If the object doesn't have a batch size yet, return "?". + // For the annotated max batch size: + // If the cluster has annotated max batch size in at least one of the nodes, + // return a string representing the annotated max batch size. Otherwise, + // return "?". + std::string ToString() const; + + private: + ClusterBatchSize& SetBatchSize(const std::optional& batch_size); + ClusterBatchSize& SetMaxBatchSize(const std::optional& batch_size); + + std::optional batch_size_; + std::optional max_batch_size_; +}; + +inline std::ostream& operator<<(std::ostream& os, + const ClusterBatchSize& batch_size) { + return os << batch_size.ToString(); +} + +// Represents the accumulated properties of a cluster during segmentation, +// including information about batch size and device assignment. Clusters shall +// have compatible properties in order to be merged together. +class ClusterProperty { + public: + ClusterProperty() {} + ClusterProperty(const ClusterBatchSize& batch_size, + const DeviceNameUtils::ParsedName& device_name); + + // Returns the batch size of the cluster and compresses the path from this + // object to the root object. + const ClusterBatchSize& BatchSize() const { return batch_size_; } + + // Returns the device name of the cluster and compresses the path from this + // object to the root object. + const DeviceNameUtils::ParsedName& DeviceName() const { return device_name_; } + + Status Merge(const ClusterProperty& other); + + private: + ClusterBatchSize batch_size_; + DeviceNameUtils::ParsedName device_name_; +}; + +// Represents a disjoint set of copyable value with type T and accumulated +// property of the values with type P. Most of the methods in this class are +// side-effecting as they also compress the path from the object to the parent +// of its containing set. +template +class UnionFind { + public: + UnionFind() : size_(1), parent_(nullptr) {} + UnionFind(const T& v, const P& p) + : size_(1), parent_(nullptr), value_(v), property_(p) {} + UnionFind(const T& v, P&& p) + : size_(1), parent_(nullptr), value_(v), property_(p) {} + + // Returns the number of elements in the set and compresses the path from + // this object to the root of the set. + int Size() { return FindRoot()->size_; } + + // Returns the accumulated property of all the elements in the set and + // compresses the path from this object to the root of the set. + const P& Property() { return FindRoot()->property_; } + + // Merges this set with 'other'. This updates the size_ and property_ of the + // set. The size_ and property_ of 'other' becomes inaccessible as only the + // size_ and property_ of the root of the set is accessible. + Status Merge(UnionFind* other); + + // Retrieves the value for the root of the set. + const T& ParentValue() { return FindRoot()->value_; } + + // Returns the value for the object. + const T& Value() const { return value_; } + + private: + // Returns the root object for the set and compresses the path from this + // object to the root object. + UnionFind* FindRoot(); + + int size_; + UnionFind* parent_; + T value_; + P property_; +}; + +template +Status UnionFind::Merge(UnionFind* other) { + UnionFind* a = FindRoot(); + UnionFind* b = other->FindRoot(); + if (a == b) return OkStatus(); + + P merged_property(a->property_); + TF_RETURN_IF_ERROR(merged_property.Merge(b->property_)); + b->parent_ = a; + a->size_ += b->size_; + a->property_ = std::move(merged_property); + return OkStatus(); +} + +template +UnionFind* UnionFind::FindRoot() { + if (!parent_) return this; + // Path compression: update intermediate nodes to point to the root of the + // equivalence class. + parent_ = parent_->FindRoot(); + return parent_; +} + +} // namespace segment +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_SEGMENT_UNION_FIND_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInferPlugin_7_0.inc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInferPlugin_7_0.inc new file mode 100644 index 0000000000000000000000000000000000000000..40c658d68210271a7dec02fb3586ebe6a3e0a420 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInferPlugin_7_0.inc @@ -0,0 +1,95 @@ +// Auto-generated, do not edit. + +extern "C" { + +nvinfer1::IPluginV2* createRPNROIPlugin(int featureStride, int preNmsTop, + int nmsMaxOut, float iouThreshold, + float minBoxSize, float spatialScale, + nvinfer1::DimsHW pooling, + nvinfer1::Weights anchorRatios, + nvinfer1::Weights anchorScales) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(int, int, int, float, float, float, nvinfer1::DimsHW, nvinfer1::Weights, nvinfer1::Weights); + static auto func_ptr = LoadSymbol("createRPNROIPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createRPNROIPlugin"); + return func_ptr(featureStride, preNmsTop, nmsMaxOut, iouThreshold, minBoxSize, spatialScale, pooling, anchorRatios, anchorScales); +} + +nvinfer1::IPluginV2* createNormalizePlugin(const nvinfer1::Weights* scales, + bool acrossSpatial, + bool channelShared, float eps) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(const nvinfer1::Weights *, bool, bool, float); + static auto func_ptr = LoadSymbol("createNormalizePlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createNormalizePlugin"); + return func_ptr(scales, acrossSpatial, channelShared, eps); +} + +nvinfer1::IPluginV2* createPriorBoxPlugin( + nvinfer1::plugin::PriorBoxParameters param) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(nvinfer1::plugin::PriorBoxParameters); + static auto func_ptr = LoadSymbol("createPriorBoxPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createPriorBoxPlugin"); + return func_ptr(param); +} + +nvinfer1::IPluginV2* createAnchorGeneratorPlugin( + nvinfer1::plugin::GridAnchorParameters* param, int numLayers) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(nvinfer1::plugin::GridAnchorParameters *, int); + static auto func_ptr = LoadSymbol("createAnchorGeneratorPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createAnchorGeneratorPlugin"); + return func_ptr(param, numLayers); +} + +nvinfer1::IPluginV2* createNMSPlugin( + nvinfer1::plugin::DetectionOutputParameters param) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(nvinfer1::plugin::DetectionOutputParameters); + static auto func_ptr = LoadSymbol("createNMSPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createNMSPlugin"); + return func_ptr(param); +} + +nvinfer1::IPluginV2* createLReLUPlugin(float negSlope) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(float); + static auto func_ptr = LoadSymbol("createLReLUPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createLReLUPlugin"); + return func_ptr(negSlope); +} + +nvinfer1::IPluginV2* createReorgPlugin(int stride) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(int); + static auto func_ptr = LoadSymbol("createReorgPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createReorgPlugin"); + return func_ptr(stride); +} + +nvinfer1::IPluginV2* createRegionPlugin( + nvinfer1::plugin::RegionParameters params) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(nvinfer1::plugin::RegionParameters); + static auto func_ptr = LoadSymbol("createRegionPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createRegionPlugin"); + return func_ptr(params); +} + +nvinfer1::IPluginV2* createClipPlugin(const char* layerName, float clipMin, + float clipMax) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(const char *, float, float); + static auto func_ptr = LoadSymbol("createClipPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createClipPlugin"); + return func_ptr(layerName, clipMin, clipMax); +} + +nvinfer1::IPluginV2* createBatchedNMSPlugin( + nvinfer1::plugin::NMSParameters param) { + using FuncPtr = nvinfer1::IPluginV2 * ( *)(nvinfer1::plugin::NMSParameters); + static auto func_ptr = LoadSymbol("createBatchedNMSPlugin"); + if (!func_ptr) LogFatalSymbolNotFound("createBatchedNMSPlugin"); + return func_ptr(param); +} + +bool initLibNvInferPlugins(void* logger, const char* libNamespace) { + using FuncPtr = bool ( *)(void *, const char *); + static auto func_ptr = LoadSymbol("initLibNvInferPlugins"); + if (!func_ptr) LogFatalSymbolNotFound("initLibNvInferPlugins"); + return func_ptr(logger, libNamespace); +} + +} // extern "C" diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInfer_7_0.inc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInfer_7_0.inc new file mode 100644 index 0000000000000000000000000000000000000000..5e9d0d66eafca13703985a5b31930fafbf05a0be --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInfer_7_0.inc @@ -0,0 +1,47 @@ +// Auto-generated, do not edit. + +extern "C" { + +void* createInferBuilder_INTERNAL(void* logger, int version) { + using FuncPtr = void * (*)(void *, int); + static auto func_ptr = LoadSymbol("createInferBuilder_INTERNAL"); + if (!func_ptr) LogFatalSymbolNotFound("createInferBuilder_INTERNAL"); + return func_ptr(logger, version); +} + +void* createInferRefitter_INTERNAL(void* engine, void* logger, int version) { + using FuncPtr = void * (*)(void *, void *, int); + static auto func_ptr = LoadSymbol("createInferRefitter_INTERNAL"); + if (!func_ptr) LogFatalSymbolNotFound("createInferRefitter_INTERNAL"); + return func_ptr(engine, logger, version); +} + +void* createInferRuntime_INTERNAL(void* logger, int version) { + using FuncPtr = void * (*)(void *, int); + static auto func_ptr = LoadSymbol("createInferRuntime_INTERNAL"); + if (!func_ptr) LogFatalSymbolNotFound("createInferRuntime_INTERNAL"); + return func_ptr(logger, version); +} + +nvinfer1::ILogger* getLogger() { + using FuncPtr = nvinfer1::ILogger * (*)(); + static auto func_ptr = LoadSymbol("getLogger"); + if (!func_ptr) LogFatalSymbolNotFound("getLogger"); + return func_ptr(); +} + +int getInferLibVersion() { + using FuncPtr = int (*)(); + static auto func_ptr = LoadSymbol("getInferLibVersion"); + if (!func_ptr) LogFatalSymbolNotFound("getInferLibVersion"); + return func_ptr(); +} + +nvinfer1::IPluginRegistry* getPluginRegistry() { + using FuncPtr = nvinfer1::IPluginRegistry * (*)(); + static auto func_ptr = LoadSymbol("getPluginRegistry"); + if (!func_ptr) LogFatalSymbolNotFound("getPluginRegistry"); + return func_ptr(); +} + +} // extern "C" diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInfer_8_0.inc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInfer_8_0.inc new file mode 100644 index 0000000000000000000000000000000000000000..d4d13e518de28a5089a8c29fab3893141f604030 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/NvInfer_8_0.inc @@ -0,0 +1,48 @@ +// Auto-generated, do not edit. + +extern "C" { + +void* createInferBuilder_INTERNAL(void* logger, int version) noexcept { + using FuncPtr = void * (*)(void *, int); + static auto func_ptr = LoadSymbol("createInferBuilder_INTERNAL"); + if (!func_ptr) LogFatalSymbolNotFound("createInferBuilder_INTERNAL"); + return func_ptr(logger, version); +} + +void* createInferRefitter_INTERNAL(void* engine, void* logger, + int version) noexcept { + using FuncPtr = void* (*)(void*, void*, int); + static auto func_ptr = LoadSymbol("createInferRefitter_INTERNAL"); + if (!func_ptr) LogFatalSymbolNotFound("createInferRefitter_INTERNAL"); + return func_ptr(engine, logger, version); +} + +void* createInferRuntime_INTERNAL(void* logger, int version) noexcept { + using FuncPtr = void * (*)(void *, int); + static auto func_ptr = LoadSymbol("createInferRuntime_INTERNAL"); + if (!func_ptr) LogFatalSymbolNotFound("createInferRuntime_INTERNAL"); + return func_ptr(logger, version); +} + +nvinfer1::ILogger* getLogger() noexcept { + using FuncPtr = nvinfer1::ILogger * (*)(); + static auto func_ptr = LoadSymbol("getLogger"); + if (!func_ptr) LogFatalSymbolNotFound("getLogger"); + return func_ptr(); +} + +int getInferLibVersion() noexcept { + using FuncPtr = int (*)(); + static auto func_ptr = LoadSymbol("getInferLibVersion"); + if (!func_ptr) LogFatalSymbolNotFound("getInferLibVersion"); + return func_ptr(); +} + +nvinfer1::IPluginRegistry* getPluginRegistry() noexcept { + using FuncPtr = nvinfer1::IPluginRegistry * (*)(); + static auto func_ptr = LoadSymbol("getPluginRegistry"); + if (!func_ptr) LogFatalSymbolNotFound("getPluginRegistry"); + return func_ptr(); +} + +} // extern "C" diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/nvinfer_plugin_stub.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/nvinfer_plugin_stub.cc new file mode 100644 index 0000000000000000000000000000000000000000..e32468b5aafb2fcd305ee51c9ed0ff602c3d8230 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/nvinfer_plugin_stub.cc @@ -0,0 +1,58 @@ +/* Copyright 2019 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/platform/env.h" +#include "tsl/platform/dso_loader.h" +#include "third_party/tensorrt/NvInferPlugin.h" + +// Implements the TensorRT API by forwarding to TensorRT loaded from the DSO. + +namespace { +// Returns DSO handle or null if loading the DSO fails. +void* GetDsoHandle() { +#ifdef PLATFORM_GOOGLE + return nullptr; +#else + static auto handle = []() -> void* { + auto handle_or = tsl::internal::DsoLoader::GetNvInferPluginDsoHandle(); + if (!handle_or.ok()) return nullptr; + return handle_or.value(); + }(); + return handle; +#endif +} + +template +T LoadSymbol(const char* symbol_name) { + void* symbol = nullptr; + if (auto handle = GetDsoHandle()) { + tensorflow::Env::Default() + ->GetSymbolFromLibrary(handle, symbol_name, &symbol) + .IgnoreError(); + } + return reinterpret_cast(symbol); +} + +void LogFatalSymbolNotFound(const char* symbol_name) { + LOG(FATAL) << symbol_name << " symbol not found."; +} +} // namespace + +#if NV_TENSORRT_MAJOR < 7 +#error TensorRT version earlier than 7 is not supported. +#elif NV_TENSORRT_MAJOR == 7 || NV_TENSORRT_MAJOR == 8 +#include "tensorflow/compiler/tf2tensorrt/stub/NvInferPlugin_7_0.inc" +#else +#error This version of TensorRT is not supported. +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/nvinfer_stub.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/nvinfer_stub.cc new file mode 100644 index 0000000000000000000000000000000000000000..48217c9b510b38e17c7682215273818e7fe96a61 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/stub/nvinfer_stub.cc @@ -0,0 +1,60 @@ +/* Copyright 2019 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/platform/env.h" +#include "tsl/platform/dso_loader.h" +#include "third_party/tensorrt/NvInfer.h" + +// Implements the TensorRT API by forwarding to TensorRT loaded from the DSO. + +namespace { +// Returns DSO handle or null if loading the DSO fails. +void* GetDsoHandle() { +#ifdef PLATFORM_GOOGLE + return nullptr; +#else + static auto handle = []() -> void* { + auto handle_or = tsl::internal::DsoLoader::GetNvInferDsoHandle(); + if (!handle_or.ok()) return nullptr; + return handle_or.value(); + }(); + return handle; +#endif +} + +template +T LoadSymbol(const char* symbol_name) { + void* symbol = nullptr; + if (auto handle = GetDsoHandle()) { + tensorflow::Env::Default() + ->GetSymbolFromLibrary(handle, symbol_name, &symbol) + .IgnoreError(); + } + return reinterpret_cast(symbol); +} + +void LogFatalSymbolNotFound(const char* symbol_name) { + LOG(FATAL) << symbol_name << " symbol not found."; +} +} // namespace + +#if NV_TENSORRT_MAJOR < 7 +#error TensorRT version earlier than 7 is not supported. +#elif NV_TENSORRT_MAJOR == 7 +#include "tensorflow/compiler/tf2tensorrt/stub/NvInfer_7_0.inc" +#elif NV_TENSORRT_MAJOR == 8 +#include "tensorflow/compiler/tf2tensorrt/stub/NvInfer_8_0.inc" +#else +#error This version of TensorRT is not supported. +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/tensorrt_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/tensorrt_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..d66833c7a0728de443ca022ef09d7b06749f0a59 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/tensorrt_test.cc @@ -0,0 +1,287 @@ +/* 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. +==============================================================================*/ +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include +#include +#include + +#include "third_party/gpus/cuda/include/cuda.h" +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "xla/stream_executor/gpu/gpu_init.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/platform/test.h" +#include "third_party/tensorrt/NvInfer.h" +#include "third_party/tensorrt/NvInferPlugin.h" +#include "third_party/tensorrt/NvInferRuntimeCommon.h" + +#ifdef TF_TRT_USE_EFFICIENT_NMS_PLUGIN +#include "third_party/tensorrt/plugin/efficientNMSPlugin/efficientNMSPlugin.h" +namespace tensorflow { +namespace tensorrt { +std::unique_ptr +MakeNMSPluginCreator(const std::string& plugin_namespace = "tftrt") { + auto pluginCreator = + std::make_unique(); + pluginCreator->setPluginNamespace(plugin_namespace.c_str()); + std::string pluginType = std::string{pluginCreator->getPluginNamespace()} + + "::" + std::string{pluginCreator->getPluginName()} + + " version " + + std::string{pluginCreator->getPluginVersion()}; + VLOG(0) << "Created plugin type " << pluginType; + return pluginCreator; +} + +struct PluginDeleter { + void operator()(nvinfer1::IPluginV2* t); +}; + +void PluginDeleter::operator()(nvinfer1::IPluginV2* t) { t->destroy(); } + +std::unique_ptr createPlugin( + const std::string& name, nvinfer1::IPluginCreator* pluginCreator, + const std::vector& pluginFields) { + if (!pluginCreator) { + return nullptr; + } + nvinfer1::PluginFieldCollection fc; + fc.nbFields = pluginFields.size(); + fc.fields = pluginFields.data(); + return std::unique_ptr{ + pluginCreator->createPlugin(name.c_str(), &fc)}; +} +} // namespace tensorrt +} // namespace tensorflow +#endif + +namespace tensorflow { +namespace tensorrt { + +class ScopedWeights { + public: + ScopedWeights(float value) : value_(value) { + w.type = nvinfer1::DataType::kFLOAT; + w.values = &value_; + w.count = 1; + } + const nvinfer1::Weights& get() { return w; } + + private: + float value_; + nvinfer1::Weights w; +}; + +class ScopedShapedWeights { + public: + ScopedShapedWeights(nvinfer1::Dims dims, float value) + : dims_(dims), + value_(std::accumulate(dims.d, dims.d + dims.nbDims, 1, + std::multiplies<>()), + value) { + w.type = nvinfer1::DataType::kFLOAT; + w.values = value_.data(); + w.count = value_.size(); + } + + nvinfer1::Dims dims_; + std::vector value_; + nvinfer1::Weights w; +}; + +const char* kInputTensor1 = "input1"; +const char* kInputTensor2 = "input2"; +const char* kOutputTensor1 = "output"; +const char* kOutputTensor2 = "output-nms"; + +// Creates a network to compute x+y. +TrtUniquePtrType CreateSerializedEngine() { + Logger& logger = *Logger::GetLogger(); + TrtUniquePtrType builder( + nvinfer1::createInferBuilder(logger)); + TrtUniquePtrType network( + builder->createNetworkV2( + 1U << static_cast( + nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH))); + // Add the input. + auto input1 = network->addInput(kInputTensor1, nvinfer1::DataType::kFLOAT, + nvinfer1::Dims4{1, 1, 1, 1}); + auto input2 = network->addInput(kInputTensor2, nvinfer1::DataType::kFLOAT, + nvinfer1::Dims4{1, 1, 1, 1}); + EXPECT_NE(input1, nullptr); + EXPECT_NE(input2, nullptr); + // Add an ILayer layer. + auto layer = network->addElementWise(*input1, *input2, + nvinfer1::ElementWiseOperation::kSUM); + EXPECT_NE(layer, nullptr); + auto output = layer->getOutput(0); + output->setName(kOutputTensor1); + network->markOutput(*output); + +#ifdef TF_TRT_USE_EFFICIENT_NMS_PLUGIN + // Add an efficient nms plugin. + ScopedShapedWeights boxes_weights(nvinfer1::Dims3(1, 10, 4), 0.0f); + ScopedShapedWeights scores_weights(nvinfer1::Dims3(1, 10, 10), 0.0f); + nvinfer1::IConstantLayer* boxes = + network->addConstant(boxes_weights.dims_, boxes_weights.w); + nvinfer1::IConstantLayer* scores = + network->addConstant(scores_weights.dims_, scores_weights.w); + + std::array nms_inputs = {boxes->getOutput(0), + scores->getOutput(0)}; + auto plugin_creator = MakeNMSPluginCreator("tftrt"); + auto plugin = createPlugin("nms_plugin_instance", plugin_creator.get(), {}); + auto nms = network->addPluginV2(nms_inputs.data(), 2, *plugin); + nms->getOutput(0)->setName(kOutputTensor2); + network->markOutput(*nms->getOutput(0)); +#else + auto sub_layer = network->addElementWise( + *input1, *input2, nvinfer1::ElementWiseOperation::kSUB); + EXPECT_NE(sub_layer, nullptr); + network->markOutput(*sub_layer->getOutput(0)); + sub_layer->getOutput(0)->setName(kOutputTensor2); +#endif + + // Build the engine. + builder->setMaxBatchSize(1); + TrtUniquePtrType builderConfig( + builder->createBuilderConfig()); + builderConfig->setMaxWorkspaceSize(1 << 20); + TrtUniquePtrType engine( + builder->buildEngineWithConfig(*network, *builderConfig)); + EXPECT_NE(engine, nullptr); + // Serialize the engine to create a model, then close everything. + TrtUniquePtrType model(engine->serialize()); + return model; +} + +template +unsigned GetBindingSizeBytes(const nvinfer1::ICudaEngine& engine, int index, + unsigned batch_size) { + unsigned vol = batch_size; + auto dims = engine.getBindingDimensions(index); + int vecDim = engine.getBindingVectorizedDim(index); + if (-1 != vecDim) // i.e., 0 != lgScalarsPerVector + { + int scalarsPerVec = engine.getBindingComponentsPerElement(index); + // Divide round up. + dims.d[vecDim] = (dims.d[vecDim] + scalarsPerVec - 1 / scalarsPerVec); + vol *= scalarsPerVec; + } + vol *= std::accumulate(dims.d, dims.d + dims.nbDims, 1, std::multiplies<>()); + return vol * sizeof(T); +} + +// Executes the network. +void Execute(nvinfer1::IExecutionContext* context, const float* input1, + const float* input2, float* output1, float* output2) { + const nvinfer1::ICudaEngine& engine = context->getEngine(); + + // We have two bindings: input and output. + ASSERT_EQ(engine.getNbBindings(), 4); + const int input_index1 = engine.getBindingIndex(kInputTensor1); + const int input_index2 = engine.getBindingIndex(kInputTensor2); + const int output_index1 = engine.getBindingIndex(kOutputTensor1); + const int output_index2 = engine.getBindingIndex(kOutputTensor2); + + // Create GPU buffers and a stream + std::vector buffers(engine.getNbBindings()); + for (int i = 0; i < buffers.size(); i++) { + ASSERT_EQ( + 0, cudaMalloc(&buffers[i], GetBindingSizeBytes(engine, i, 1))); + } + + cudaStream_t stream; + ASSERT_EQ(0, cudaStreamCreate(&stream)); + + // Copy the input to the GPU, execute the network, and copy the output back. + // + // Note that since the host buffer was not created as pinned memory, these + // async copies are turned into sync copies. So the following synchronization + // could be removed. + ASSERT_EQ(0, cudaMemcpyAsync(buffers[input_index1], input1, sizeof(float), + cudaMemcpyHostToDevice, stream)); + ASSERT_EQ(0, cudaMemcpyAsync(buffers[input_index2], input2, sizeof(float), + cudaMemcpyHostToDevice, stream)); + context->enqueueV2(buffers.data(), stream, nullptr); + ASSERT_EQ(0, cudaMemcpyAsync(output1, buffers[output_index1], sizeof(float), + cudaMemcpyDeviceToHost, stream)); + ASSERT_EQ( + 0, cudaMemcpyAsync(output2, buffers[output_index2], + GetBindingSizeBytes(engine, output_index2, 1), + cudaMemcpyDeviceToHost, stream)); + cudaStreamSynchronize(stream); + + // Release the stream and the buffers + for (int i = 0; i < buffers.size(); i++) { + ASSERT_EQ(0, cudaFree(buffers[i])); + } + cudaStreamDestroy(stream); +} + +TEST(TensorrtTest, BasicFunctions) { + // We must register the plugin creator in order to deserialize the plugin. +#ifdef TF_TRT_USE_EFFICIENT_NMS_PLUGIN + auto plugin_creator = MakeNMSPluginCreator("tftrt"); + getPluginRegistry()->registerCreator(*plugin_creator, "tftrt"); +#endif + + // Handle the case where the test is run on machine with no gpu available. + if (CHECK_NOTNULL(se::GPUMachineManager())->VisibleDeviceCount() <= 0) { + LOG(WARNING) << "No gpu device available, probably not being run on a gpu " + "machine. Skipping..."; + return; + } + + // Create a serialized engine + TrtUniquePtrType model = CreateSerializedEngine(); + // Use the model to create an engine and then an execution context. + Logger& logger = *Logger::GetLogger(); + TrtUniquePtrType runtime( + nvinfer1::createInferRuntime(logger)); + TrtUniquePtrType engine( + runtime->deserializeCudaEngine(model->data(), model->size(), nullptr)); + TrtUniquePtrType context( + engine->createExecutionContext()); + + // Execute the network. + float input1 = 1234; + float input2 = 567; + + std::vector output1( + GetBindingSizeBytes(*engine, 2, 1) / sizeof(float), 0.0f); + + std::vector output2( + GetBindingSizeBytes(*engine, 3, 1) / sizeof(int32), 0.0f); + + ASSERT_EQ(output1.size(), 1); + ASSERT_EQ(output2.size(), 1); + + Execute(context.get(), &input1, &input2, output1.data(), output2.data()); + EXPECT_EQ(output1[0], input1 + input2); + +#ifdef TF_TRT_USE_EFFICIENT_NMS_PLUGIN + EXPECT_EQ(output2[0], 0); +#else + EXPECT_EQ(output2[0], 667); +#endif // TF_TRT_USE_EFFICIENT_NMS_PLUGIN +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api.cc new file mode 100644 index 0000000000000000000000000000000000000000..6c72605aec55744ec16b4fd177af88838386dc57 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api.cc @@ -0,0 +1,512 @@ +/* Copyright 2021 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/tf2tensorrt/trt_convert_api.h" + +#include +#include +#include + +#include "absl/strings/str_join.h" +#include "tensorflow/cc/tools/freeze_saved_model.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/grappler/clusters/cluster.h" +#include "tensorflow/core/grappler/clusters/single_machine.h" +#include "tensorflow/core/grappler/clusters/utils.h" +#include "tensorflow/core/grappler/devices.h" +#include "tensorflow/core/grappler/grappler_item.h" +#include "tensorflow/core/grappler/grappler_item_builder.h" +#include "tensorflow/core/grappler/optimizers/meta_optimizer.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/protobuf/meta_graph.pb.h" +#include "tensorflow/core/public/session.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { + +namespace tensorrt { +namespace { + +// Creates and provisions a new cluster. The caller must call Shutdown before +// the cluster is destroyed. +Status NewCluster(grappler::Cluster** cluster) { + int num_cpu_cores = grappler::GetNumAvailableLogicalCPUCores(); + int num_gpus = grappler::GetNumAvailableGPUs(); + int timeout_s = 60 * 10; + *cluster = new grappler::SingleMachine(timeout_s, num_cpu_cores, num_gpus); + (*cluster)->DisableDetailedStats(true); + (*cluster)->AllowSoftPlacement(true); + (*cluster)->SetNumWarmupSteps(10); + TF_RETURN_IF_ERROR((*cluster)->Provision()); + return OkStatus(); +} + +Status RunGrappler(const MetaGraphDef& meta_graph_def, + const std::vector& input_names, + const std::vector& output_names, + const ConfigProto& config_proto, grappler::Cluster* cluster, + GraphDef* out_graph_def) { + grappler::ItemConfig item_config; + + for (const string& name : input_names) { + item_config.feed_nodes.insert(name); + } + for (const string& name : output_names) { + item_config.fetch_nodes.insert(name); + } + + std::unique_ptr item = + grappler::GrapplerItemFromMetaGraphDef("tf_graph", meta_graph_def, + item_config); + if (!item) { + return tensorflow::errors::Internal( + "Failed to create grappler item from MetaGraphDef."); + } + + tensorflow::DeviceBase* cpu_device = nullptr; + TF_RETURN_IF_ERROR(grappler::RunMetaOptimizer( + std::move(*item), config_proto, cpu_device, cluster, out_graph_def)); + VLOG(2) << "Grappler finished\n"; + return OkStatus(); +} + +Status ImportGraphDefToSession(Session* session, const GraphDef& graph_def, + const string& prefix) { + ImportGraphDefOptions opts; + opts.prefix = prefix; + Graph graph(OpRegistry::Global()); + TF_RETURN_IF_ERROR(ImportGraphDef(opts, graph_def, &graph, nullptr)); + GraphDef new_graph_def; + graph.ToGraphDef(&new_graph_def); + TF_RETURN_IF_ERROR(session->Extend(new_graph_def)); + return OkStatus(); +} + +Status GetTrtRewriterConfig(const TfTrtConversionParams& params, + const GraphDef& frozen_graph_def, + RewriterConfig* opt_config) { + opt_config->set_meta_optimizer_iterations(tensorflow::RewriterConfig::ONE); + opt_config->set_min_graph_nodes(-1); // do not skip small graphs + + // Turn off remapping. + opt_config->set_remapping(RewriterConfig_Toggle::RewriterConfig_Toggle_OFF); + + // If the graph has QDQ nodes, then we need to disable folding of the + // QDQ with constants. Otherwise, the conversion will not work correctly. + // Ideally, we do this after segmentation and outlining of TRT regions to + // functions, but we currently lack that capability. Disabling QDQ-const + // folding doesn't matter if you don't have QDQ nodes, so we always enable + // this. + opt_config->set_experimental_disable_folding_quantization_emulation( + IS_TRT_VERSION_GE(8, 0, 0, 0)); + + // Initial transformations before TensorRTOptimizer is called + opt_config->add_optimizers("function"); + opt_config->add_optimizers("constfold"); + opt_config->add_optimizers("layout"); + opt_config->add_optimizers("constfold"); + + // Parameters for TensorRTOptimizer + auto trt_optimizer = opt_config->add_custom_optimizers(); + trt_optimizer->set_name("TensorRTOptimizer"); + + auto trt_parameter_map = trt_optimizer->mutable_parameter_map(); + (*trt_parameter_map)["is_dynamic_op"].set_b(true); + (*trt_parameter_map)["minimum_segment_size"].set_i( + params.minimum_segment_size); + string prec_string; + TF_RETURN_IF_ERROR( + TrtPrecisionModeToName(params.precision_mode, &prec_string)); + (*trt_parameter_map)["precision_mode"].set_s(prec_string); + (*trt_parameter_map)["max_batch_size"].set_i(1); + (*trt_parameter_map)["max_workspace_size_bytes"].set_i( + params.max_workspace_size_bytes); + (*trt_parameter_map)["max_cached_engines"].set_i(params.max_cached_engines); + (*trt_parameter_map)["use_calibration"].set_b(params.use_calibration); + (*trt_parameter_map)["profile_strategy"].set_s( + ProfileStrategyToName(params.profile_strategy)); + (*trt_parameter_map)["use_implicit_batch"].set_b(!params.use_dynamic_shape); + (*trt_parameter_map)["_allow_build_at_runtime"].set_b( + params.allow_build_at_runtime); + return OkStatus(); +} + +// Runs TRTOptimizer grappler pass. +Status RunTfTrt(const MetaGraphDef& meta_graph_def, + const std::vector& input_names, + const std::vector& output_names, + const RewriterConfig& rewriter_config, + GraphDef* segmented_graph_def) { + ConfigProto config_proto; + *config_proto.mutable_graph_options()->mutable_rewrite_options() = + rewriter_config; + + VLOG(4) << "Setting up Grappler parameters\n" << config_proto.DebugString(); + std::unique_ptr cluster; + grappler::Cluster* p_cluster; + mutex mu_cluster; // There can be only one provisioned cluster per process. + mutex_lock lock(mu_cluster); + TF_RETURN_IF_ERROR(NewCluster(&p_cluster)); + cluster.reset(p_cluster); + TF_RETURN_IF_ERROR(RunGrappler(meta_graph_def, input_names, output_names, + config_proto, cluster.get(), + segmented_graph_def)); + TF_RETURN_IF_ERROR(cluster->Shutdown()); + return OkStatus(); +} + +// Sets the _profile_generation mode attribute of all TRTEngineOp nodes in the +// graph to mode. +Status SetProfileGenerationMode(GraphDef* graph_def, bool mode) { + VLOG(3) << "Setting _profile_generation_mode=" << mode; + std::string op{"TRTEngineOp"}; + for (auto& node : *(graph_def->mutable_node())) { + if (!op.compare(node.op())) { + auto* attr = node.mutable_attr(); + AttrValue profile_generation_mode; + profile_generation_mode.set_b(mode); + (*attr)["_profile_generation_mode"] = profile_generation_mode; + } + } + return OkStatus(); +} + +Status RunSession(Session* session, const std::vector& input_names, + const std::vector& output_names, + const std::vector& input_tensors, + string prefix = "") { + TRT_ENSURE(!input_names.empty()); + TRT_ENSURE(!output_names.empty()); + TRT_ENSURE(!input_tensors.empty()); + + std::vector> input_pairs; + std::vector prefixed_output_names; + auto prefixed_name = [](std::string prefix, std::string name) { + return !prefix.empty() ? absl::StrJoin({prefix, name}, "/") : name; + }; + for (int i = 0; i < input_names.size(); i++) { + input_pairs.push_back( + {prefixed_name(prefix, input_names.at(i)), input_tensors.at(i)}); + } + for (int i = 0; i < output_names.size(); i++) { + prefixed_output_names.push_back(prefixed_name(prefix, output_names.at(i))); + } + std::vector output_tensors; + for (int i = 0; i < output_names.size(); i++) { + output_tensors.push_back({}); + } + VLOG(3) << "TF-TRT Build mode: running inference\n"; + TF_RETURN_IF_ERROR( + session->Run(input_pairs, prefixed_output_names, {}, &output_tensors)); + return OkStatus(); +} + +// Runs the model to create the engines. In dynamic shape mode, before creating +// the engines, we provide shapes to define optimization profiles. +Status Build(GraphDef& segmented_graph_def, + const std::vector& input_names, + const std::vector& output_names, + const std::vector>& inputs, + Session* session, const TfTrtConversionParams params) { + VLOG(2) << "Building the model"; + bool need_collect_profiles = params.use_dynamic_shape && inputs.size() > 1; + if (need_collect_profiles) { + TF_RETURN_IF_ERROR(SetProfileGenerationMode(&segmented_graph_def, true)); + } + TF_RETURN_IF_ERROR(session->Create(segmented_graph_def)); + string prefix = ""; + if (need_collect_profiles) { + for (auto const& input : inputs) { + TF_RETURN_IF_ERROR(RunSession(session, input_names, output_names, input)); + } + prefix = "TrtBuildStep"; + TF_RETURN_IF_ERROR(SetProfileGenerationMode(&segmented_graph_def, false)); + VLOG(3) << "Importing graph with _profile_generation_mode disabled"; + TF_RETURN_IF_ERROR( + ImportGraphDefToSession(session, segmented_graph_def, prefix)); + } + TF_RETURN_IF_ERROR( + RunSession(session, input_names, output_names, *inputs.begin(), prefix)); + return OkStatus(); +} + +// Returns the resource manager associated with the node. +Status GetResourceManager(const NodeDef& node, Session* session, + ResourceMgr** rm) { + const DeviceMgr* device_mgr; + TF_RETURN_IF_ERROR(session->LocalDeviceManager(&device_mgr)); + Device* device; + string device_name = node.device().empty() + ? "/job:localhost/replica:0/task:0/device:GPU:0" + : node.device(); + TF_RETURN_IF_ERROR(device_mgr->LookupDevice(device_name, &device)); + *rm = device->resource_manager(); + return OkStatus(); +} + +// Looks up the cache resource associated with the TRT node. +Status GetEngineCacheResource(const NodeDef& node, Session* session, + TRTEngineCacheResource** resource) { + ResourceMgr* rm; + TF_RETURN_IF_ERROR(GetResourceManager(node, session, &rm)); + + absl::string_view resource_name = node.name(); + size_t last_slash = resource_name.find_last_of('/'); + if (last_slash != absl::string_view::npos) { + resource_name.remove_prefix(last_slash + 1); + } + const std::string container(kTfTrtContainerName); + *resource = nullptr; + TF_RETURN_IF_ERROR( + rm->Lookup(container, std::string(resource_name), resource)); + if (resource == nullptr || (*resource)->cache_.size() == 0) { + return errors::Internal("Engine cache not found for", resource_name); + } + return OkStatus(); +} + +// Looks up the engine from the engine cache, and serializes the engine. +Status ReadSerializedEngine( + const NodeDef& node, Session* session, + TrtUniquePtrType* engine_data) { + TRTEngineCacheResource* resource; + TF_RETURN_IF_ERROR(GetEngineCacheResource(node, session, &resource)); + core::ScopedUnref unref_cache_res(resource); + if (resource->cache_.size() > 1) { + return errors::Internal( + "Multiple engines found, but we can only serialize one"); + } + const std::unique_ptr& engine = + resource->cache_.begin()->second; + if (!engine) { + return errors::Internal("Engine not found for", node.name()); + } + + if (engine->GetCudaEngine()) { + // Serialize the engine. + engine_data->reset(engine->GetCudaEngine()->serialize()); + } else { + LOG(WARNING) << "Engine cache contains nullptr"; + } + + return OkStatus(); +} + +// Saves the TRT engines as attributes of the TRTEngineOp nodes. +Status ConvertToStaticEngine(const GraphDef graph_def, + GraphDef* static_graph_def, Session* session) { + *static_graph_def = graph_def; + VLOG(1) << "Saving TRT engines as static engine"; + std::string op{"TRTEngineOp"}; + for (auto& node : *(static_graph_def->mutable_node())) { + if (!op.compare(node.op())) { + VLOG(2) << "Saving TRT engine for " << node.name() + << ", device: " << node.device(); + TrtUniquePtrType engine_data; + TF_RETURN_IF_ERROR(ReadSerializedEngine(node, session, &engine_data)); + auto* attr = node.mutable_attr(); + AttrValue static_engine; + static_engine.set_b(true); + AttrValue engine_string; + if (engine_data) { + engine_string.set_s(engine_data->data(), engine_data->size()); + } + (*attr)["static_engine"] = static_engine; + (*attr)["serialized_segment"] = engine_string; + } + } + return OkStatus(); +} + +Status ValidateConversionParams(const TfTrtConversionParams& p, int n_inputs) { + if (p.precision_mode == TrtPrecisionMode::INT8 && p.use_calibration) { + return errors::InvalidArgument( + "Calibration not yet implemented through the C++ interface. Please use " + "our Python API for calibration."); + } + if (p.convert_to_static_engine && n_inputs == 0) { + return errors::InvalidArgument( + "TRT Engine needs to be built before we can convert it to static " + "engine. Please provide input data to build the model."); + } + if (!p.convert_to_static_engine && n_inputs >= 0) { + // After the conversion, the session that was used to build the engines + // will be destroyed. If we do not convert the engine to static engine, + // then we loose the engines. + // + // TODO(tfeher): Provide a way to save dynamic engines and remove this + // warning. + LOG(WARNING) + << "Skipping build mode because we cannot save the " + "engines. Use convert_to_static_engines=true conversion " + "parameter to enable build mode and save the engines in the graph."; + } + if (!p.allow_build_at_runtime && n_inputs == 0) { + LOG(WARNING) + << "TRT will not be used since allow_build_at_runtime is disabled and " + "no inputs are provided to build during conversion."; + } + return OkStatus(); +} + +// Returns configuration used during the build step session run. +tensorflow::SessionOptions GetSessionConfg() { + // We also need to disable constant folding because we already ran constant + // folding and may have prevented quantization operation folding on purpose. + tensorflow::SessionOptions opts; + auto* rewriter_opts = + opts.config.mutable_graph_options()->mutable_rewrite_options(); + rewriter_opts->set_experimental_disable_folding_quantization_emulation(true); + + // It seems that we need to disable the optimizer entirely to prevent the + // folding. + rewriter_opts->set_disable_meta_optimizer(true); + + // Disable optimizations for static graph to allow calls to Session::Extend. + opts.config.mutable_experimental()->set_disable_optimize_for_static_graph( + true); + return opts; +} + +} // namespace + +StatusOr ConvertAndBuild( + const GraphDef& frozen_graph_def, const std::vector& input_names, + const std::vector& output_names, + const std::vector>& inputs, + const TfTrtConversionParams& conv_params) { + TF_RETURN_IF_ERROR(ValidateConversionParams(conv_params, inputs.size())); + MetaGraphDef meta_graph; + *meta_graph.mutable_graph_def() = frozen_graph_def; + + RewriterConfig rewriter_config; + TF_RETURN_IF_ERROR( + GetTrtRewriterConfig(conv_params, frozen_graph_def, &rewriter_config)); + + GraphDef segmented_graph_def; + TF_RETURN_IF_ERROR(RunTfTrt(meta_graph, input_names, output_names, + rewriter_config, &segmented_graph_def)); + + GraphDef output; + + if (!inputs.empty() && conv_params.convert_to_static_engine) { + // The TRTOptimization pass has inserted placeholder TRTEngineOps. Here we + // trigger conversion by inferring the graph. + std::unique_ptr session( + tensorflow::NewSession(GetSessionConfg())); + if (!session) { + return errors::Internal("Failed to create build session"); + } + + TF_RETURN_IF_ERROR(Build(segmented_graph_def, input_names, output_names, + inputs, session.get(), conv_params)); + + TF_RETURN_IF_ERROR( + ConvertToStaticEngine(segmented_graph_def, &output, session.get())); + } else { + output = segmented_graph_def; + } + VLOG(1) << "TF-TRT conversion finished"; + return output; +} + +Status InlineFunctions(const MetaGraphDef& meta_graph_def, + GraphDef* out_graph_def) { + ConfigProto config_proto; + auto opt_config = + config_proto.mutable_graph_options()->mutable_rewrite_options(); + + opt_config->set_meta_optimizer_iterations(tensorflow::RewriterConfig::ONE); + opt_config->set_min_graph_nodes(-1); // do not skip small graphs + opt_config->add_optimizers("function"); + + TF_RETURN_IF_ERROR(RunGrappler(meta_graph_def, {}, {}, config_proto, nullptr, + out_graph_def)); + + VLOG(2) << "Graph is inlined"; + return OkStatus(); +} + +// Freezes the graph. It is assumed that the functions are inlined and the +// variables are initialized. +Status FreezeGraph(SavedModelBundle& bundle, MetaGraphDef* frozen_meta_graph) { + std::unordered_set inputs; + std::unordered_set outputs; + GraphDef frozen_graph_def; + TF_RETURN_IF_ERROR( + FreezeSavedModel(bundle, &frozen_graph_def, &inputs, &outputs)); + + *frozen_meta_graph = bundle.meta_graph_def; + GraphDef* gdef = frozen_meta_graph->mutable_graph_def(); + *gdef = frozen_graph_def; + + VLOG(2) << "Graph frozen"; + return OkStatus(); +} + +// Returns the name of nodes listed in the signature definition. +std::vector GetNodeNames( + const google::protobuf::Map& signature) { + std::vector names; + for (auto const& item : signature) { + absl::string_view name = item.second.name(); + // Remove tensor suffix like ":0". + size_t last_colon = name.find_last_of(':'); + if (last_colon != absl::string_view::npos) { + name.remove_suffix(name.size() - last_colon); + } + names.push_back(std::string(name)); + } + return names; +} + +StatusOr ConvertAndBuild( + SavedModelBundle* bundle, const std::string& signature_key, + const std::vector>& inputs, + const TfTrtConversionParams& conversion_params) { + // Inline the functions. + GraphDef inlined_graph_def; + TF_RETURN_IF_ERROR( + InlineFunctions(bundle->meta_graph_def, &inlined_graph_def)); + + // Replace the graph_def with the inlined graph. Note that bundle->session + // still has the original graph. + *bundle->meta_graph_def.mutable_graph_def() = inlined_graph_def; + + // Freeze variables. + MetaGraphDef frozen_meta_graph; + TF_RETURN_IF_ERROR(FreezeGraph(*bundle, &frozen_meta_graph)); + + // Convert. + auto signature_map = bundle->GetSignatures(); + const tensorflow::SignatureDef& signature = signature_map[signature_key]; + std::vector input_names = GetNodeNames(signature.inputs()); + std::vector output_names = GetNodeNames(signature.outputs()); + return ConvertAndBuild(frozen_meta_graph.graph_def(), input_names, + output_names, inputs, conversion_params); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api.h new file mode 100644 index 0000000000000000000000000000000000000000..c963359a001b84530dd093ef1de6cc15ff6e565d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api.h @@ -0,0 +1,129 @@ +/* Copyright 2021 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_TF2TENSORRT_TRT_CONVERT_API_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_TRT_CONVERT_API_H_ + +#include +#include +#include + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/statusor.h" +#include "tensorflow/core/protobuf/meta_graph.pb.h" + +namespace tensorflow { + +struct SavedModelBundle; + +namespace tensorrt { + +struct TfTrtConversionParams { + // Corresponds 'workspaceSize' parameter of + // nvinfer1::IBuilderConfig::setMaxWorkspaceSize. +#if IS_TRT_VERSION_GE(8, 4, 0, 0) + // Must use `LLONG_MAX - 512` to avoid overflow during casting. + size_t max_workspace_size_bytes = LLONG_MAX - 512; +#else + size_t max_workspace_size_bytes = 1 << 30; // 1,073,741,824 +#endif + + // Minimum precision used by the TRT Engine. + TrtPrecisionMode precision_mode = TrtPrecisionMode::FP32; + + // The minimum number of nodes required for a subgraph to be replaced by + // TRTEngineOp. Note that many small TRT subgraphs could be detrimental for + // performance, increasing the minimum segment size can help avoid the + // problem. + int minimum_segment_size = 3; + + // Max number of cached TRT engines for dynamic TRT ops (by default we have + // dynamic TRT ops). + int max_cached_engines = 1; + + // Note that calibration is currently not implemented with the C++ converter. + // This argument is ignored if precision_mode is not INT8. If set to True, the + // implementation will use the user provided inputs to generate calibration + // data. If set to False, quantization nodes will be expected for every tensor + // in the graph (excluding those which will be fused). If a range is missing, + // an error will occur. Please note that accuracy may be negatively affected + // if there is a mismatch between which tensors TRT quantizes and which + // tensors were trained with fake quantization. + bool use_calibration = true; + + // Whether to enable dynamic shape mode for the TRT engines. It is + // recommended to use_dynamic_shape mode to handle dynamic input shape. + // Enabling dynamic shape mode can also improve the conversion rate of graphs + // with static input shape. + bool use_dynamic_shape = true; + + // In dynamic shape mode we create an engine that can handle various input + // shape ranges. We derive the shape optimization profiles for the TRT engines + // in the graph based on user provided input data and profile_strategy. + ProfileStrategy profile_strategy = ProfileStrategy::kRange; + + // Whether to allow building TRT engines at runtime. If no TensorRT engine can + // be found in cache that can handle the given inputs during runtime, then a + // new TensorRT engine is built at runtime if allow_build_at_runtime=True, + // otherwise native TF is used. We recommend to set this value false and build + // the engine in advance, to avoid runtime overhead. + bool allow_build_at_runtime = true; + + // Record the TRT engine as an attribute of the TRTEngineOp. This is only + // valid when max_cached_engines == 1. Note: the frozen graph together with + // the serialized engines have to be below 2GiB (protobuf size limit). If + // convert_to_static_engine = false, then the converted graph_def only + // contains placeholder TRTEngineOp nodes. + bool convert_to_static_engine = true; +}; + +/** + * Converts the graph with TF-TRT. + * + * Performs TF-TRT conversion and returns the converted GraphDef. If inputs is + * not empty and convert_to_static_engine is requested, we also build the + * engines and convert the engines to static engines. + * + * Arguments: + * - frozen_graph_def input graph, it is assumed to be frozen + * - input_names names of the input tensors + * - output_names names of the output tensors + * - inputs tensors that we will use as input while building the TRT engines + * - conv_params parameters for the TF-TRT conversion + * + * Returns the converted graph_def. + */ +StatusOr ConvertAndBuild( + const GraphDef& frozen_graph_def, const std::vector& input_names, + const std::vector& output_names, + const std::vector>& inputs, + const TfTrtConversionParams& conv_params); + +StatusOr ConvertAndBuild( + SavedModelBundle* bundle, + const std::string& signature_key = "serving_default", + const std::vector>& inputs = {}, + const TfTrtConversionParams& conversion_params = TfTrtConversionParams()); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_TRT_CONVERT_API_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..72ab04463185fa1c2248169d39b189a05c9d68b5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/trt_convert_api_test.cc @@ -0,0 +1,358 @@ +/* Copyright 2021 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/trt_convert_api.h" + +#include "tensorflow/cc/ops/resource_variable_ops.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/cc/ops/state_ops.h" +#include "tensorflow/cc/saved_model/loader.h" +#include "tensorflow/core/framework/function_testlib.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/protobuf/meta_graph.pb.h" +#include "tensorflow/core/public/session.h" + +namespace tensorflow { +namespace tensorrt { + +struct TestParam { + TfTrtConversionParams conv_params; + std::vector> input_shapes; +}; + +class TrtConverterTest + : public ::testing::TestWithParam> { + protected: + TrtConverterTest() { + param_ = std::get<0>(GetParam()); + use_variable_ = std::get<1>(GetParam()); + use_function_ = std::get<2>(GetParam()); + input_tensors_ = GetInputTensors(); + } + + // Returns the following graph: output = input * [42, 137] + input + GraphDef GetGraphDef(PartialTensorShape input_shape) { + Scope root = Scope::NewRootScope(); + Output c; + c = ops::Const(root.WithOpName("my_const"), {{42.0f, 137.0f}}); + Output v; + if (use_variable_) { + Output v_handle = ops::VarHandleOp(root.WithOpName("my_var"), + DataType::DT_FLOAT, {1, 2}); + v = ops::ReadVariableOp(root.WithOpName("my_var/Read/ReadVariableOp"), + v_handle, DataType::DT_FLOAT); + auto v_init = + ops::AssignVariableOp(root.WithOpName("my_var/init"), v_handle, c); + } else { + v = c; + } + const auto attrs = ops::Placeholder::Shape(input_shape); + auto x = ops::Placeholder(root.WithOpName("input"), DT_FLOAT, attrs); + auto y = ops::Mul(root.WithOpName("my_mul"), x, v); + auto z = ops::Add(root.WithOpName("my_add"), x, y); + auto q = ops::Identity(root.WithOpName("output"), z); + + GraphDef out; + TF_CHECK_OK(root.ToGraphDef(&out)); + return out; + } + + GraphDef GetGraphWithFunction(PartialTensorShape input_shape) { + using ::tensorflow::test::function::GDef; + using ::tensorflow::test::function::NDef; + const Tensor kOne = test::AsScalar(1.0f); + TensorShapeProto value_shape_proto; + kOne.shape().AsProto(&value_shape_proto); + TensorShapeProto input_shape_proto; + input_shape.AsProto(&input_shape_proto); + NodeDef value_node; + if (use_variable_) { + value_node = + NDef("my_value", "Identity", {"my_var:0"}, {{"T", DT_RESOURCE}}); + } else { + value_node = + NDef("my_value", "Identity", {"my_const:0"}, {{"T", DT_FLOAT}}); + } + GraphDef gdef = GDef( + { + NDef("input", "Placeholder", {}, + {{"dtype", DT_FLOAT}, {"shape", input_shape_proto}}), + NDef("my_const", "Const", {}, + {{"dtype", DT_FLOAT}, {"value", kOne}}), + value_node, + NDef("call", "StatefulPartitionedCall", {"input", "my_value"}, + {{"Tin", DataTypeSlice{DT_FLOAT, use_variable_ ? DT_RESOURCE + : DT_FLOAT}}, + {"Tout", DataTypeSlice{DT_FLOAT}}, + {"f", FunctionDefHelper::FunctionRef("f", {})}}), + NDef("output", "Identity", {"call:0"}, {{"T", DT_FLOAT}}), + }, + {}); + FunctionDef fdef; + if (use_variable_) { + *gdef.add_node() = + NDef("my_var", "VarHandleOp", {}, + {{"dtype", DT_FLOAT}, {"shape", value_shape_proto}}); + + *gdef.add_node() = NDef("my_var/init", "AssignVariableOp", + {"my_var", "my_const"}, {{"dtype", DT_FLOAT}}); + *gdef.add_node() = NDef("my_var/Read/ReadVariableOp", "ReadVariableOp", + {"my_var"}, {{"dtype", DT_FLOAT}}); + // Define function f(x, v) = x * v + x, where v is a variable. + fdef = FunctionDefHelper::Define( + "f", // Name + {"x: float", "v: resource"}, // Args + {"q: float"}, // Returns + {}, // Attr def + // Nodes + {{{"my_var/Read/ReadVariableOp"}, + "ReadVariableOp", + {"v"}, + {{"dtype", DT_FLOAT}}}, + {{"my_mul"}, + "Mul", + {"x", "my_var/Read/ReadVariableOp"}, + {{"T", DT_FLOAT}}}, + {{"my_add"}, "AddV2", {"x", "my_mul"}, {{"T", DT_FLOAT}}}, + {{"q"}, "Identity", {"my_add"}, {{"T", DT_FLOAT}}}}); + } else { + // Define function f(x, v) = x * v + x, where v is const value. + fdef = FunctionDefHelper::Define( + "f", // Name + {"x: float", "v: float"}, // Args + {"q: float"}, // Returns + {}, // Attr def + // Nodes + {{{"my_mul"}, "Mul", {"x", "v"}, {{"T", DT_FLOAT}}}, + {{"my_add"}, "AddV2", {"x", "my_mul"}, {{"T", DT_FLOAT}}}, + {{"q"}, "Identity", {"my_add"}, {{"T", DT_FLOAT}}}}); + } + *gdef.mutable_library()->add_function() = fdef; + + return gdef; + } + + // Returns the following graph: output = input * [42, 137] + input + MetaGraphDef GetModel() { + PartialTensorShape shape({-1, 2}); + MetaGraphDef out; + if (use_function_) { + *(out.mutable_graph_def()) = GetGraphWithFunction(shape); + } else { + *(out.mutable_graph_def()) = GetGraphDef(shape); + } + VLOG(2) << out.graph_def().DebugString(); + TensorShapeProto shape_proto; + shape.AsProto(&shape_proto); + SignatureDef signature_def; + (*signature_def.mutable_inputs())["input"].set_name("input:0"); + (*signature_def.mutable_inputs())["input"].set_dtype(DT_FLOAT); + *(*signature_def.mutable_inputs())["input"].mutable_tensor_shape() = + shape_proto; + (*signature_def.mutable_outputs())["output"].set_name("output:0"); + (*signature_def.mutable_outputs())["output"].set_dtype(DT_FLOAT); + *(*signature_def.mutable_outputs())["output"].mutable_tensor_shape() = + shape_proto; + (*out.mutable_signature_def())["serving_default"] = signature_def; + + VLOG(2) << signature_def.DebugString(); + return out; + } + + Status GetSavedModelBundle(SavedModelBundle* bundle) { + bundle->meta_graph_def = GetModel(); + Session* session = nullptr; + TF_RETURN_IF_ERROR(NewSession(tensorflow::SessionOptions(), &session)); + TF_RETURN_IF_ERROR(session->Create(bundle->meta_graph_def.graph_def())); + bundle->session.reset(session); + TF_RETURN_IF_ERROR(session->Run(/* inputs */ {}, /*outputs*/ {}, + /*targets*/ {"my_var/init"}, nullptr)); + return OkStatus(); + } + + // Confirms that we have a TRT node with the correct attributes. + void CheckTrtNode(const GraphDef& converted_graph_def) { + int n_trt_ops = 0; + string op_name{"TRTEngineOp"}; + for (const auto& node : converted_graph_def.node()) { + if (!op_name.compare(node.op())) { + n_trt_ops++; + const auto& attr = node.attr(); + EXPECT_EQ(attr.at("static_engine").b(), + param_.conv_params.convert_to_static_engine); + if (param_.conv_params.convert_to_static_engine) { + VLOG(2) << "Found serialized segment with size " + << attr.at("serialized_segment").s().size(); + EXPECT_GT(attr.at("serialized_segment").s().size(), 0); + } + } + } + EXPECT_EQ(n_trt_ops, 1); + } + + // Creates a list of input tensors, they will be used to build the engines. + std::vector> GetInputTensors() { + std::vector> input_tensors; + for (const std::vector& shape : param_.input_shapes) { + Tensor tensor(DT_FLOAT, TensorShape(shape)); + test::FillIota(&tensor, 1.0f); + input_tensors.push_back({tensor}); + } + return input_tensors; + } + + void RunAndCompareResults(Session* session, + const GraphDef& converted_graph_def) { + // Create a session to execute the converted graph. + Session* p_session = nullptr; + TF_EXPECT_OK(NewSession(SessionOptions(), &p_session)); + std::unique_ptr trt_session(p_session); + TF_EXPECT_OK(trt_session->Create(converted_graph_def)); + + // Run models and compare the output. + for (const std::vector& input : input_tensors_) { + std::vector outputs; + TF_EXPECT_OK( + session->Run({{"input", input.at(0)}}, {"output"}, {}, &outputs)); + std::cout << outputs.at(0).DebugString() << std::endl; + + std::vector trt_outputs; + TF_EXPECT_OK(trt_session->Run({{"input", input.at(0)}}, {"output"}, {}, + &trt_outputs)); + std::cout << trt_outputs.at(0).DebugString() << std::endl; + ASSERT_EQ(outputs.size(), 1); + ASSERT_EQ(trt_outputs.size(), 1); + tensorflow::test::ExpectEqual(outputs[0], trt_outputs[0]); + } + } + + void ConvertAndRunFrozenGraph() { + MetaGraphDef meta_graph_def = GetModel(); + + StatusOr result = tensorrt::ConvertAndBuild( + meta_graph_def.graph_def(), {"input"}, {"output"}, input_tensors_, + param_.conv_params); + TF_ASSERT_OK(result.status()); + const GraphDef& converted_graph_def = result.value(); + CheckTrtNode(converted_graph_def); + + // Create a session to execute the original graph. + Session* p_session = nullptr; + TF_EXPECT_OK(NewSession(SessionOptions(), &p_session)); + std::unique_ptr session(p_session); + TF_EXPECT_OK(session->Create(meta_graph_def.graph_def())); + + RunAndCompareResults(session.get(), converted_graph_def); + } + + void ConvertAndRunSavedModel() { + SavedModelBundle bundle; + TF_CHECK_OK(GetSavedModelBundle(&bundle)); + + StatusOr result = tensorrt::ConvertAndBuild( + &bundle, "serving_default", input_tensors_, param_.conv_params); + TF_ASSERT_OK(result.status()); + const GraphDef& converted_graph_def = result.value(); + CheckTrtNode(converted_graph_def); + + RunAndCompareResults(bundle.GetSession(), converted_graph_def); + } + + TestParam param_; + bool use_variable_; + bool use_function_; + std::vector> input_tensors_; +}; + +INSTANTIATE_TEST_CASE_P( + TrtConverterTestInstantiation, TrtConverterTest, + ::testing::Combine( + ::testing::Values( + // Dynamic shape mode test with convert_to_static_engine=true. + TestParam{TfTrtConversionParams{ + 1 << 20, // max workspace size + TrtPrecisionMode::FP32, + 3, // minimum_segment_size + 1, // max_cached_engines + false, // use_calibration + true, // use_dynamic_shape + ProfileStrategy::kOptimal, + true, // allow_build_at_runtime + true // convert_to_static_engine + }, + {{1, 2}, {4, 2}}}, + // Implicit batch mode test with convert_to_static_engine=true. + TestParam{TfTrtConversionParams{ + 1 << 20, // max workspace size + TrtPrecisionMode::FP16, + 3, // minimum_segment_size + 1, // max_cached_engines + false, // use_calibration + false, // use_dynamic_shape + ProfileStrategy::kRange, + true, // allow_build_at_runtime + true // convert_to_static_engine + }, + {{1, 2}}}, + // Dynamic shape mode test convert_to_static_engine=false: we cannot + // save the engines, therefore we do not generate profiles. A single + // engine will be built during runtime, with profile that matches + // the first shape ({1,2}). The second shape will run as native + // segment. + TestParam{TfTrtConversionParams{ + 1 << 20, // max workspace size + TrtPrecisionMode::FP32, + 3, // minimum_segment_size + 1, // max_cached_engines + false, // use_calibration + true, // use_dynamic_shape + ProfileStrategy::kOptimal, + true, // allow_build_at_runtime + false // convert_to_static_engine + }, + {{1, 2}, {4, 2}}}, + // Implicit batch mode test with convert_to_static_engine=false. + // We will have two engines in the cache to handle the two shapes. + TestParam{TfTrtConversionParams{ + 1 << 20, // max workspace size + TrtPrecisionMode::FP16, + 3, // minimum_segment_size + 2, // max_cached_engines + false, // use_calibration + false, // use_dynamic_shape + ProfileStrategy::kRange, + true, // allow_build_at_runtime + false // convert_to_static_engine + }, + {{1, 2}, {4, 2}}}), + ::testing::Values(false, true), // use_variables + ::testing::Values(false, true))); // use_function + +TEST_P(TrtConverterTest, Basic) { + if (use_variable_) { + ConvertAndRunSavedModel(); + } else { + ConvertAndRunFrozenGraph(); + } +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..a333782caf241dad4b4ef2d2c77ff6ffacd0541a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils.cc @@ -0,0 +1,57 @@ +/* Copyright 2019 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/tf2tensorrt/utils/py_utils.h" + +#include + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/op_converter_registry.h" +#include "tsl/platform/dso_loader.h" +#include "third_party/tensorrt/NvInfer.h" +#endif + +namespace tensorflow { +namespace tensorrt { + +bool IsGoogleTensorRTEnabled() { +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#if TF_USE_TENSORRT_STATIC + LOG(INFO) << "TensorRT libraries are statically linked, skip dlopen check"; + return true; +#else // TF_USE_TENSORRT_STATIC + auto handle_or = tsl::internal::DsoLoader::TryDlopenTensorRTLibraries(); + if (!handle_or.ok()) { + LOG_WARNING_WITH_PREFIX << "Could not find TensorRT"; + } + return handle_or.ok(); +#endif // TF_USE_TENSORRT_STATIC +#else // GOOGLE_CUDA && GOOGLE_TENSORRT + return false; +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +} + +std::vector GetRegisteredOpConverters() { +#if GOOGLE_CUDA && GOOGLE_TENSORRT + auto* registry = tensorflow::tensorrt::convert::GetOpConverterRegistry(); + return registry->ListRegisteredOps(); +#else + return {"undef"}; +#endif +} + +} // namespace tensorrt +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..5526674d488a782718bb2b5f14fc79620b064606 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils.h @@ -0,0 +1,32 @@ +/* Copyright 2019 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_TF2TENSORRT_UTILS_PY_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_PY_UTILS_H_ + +#include +#include + +namespace tensorflow { +namespace tensorrt { + +bool IsGoogleTensorRTEnabled(); + +std::vector GetRegisteredOpConverters(); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_PY_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils_wrapper.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils_wrapper.cc new file mode 100644 index 0000000000000000000000000000000000000000..42f4035ced08a2d3365ea55ccafe24abd4e135db --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/py_utils_wrapper.cc @@ -0,0 +1,44 @@ +/* Copyright 2020 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 + +#include "pybind11/pybind11.h" // from @pybind11 +#include "pybind11/stl.h" // from @pybind11 +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/py_utils.h" + +std::tuple get_linked_tensorrt_version() { + return tensorflow::tensorrt::GetLinkedTensorRTVersion(); +} + +std::tuple get_loaded_tensorrt_version() { + return tensorflow::tensorrt::GetLoadedTensorRTVersion(); +} + +PYBIND11_MODULE(_pywrap_py_utils, m) { + m.doc() = "_pywrap_py_utils: Various TensorRT utilities"; + m.def("get_linked_tensorrt_version", get_linked_tensorrt_version, + "Return the compile time TensorRT library version as the tuple " + "(Major, Minor, Patch)."); + m.def("get_loaded_tensorrt_version", get_loaded_tensorrt_version, + "Return the runtime time TensorRT library version as the tuple " + "(Major, Minor, Patch)."); + m.def("is_tensorrt_enabled", tensorflow::tensorrt::IsGoogleTensorRTEnabled, + "Returns True if TensorRT is enabled."); + m.def("get_registered_op_converters", + tensorflow::tensorrt::GetRegisteredOpConverters, + "Return a list of registered op converters by operation name"); +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.cc new file mode 100644 index 0000000000000000000000000000000000000000..609d2833655364c097b15f0357be0ab929e4ec5e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.cc @@ -0,0 +1,115 @@ +/* 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/tf2tensorrt/utils/trt_allocator.h" + +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +// std::align is not supported, so this method mimic its behavior. +// +// NOTE(aaroey): according to the TensorRT API, +// nvinfer1::IGpuAllocator::allocate() uses uint64_t type for size and alignment +// parameters, so here we use the same type to make it compatible. +void* Align(uint64_t alignment, uint64_t size, void*& ptr, uint64_t& space) { + QCHECK_GT(alignment, 0ul) << "alignment must be greater than 0."; + QCHECK_EQ(0, alignment & (alignment - 1)) << "Alignment must be power of 2."; + QCHECK_GT(size, 0ul) << "size must be greater than 0."; + QCHECK(ptr) << "ptr must not be nullptr."; + QCHECK_GT(space, 0ul) << "space must be greater than 0."; + const uintptr_t ptr_val = reinterpret_cast(ptr); + QCHECK_GE(ptr_val + space, ptr_val) << "Provided space overflows."; + + if (size > space) return nullptr; + const uintptr_t aligned_ptr_val = ((ptr_val + alignment - 1) & -alignment); + if (aligned_ptr_val > ptr_val + space - size) return nullptr; + ptr = reinterpret_cast(aligned_ptr_val); + const uintptr_t diff = aligned_ptr_val - ptr_val; + space -= diff; + return ptr; +} + +} // namespace tensorrt +} // namespace tensorflow + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +void* TRTDeviceAllocator::allocate(uint64_t size, uint64_t alignment, + uint32_t flags) noexcept { + if (size == 0) return nullptr; + // WAR for allocator alignment requirement. Certain cuda API calls require GPU + // memory with alignment to cudaDeviceProp::textureAlignment. + // See issue #20856 + alignment = 512; + assert((alignment & (alignment - 1)) == 0); // zero or a power of 2. + uint64_t total_size = size + alignment; + // TODO(aaroey): AllocateRaw takes size_t size as input, so it'll produce + // unexpected result when TRT tries to allocate more bytes than size_t can + // carry. Fix this. + // + // Fail immediately if allocation fails, rather than waiting 10 seconds and + // failing then anyway. + // TensorRT 7 can also switch to a different algorithm for a layer if an + // algorithm uses too much memory. If we don't fail immediately building the + // engine can be *very* slow with TensorRT7 when GPU memory is limited. + AllocationAttributes attributes; + attributes.retry_on_failure = false; + void* mem = allocator_->AllocateRaw(alignment, total_size, attributes); + if (!mem) return nullptr; + + void* alloc_mem = mem; + QCHECK(Align(alignment, size, mem, total_size)); + mutex_lock lock(mu_); + if (mem != alloc_mem) { + QCHECK(mem_map_.insert({mem, alloc_mem}).second); + } + VLOG(2) << "Allocated " << total_size << " bytes memory @" << alloc_mem + << "; aligned to " << size << " bytes @" << mem << " with alignment " + << alignment; + return mem; +} + +TRTDeviceAllocator::TRTDeviceAllocator(Allocator* allocator) + : allocator_(allocator) { + VLOG(1) << "Using " << allocator->Name() << " allocator from TensorFlow"; +} + +void TRTDeviceAllocator::free(void* memory) noexcept { + mutex_lock lock(mu_); + VLOG(2) << "Deallocating @ " << memory; + // allocated memory adjusted for alignment, restore the original pointer + if (memory) { + auto alloc_mem = mem_map_.find(memory); + if (alloc_mem != mem_map_.end()) { + memory = alloc_mem->second; + mem_map_.erase(alloc_mem->first); + } + allocator_->DeallocateRaw(memory); + } +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..3ad2ef7b6367f5bcc3146733c50ede1226c86210 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h @@ -0,0 +1,73 @@ +/* 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_TF2TENSORRT_UTILS_TRT_ALLOCATOR_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ALLOCATOR_H_ + +#include + +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/mutex.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { +// std::align is not supported, so this function mimic its behavior. +void* Align(uint64_t alignment, uint64_t size, void*& ptr, uint64_t& space); +} // namespace tensorrt +} // namespace tensorflow + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +class TRTBaseAllocator : public nvinfer1::IGpuAllocator { + // Base allocator class so we can have a virtual destructor; + public: + // python wrapper seems to be not happy with an pure virtual destructor; + virtual ~TRTBaseAllocator() = default; +}; + +class TRTDeviceAllocator : public TRTBaseAllocator { + // Allocator implementation wrapping TF device allocators. + public: + TRTDeviceAllocator(Allocator* allocator); + + // TODO(aaroey): base class doesn't have a virtual destructor, work with + // Nvidia to fix it. + virtual ~TRTDeviceAllocator() { + VLOG(1) << "Destroying allocator attached to " << allocator_->Name(); + } + void* allocate(uint64_t size, uint64_t alignment, + uint32_t flags) noexcept override; + void free(void* memory) noexcept override; + + private: + mutex mu_; + Allocator* allocator_; + + // supporting alignment from allocation request requires a map to free; + std::unordered_map mem_map_ TF_GUARDED_BY(mu_); +}; + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ALLOCATOR_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a03032330950598540807ba24044739acd19cd61 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_allocator_test.cc @@ -0,0 +1,87 @@ +/* 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/tf2tensorrt/utils/trt_allocator.h" + +#include + +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace tensorrt { + +bool RunTest(const uint64_t alignment, const uint64_t size, + const intptr_t orig_ptr_val, const uint64_t orig_space) { + void* const orig_ptr = reinterpret_cast(orig_ptr_val); + void* ptr = orig_ptr; + uint64_t space = orig_space; + void* result = Align(alignment, size, ptr, space); + if (result == nullptr) { + EXPECT_EQ(orig_ptr, ptr); + EXPECT_EQ(orig_space, space); + return false; + } else { + EXPECT_EQ(result, ptr); + const intptr_t ptr_val = reinterpret_cast(ptr); + EXPECT_EQ(0, ptr_val % alignment); + EXPECT_GE(ptr_val, orig_ptr_val); + EXPECT_GE(space, size); + EXPECT_LE(space, orig_space); + EXPECT_EQ(ptr_val + space, orig_ptr_val + orig_space); + return true; + } +} + +TEST(TRTAllocatorTest, Align) { + for (const uint64_t space : + {1ul, 2ul, 3ul, 4ul, 7ul, 8ul, 9ul, 10ul, 16ul, 32ul, 511ul, 512ul, + 513ul, 700ul, 12345ul, 1ul << 32}) { + for (uint64_t alignment = 1; alignment <= space * 4; alignment *= 2) { + for (const uintptr_t ptr_val : + {static_cast(1), + alignment == 1 ? static_cast(1) : alignment - 1, + alignment, alignment + 1, alignment + (alignment / 2)}) { + if (ptr_val % alignment == 0) { + for (const uint64_t size : + {static_cast(1), + space == 1 ? static_cast(1) : space - 1, space, + space + 1}) { + EXPECT_EQ(space >= size, RunTest(alignment, size, ptr_val, space)); + } + } else { + EXPECT_FALSE(RunTest(alignment, space, ptr_val, space)); + const uint64_t diff = alignment - ptr_val % alignment; + if (space > diff) { + EXPECT_TRUE( + RunTest(alignment, space - diff, ptr_val + diff, space - diff)); + for (const uint64_t size : + {static_cast(1), + space - diff > 1 ? space - diff - 1 + : static_cast(1), + space - diff, space - diff + 1, space - 1}) { + EXPECT_EQ(space - diff >= size, + RunTest(alignment, size, ptr_val, space)); + } + } else { + EXPECT_FALSE(RunTest(alignment, 1, ptr_val, space)); + } + } + } + } + } +} + +} // namespace tensorrt +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_instance.proto b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_instance.proto new file mode 100644 index 0000000000000000000000000000000000000000..965cd431bbbeb09e59a3400a48c35896381307af --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_instance.proto @@ -0,0 +1,19 @@ +syntax = "proto3"; + +package tensorflow.tensorrt; + +import "tensorflow/core/framework/tensor_shape.proto"; + +// Containing information for a serialized TensorRT engine. +message TRTEngineInstance { + // The input shapes of the TRT engine. + repeated TensorShapeProto input_shapes = 1; + + // The serialized TRT engine. + // + // TODO(laigd): consider using a more efficient in-memory representation + // instead of string which is the default here. + bytes serialized_engine = 2; + + // TODO(laigd): consider adding calibration stats, precision_modes, etc. +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..c8dc03cfeb8ffeded8e4237687532d1aad6d71be --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.cc @@ -0,0 +1,286 @@ +/* Copyright 2020 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/tf2tensorrt/utils/trt_engine_utils.h" + +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_execution_context.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/profiler/lib/traceme.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +using absl::StrCat; + +ExecutionContext ExecutionContext::Create(nvinfer1::ICudaEngine* cuda_engine) { + bool has_int32_output = false; + for (int i = 0; i < cuda_engine->getNbBindings(); i++) { + if (!cuda_engine->bindingIsInput(i) && + cuda_engine->getBindingDataType(i) == nvinfer1::DataType::kINT32) { + has_int32_output = true; + break; + } + } + if (!IS_TRT_VERSION_GE(8, 0, 0, 0) && has_int32_output) { + // TODO(nvbugs/3390469): Remove this workaround when the bug is fixed. + nvinfer1::IExecutionContext* execution_context = + cuda_engine->createExecutionContext(); + return ExecutionContext(execution_context, true); + } + + nvinfer1::IExecutionContext* execution_context = + cuda_engine->createExecutionContextWithoutDeviceMemory(); + return ExecutionContext(execution_context, false); +} + +Status GetTrtBindingShape(const nvinfer1::ICudaEngine* cuda_engine, + const nvinfer1::IExecutionContext* execution_context, + int binding_index, bool use_implicit_batch, + int batch_size, TensorShape& shape) { + tensorflow::profiler::TraceMe activity( + "getBindingDimensions", tensorflow::profiler::TraceMeLevel::kInfo); + nvinfer1::Dims dims = + use_implicit_batch + ? cuda_engine->getBindingDimensions(binding_index) + : execution_context->getBindingDimensions(binding_index); + if (!use_implicit_batch) { + if (dims.nbDims == -1) { + return errors::Internal( + "Binding index out of range. This can happen if profile is not set, " + "or the network is invalid for the current profile."); + } + } + TF_RETURN_IF_ERROR(DimsAdapter(dims).TensorShape( + &shape, + use_implicit_batch ? std::optional(batch_size) : std::nullopt)); + return OkStatus(); +} + +Status SetupBindings(nvinfer1::ICudaEngine* cuda_engine, const Tensor& tensor, + std::vector& buffers, int binding_index) { + tensorflow::profiler::TraceMe activity( + "SetBindingPointers", tensorflow::profiler::TraceMeLevel::kInfo); + const auto dtype = cuda_engine->getBindingDataType(binding_index); + VLOG(2) << "<<<<<<<<< SetupBindings with dtype = " << (int)dtype; + switch (dtype) { + case nvinfer1::DataType::kFLOAT: + buffers[binding_index] = const_cast(tensor.flat().data()); + break; + case nvinfer1::DataType::kHALF: + buffers[binding_index] = + const_cast(tensor.flat().data()); + break; + case nvinfer1::DataType::kINT8: + return errors::Internal("INT8 inputs are not supported yet!"); + case nvinfer1::DataType::kINT32: + buffers[binding_index] = const_cast(tensor.flat().data()); + break; +#if IS_TRT_VERSION_GE(8, 2, 0, 0) + case nvinfer1::DataType::kBOOL: + buffers[binding_index] = const_cast(tensor.flat().data()); + break; +#endif +#if IS_TRT_VERSION_GE(8, 5, 0, 0) + case nvinfer1::DataType::kUINT8: + buffers[binding_index] = const_cast(tensor.flat().data()); + break; +#endif +#if IS_TRT_VERSION_GE(8, 6, 0, 0) + case nvinfer1::DataType::kFP8: + return errors::Internal("FP8 inputs are not supported yet!"); +#endif + default: + return errors::Internal("Unknown TRT data type: ", + static_cast(dtype)); + } + return OkStatus(); +} + +// Sets up bindings. +Status SetTrtEngineInputs(nvinfer1::ICudaEngine* cuda_engine, + nvinfer1::IExecutionContext* execution_context, + const int trt_profile_idx, + std::vector& buffers, bool use_implicit_batch, + int num_batch, + const TrtShapeOptimizationProfile& profiles, + OpKernelContext* ctx, const DataVec* input_vec) { + tensorflow::profiler::TraceMe activity( + "SetTrtEngineInputs", tensorflow::profiler::TraceMeLevel::kInfo); + int n_inputs = ctx ? ctx->num_inputs() : (input_vec ? input_vec->size() : 0); + // Setup engine inputs. + for (int i = 0; i < n_inputs; i++) { + const Tensor& input_tensor = ctx ? ctx->input(i) : input_vec->at(i).tensor; + const TensorShape& input_shape = input_tensor.shape(); + + // Skip resource inputs. + if (input_tensor.dtype() == DataType::DT_RESOURCE) { + continue; + } + + const string input_name = + ctx ? StrCat(IONamePrefixes::kInputPHName, i) : input_vec->at(i).name; + int binding_index; + Status status = GetTrtBindingIndex(input_name.c_str(), trt_profile_idx, + cuda_engine, &binding_index); + if (IS_TRT_VERSION_GE(8, 0, 0, 0)) { + TF_RETURN_IF_ERROR(status); + } else if (!status.ok()) { + // Before TRT 8, an input tensor can be pruned if it is not used by the + // network (e.g. only its shape is used, but the shape is already defined + // by the optimization profile by setting min=max). nvbugs/3153064 + VLOG(2) << "Skipping pruned input " << input_name; + continue; + } + + if (use_implicit_batch && ctx) { + // Ensure all inputs have the same batch size + if (num_batch != input_shape.dim_size(0)) { + const string msg = + StrCat("Input data has inconsistent batch size: ", num_batch, + " vs ", input_shape.dim_size(0)); + return errors::NotFound(msg); + } + } + // Set known input dimensions. This is necessary because TRT network + // could be made with dynamic dimensions. + if (!use_implicit_batch) { + TF_RETURN_IF_ERROR(profiles.SetInputShapeBinding( + i, binding_index, cuda_engine, execution_context)); + + if (cuda_engine->isExecutionBinding(binding_index)) { + tensorflow::profiler::TraceMe activity( + "SetTrtEngineInputs::setBindingDimensions", + tensorflow::profiler::TraceMeLevel::kInfo); + auto adap = DimsAdapter::Create(input_shape); + TRT_ENSURE_OK(adap); + nvinfer1::Dims trt_dims = adap->AsTrtDims(); + if (execution_context->getBindingDimensions(binding_index) != + trt_dims) { + VLOG(2) << "Setting binding dimensions for idx " << binding_index; + bool ret = + execution_context->setBindingDimensions(binding_index, trt_dims); + if (!ret) { + VLOG(2) << "Error setting engine input " << binding_index << " " + << DebugString(trt_dims); + return errors::Internal( + "Binding dimension does not fit selected profile."); + } + } + } + } + // Setup input bindings. + TF_RETURN_IF_ERROR( + SetupBindings(cuda_engine, input_tensor, buffers, binding_index)); + } + + // Ensure all network dynamic dimensions (if any) are set in execution + // context. + if (!execution_context->allInputDimensionsSpecified()) { + return errors::Internal( + "Failed to set dimensions for all dynamic input tensors"); + } + if (!execution_context->allInputShapesSpecified()) { + return errors::Internal( + "Failed to set dimensions for all shape input tensors."); + } + return OkStatus(); +} + +Status SetTrtEngineOutputs(nvinfer1::ICudaEngine* cuda_engine, + nvinfer1::IExecutionContext* execution_context, + int trt_profile_idx, std::vector& buffers, + bool use_implicit_batch, int batch_size, + OpKernelContext* ctx, DataVec* outputs) { + tensorflow::profiler::TraceMe activity( + "SetTrtEngineOutputs", tensorflow::profiler::TraceMeLevel::kInfo); + // Either one of ctx or outpus should be specified + int n_outputs = ctx ? ctx->num_outputs() : (outputs ? outputs->size() : 0); + for (int i = 0; i < n_outputs; i++) { + const string output_name = + ctx ? StrCat(IONamePrefixes::kOutputPHName, i) : outputs->at(i).name; + int binding_index; + TF_RETURN_IF_ERROR(GetTrtBindingIndex(output_name.c_str(), trt_profile_idx, + cuda_engine, &binding_index)); + + // Get TRT output shapes for allocating output memory. + TensorShape output_shape; + TF_RETURN_IF_ERROR(GetTrtBindingShape(cuda_engine, execution_context, + binding_index, use_implicit_batch, + batch_size, output_shape)); + + // Allocate output tensor of TRTEngineOp. + Tensor* output_tensor = nullptr; + if (ctx) { + tensorflow::profiler::TraceMe activity( + "AllocateOutput", tensorflow::profiler::TraceMeLevel::kInfo); + TF_RETURN_IF_ERROR(ctx->allocate_output(i, output_shape, &output_tensor)); + } else { + // This path is used for unit tests. The tensor is already allocated. + // Its shape is not necessarily set correctly, we fix that. + VLOG(2) << "Applying shape " << output_shape.DebugString() + << " on output."; + output_tensor = &(outputs->at(i).tensor); + bool status = output_tensor->CopyFrom(*output_tensor, output_shape); + if (!status) { + return errors::Internal( + "Buffer size (", output_tensor->NumElements(), + ") do not match while reshaping output tensors to shape ", + output_shape.DebugString()); + } + } + + // Set up output bindings. + TF_RETURN_IF_ERROR( + SetupBindings(cuda_engine, *output_tensor, buffers, binding_index)); + } + return OkStatus(); +} + +Status TrtEnqueue(nvinfer1::IExecutionContext* execution_context, + std::vector& buffers, cudaStream_t stream, + bool use_implicit_batch, int batch_size) { + tensorflow::profiler::TraceMe activity( + "TrtEnqueue", tensorflow::profiler::TraceMeLevel::kInfo); + bool ret = false; + if (use_implicit_batch) { + ret = execution_context->enqueue(batch_size, &buffers[0], stream, nullptr); + VLOG(1) << "Called IExecutionContext::enqueue"; + } else { + ret = execution_context->enqueueV2(&buffers[0], stream, nullptr); + VLOG(1) << "Called IExecutionContext::enqueueV2"; + } + if (!ret) { + return errors::Internal("Failed to enqueue batch for TRT engine"); + } + // Synchronization will be done by TF. + return OkStatus(); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..b275254d59d867b6835ee3ff96dcac52c9225ebf --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h @@ -0,0 +1,82 @@ +/* Copyright 2020 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_TF2TENSORRT_UTILS_TRT_ENGINE_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ENGINE_UTILS_H_ + +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/common/datavec.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/status.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +using ::tsl::StatusOr; + +// Creates a TensorRT execution context. +ExecutionContext CreateExecutionContext(nvinfer1::ICudaEngine* cuda_engine); + +// Sets input buffers for TRT from a list of input tensors. The input tensors +// are either defined by ctx or by input_vec. +Status SetTrtEngineInputs(nvinfer1::ICudaEngine* cuda_engine, + nvinfer1::IExecutionContext* execution_context, + const int trt_profile_idx, + std::vector& buffers, bool use_implicit_batch, + int num_batch, + const TrtShapeOptimizationProfile& profiles, + OpKernelContext* ctx = nullptr, + const DataVec* input_vec = nullptr); + +// Returns the shape of a binding from TensorRT. +// +// The binding is identified by its binding_index. The batch_size argument is +// ignored if use_implicit_batch==false. The shape is returned in the last +// argument. +Status GetTrtBindingShape(const nvinfer1::ICudaEngine* cuda_engine, + const nvinfer1::IExecutionContext* execution_context, + int binding_index, bool use_implicit_batch, + int batch_size, TensorShape& shape); + +// Defines output buffers for TRT. The buffers are allocated by ctx, if ctx is +// not null. Otherwise it is expected that the outputs DataVec is not null, and +// the Tensors in outputs are already allocated. +Status SetTrtEngineOutputs(nvinfer1::ICudaEngine* cuda_engine, + nvinfer1::IExecutionContext* execution_context, + int trt_profile_idx, std::vector& buffers, + bool use_implicit_batch, int batch_size = 0, + OpKernelContext* ctx = nullptr, + DataVec* outputs = nullptr); + +// Enqueues TensorRT inference job. The batch_size argument is only relevant in +// implicit batch mode. +Status TrtEnqueue(nvinfer1::IExecutionContext* execution_context, + std::vector& buffers, cudaStream_t stream, + bool use_implicit_batch, int batch_size = 1); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_ENGINE_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_execution_context.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_execution_context.h new file mode 100644 index 0000000000000000000000000000000000000000..4ba2d3b641bb32268ded9d1f1a01d12b55ff66c7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_execution_context.h @@ -0,0 +1,43 @@ +/* Copyright 2021 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_TF2TENSORRT_UTILS_TRT_EXECUTION_CONTEXT_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_EXECUTION_CONTEXT_H_ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +// A wrapper for the TensorRT execution context which will destroy the TensorRT +// execution context when the object goes out of scope. +class ExecutionContext : public TrtUniquePtrType { + public: + ExecutionContext(nvinfer1::IExecutionContext* context, bool has_memory) + : TrtUniquePtrType(context), + has_device_memory_(has_memory) {} + static ExecutionContext Create(nvinfer1::ICudaEngine* cuda_engine); + + bool HasDeviceMemory() { return has_device_memory_; } + + private: + bool has_device_memory_; +}; + +}; // namespace tensorrt +}; // namespace tensorflow +#endif +#endif diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.cc new file mode 100644 index 0000000000000000000000000000000000000000..9432317740de24ff79c90fe20939b1bd25c0a769 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.cc @@ -0,0 +1,35 @@ +/* Copyright 2022 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/tf2tensorrt/convert/utils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/core/util/env_var.h" + +namespace tensorflow { +namespace tensorrt { + +bool isExperimentalFeatureActivated(string feature_name) { + string envvar_str; + TF_CHECK_OK( + ReadStringFromEnvVar("TF_TRT_EXPERIMENTAL_FEATURES", "", &envvar_str)); + return envvar_str.find(feature_name) != string::npos; +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.h new file mode 100644 index 0000000000000000000000000000000000000000..dc11ade29091f5d32e01f3b1f19a007fdb549259 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.h @@ -0,0 +1,31 @@ +/* Copyright 2022 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_TF2TENSORRT_UTILS_TRT_EXPERIMENTAL_FEATURES_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_EXPERIMENTAL_FEATURES_H_ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +bool isExperimentalFeatureActivated(string feature_name); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_EXPERIMENTAL_FEATURES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.cc new file mode 100644 index 0000000000000000000000000000000000000000..156b00e38d76b02b5f821c4356a8e77dfe7fe5e4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.cc @@ -0,0 +1,150 @@ +/* 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/tf2tensorrt/utils/trt_int8_calibrator.h" + +#include +#include + +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" + +namespace tensorflow { +namespace tensorrt { + +// set the batch size before constructing the thread to execute engine +int TRTInt8Calibrator::getBatchSize() const noexcept { return batch_size_; } + +TRTInt8Calibrator::TRTInt8Calibrator( + const std::unordered_map>& dev_buffers, + int batch_size, string engine_name) + : batch_size_(batch_size), + done_(false), + dev_buffers_(dev_buffers), + // Make sure setBatch() waits until getBatch() is called (the first time). + calib_running_(true), + batch_is_set_(false), + engine_name_(engine_name) {} + +TRTInt8Calibrator::TRTInt8Calibrator(const string& calib_data) + : batch_size_(0), + done_(true), + calib_running_(false), + batch_is_set_(false), + calibration_table_(calib_data) {} + +bool TRTInt8Calibrator::setBatch(const std::unordered_map& data, + const cudaStream_t stream) { + mutex_lock lock(cond_mtx_); + + // Wait while the queue is full or calibration is running. + while ((calib_running_ || batch_is_set_) && !done_) cond_.wait(lock); + if (done_) return false; + CHECK(!calib_running_ && !batch_is_set_); + VLOG(1) << "Set Batch Waiting finished"; + + // Sets the batch. + for (const auto& it : data) { + auto devptr = dev_buffers_.find(it.first); + if (devptr == dev_buffers_.end()) { + LOG(FATAL) << "FATAL " << engine_name_ << " input name '" << it.first + << "' does not match with the buffer names"; + } + const auto& d = devptr->second; + + // TODO(sami,aaroey): Need to figure out a way to ensure synchronization + // between stream, perhaps using a tensor? + auto status = cudaMemcpyAsync(d.first, it.second, d.second, + cudaMemcpyDeviceToDevice, stream); + if (status != cudaSuccess) { + LOG(FATAL) << "cudaMemcpy " << engine_name_ << " for '" << it.first + << "' failed with " << status; + } + } + + // TODO(Sami, aaorey): Find an alternative way! + // we have to wait for the stream before returning! + cudaStreamSynchronize(stream); + batch_is_set_ = true; + cond_.notify_all(); + return true; +} + +bool TRTInt8Calibrator::getBatch(void** bindings, const char** names, + int num_bindings) noexcept { + mutex_lock lock(cond_mtx_); + // Notify finish of last round of calibration. + calib_running_ = false; + cond_.notify_all(); + + // Wait until new batch arrives + while ((!batch_is_set_ && !done_)) cond_.wait(lock); + if (done_) return false; + + // Gets the batch + for (int i = 0; i < num_bindings; i++) { + auto it = dev_buffers_.find(names[i]); + if (it == dev_buffers_.end()) { + LOG(FATAL) << "Calibration engine asked for unknown tensor name '" + << names[i] << "' at position " << i; + } + bindings[i] = it->second.first; + } + batch_is_set_ = false; + calib_running_ = true; + return true; +} + +void TRTInt8Calibrator::waitAndSetDone() { + mutex_lock lock(cond_mtx_); + // Wait while the queue is full or calibration is running, so we don't miss + // the last batch. + while ((calib_running_ || batch_is_set_) && !done_) cond_.wait(lock); + if (!done_) { + done_ = true; + cond_.notify_all(); + dev_buffers_.clear(); + } +} + +const void* TRTInt8Calibrator::readCalibrationCache( + std::size_t& length) noexcept { + if (calibration_table_.empty()) return nullptr; + length = calibration_table_.size(); + return calibration_table_.data(); +} + +void TRTInt8Calibrator::setDone() { + mutex_lock lock(cond_mtx_); + done_ = true; + cond_.notify_all(); +} + +void TRTInt8Calibrator::writeCalibrationCache(const void* ptr, + std::size_t length) noexcept { + calibration_table_ = string(static_cast(ptr), length); + VLOG(1) << "Got calibration data for " << engine_name_ << " @" << ptr + << " length=" << length; +} +TRTInt8Calibrator::~TRTInt8Calibrator() { + VLOG(1) << "Destroying calibrator for " << engine_name_; +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h new file mode 100644 index 0000000000000000000000000000000000000000..fcf4a233edf6a493ee5de382b064defd11b1e822 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h @@ -0,0 +1,102 @@ +/* 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_TF2TENSORRT_UTILS_TRT_INT8_CALIBRATOR_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_INT8_CALIBRATOR_H_ + +#include +#include +#include +#include + +#include "tensorflow/core/platform/mutex.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +// This class provides a 1 element queue to match TFs push model to +// TRTs pull model for calibration. When TRT implements a means for +// a push calibration This class should be updated accordingly + +// IInt8EntropyCalibrator2 is preferred for TRT 5.1+. +struct TRTInt8Calibrator : public nvinfer1::IInt8EntropyCalibrator2 { + public: + // Construct a calibrator for future calibration. + TRTInt8Calibrator( + const std::unordered_map>& dev_buffers, + int batch_size, string engine_name); + + // Construct a finalized calibrator where we don't need to run calibration any + // more, as the calibration data is provided. + TRTInt8Calibrator(const string& calibration_data); + + ~TRTInt8Calibrator(); + + int getBatchSize() const noexcept override; + + bool getBatch(void* bindings[], const char* names[], + int num_bindings) noexcept override; + + // Feed calibration data to the calibrator, and return true if the data is + // accepted. Return false if the calibrator has been terminated. + bool setBatch(const std::unordered_map& data, + const cudaStream_t stream); + + // Wait until the last batch is consumed by the calibrator and set done. + void waitAndSetDone(); + + // Notify that calibration is done and future batches provided by setBatch() + // will be ignored. + void setDone(); + + // If not null, calibration is skipped. + const void* readCalibrationCache(std::size_t& length) noexcept override; + + void writeCalibrationCache(const void* ptr, + std::size_t length) noexcept override; + + const string& getCalibrationTableAsString() { return calibration_table_; } + + private: + const int batch_size_; + + // mutex for condition_variable + mutex cond_mtx_; + + // condition variable to implement producer-consumer queue for calibration + condition_variable cond_; + + // Is calibration finished? + bool done_; + + // Map to keep tensorrt input buffers and sizes keyed with buffer names + std::unordered_map> dev_buffers_; + + bool calib_running_; + bool batch_is_set_; + + string engine_name_; + string calibration_table_; +}; + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_INT8_CALIBRATOR_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_logger.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_logger.cc new file mode 100644 index 0000000000000000000000000000000000000000..09cd6aa004cd2434dfc84480e70f5c39784efbb2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_logger.cc @@ -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. +==============================================================================*/ + +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/logger_registry.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_experimental_features.h" +#include "tensorflow/core/platform/logging.h" + +namespace tensorflow { +namespace tensorrt { + +bool filter_string(string msg) { + // This function checks for known substrings that shall be ignored. + + static const std::vector substr_patterns{ + // Automatic messages generated by TensorRT when combined with + // Automatic Mixed Precision - TensorRT 8.2 + "Missing scale and zero-point for", + "Subnormal FP16 values detected", + "If this is not the desired behavior, please modify the weights", + "had the following issues when converted to FP16", + "Values less than smallest positive FP16 Subnormal value detected.", + // Deprecation Warnings + "The implicit batch dimension mode has been deprecated.", + "The getMaxBatchSize() function should not be used with an engine built", + // Input-Warnings + "[RemoveDeadLayers] Input Tensor input is unused or used only at", + "Unused Input:", + // Data Type Warnings + "Tensor DataType is determined at build time for tensors not marked as", + // Myelin Performance Warning in dynamic shape mode + "Myelin graph with multiple dynamic values may have poor performance", + "(# 0 (SHAPE", + "CUDA lazy loading is not enabled. Enabling it can significantly reduce", + }; + + for (int i = 0; i < substr_patterns.size(); i++) { + std::size_t is_found = msg.find(substr_patterns[i]); + if (is_found != string::npos) { + return true; + } + } + return false; +} + +// Use TF logging for TensorRT information +void Logger::log(Severity severity, const char* msg) noexcept { + static const bool filter_messages = []() { + return !isExperimentalFeatureActivated("disable_logger_filtering"); + }(); + + if (filter_messages && filter_string(msg)) return; + + if (!isValidSeverity(severity, msg) || suppressedMsg_ & (1 << (int)severity)) + return; + + // Suppress info-level messages + switch (severity) { + case Severity::kVERBOSE: + case Severity::kINFO: { // Mark TRT info messages as debug! + VLOG(2) << name_ << " " << msg; + break; + } + case Severity::kWARNING: { + LOG_WARNING_WITH_PREFIX << name_ << " " << msg; + break; + } + case Severity::kERROR: { + LOG(ERROR) << name_ << " " << msg; + break; + } + case Severity::kINTERNAL_ERROR: { + LOG(FATAL) << name_ << " " << msg; + break; + } + } +} + +void Logger::suppressLoggerMsgs(Severity severity) { + if (isValidSeverity(severity)) { + suppressedMsg_ |= 1 << (int)severity; + } +} + +void Logger::unsuppressLoggerMsgs(Severity severity) { + if (isValidSeverity(severity)) { + suppressedMsg_ &= (-1) ^ (1 << (int)severity); + } +} + +bool Logger::isValidSeverity(Severity severity, const char* msg) noexcept { + switch (severity) { + case Severity::kVERBOSE: + case Severity::kINFO: + case Severity::kWARNING: + case Severity::kERROR: + case Severity::kINTERNAL_ERROR: + return true; + } + return false; +} + +// static +Logger* Logger::GetLogger() { + static Logger* logger = new Logger("DefaultLogger"); + return logger; +} + +REGISTER_TENSORRT_LOGGER("DefaultLogger", Logger::GetLogger()); + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_logger.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_logger.h new file mode 100644 index 0000000000000000000000000000000000000000..1cf1f9862fcfc89d48da26aad9a459d1de5fd1ac --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_logger.h @@ -0,0 +1,50 @@ +/* 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_TF2TENSORRT_UTILS_TRT_LOGGER_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_LOGGER_H_ + +#include "tensorflow/core/platform/types.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +// Logger for GIE info/warning/errors +class Logger : public nvinfer1::ILogger { + public: + Logger(string name = "DefaultLogger") : name_(name) {} + void log(nvinfer1::ILogger::Severity severity, + const char* msg) noexcept override; + void suppressLoggerMsgs(nvinfer1::ILogger::Severity severity); + void unsuppressLoggerMsgs(nvinfer1::ILogger::Severity severity); + void unsuppressAllLoggerMsgs() { suppressedMsg_ = 0; } + static Logger* GetLogger(); + + private: + bool isValidSeverity(nvinfer1::ILogger::Severity severity, + const char* msg = nullptr) noexcept; + const string name_; + unsigned int suppressedMsg_ = 0; +}; + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_LOGGER_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.cc new file mode 100644 index 0000000000000000000000000000000000000000..32aaeb98273af2661f1dfd0af95487b9b0e4979d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.cc @@ -0,0 +1,143 @@ +/* Copyright 2019 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/tf2tensorrt/utils/trt_lru_cache.h" + +#include + +#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/mutex.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +string CalibrationContext::TerminateCalibration() { + mutex_lock l(mu_); + if (terminated_) return calibration_table_; + + TRTInt8Calibrator* raw_calibrator = calibrator_.get(); + raw_calibrator->waitAndSetDone(); + terminated_ = true; + + // At this point the calibration thread `thr_` is woken up and can + // transfer the ownership of `calibrator_` and `engine_` at any time, so + // it's not safe to use `calibrator_` below, but we can still access it + // using raw pointer. + // TODO(laigd): make TRTEngineOp::AllocateCalibrationResources() a member + // function of this class instead. + + thr_->join(); + calibration_table_ = raw_calibrator->getCalibrationTableAsString(); + return calibration_table_; +} + +const absl::string_view kTfTrtContainerName = "TF-TRT"; + +Logger& TRTEngineCacheResource::GetLogger() { + static Logger* logger = new Logger(); + return *logger; +} + +TRTEngineCacheResource::TRTEngineCacheResource(OpKernelContext* ctx, + size_t capacity) + : cache_(capacity) { + auto device = ctx->device(); + auto alloc = device->GetAllocator(AllocatorAttributes()); + if (!alloc) { + LOG(ERROR) << "Can't find device allocator for gpu device " + << device->name(); + allocator_ = nullptr; + } else { + allocator_.reset(new TRTDeviceAllocator(alloc)); + } +} + +TRTEngineCacheResource::~TRTEngineCacheResource() { + VLOG(1) << "Destroying TRTEngineCacheResource..."; +} + +string TRTEngineCacheResource::DebugString() const { + std::stringstream oss; + using std::dec; + using std::endl; + using std::hex; + oss << "TRTEngineCacheResource: "; + oss << "TRTBaseAllocator = " << hex << allocator_.get() << dec << ", "; + oss << "LRUCache = " << hex << &cache_ << dec << endl; + oss << "Containing " << cache_.size() << " entries: " << endl; + for (const auto& item : cache_) { + mutex_lock lock(item.second->mu); + oss << TensorShapeUtils::ShapeListString(item.first) << ": " << hex + << "ICudaEngine: " << item.second->GetCudaEngine() << ", " + << "IExecutionContext: "; + absl::c_for_each( + item.second->execution_contexts, + [&](const ExecutionContext& ctx) { oss << ctx.get() << ","; }); + oss << dec << endl; + } + return oss.str(); +} + +EngineContext* TRTEngineCacheResource::GetEngineContext( + const std::vector& input_shapes) { + EngineContext* engine_context = nullptr; + int64 min_matched_batch_size = std::numeric_limits::max(); + for (const auto& pair : cache_) { + const std::vector& cached_input_shapes = pair.first; + // This should not happen, but just for safety. + if (input_shapes.size() != cached_input_shapes.size()) { + LOG(ERROR) << "Input shape list size mismatch" + << ", cached size: " << cached_input_shapes.size() + << " vs. input size: " << input_shapes.size(); + } + if (AreShapesCompatible(input_shapes, cached_input_shapes)) { + const int cached_batch_size = cached_input_shapes[0].dim_size(0); + if (min_matched_batch_size > cached_batch_size) { + min_matched_batch_size = cached_batch_size; + engine_context = pair.second.get(); + } + } + } + return engine_context; +} + +EngineContext* TRTEngineCacheResource::GetEngineContext(const int profile_id) { + if (profiles_.NeedProfiles() && profile_id >= profiles_.GetNumProfiles()) { + LOG(ERROR) << "Out of range: profile_id " << profile_id + << " is larger than number of profiles " + << profiles_.GetNumProfiles(); + return nullptr; + } + if (cache_.size() > 1) { + LOG(ERROR) << "Cache is expected to have at most " + << "1 engine in explicit batch mode where profiles are used."; + return nullptr; + } + if (cache_.size() == 0) { + return nullptr; + } + return cache_.begin()->second.get(); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h new file mode 100644 index 0000000000000000000000000000000000000000..6eebc6bb54e807afdca820975625373136c6d9b3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h @@ -0,0 +1,261 @@ +/* Copyright 2019 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_TF2TENSORRT_UTILS_TRT_LRU_CACHE_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_LRU_CACHE_H_ + +#include +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_allocator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_int8_calibrator.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/lib/core/errors.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +namespace tensorflow { +namespace tensorrt { + +template +class LRUCache { + public: + typedef Value value_type; + typedef Key key_type; + typedef HashFunction hasher; + typedef typename std::unordered_map map_type; + typedef typename map_type::iterator iterator; + typedef typename map_type::const_iterator const_iterator; + + LRUCache() : capacity_(0) {} + explicit LRUCache(size_t capacity) : capacity_(capacity) {} + + size_t capacity() const { return capacity_; } + + void reserve(size_t capacity) { + capacity_ = capacity; + DiscardOld(); + } + + size_t size() const { return objects_.size(); } + + size_t count(const key_type& key) const { return objects_.count(key); } + + value_type& at(const key_type& key) { return Touch(key); } + + const_iterator begin() const { return objects_.begin(); } + const_iterator end() const { return objects_.end(); } + + iterator begin() { return objects_.begin(); } + iterator end() { return objects_.end(); } + + template + std::pair emplace(Args&&... args) { + DiscardOld(1); + std::pair result = + objects_.emplace(std::forward(args)...); + key_type key = result.first->first; + if (result.second) { + keys_.push_front(key); + } else { + TouchNoCheck(key); // The key must exist in this case. + } + return result; + } + + private: + std::unordered_map objects_; + std::list keys_; + size_t capacity_; + value_type not_found_value_; + + value_type& Touch(const key_type& key) { + // Check that the key exists, and let it return std::out_of_range error if + // not. + value_type& value = objects_.at(key); + TouchNoCheck(key); + return value; + } + + void TouchNoCheck(const key_type& key) { + auto rank = std::find(keys_.begin(), keys_.end(), key); + if (rank != keys_.begin()) { + keys_.erase(rank); + keys_.push_front(key); + } + } + + // Creates n free positions in cache + void DiscardOld(size_t n = 0) { + DCHECK(capacity_ >= n) << "Insufficient capacity in cache (capacity = " + << capacity_ << ", requested " << n << ")"; + while (objects_.size() > (capacity_ - n)) { + key_type discard_key = keys_.back(); + keys_.pop_back(); + objects_.erase(discard_key); + } + } +}; + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +struct EngineContext { + EngineContext() {} // Creates an empty context. + EngineContext(TrtUniquePtrType&& cuda_engine, + ExecutionContext&& execution_context) + : cuda_engine_(std::move(cuda_engine)) { + execution_contexts.push_back(std::move(execution_context)); + device_memory_size_ = + cuda_engine_ ? cuda_engine_->getDeviceMemorySize() : 0; + } + EngineContext(TrtUniquePtrType&& cuda_engine, + std::vector&& execution_contexts) + : cuda_engine_(std::move(cuda_engine)), + execution_contexts(std::move(execution_contexts)) { + device_memory_size_ = + cuda_engine_ ? cuda_engine_->getDeviceMemorySize() : 0; + } + + mutex mu; + + nvinfer1::ICudaEngine* GetCudaEngine() { return cuda_engine_.get(); } + + Status GetExecutionContext(int idx, nvinfer1::IExecutionContext** exec_ctx, + bool* has_device_memory) + TF_EXCLUSIVE_LOCKS_REQUIRED(mu) { + if (idx >= execution_contexts.size()) { + return errors::Internal("Requested engine context with index ", idx, + ", but only ", execution_contexts.size(), + "contexts are present."); + } + *exec_ctx = execution_contexts[idx].get(); + *has_device_memory = execution_contexts[idx].HasDeviceMemory(); + return OkStatus(); + } + + int GetNumContexts() { + mutex_lock lock(mu); + return execution_contexts.size(); + } + + size_t GetDeviceMemorySize() { return device_memory_size_; } + + private: + // Note: declaration has to come before execution_contexts, to ensure proper + // order of destruction. + TrtUniquePtrType cuda_engine_; + + public: + // In explicit batch mode, we maintain a vector of contexts for each engine, + // where each context is created for a specific profile. This is because it is + // either not possible or non-trivial to change the profile of a context for + // the following reasons: + // - To switch profiles (from TRT 7), one must first ensure that all inference + // calls in that context are finished. This would require an additional + // synchronization before we call setOptimizationProfile. To avoid this + // extra sync call, we maintain separate execution context for each profile. + // IExecutionContext object is not thread safe: only one thread should use it + // for inference at a time therefore we need a mutex. More details at + // https://docs.nvidia.com/deeplearning/sdk/tensorrt-best-practices/index.html#thread-safety + // Additional discussion about execution context management and thread safety + // at https://github.com/tensorflow/tensorflow/issues/36959 + std::vector execution_contexts TF_GUARDED_BY(mu); + + private: + // Until TRT 8.4 ICudaEngine::getDeviceMemorySize() has a non-negligible + // latency. Since its value remains constant, we can cache it. + size_t device_memory_size_; +}; +// Contains the context required to build the calibration data. +class CalibrationContext { + public: + string TerminateCalibration(); + + // Lookup table for temporary staging areas of input tensors for calibration. + std::unordered_map> device_buffers_; + + // Temporary staging areas for calibration inputs. + std::vector device_tensors_; + + std::unique_ptr calibrator_; + TrtUniquePtrType builder_; + TrtUniquePtrType engine_; + // TODO(sami): Use threadpool threads! + std::unique_ptr thr_; + + private: + mutex mu_; + bool terminated_ TF_GUARDED_BY(mu_) = false; + std::string calibration_table_ TF_GUARDED_BY(mu_); +}; + +ABSL_CONST_INIT extern const absl::string_view kTfTrtContainerName; + +class TRTEngineCacheResource : public ResourceBase { + public: + // According to the TensorRT API, the logger is considered a singleton by the + // TensorRT library, and multiple instances of IRuntime and/or IBuilder must + // all use the same logger. So here we make it a singleton. + // + // TODO(laigd): use this logger in all places where conversion happens. + static Logger& GetLogger(); + + TRTEngineCacheResource(OpKernelContext* ctx, size_t capacity); + + ~TRTEngineCacheResource() override; + + string DebugString() const override; + + // Returns the EngineContext that is compatible with input_shapes. + // Returns nullptr if no compatible EngineContexts is found in cache. + EngineContext* GetEngineContext(const std::vector& input_shapes); + + // Returns the EngineContext that is compatible with profile_id. + // This function should be only called in explicit batch mode where + // cache size is expected to be at most one. + // Returns nullptr if no compatible EngineContexts is found in cache. + EngineContext* GetEngineContext(const int profile_id); + + // Keep device allocator for TRT. + std::unique_ptr allocator_; + + // Declare cache after allocator so that it is destroyed before allocator is. + LRUCache, std::unique_ptr, + VectorTensorShapeHasher> + cache_; + + // TODO(hinsu): Use different calibration context for the available shapes and + // attach it to each item of the cache. + std::unique_ptr calib_ctx_; + + // This object maintains all the optimization profiles during profile + // generation and engine build. During runtime the list of profiles is used to + // look up a matching profile for the input data. + TrtShapeOptimizationProfile profiles_; +}; + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +} // namespace tensorrt +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_LRU_CACHE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e611531569c5ec1d90ceced31b5db9e87e31442a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache_test.cc @@ -0,0 +1,59 @@ +/* Copyright 2019 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/tf2tensorrt/utils/trt_lru_cache.h" + +#include + +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace tensorrt { + +TEST(LRUCacheTest, Basic) { + LRUCache> cache; + cache.reserve(2); + // Insert 10 + cache.emplace(10, 100); + EXPECT_EQ(cache.size(), 1); + EXPECT_EQ(cache.count(10), 1); + EXPECT_EQ(cache.at(10), 100); + EXPECT_EQ(cache.count(100), 0); + // Insert 20 + cache.emplace(20, 200); + EXPECT_EQ(cache.size(), 2); + EXPECT_EQ(cache.count(10), 1); + EXPECT_EQ(cache.count(20), 1); + EXPECT_EQ(cache.at(10), 100); + EXPECT_EQ(cache.at(20), 200); + EXPECT_EQ(cache.count(100), 0); + EXPECT_EQ(cache.count(200), 0); + // Insert 30, Evicting 10 + cache.emplace(30, 300); + EXPECT_EQ(cache.count(10), 0); + EXPECT_EQ(cache.count(20), 1); + EXPECT_EQ(cache.count(30), 1); + // Touch 20 + cache.at(20); + // Insert 40, Evicting 30 + cache.emplace(40, 400); + EXPECT_EQ(cache.count(10), 0); + EXPECT_EQ(cache.count(20), 1); + EXPECT_EQ(cache.count(30), 0); + EXPECT_EQ(cache.count(40), 1); +} + +} // namespace tensorrt +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.cc new file mode 100644 index 0000000000000000000000000000000000000000..9c9861b2f2c9cbe6012f56da0f3318506aa67dd4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.cc @@ -0,0 +1,661 @@ +/* Copyright 2020 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/tf2tensorrt/utils/trt_shape_optimization_profiles.h" + +#include +#include + +#include "absl/algorithm/container.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/core/platform/stream_executor.h" +#include "tensorflow/core/profiler/lib/traceme.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "third_party/gpus/cuda/include/cuda_runtime_api.h" + +namespace tensorflow { +namespace tensorrt { + +// Returns a vector of nvinfer1::Dims for a vector of TensorShapes. +template +std::vector GetDimVec(std::vector shape_vec) { + std::vector dimvec(shape_vec.size()); + absl::c_transform(shape_vec, dimvec.begin(), [](TensorShapeType shape) { + auto adap = DimsAdapter::Create(shape); + TF_CHECK_OK(adap.status()); + return adap->AsTrtDims(); + }); + return dimvec; +} + +// In dynamic shape mode the optimization profile dims are only allowed to +// differ from the network input dims where the network input dims have -1 +// values. We enforce this condition by changing prof_dims if necessary. +void EnforceCompatibility(nvinfer1::Dims* prof_dims, + const PartialTensorShape& input_shape) { + for (int i = 0; i < input_shape.dims(); i++) { + if (input_shape.dim_size(i) != -1) { + prof_dims->d[i] = input_shape.dim_size(i); + } + } +} + +void SetImplicitBatchModeCompatibleProfile( + const std::vector& dimvec, std::vector* min, + std::vector* opt, std::vector* max) { + *min = dimvec; + for (auto& dim : *min) { + // Shape value tensors can have -1 value as a wildcard. We do not change + // in that case. + if (dim.d[0] != -1) dim.d[0] = 1; // Set min batch size to 1. + } + *opt = dimvec; + *max = dimvec; +} + +void TrtShapeOptimizationProfile::ImplicitBatchModeCompatibleStrategy( + const std::vector>& collected_shapes) { + for (auto& shape_vec : collected_shapes) { + std::vector min, opt, max; + SetImplicitBatchModeCompatibleProfile(shape_vec, &min, &opt, &max); + VLOG(2) << "Initializing optimization profile config with min=" + << DebugString(min) << ", opt=max=" << DebugString(max); + OptimizationProfileConfig profConfig{min, opt, max}; + profiles_.push_back(std::move(profConfig)); + } +} + +// Applies a binary operation for each dimension of the input shapes. +// x[i].d[k] = op(x[i].d[k], y[i].d[k]), where i enumerates the input tensors, +// and k enumerates the dimensions of the tensors. The BinaryOperation may be +// std::min, std::max etc. +template +Status ShapeProfileBinaryOp(std::vector* x, + const std::vector& y, + BinaryOperation op) { + if (x->size() != y.size()) + return errors::InvalidArgument( + "Number of input tensors differ during profile creation"); + for (int i = 0; i < x->size(); i++) { + if (x->at(i).nbDims != y[i].nbDims) + return errors::InvalidArgument( + "Number of input dimensions differ during profile creation at dim ", + i, ", values ", x->at(i).nbDims, y[i].nbDims); + for (int j = 0; j < x->at(i).nbDims; j++) { + x->at(i).d[j] = op(x->at(i).d[j], y[i].d[j]); + } + } + return OkStatus(); +} + +Status TrtShapeOptimizationProfile::RangeStrategy( + const std::vector>& collected_shapes) { + if (collected_shapes.empty()) return OkStatus(); + + std::vector min = collected_shapes[0]; + std::vector max = min; + + for (int i = 1; i < collected_shapes.size(); i++) { + TF_RETURN_IF_ERROR( + ShapeProfileBinaryOp(&min, collected_shapes[i], + [](int a, int b) { return std::min(a, b); })); + TF_RETURN_IF_ERROR( + ShapeProfileBinaryOp(&max, collected_shapes[i], + [](int a, int b) { return std::max(a, b); })); + } + VLOG(2) << "Initializing optimization profile config with min=" + << DebugString(min) << ", opt=max=" << DebugString(max); + OptimizationProfileConfig profConfig{min, max, max}; + profiles_.push_back(std::move(profConfig)); + return OkStatus(); +} + +void TrtShapeOptimizationProfile::OptimalStrategy( + const std::vector>& collected_shapes) { + for (auto& shape_vec : collected_shapes) { + std::vector min = shape_vec; + std::vector opt = min; + std::vector max = min; + VLOG(2) << "Initializing optimization profile config with min=opt=max=" + << DebugString(min); + OptimizationProfileConfig profConfig{min, opt, max}; + profiles_.push_back(std::move(profConfig)); + } +} + +// Collects the values of tensors that are ShapeTensorCompatible to. The values +// are stored in the actual_shape_values_ member variable. +Status TrtShapeOptimizationProfile::CollectShapeValues(OpKernelContext* ctx) { + tensorflow::profiler::TraceMe activity( + "TrtShapeOptimizationProfile::CollectShapeValues", + tensorflow::profiler::TraceMeLevel::kInfo); + cudaStream_t stream = reinterpret_cast(CHECK_NOTNULL( + ctx->op_device_context()->stream()->platform_specific_handle().stream)); + actual_shape_values_.resize(ctx->num_inputs()); + if (is_shape_tensor_.empty()) { + is_shape_tensor_.resize(ctx->num_inputs()); + for (int i = 0; i < ctx->num_inputs(); i++) { + is_shape_tensor_[i] = IsTrtShapeTensorCompatible(ctx->input(i)); + } + } + int n_shape_val = 0; + // First copy all the shape value candidates into actual_shape_values_ vector. + for (int i = 0; i < ctx->num_inputs(); i++) { + if (is_shape_tensor_[i]) { + if (ctx->input_dtype(i) != DT_INT32) { + // In case the is_shape_tensor mask was initialized with the input + // shapes only (without knowledge of dtype) then we apply correction. + is_shape_tensor_[i] = false; + continue; + } + if (input_shape_values_.size() > 0 && + input_shape_values_[0][i].nbDims != ctx->input(i).NumElements()) { + // Shape tensor dims should not change. It must be a value tensor. + is_shape_tensor_[i] = false; + continue; + } + // We have to copy the shape values to the host, because TRT's + // ExecutionContext::setInputShapeBinding expects a host pointer. + n_shape_val++; + const Tensor& input = ctx->input(i); + actual_shape_values_[i].nbDims = input.NumElements(); + auto ret = cudaMemcpyAsync( + actual_shape_values_[i].d, input.flat().data(), + input.NumElements() * sizeof(int32), cudaMemcpyDeviceToHost, stream); + if (ret != 0) { + return errors::Internal("Could not copy shape tensor values"); + } + VLOG(2) << "Input " << i << " is (probably) a shape tensor, n_values=" + << input.NumElements(); + } else { + actual_shape_values_[i] = {0, {}}; + } + } + if (n_shape_val > 0) { + // If we have any shape values candidates, then wait until data is copied + // to host. + cudaStreamSynchronize(stream); + } + return OkStatus(); +} + +// Collects the values of tensors that are ShapeTensorCompatible to. To be used +// for unit tests. +Status TrtShapeOptimizationProfile::CollectShapeValues(const DataVec& input) { + actual_shape_values_.resize(input.size()); + for (int i = 0; i < input.size(); i++) { + if (is_shape_tensor_[i]) { + if (!IsTrtShapeTensorCompatible(input[i].tensor)) { + return errors::Internal("Inconsistent shape tensor ", input[i].name, + ", ", i); + } + int n_elements = input[i].tensor.NumElements(); + actual_shape_values_[i].nbDims = n_elements; + // During unit tests, the data is in unified memory + std::copy(input[i].tensor.flat().data(), + input[i].tensor.flat().data() + n_elements, + actual_shape_values_[i].d); + VLOG(2) << "Collected tensor shape values " + << DebugString(actual_shape_values_[i]); + } else { + actual_shape_values_[i] = {0, {}}; + } + } + return OkStatus(); +} + +// Adjusts shape value profile to prevent TRT from removing shape value input +// bindings whose value is redundant (only a single value matches the profile). +// This should be removed once the NVIDIA bug 3153064 is fixed. +void FixShapeValueProfile(OptimizationProfileConfig* prof, + const std::vector& is_shape_tensor) { + int shape_value_offset = is_shape_tensor.size(); + for (int i = 0; i < is_shape_tensor.size(); i++) { + if (is_shape_tensor[i] && + std::equal(prof->min[shape_value_offset + i].d, + prof->min[shape_value_offset + i].d + + prof->min[shape_value_offset + i].nbDims, + prof->max[shape_value_offset + i].d)) { + prof->max[shape_value_offset + i].d[0]++; + VLOG(2) << "Adjusted profile for shape value tensor " << i << " " + << DebugString(prof->max[shape_value_offset + i]); + } else { + VLOG(2) << i << " is not a shape tensor." << is_shape_tensor[i]; + } + } +} + +// Checks whether rhs is already contained in values. +bool AlreadyCollected(const std::vector>& values, + const std::vector& rhs) { + for (auto& lhs : values) { + bool ret = lhs.size() == rhs.size(); + for (int i = 0; ret && i < lhs.size(); i++) { + ret &= lhs[i].nbDims == rhs[i].nbDims; + for (int j = 0; ret && j < lhs[i].nbDims; j++) { + ret &= (lhs[i].d[j] == rhs[i].d[j]); + } + } + if (ret) return true; + } + return false; +} + +void TrtShapeOptimizationProfile::InitProfiles( + const std::vector& input_partial_shapes, + ProfileStrategy strategy) { + strategy_ = strategy; + if (input_shapes_.size() == 0) { + VLOG(1) << "Not creating profiles without input_shapes. " + "You have to enable profile generation mode first (build)."; + return; + } + // Preprocess the vector of input shapes and shape values: + // - Converts TensorShape -> nvinfer::Dims. + // - Concatenates the shape values after the input shapes: + // dimvec = [dim0, dim1,..., shapeval0, shapval1, ...] + // - Ensures that the list is unique. + std::vector> collected_shapes; + for (int i = 0; i < input_shapes_.size(); i++) { + auto shape_vec = input_shapes_[i]; + VLOG(2) << "Initprofiles, processing shape " << i; + if (!shape_vec.empty()) { + // Correct for values that are mistakenly used as shape values + for (int k = 0; k < input_shape_values_[i].size(); k++) { + if (!is_shape_tensor_[k]) + input_shape_values_[i][k] = nvinfer1::Dims{0, {}}; + } + std::vector dimvec = GetDimVec(shape_vec); + dimvec.insert(dimvec.end(), input_shape_values_[i].begin(), + input_shape_values_[i].end()); + // TODO(tfeher): This condition should not apply for explicit profile. In + // that case consicutive elements in collected_shapes contain the user + // defined values of min, opt and max, and it is valid the have min = opt + // and opt = max. + if (!AlreadyCollected(collected_shapes, dimvec)) { + collected_shapes.push_back(dimvec); + } + } + } + switch (strategy_) { + case ProfileStrategy::kImplicitBatchModeCompatible: + VLOG(1) << "Creating profiles with ImplicitBatchModeCompatible strategy"; + ImplicitBatchModeCompatibleStrategy(collected_shapes); + break; + // Treat all other strategies the same as kOptimal for now. Implementing + // those is outlined in the dynamic shape support implementation plan. + case ProfileStrategy::kRange: + VLOG(1) << "Creating profiles with Range strategy"; + TF_CHECK_OK(RangeStrategy(collected_shapes)); + break; + case ProfileStrategy::kRangeOptimal: + VLOG(1) << "Creating profiles with RangeOptimal strategy"; + OptimalStrategy(collected_shapes); + TF_CHECK_OK(RangeStrategy(collected_shapes)); + break; + case ProfileStrategy::kOptimal: + VLOG(1) << "Creating profiles with Optimal strategy"; + OptimalStrategy(collected_shapes); + break; + } + // Define a mask that describe which input could be a shape tensor. Note + // that here we can have false positives. The shape tensor mask will be + // updated once the network is constructed. + SetShapeTensorMask(input_partial_shapes); + if (input_partial_shapes.size() > 0) { + for (OptimizationProfileConfig& prof : profiles_) { + // TODO: Remove this when the bug is fixed. +#if !IS_TRT_VERSION_GE(8, 0, 0, 0) + FixShapeValueProfile(&prof, is_shape_tensor_); +#endif + for (int i = 0; i < input_partial_shapes.size(); i++) { + auto network_input = input_partial_shapes[i]; + EnforceCompatibility(&prof.min[i], network_input); + EnforceCompatibility(&prof.opt[i], network_input); + EnforceCompatibility(&prof.max[i], network_input); + } + } + } +} + +void TrtShapeOptimizationProfile::InitCalibProfile( + const std::vector& shapes) { + VLOG(1) << "Collected shape(s) " << DebugString(shapes) << " for " + << " calibration profile."; + auto shape_vec = shapes; + if (!shape_vec.empty()) { + std::vector dimvec = GetDimVec(shape_vec); + dimvec.insert(dimvec.end(), actual_shape_values_.begin(), + actual_shape_values_.end()); + VLOG(2) << "Initializing calibration optimization profile config with " + << "min=opt=max " << DebugString(dimvec); + + OptimizationProfileConfig profConfig{dimvec, dimvec, dimvec}; + calib_profiles_ = std::move(profConfig); + } else { + VLOG(2) << "Failed to initialize calibration optimization profile."; + } +} + +Status TrtShapeOptimizationProfile::AddProfiles( + nvinfer1::IBuilder* builder, nvinfer1::IBuilderConfig* config, + const nvinfer1::INetworkDefinition* network) { + // Create optimization profile for calibration if necessary. + if (!calib_profiles_.min.empty()) { + VLOG(2) << "Setting up calibration profiles"; + auto* calibProfile = builder->createOptimizationProfile(); + Status status = + calib_profiles_.SetDimensions(network, calibProfile, input_mask_); + if (!status.ok()) { + return status; + } + bool result = false; + if (calibProfile->isValid()) { + result = config->setCalibrationProfile(calibProfile); + } else { + VLOG(2) << "Calibration profile is not valid"; + } + if (result) { + VLOG(2) << "Added calibration optimization profile " + << calib_profiles_.DebugString() << " to builder config."; + } else { + VLOG(2) << "FAILED TO ADD PROFILE"; + LOG(ERROR) << "Failed to add calibration optimization profile " + << calib_profiles_.DebugString() + << ". This usually happens when profile is invalid."; + } + } + // Create a vector of optimization profiles. + for (int i = 0; i < profiles_.size(); i++) { + auto* optProfile = builder->createOptimizationProfile(); + Status status = + profiles_[i].SetDimensions(network, optProfile, input_mask_); + if (!status.ok()) { + return status; + } + int idx = -1; + if (optProfile->isValid()) { + idx = config->addOptimizationProfile(optProfile); + } + if (idx >= 0) { + if (i != idx) { + return errors::Internal( + "Profile index of engine config is different from source profile " + "index: ", + i, " != ", idx); + } + VLOG(1) << "Added optimization profile " << profiles_[i].DebugString() + << " with idx " << idx << " to builder config."; + } else { + LOG(ERROR) << "Failed to add optimization profile " + << profiles_[i].DebugString() + << ". This usually happens when profile is invalid."; + } + } + if (!profiles_.empty() && config->getNbOptimizationProfiles() == 0) { + return errors::Internal("Failure in adding an optimization profile."); + } + need_profiles_ = config->getNbOptimizationProfiles() > 0; + // Update the mask that flag shape tensors. The network is known now, + // the mask will be correct. + SetShapeTensorMask(network); + is_pruned_input_.resize(network->getNbInputs()); + absl::c_fill(is_pruned_input_, false); + return OkStatus(); +} + +Status TrtShapeOptimizationProfile::ConfigureBuilder( + nvinfer1::IBuilder* builder, nvinfer1::IBuilderConfig* config, + const nvinfer1::INetworkDefinition* network) { + TF_RETURN_IF_ERROR(AddProfiles(builder, config, network)); + return OkStatus(); +} + +// Sets the shape tensor mask from the TRT engine definition. +void TrtShapeOptimizationProfile::SetShapeTensorMask( + const nvinfer1::ICudaEngine* engine, int n_inputs) { + is_shape_tensor_.resize(n_inputs, false); + for (int i = 0; i < n_inputs; i++) { + int binding_index; + Status status = GetTrtBindingIndex(i, 0, engine, &binding_index); + if (!status.ok()) { + continue; + } + is_shape_tensor_[i] = engine->isShapeBinding(binding_index); + if (is_shape_tensor_[i]) { + VLOG(2) << "Found shape tensor at " << i; + } + } + has_shape_tensor_ = + absl::c_any_of(is_shape_tensor_, [](bool b) { return b; }); +} + +// Sets the shape tensor mask using the network definition. +void TrtShapeOptimizationProfile::SetShapeTensorMask( + const nvinfer1::INetworkDefinition* network) { + int n_inputs = network->getNbInputs(); + is_shape_tensor_.resize(n_inputs, false); + for (int i = 0; i < n_inputs; i++) { + const ITensorProxyPtr input = network->getInput(i); + is_shape_tensor_[i] = input->isShapeTensor(); + if (is_shape_tensor_[i]) { + VLOG(2) << "Found shape tensor " << input->getName() << " at " << i; + } + } + has_shape_tensor_ = + absl::c_any_of(is_shape_tensor_, [](bool b) { return b; }); +} + +// Sets the shape tensor mask using the input partial shapes. This only tells +// whether the tensors are shape value compatible, only the final network +// definition or the engine would give concrete answers. +void TrtShapeOptimizationProfile::SetShapeTensorMask( + const std::vector& input_partial_shapes) { + if (is_shape_tensor_.size() == input_partial_shapes.size()) { + // Already initialized, e.g. by TRTEngineOp::ComputeAsync(). + return; + } + is_shape_tensor_.resize(input_partial_shapes.size(), false); + for (int i = 0; i < input_partial_shapes.size(); i++) { + is_shape_tensor_[i] = IsTrtShapeTensorCompatible(input_partial_shapes[i]); + if (is_shape_tensor_[i]) { + VLOG(2) << "Found shape compatible tensor at " << i; + } + } + has_shape_tensor_ = + absl::c_any_of(is_shape_tensor_, [](bool b) { return b; }); +} + +int TrtShapeOptimizationProfile::GetProfileNumber( + const std::vector& shapes) { + tensorflow::profiler::TraceMe activity( + "TrtShapeOptimizationProfile::GetProfileNumber", + tensorflow::profiler::TraceMeLevel::kInfo); + if (!need_profiles_) return 0; + // TODO(tfeher): Return the best profile not just the first compatible. + for (int i = 0; i < profiles_.size(); i++) { + if (profiles_[i].IncludesShapes(shapes, HasShapeTensor(), + actual_shape_values_, is_pruned_input_, + is_shape_tensor_)) { + return i; + } + } + VLOG(1) << "Profile not found for input shapes " << DebugString(shapes); + VLOG(2) << " and shape values " << DebugString(actual_shape_values_); + return -1; +} + +Status TrtShapeOptimizationProfile::CreateExecutionContexts( + nvinfer1::ICudaEngine* engine, + std::vector* exec_contexts) { + int i = 0; + // The following loop runs once if we have static shapes, to create a single + // execution context without profiles. In dynamic mode we create one context + // for each profile and set the corresponding optimization profile. + do { + VLOG(1) << "Creating execution context " << i; + ExecutionContext context = ExecutionContext::Create(engine); + if (i > 0) { + // This condition is needed for two reasons: + // - using static shapes we do not have any profiles so we cannot call + // set optimizationprofiles. + // - The 0th profile is set implicitly for the first execution context + // therefore we do not need to set. + if (!context->setOptimizationProfile(i)) { + return errors::Internal("Could not set TRT optimization profile."); + } + } + exec_contexts->push_back(std::move(context)); + i++; + } while (i < profiles_.size()); + + return OkStatus(); +} + +Status TrtShapeOptimizationProfile::SetInputShapeBinding( + int input_index, int binding_index, nvinfer1::ICudaEngine* cuda_engine, + nvinfer1::IExecutionContext* exec_context) const { + tensorflow::profiler::TraceMe activity( + "TrtShapeOptimizationProfile::SetInputShapeBinding", + tensorflow::profiler::TraceMeLevel::kInfo); + if (cuda_engine->isShapeBinding(binding_index)) { + // Input shape binding data has to be in host memory. That is the reason + // we can't use input_tensor.flat().data(). which contains the same + // values in device memory. Instead, we use data that was copied to host + // by CollectShapeValues. + VLOG(2) << "Setting input shape binding for idx " << binding_index + << ", with values " + << DebugString(actual_shape_values_.at(input_index)); + bool ret = exec_context->setInputShapeBinding( + binding_index, actual_shape_values_.at(input_index).d); + if (!ret) { + return errors::Internal("Could not set input shape binding for idx ", + binding_index); + } + } + return OkStatus(); +} + +// If binding_idx is a shape tensor, then returns the associated min/max/opt +// shape values from prof_idx. +nvinfer1::Dims GetDimsFromShapeVal(int prof_idx, int binding_idx, + nvinfer1::OptProfileSelector selector, + const nvinfer1::ICudaEngine* engine) { + if (engine->isShapeBinding(binding_idx)) { + const int32* shape_val_ptr = + engine->getProfileShapeValues(binding_idx, prof_idx, selector); + if (shape_val_ptr) { + VLOG(2) << "Found shape value in prof " << prof_idx << ", binding " + << binding_idx; + nvinfer1::Dims dims = engine->getBindingDimensions(binding_idx); + // nbDims == 0 represent scalar, -1 represents invalid dim + int n_values = (dims.nbDims == 0) ? 1 : dims.d[0]; + if (n_values > 0) { + dims.nbDims = n_values; + std::copy(shape_val_ptr, shape_val_ptr + n_values, dims.d); + } + return dims; + } + } + return {0, {0}}; +} + +Status TrtShapeOptimizationProfile::SetPrunedMask( + const nvinfer1::ICudaEngine* engine, int n_network_inputs) { + is_pruned_input_.resize(n_network_inputs); + absl::c_fill(is_pruned_input_, false); + for (int j = 0; j < n_network_inputs; j++) { + int binding_idx; + Status status = GetTrtBindingIndex(j, 0, engine, &binding_idx); + if (!status.ok()) { + // Before TRT 8, an input tensor can be pruned (nvbugs/3153064) + // Resource inputs are also unknown by TRT, so we can treat them as + // pruned (the engine includes the variable as weights). + is_pruned_input_[j] = true; + VLOG(2) << "Skipping pruned input " << j; + continue; + } + } + return OkStatus(); +} + +Status TrtShapeOptimizationProfile::RestoreProfiles( + const nvinfer1::ICudaEngine* engine, int n_network_inputs) { + need_profiles_ = false; + if (!engine) { + // We do not need to restore profiles for an empty engine. + return OkStatus(); + } + if (engine->hasImplicitBatchDimension()) { + // Nothing to do, we cannot have profiles in implicit batch mode. + return OkStatus(); + } + int n_profiles = engine->getNbOptimizationProfiles(); + need_profiles_ = n_profiles > 0; + int n_inputs = GetNumberOfEngineInputs(engine); + if (n_inputs > n_network_inputs) { + return errors::Internal("Incorrect number of engine inputs"); + } + VLOG(2) << "Attempting to restore " << n_profiles << " profiles, each with " + << n_inputs << " inputs"; + SetShapeTensorMask(engine, n_network_inputs); + + TF_RETURN_IF_ERROR(SetPrunedMask(engine, n_network_inputs)); + + for (int prof_idx = 0; prof_idx < n_profiles; prof_idx++) { + OptimizationProfileConfig cfg; + + cfg.min.resize(n_network_inputs * 2); + cfg.max.resize(n_network_inputs * 2); + cfg.opt.resize(n_network_inputs * 2); + // restore shape values + for (int j = 0; j < n_network_inputs; j++) { + if (is_pruned_input_[j]) continue; + int binding_idx; + TF_RETURN_IF_ERROR(GetTrtBindingIndex(j, 0, engine, &binding_idx)); + + nvinfer1::Dims min = engine->getProfileDimensions( + binding_idx, prof_idx, nvinfer1::OptProfileSelector::kMIN); + nvinfer1::Dims max = engine->getProfileDimensions( + binding_idx, prof_idx, nvinfer1::OptProfileSelector::kMAX); + nvinfer1::Dims opt = engine->getProfileDimensions( + binding_idx, prof_idx, nvinfer1::OptProfileSelector::kOPT); + cfg.min[j] = min; + cfg.max[j] = max; + cfg.opt[j] = opt; + + cfg.min[j + n_inputs] = GetDimsFromShapeVal( + prof_idx, binding_idx, nvinfer1::OptProfileSelector::kMIN, engine); + cfg.max[j + n_inputs] = GetDimsFromShapeVal( + prof_idx, binding_idx, nvinfer1::OptProfileSelector::kMAX, engine); + cfg.opt[j + n_inputs] = GetDimsFromShapeVal( + prof_idx, binding_idx, nvinfer1::OptProfileSelector::kOPT, engine); + } + VLOG(2) << "Restored profile " << cfg.DebugString(); + profiles_.push_back(std::move(cfg)); + } + return OkStatus(); +} + +int TrtShapeOptimizationProfile::GetNumProfiles() const { + return profiles_.size(); +} + +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h new file mode 100644 index 0000000000000000000000000000000000000000..999d6789262fdae8373b696c6cc76755a32fda26 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles.h @@ -0,0 +1,351 @@ +/* Copyright 2020 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_TF2TENSORRT_UTILS_TRT_SHAPE_OPTIMIZATION_PROFILES_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_SHAPE_OPTIMIZATION_PROFILES_H_ + +#include +#include +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/common/datavec.h" +#include "tensorflow/compiler/tf2tensorrt/convert/trt_parameters.h" +#include "tensorflow/compiler/tf2tensorrt/convert/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_execution_context.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/strings/str_util.h" +#include "tensorflow/core/lib/strings/strcat.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +// Stores optimization profile parameters (min/opt/max of each input shape). +// +// A TensorRT optimization profile describes the possible min/max values of +// each dynamic input shape along with an optimum value. These values are used +// by the TensorRT builder to select the best kernel for the optimum value among +// those kernels that are valid for all input tensors in the [min, max] range. +struct OptimizationProfileConfig { + // Length of vector == 2*num_inputs to engine. min[0:num_inputs-1] are the min + // input dimensions for execution tensors. If engine has shape input tensors, + // then min[num_inputs + i] store the shape value for input i. For inputs that + // are not shape tensors min = opt = max = {0, {}}. + // + // When the OptimizationProfileConfig is created from the network definition + // (AddProfiles), then each elements of the min, opt, max vectors are defined. + // When the OptimizationProfileConfig object is restored during engine + // deserialization (RestoreProfiles), then some inputs can be pruned + // (see TrtShapeOptimizationProfile::is_pruned_input_). In that case min[i] + // is not defined for pruned inputs (same is true for opt and max). + std::vector min; + std::vector opt; + std::vector max; + + string DebugString() const { + using absl::StrCat; + return StrCat("[min: ", tensorflow::tensorrt::DebugString(min), + ", opt: : ", tensorflow::tensorrt::DebugString(opt), + ", max: ", tensorflow::tensorrt::DebugString(max), "]"); + } + + // Sets the min/opt/max dimensions for profile. + // + // The given min/opt/max dimensions should satisfy the condition + // min <= opt <= max. Additionally TRT requires that the min/opt/max values + // are compatible with the network input. Compatibility is defined the + // following way: let dim be the shape of an input binding and min/opt/max the + // corresponding profile dims. TRT requires that dim.d[k] must be -1 if + // (min.d[k] != dim.d[k] || opt.d[k] != dim.d[k] || max.d[k] != dim.d[k]). + // + // Parameters: + // network - TensorRT network, used to enumerate all the input tensors + // profile - on exit the profile information will be set for each input tensor + // input_mask - 1 for TRT inputs, 0 for TF inputs that are not TRT inputs + Status SetDimensions(const nvinfer1::INetworkDefinition* network, + nvinfer1::IOptimizationProfile* profile, + const std::vector& input_mask) const { + int n_inputs_trt = network->getNbInputs(); + int n_inputs_tf = opt.size() / 2; + /// TODO(lsugy): check that the sum of the mask equals n_inputs. + if (input_mask.size() != n_inputs_tf) { + return errors::Internal("Incorrect input mask size: ", input_mask.size()); + } + int n_mask_true = 0; + for (bool mask_val : input_mask) { + if (mask_val) { + n_mask_true++; + } + } + if (n_mask_true != n_inputs_trt) { + return errors::Internal( + "Number of true elements in input_mask (", n_mask_true, + ") doesn't match expected TRT inputs (", n_inputs_trt, ")"); + } + int j = 0; + for (int i = 0; i < n_inputs_tf; i++) { + if (input_mask[i]) { + const ITensorProxyPtr input = network->getInput(j); + const char* name = input->getName(); + if (input->isShapeTensor()) { + int idx = i + n_inputs_tf; + VLOG(2) << "Setting shape values for " << name << ", " + << ::tensorflow::tensorrt::DebugString(opt[idx]); + profile->setShapeValues(name, nvinfer1::OptProfileSelector::kMIN, + min[idx].d, min[idx].nbDims); + profile->setShapeValues(name, nvinfer1::OptProfileSelector::kOPT, + opt[idx].d, opt[idx].nbDims); + profile->setShapeValues(name, nvinfer1::OptProfileSelector::kMAX, + max[idx].d, max[idx].nbDims); + } + VLOG(2) << "Setting input dimensions for " << name << ", " + << ::tensorflow::tensorrt::DebugString(opt[i]); + profile->setDimensions(name, nvinfer1::OptProfileSelector::kMIN, + min[i]); + profile->setDimensions(name, nvinfer1::OptProfileSelector::kOPT, + opt[i]); + profile->setDimensions(name, nvinfer1::OptProfileSelector::kMAX, + max[i]); + + j++; + } + } + return OkStatus(); + } + + // Returns true if profile range completely includes the given shapes. + bool IncludesShapes(const std::vector& shapes, + bool has_shape_tensor, + const std::vector& shape_values, + const std::vector& is_pruned_input, + const std::vector& is_shape_tensor) const { + // min, max, and opt must have the same size which is already verified in + // SetDimensions. + if (min.size() != shapes.size() * 2 || + (has_shape_tensor && min.size() != shape_values.size() * 2)) { + VLOG(2) << "Profile size mismatch min size " << min.size() + << " vs input shapes size " << shapes.size() << " " + << shape_values.size(); + return false; + } + for (int i = 0; i < shapes.size(); i++) { + if (is_pruned_input[i]) { + continue; + } + auto current_shape = shapes[i]; + // min, max, and opt must have the same nbDims, which is already verified + // in SetDimensions. + if (min[i].nbDims != current_shape.dims()) { + return false; + } + // Check if range [min, max] includes current_shape. + for (int dim = 0; dim < current_shape.dims(); dim++) { + if ((min[i].d[dim] > current_shape.dim_size(dim)) || + (max[i].d[dim] < current_shape.dim_size(dim))) { + return false; + } + } + } + // Check shape values. + if (has_shape_tensor) { + int offset = shapes.size(); + for (int i = 0; i < shape_values.size(); i++) { + if (is_pruned_input[i] || !is_shape_tensor[i]) { + continue; + } + auto shape_val = shape_values[i]; + // min, max, and opt must have the same nbDims, which is already + // verified in SetDimensions. + if (min[i + offset].nbDims != shape_val.nbDims) { + return false; + } + // Check if range [min, max] includes shape_val. + for (int dim = 0; dim < shape_val.nbDims; dim++) { + if (min[i + offset].d[dim] > shape_val.d[dim] || + max[i + offset].d[dim] < shape_val.d[dim]) { + return false; + } + } + } + } + return true; + } +}; + +// Manages Optimization profiles during TRT Engine construction. +// +// An optimization profile describes a range of dimensions for each TRT network +// input, and the optimal dimensions that the auto-tuner should use for +// optimization. +// +// This class stores the list of input shapes that were seen during the +// build/profile_generation_mode phase, and using them it creates a set of +// OptimizationProfileConfigs. These configs will be added to IBuilderConfig +// before the engine is created. +class TrtShapeOptimizationProfile { + public: + TrtShapeOptimizationProfile() {} + + // Stores input shape information during profile_generation_mode. + void AddShape(const std::vector& shapes) { + input_shapes_.push_back(shapes); + input_shape_values_.push_back(actual_shape_values_); + VLOG(1) << "Collected shape(s) " << DebugString(shapes) << " for profiles."; + } + + // Stores the input mask. + void SetInputMask(const std::vector& input_mask) { + input_mask_ = input_mask; + } + + // Collects ShapeTensorCompatible tensor values. This is needed both during + // profile_generation_mode and during normal inference calls. + Status CollectShapeValues(OpKernelContext* ctx); + + // Collects ShapeTensorCompatible tensor values, used only for unit tests. + Status CollectShapeValues(const DataVec& input); + + void clear() { profiles_.clear(); } + + // Returns the profile number that should be used to execute the network with + // the given input shapes. Returns -1 if none of cached profiles are + // compatible with the given input shapes. + int GetProfileNumber(const std::vector& shapes); + + // Creates optimization profiles and add them to the builder config. + Status ConfigureBuilder(nvinfer1::IBuilder* builder, + nvinfer1::IBuilderConfig* config, + const nvinfer1::INetworkDefinition* network); + + // Creates execution contexts for each optimization profile. + Status CreateExecutionContexts(nvinfer1::ICudaEngine* engine, + std::vector* exec_contexts); + + Status SetInputShapeBinding(int input_index, int binding_index, + nvinfer1::ICudaEngine* cuda_engine, + nvinfer1::IExecutionContext* exec_context) const; + + // Creates optimization profiles profiles_ for the set of concrete input + // shapes collected in input_shapes_. The input_partial_shapes of the network + // is used to ensure that the created optimization profiles are compatible + // with the network. + void InitProfiles(const std::vector& input_partial_shapes, + ProfileStrategy strategy); + + void InitCalibProfile(const std::vector& shapes); + + // Returns number of created profiles. + int GetNumProfiles() const; + + bool HasShape() const { return !input_shapes_.empty(); } + bool NeedProfiles() const { return need_profiles_; } + + // Restores profiles from the engine (used after deserialization). + Status RestoreProfiles(const nvinfer1::ICudaEngine* engine, + int n_network_inputs); + + // Whether the network has any shape tensors. + bool HasShapeTensor() const { return has_shape_tensor_; } + + void SetShapeTensorMask(const nvinfer1::INetworkDefinition* network); + + // Whether the optimization profiles describe input that can be handled with + // a static engine (only 1 profile with min=max). + bool IsStaticCompatible() { + return strategy_ == ProfileStrategy::kOptimal && profiles_.size() == 1 +#if !IS_TRT_VERSION_GE(8, 0, 0, 0) + && !HasShapeTensor() +#endif + ; + // TODO(tfeher): remove !HasShapeTensor() condition once the + // FixShapeValueProfile workaround is turned off. + } + + private: + // Set of input shape vetors that we collect during profile_generation_mode. + std::vector> input_shapes_; + + // Input shape values that we collect during profile_generation_mode. If the + // tensor is not compatible with a TRT shape tensor then an empty shape is + // stored. + std::vector> input_shape_values_; + + // Shape values present in the current inference call. + std::vector actual_shape_values_; + + // The optimization profiles generated from input_shapes_. + std::vector profiles_; + + // The optimization profile for calibration. + OptimizationProfileConfig calib_profiles_; + + // A TRTEngineOp can have resource inputs. These are treated as constants: + // their value is read during conversion and stored as weights in the TRT + // engine. This means that resource inputs have no corresponding TRT engine + // input, and we do not need to provide profile information for these. The + // input mask helps to identify the TRT inputs, where we need to define + // optimization profiles. + std::vector input_mask_; + + // Whether the network has any shape tensors. Initially we assume that the + // network might have a shape value input. This will be updated when the + // network is created / engine is deserialized. + bool has_shape_tensor_ = true; + + // Whether the network/engine requires optimization profiles. + bool need_profiles_ = false; + + // Whether an input tensor is a shape tensor. + std::vector is_shape_tensor_; + + // Whether a network input was pruned (only in TRT 7). + std::vector is_pruned_input_; + + // Optimization profile generation strategy. + ProfileStrategy strategy_; + + // Adds optimization profiles to the builder config. + Status AddProfiles(nvinfer1::IBuilder* builder, + nvinfer1::IBuilderConfig* config, + const nvinfer1::INetworkDefinition* network); + + void SetShapeTensorMask(const nvinfer1::ICudaEngine* engine, int n_inputs); + void SetShapeTensorMask( + const std::vector& input_partial_shapes); + + Status SetPrunedMask(const nvinfer1::ICudaEngine* engine, + int n_network_inputs); + + void ImplicitBatchModeCompatibleStrategy( + const std::vector>& collected_shapes); + void OptimalStrategy( + const std::vector>& collected_shapes); + Status RangeStrategy( + const std::vector>& collected_shapes); +}; + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_SHAPE_OPTIMIZATION_PROFILES_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..dedd15c670266ebb88d62da5401fe1c3ecd12529 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_shape_optimization_profiles_test.cc @@ -0,0 +1,256 @@ +/* Copyright 2020 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include + +#include + +#include "absl/memory/memory.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_lru_cache.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/test.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { + +std::vector DimVecToShapeVec( + std::vector dimvec, + bool expand_with_empty_shape_values = false) { + std::vector shapevec(dimvec.size()); + for (int i = 0; i < dimvec.size(); i++) { + TensorShape shape; + TF_CHECK_OK( + TensorShapeUtils::MakeShape(dimvec[i].d, dimvec[i].nbDims, &shape)); + shapevec[i] = shape; + } + if (expand_with_empty_shape_values) { + shapevec.resize(2 * dimvec.size()); // Append empty shape values + } + return shapevec; +} + +bool DimsContained(const nvinfer1::Dims& dim, const nvinfer1::Dims& min, + const nvinfer1::Dims& max) { + if (dim.nbDims != min.nbDims || dim.nbDims != max.nbDims) { + return false; + } + for (int i = 0; i < dim.nbDims; i++) { + if (dim.d[i] < min.d[i] || dim.d[i] > max.d[i]) { + return false; + } + } + return true; +} + +bool DimsEqual(const nvinfer1::Dims& a, const nvinfer1::Dims& b) { + if (a.nbDims != b.nbDims) { + return false; + } + for (int i = 0; i < a.nbDims; i++) { + if (a.d[i] != b.d[i]) { + return false; + } + } + return true; +} + +class TrtShapeOptimizationProfileTest + : public ::testing::TestWithParam { + protected: + TrtShapeOptimizationProfileTest() { + strategy_ = GetParam(); + builder_ = TrtUniquePtrType( + nvinfer1::createInferBuilder(logger_)); + network_ = TrtUniquePtrType( + builder_->createNetworkV2(flags_)); + builder_config_ = TrtUniquePtrType( + builder_->createBuilderConfig()); + builder_config_->setMaxWorkspaceSize(1 << 10); + } + + // Defines a simple network: output = input1 + input2. + void DefineNetwork(nvinfer1::INetworkDefinition* network, + nvinfer1::Dims3& dims) { + ITensorProxyPtr input1 = + network->addInput("input1", nvinfer1::DataType::kFLOAT, dims); + EXPECT_NE(nullptr, input1->trt_tensor()); + + ITensorProxyPtr input2 = + network->addInput("input2", nvinfer1::DataType::kFLOAT, dims); + EXPECT_NE(nullptr, input2->trt_tensor()); + + auto layer = + network->addElementWise(*input1->trt_tensor(), *input2->trt_tensor(), + nvinfer1::ElementWiseOperation::kSUM); + EXPECT_NE(nullptr, layer); + // Mark the output. + ITensorProxyPtr output = layer->getOutput(0); + output->setName("output"); + network->markOutput(*output->trt_tensor()); + } + + void CheckProfile(const std::vector& dimvec, + TrtShapeOptimizationProfile* profile, bool has_prof, + bool test_optimality) { + std::vector shape_vec = DimVecToShapeVec(dimvec); + int idx = profile->GetProfileNumber(shape_vec); + ASSERT_EQ(idx >= 0, has_prof); + if (idx < 0) return; + int prof_idx = exec_contexts_[idx]->getOptimizationProfile(); + ASSERT_GE(prof_idx, 0); + for (int j = 0; j < dimvec.size(); j++) { + nvinfer1::Dims min = engine->getProfileDimensions( + j, prof_idx, nvinfer1::OptProfileSelector::kMIN); + nvinfer1::Dims max = engine->getProfileDimensions( + j, prof_idx, nvinfer1::OptProfileSelector::kMAX); + nvinfer1::Dims opt = engine->getProfileDimensions( + j, prof_idx, nvinfer1::OptProfileSelector::kOPT); + + // This should always hold. + EXPECT_TRUE(DimsContained(dimvec[j], min, max)); + + if (test_optimality) { + // We shall have selected an optimal strategy. + EXPECT_TRUE(DimsEqual(dimvec[j], opt)); + } + } + } + + Logger& logger_ = *Logger::GetLogger(); + TrtUniquePtrType builder_; + TrtUniquePtrType network_; + TrtUniquePtrType builder_config_; + TrtUniquePtrType engine; + std::vector exec_contexts_; + // The order is important: exec_context_ must be destroyed first, and logger + // at last. + const uint32_t flags_ = + 1U << static_cast( + nvinfer1::NetworkDefinitionCreationFlag::kEXPLICIT_BATCH); + ProfileStrategy strategy_; +}; + +INSTANTIATE_TEST_CASE_P( + OptProfilesTestInstantiation, TrtShapeOptimizationProfileTest, + ::testing::Values(ProfileStrategy::kRange, ProfileStrategy::kOptimal, + ProfileStrategy::kRangeOptimal, + ProfileStrategy::kImplicitBatchModeCompatible)); + +TEST_P(TrtShapeOptimizationProfileTest, Static) { + // Static mode does not depend on strategies, we test only once. + if (strategy_ != ProfileStrategy::kRange) return; + + // Network with static input shape. + nvinfer1::Dims3 dims(8, 8, 10); + DefineNetwork(network_.get(), dims); + + TrtShapeOptimizationProfile profile; + + // Configure and build engine - should be a no-op. + TF_CHECK_OK(profile.ConfigureBuilder(builder_.get(), builder_config_.get(), + network_.get())); + + engine = TrtUniquePtrType( + builder_->buildEngineWithConfig(*network_, *builder_config_)); + EXPECT_NE(nullptr, engine); + TF_CHECK_OK(profile.CreateExecutionContexts(engine.get(), &exec_contexts_)); + // A single execution context should be created for a graph with static input. + ASSERT_EQ(exec_contexts_.size(), 1); + EXPECT_NE(nullptr, exec_contexts_[0]); + + std::vector dim_vec(2, dims); + std::vector shape_vec = DimVecToShapeVec(dim_vec); + EXPECT_EQ(0, profile.GetProfileNumber(shape_vec)); +} + +TEST_P(TrtShapeOptimizationProfileTest, Dynamic) { + // Network with dynamic input shapes. + nvinfer1::Dims3 dims(-1, -1, 10); + DefineNetwork(network_.get(), dims); + + TrtShapeOptimizationProfile profile; + + // Set the input mask to true (no resource input) + std::vector input_mask(2, true); + profile.SetInputMask(input_mask); + + std::vector> input_profiles{ + {nvinfer1::Dims3(2, 2, 10), nvinfer1::Dims3(2, 2, 10)}, + {nvinfer1::Dims3(3, 3, 10), nvinfer1::Dims3(3, 3, 10)}, + {nvinfer1::Dims3(16, 16, 10), nvinfer1::Dims3(16, 16, 10)}, + }; + + std::vector unseen_shapes{nvinfer1::Dims3(5, 5, 10), + nvinfer1::Dims3(9, 9, 10)}; + + // Simulate a profile collection phase. + for (auto dim_vec : input_profiles) { + std::vector shape_vec = DimVecToShapeVec(dim_vec, true); + profile.AddShape(shape_vec); + } + std::vector input_partial_shapes; + TF_CHECK_OK(GetNetworkInputShapes(network_.get(), &input_partial_shapes)); + profile.InitProfiles(input_partial_shapes, strategy_); + + // Configure and build engine. + TF_CHECK_OK(profile.ConfigureBuilder(builder_.get(), builder_config_.get(), + network_.get())); + engine = TrtUniquePtrType( + builder_->buildEngineWithConfig(*network_.get(), *builder_config_.get())); + ASSERT_NE(nullptr, engine); + + TF_CHECK_OK(profile.CreateExecutionContexts(engine.get(), &exec_contexts_)); + + int n_profiles_exp; + switch (strategy_) { + case (ProfileStrategy::kImplicitBatchModeCompatible): + case (ProfileStrategy::kOptimal): + n_profiles_exp = input_profiles.size(); + break; + case (ProfileStrategy::kRange): + n_profiles_exp = 1; + break; + case (ProfileStrategy::kRangeOptimal): + n_profiles_exp = 1 + input_profiles.size(); + break; + } + // Each profile has an associated execution context. + EXPECT_EQ(exec_contexts_.size(), n_profiles_exp); + + profile.SetShapeTensorMask(network_.get()); + + EXPECT_EQ(profile.HasShapeTensor(), false); + + // Check if the profiles are assigned correctly. + for (auto dimvec : input_profiles) { + bool test_optimal_prof = strategy_ == ProfileStrategy::kOptimal || + strategy_ == ProfileStrategy::kRangeOptimal; + CheckProfile(dimvec, &profile, true, test_optimal_prof); + } + bool has_prof = (strategy_ == ProfileStrategy::kRange || + strategy_ == ProfileStrategy::kRangeOptimal); + CheckProfile(unseen_shapes, &profile, has_prof, false); +} + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h new file mode 100644 index 0000000000000000000000000000000000000000..f02b554257add83da5c2bfa9acec30459ce5feb1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_tensor_proxy.h @@ -0,0 +1,458 @@ +/* Copyright 2021 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_TF2TENSORRT_UTILS_TRT_TENSOR_PROXY_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_TENSOR_PROXY_H_ + +#include +#include +#include +#include + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/core/platform/logging.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { + +namespace tensorrt { + +// SimpleITensor implements part of the ITensor interfaces to support the TF-TRT +// validator, as well as some TF-TRT tests. The former use case only utilizes +// the interfaces related to shape and type information. +class SimpleITensor { + public: + SimpleITensor(nvinfer1::DataType trt_dtype, const nvinfer1::Dims& trt_dims) + : trt_dtype_(trt_dtype), trt_dims_(trt_dims) {} + + SimpleITensor() : dynamic_range_min_(0.0f), dynamic_range_max_(0.0f) {} + SimpleITensor(const nvinfer1::Dims& dims) + : trt_dims_(dims), dynamic_range_min_(0.0f), dynamic_range_max_(0.0f) {} + + SimpleITensor(const std::vector& dims) { + trt_dims_.nbDims = dims.size(); + for (int i = 0; i < dims.size(); ++i) { + trt_dims_.d[i] = dims[i]; + } + dynamic_range_min_ = 0.0f; + dynamic_range_max_ = 0.0f; + } + + void setName(const char* name) {} + + const char* getName() const { return ""; } + + void setDimensions(nvinfer1::Dims dimensions) { trt_dims_ = dimensions; } + + nvinfer1::Dims getDimensions() const { return trt_dims_; } + + void setType(nvinfer1::DataType trt_dtype) { trt_dtype_ = trt_dtype; } + + nvinfer1::DataType getType() const { return trt_dtype_; } + + bool isNetworkInput() const { return false; } + + bool isNetworkOutput() const { return false; } + + void setBroadcastAcrossBatch(bool broadcastAcrossBatch) {} + + bool getBroadcastAcrossBatch() const { return false; } + + nvinfer1::TensorLocation getLocation() const { return location_; } + + void setLocation(nvinfer1::TensorLocation location) { location_ = location; } + bool setDynamicRange(float min, float max) { + dynamic_range_max_ = max; + dynamic_range_min_ = min; + return true; + } + + float getDynamicRange() const { + return (std::abs(dynamic_range_min_) + dynamic_range_max_) / 2.f; + } + bool dynamicRangeIsSet() const { return true; } + + void resetDynamicRange() { + dynamic_range_min_ = 0.f; + dynamic_range_max_ = 0.f; + } + float getDynamicRangeMin() const { return dynamic_range_min_; } + + float getDynamicRangeMax() const { return dynamic_range_max_; } + + void setAllowedFormats(nvinfer1::TensorFormats formats) {} + + nvinfer1::TensorFormats getAllowedFormats() const { return 1; } + + bool isShapeTensor() const { return false; } + bool isExecutionTensor() const { return true; } + + private: + nvinfer1::DataType trt_dtype_; + nvinfer1::Dims trt_dims_; + std::string name_; + nvinfer1::TensorLocation location_; + float dynamic_range_min_; + float dynamic_range_max_; +}; + +enum class TensorType : int { kTRT, kSIMPLE }; + +class ITensorProxy { + public: + //! ITensor not owned + ITensorProxy(nvinfer1::ITensor* trt_tensor) + : trt_tensor_(trt_tensor), ttype_(TensorType::kTRT) {} + + //! SimpleITensor owned + ITensorProxy(SimpleITensor* simple_itensor) + : simple_tensor_(simple_itensor), ttype_(TensorType::kSIMPLE) {} + + //! SimpleITensor owned + explicit ITensorProxy(nvinfer1::DataType trt_dtype, + const nvinfer1::Dims& trt_dims) + : simple_tensor_(std::unique_ptr( + new SimpleITensor(trt_dtype, trt_dims))), + ttype_(TensorType::kSIMPLE) {} + + //! Variants for testing purposes + ITensorProxy() + : simple_tensor_(std::unique_ptr(new SimpleITensor())), + ttype_(TensorType::kSIMPLE) {} + + explicit ITensorProxy(const nvinfer1::Dims& dims) + : simple_tensor_(std::unique_ptr(new SimpleITensor(dims))), + ttype_(TensorType::kSIMPLE) {} + + explicit ITensorProxy(const std::vector& dims) + : simple_tensor_(std::unique_ptr(new SimpleITensor(dims))), + ttype_(TensorType::kSIMPLE) {} + + bool is_trt_tensor() const { + CHECK(validate()); + return trt_tensor_ != nullptr; + } + + bool is_simple_tensor() const { + CHECK(validate()); + return simple_tensor_ != nullptr; + } + + TensorType ttype() const { return ttype_; } + + nvinfer1::ITensor* trt_tensor() const { + CHECK_NOTNULL(trt_tensor_); + CHECK(ttype_ == TensorType::kTRT); + return trt_tensor_; + } + + SimpleITensor* simple_tensor() const { + CHECK_NOTNULL(simple_tensor_); + CHECK(ttype_ == TensorType::kSIMPLE); + return simple_tensor_.get(); + } + + void setName(const char* name) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setName(name); + case TensorType::kSIMPLE: + return simple_tensor_->setName(name); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + const char* getName() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getName(); + case TensorType::kSIMPLE: + return simple_tensor_->getName(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + void setDimensions(nvinfer1::Dims dimensions) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setDimensions(dimensions); + case TensorType::kSIMPLE: + return simple_tensor_->setDimensions(dimensions); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + nvinfer1::Dims getDimensions() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getDimensions(); + case TensorType::kSIMPLE: + return simple_tensor_->getDimensions(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + void setType(nvinfer1::DataType type) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setType(type); + case TensorType::kSIMPLE: + return simple_tensor_->setType(type); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + nvinfer1::DataType getType() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getType(); + case TensorType::kSIMPLE: + return simple_tensor_->getType(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool isNetworkInput() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->isNetworkInput(); + case TensorType::kSIMPLE: + return simple_tensor_->isNetworkInput(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool isNetworkOutput() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->isNetworkOutput(); + case TensorType::kSIMPLE: + return simple_tensor_->isNetworkOutput(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + void setBroadcastAcrossBatch(bool broadcastAcrossBatch) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setBroadcastAcrossBatch(broadcastAcrossBatch); + case TensorType::kSIMPLE: + return simple_tensor_->setBroadcastAcrossBatch(broadcastAcrossBatch); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool getBroadcastAcrossBatch() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getBroadcastAcrossBatch(); + case TensorType::kSIMPLE: + return simple_tensor_->getBroadcastAcrossBatch(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + nvinfer1::TensorLocation getLocation() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getLocation(); + case TensorType::kSIMPLE: + return simple_tensor_->getLocation(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + void setLocation(nvinfer1::TensorLocation location) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setLocation(location); + case TensorType::kSIMPLE: + return simple_tensor_->setLocation(location); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool setDynamicRange(float min, float max) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setDynamicRange(min, max); + case TensorType::kSIMPLE: + return simple_tensor_->setDynamicRange(min, max); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool dynamicRangeIsSet() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->dynamicRangeIsSet(); + case TensorType::kSIMPLE: + return simple_tensor_->dynamicRangeIsSet(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + void resetDynamicRange() { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->resetDynamicRange(); + case TensorType::kSIMPLE: + return simple_tensor_->resetDynamicRange(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + float getDynamicRangeMin() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getDynamicRangeMin(); + case TensorType::kSIMPLE: + return simple_tensor_->getDynamicRangeMin(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + float getDynamicRangeMax() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getDynamicRangeMax(); + case TensorType::kSIMPLE: + return simple_tensor_->getDynamicRangeMax(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } +#if !IS_TRT_VERSION_GE(8, 0, 0, 0) + float getDynamicRange() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getDynamicRange(); + case TensorType::kSIMPLE: + return simple_tensor_->getDynamicRange(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } +#endif + void setAllowedFormats(nvinfer1::TensorFormats formats) { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->setAllowedFormats(formats); + case TensorType::kSIMPLE: + return simple_tensor_->setAllowedFormats(formats); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + nvinfer1::TensorFormats getAllowedFormats() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->getAllowedFormats(); + case TensorType::kSIMPLE: + return simple_tensor_->getAllowedFormats(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool isShapeTensor() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->isShapeTensor(); + case TensorType::kSIMPLE: + return simple_tensor_->isShapeTensor(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + bool isExecutionTensor() const { + switch (ttype_) { + case TensorType::kTRT: + return trt_tensor_->isExecutionTensor(); + case TensorType::kSIMPLE: + return simple_tensor_->isExecutionTensor(); + } + LOG(FATAL) << "Unsupported itensor_ type"; + } + + private: + bool validate() const { + return (trt_tensor_ && !simple_tensor_) || (!trt_tensor_ && simple_tensor_); + } + + // When ITensorProxy represents an ITensor, the ITensor can be either passed + // by the caller via the constructor that takes an ITensor* as parameter, or + // be created as a SimpleITensor. + // + // In the first case, the ITensor pointer is stored in 'tensor_' below, and + // the ITensor itself is not owned by this class. This method is used by + // Converter (e.g. AddInputTensor) and op converters during TRT network + // construction, where the TRT network owns the ITensor. + // + nvinfer1::ITensor* trt_tensor_ = nullptr; // Not owned. + // In the second case, the created SimpleITensor is stored in + // 'simple_itensor_' below and is owned by this class. SimpleITensor is a fake + // implementation of ITensor and is used for testing and by TrtNodeValidator + // to validate the graph nodes. + std::shared_ptr simple_tensor_ = nullptr; + + TensorType ttype_; +}; + +class ITensorProxyPtr { + public: + ITensorProxyPtr(std::nullptr_t) : p_(nullptr) {} + ITensorProxyPtr(ITensorProxy* p) : p_(p) {} + ITensorProxyPtr(nvinfer1::ITensor* p) : p_(new ITensorProxy(p)) {} + ITensorProxyPtr(SimpleITensor* p) : p_(new ITensorProxy(p)) {} + + ITensorProxyPtr() : p_(new ITensorProxy()) {} + ITensorProxyPtr(const nvinfer1::Dims& dims) : p_(new ITensorProxy(dims)) {} + ITensorProxyPtr(const std::vector& dims) : p_(new ITensorProxy(dims)) {} + + std::shared_ptr p_{nullptr}; + ITensorProxy* operator->() { return p_.get(); } + ITensorProxy* operator->() const { return p_.get(); } + ITensorProxy* operator*() { return p_.get(); } + ITensorProxy* operator*() const { return p_.get(); } +}; + +inline bool operator==(const ITensorProxyPtr& p1, const ITensorProxyPtr& p2) { + if (p1.p_ == nullptr) { + return p2.p_ == nullptr; + } + if (p2.p_ == nullptr) { + return p1.p_ == nullptr; + } + return (p1->ttype() == p2->ttype()) && + ((p1->ttype() == TensorType::kTRT && + p1->trt_tensor() == p2->trt_tensor()) || + (p1->ttype() == TensorType::kSIMPLE && + p1->simple_tensor() == p2->simple_tensor())); +} + +inline bool operator!=(const ITensorProxyPtr& p1, const ITensorProxyPtr& p2) { + return !(p1 == p2); +} + +struct ITensorProxyHash { + size_t operator()(const ITensorProxyPtr& tensor) const { + return reinterpret_cast(tensor.p_.get()); + } +}; + +} // namespace tensorrt +} // namespace tensorflow +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT + +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_TENSOR_PROXY_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.cc new file mode 100644 index 0000000000000000000000000000000000000000..12e686af09690658acf3a6e14b8b9846d904d43a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.cc @@ -0,0 +1,76 @@ +/* Copyright 2021 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/tf2tensorrt/utils/trt_testutils.h" + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include +#include + +#include + +namespace tensorflow { + +namespace tensorrt { +namespace convert { + +::testing::Matcher> ArrayFloatNear( + const std::vector& values, float max_abs_error, bool nan_sensitive) { + std::vector<::testing::Matcher> matchers; + matchers.reserve(values.size()); + for (const float& v : values) { + if (nan_sensitive) { + matchers.emplace_back(::testing::NanSensitiveFloatNear(v, max_abs_error)); + } else if (max_abs_error == 0) { + matchers.emplace_back(::testing::FloatEq(v)); + } else { + EXPECT_GE(max_abs_error, 0); + matchers.emplace_back(::testing::FloatNear(v, max_abs_error)); + } + } + return ::testing::ElementsAreArray(matchers); +} + +nvinfer1::Dims CreateDims(const std::vector& d) { + nvinfer1::Dims dims; + dims.nbDims = d.size(); + for (int i = 0; i < d.size(); ++i) { + dims.d[i] = d[i]; + } + return dims; +} + +NodeDef MakeNodeDef(const std::string& name, const std::string& op, + const std::vector& inputs, + const std::map attrs) { + NodeDef node_def; + node_def.set_name(name); + node_def.set_op(op); + for (const auto& input : inputs) { + node_def.add_input(input); + } + for (const auto& attr : attrs) { + (*node_def.mutable_attr())[attr.first] = attr.second; + } + return node_def; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.h new file mode 100644 index 0000000000000000000000000000000000000000..29b631a11da3fe165c4203538a233606137edf19 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils.h @@ -0,0 +1,183 @@ +/* Copyright 2021 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_TF2TENSORRT_UTILS_TRT_TESTUTILS_H_ +#define TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_TESTUTILS_H_ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include +#include +#include +#include +#include + +#include +#include +#include "absl/strings/str_format.h" +#include "absl/types/span.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/convert/convert_nodes.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_engine_utils.h" +#include "tensorflow/core/framework/node_def.pb.h" // NOLINT +#include "tensorflow/core/framework/tensor.pb.h" // NOLINT +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { +// Creates a node with the given op, inputs, and attributes. +NodeDef MakeNodeDef(const std::string& name, const std::string& op, + const std::vector& inputs, + const std::map attrs = {}); + +// Creates a constant node with the given name and values arranged in the given +// shape. +template +NodeDef MakeConstNodeDef(const std::string& name, const std::vector& vals, + const TensorShape& shape) { + Scope s = Scope::NewRootScope(); + Tensor t = test::AsTensor(vals, shape); + auto const_op = ops::Const(s.WithOpName(name), t); + return const_op.node()->def(); +} + +// Creates a constant node with the given name and values, assuming a 1-D shape. +template +NodeDef MakeConstNodeDef(const std::string& name, const std::vector& vals) { + TensorShape shape; + const std::vector shape_dims = {static_cast(vals.size())}; + TF_EXPECT_OK(TensorShapeUtils::MakeShape(shape_dims, &shape)); + return MakeConstNodeDef(name, vals, shape); +} + +// Creates an nvinfer1::Dims struct from the given vector. +nvinfer1::Dims CreateDims(const std::vector& d); + +// A gmock matcher that check that elements of a float vector match to a given +// tolerance. +::testing::Matcher> ArrayFloatNear( + const std::vector& values, float max_abs_error = 1e-5, + bool nan_sensitive = false); + +// nvinfer1::Dims gMock matchers + +// matches nvinfer1::Dims to initializer list or vector of ints +// Example: EXPECT_THAT(my_dims, DimsAreArray({1, 2, 3})) +MATCHER_P(DimsAreArrayHelper, array_value, + absl::StrFormat("%s [%s]", negation ? "are" : "are not", + ::testing::PrintToString(array_value))) { + if (arg.nbDims != array_value.size()) return false; + for (int i = 0; i < arg.nbDims; ++i) { + if (arg.d[i] != array_value[i]) { + return false; + } + } + return true; +} +using DimsAreArray = DimsAreArrayHelperMatcherP>; + +// nvinfer1::INetworkDefinition gMock matchers + +// Checks that layer names are equal to initializer list or vector of strings. +// Example: EXPECT_THAT(my_network, LayerNamesAreArray({"conv1", "conv2"})) +MATCHER_P(LayerNamesAreArrayHelper, array_value, + absl::StrFormat("layer names %s [%s]", negation ? "are" : "are not", + ::testing::PrintToString(array_value))) { + if (array_value.size() != arg->getNbLayers()) return false; + for (int i = 0; i < arg->getNbLayers(); ++i) { + if (arg->getLayer(i)->getName() == nullptr) { + return false; + } + } + return true; +} +using LayerNamesAreArray = + LayerNamesAreArrayHelperMatcherP>; + +// Checks layer names are all non-empty. +MATCHER(LayerNamesNonEmpty, "") { + for (int i = 0; i < arg->getNbLayers(); ++i) { + if (arg->getLayer(i)->getName() == nullptr) { + return false; + } + } + return true; +} + +// TRT_ShapedWeights gMock matchers. + +// Checks that the weight dimensions are values are equal to the given values. +// Example: EXPECT_THAT(my_weights, +// ShapedWeightsHasDimsAndValues({1, 2},{1.0f, 2.0f})) +MATCHER_P2(ShapedWeightsHasDimsAndValuesHelper, dims_vec, expected_values, "") { + DimsAdapter dims(dims_vec); + if (arg.Shape() != dims) { + return false; + } + if (arg.count() != expected_values.size()) { + return false; + } + using T = typename decltype(expected_values)::value_type; + const T* actual_values = arg.template GetPointer(); + for (int i = 0; i < expected_values.size(); ++i) { + if (expected_values[i] != actual_values[i]) { + return false; + } + } + return true; +} + +template +using ShapedWeightsHasDimsAndValues = + ShapedWeightsHasDimsAndValuesHelperMatcherP2, + std::vector>; + +// std::vector convenience utilities. + +// Creates a new vector by casting all values of the given InCType vector to +// OutCType. +template +std::vector CastVector( + const gtl::ArraySlice& vals) { // non-absl ok + std::vector res(vals.size()); + std::transform(vals.begin(), vals.end(), res.begin(), + [](const InCType in_val) -> OutCType { + return static_cast(in_val); + }); + return res; +} + +// Creates a new vector of the given size and fills it with an increasing +// sequence starting from the given start_value using std::iota. +template +std::vector CreateVectorIota(int size, CType start_value = CType(0)) { + std::vector res(size); + std::iota(res.begin(), res.end(), start_value); + return res; +} + +} // namespace convert +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT +#endif // TENSORFLOW_COMPILER_TF2TENSORRT_UTILS_TRT_TESTUTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..d6be2488ec08348753580f9e5137af1eb516f399 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2tensorrt/utils/trt_testutils_test.cc @@ -0,0 +1,99 @@ +/* Copyright 2021 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. +==============================================================================*/ + +#if GOOGLE_CUDA && GOOGLE_TENSORRT + +#include "tensorflow/compiler/tf2tensorrt/utils/trt_testutils.h" + +#include "tensorflow/compiler/tf2tensorrt/common/utils.h" +#include "tensorflow/compiler/tf2tensorrt/utils/trt_logger.h" +#include "third_party/tensorrt/NvInfer.h" + +namespace tensorflow { +namespace tensorrt { +namespace convert { + +using ::testing::AllOf; +using ::testing::AnyOf; +using ::testing::Eq; +using ::testing::Not; + +TEST(TrtDimsMatcher, ParameterizedMatchers) { + EXPECT_THAT(nvinfer1::Dims4(1, 2, 3, 4), DimsAreArray({1, 2, 3, 4})); + // Check empty dims. + EXPECT_THAT(nvinfer1::Dims{}, Not(DimsAreArray({1, 2}))); + std::vector empty_dims; + EXPECT_THAT(nvinfer1::Dims{}, DimsAreArray(empty_dims)); + // Check mismatching values. + EXPECT_THAT(nvinfer1::Dims4(1, 2, 3, 4), Not(DimsAreArray({1, 2, 3, 5}))); + // Check mismatching number of arguments. + EXPECT_THAT(nvinfer1::Dims4(1, 2, 3, 4), Not(DimsAreArray({1, 2, 5}))); +} + +TEST(TrtDimsMatcher, EqualityMatcher) { + EXPECT_THAT(nvinfer1::Dims4(1, 2, 3, 4), Eq(nvinfer1::Dims4(1, 2, 3, 4))); + // Check empty dims. + EXPECT_THAT(nvinfer1::Dims{}, Eq(nvinfer1::Dims())); + // Check empty Dims is not equal to DimsHW, since their sizes differ. + EXPECT_THAT(nvinfer1::Dims{}, Not(Eq(nvinfer1::DimsHW()))); + // Check mismatching values. + EXPECT_THAT(nvinfer1::Dims4(1, 2, 3, 4), + Not(Eq(nvinfer1::Dims4(1, 2, 3, 3)))); + // Check mismatching number of arguments. + EXPECT_THAT(nvinfer1::Dims4(1, 2, 3, 4), Not(Eq(nvinfer1::Dims2(1, 2)))); +} + +TEST(INetworkDefinitionMatchers, CorrectlyMatch) { + Logger& logger = *Logger::GetLogger(); + TrtUniquePtrType builder( + nvinfer1::createInferBuilder(logger)); + TrtUniquePtrType network( + builder->createNetworkV2(0L)); + + // Empty network checks. + EXPECT_THAT(network.get(), AllOf(Not(LayerNamesAreArray({"some layer"})), + LayerNamesNonEmpty())); + + // Add the input and FC layers. + nvinfer1::Weights weights; + weights.type = nvinfer1::DataType::kFLOAT; + std::array vals; + weights.values = vals.data(); + weights.count = 1; + auto input = network->addInput("input-tensor", nvinfer1::DataType::kFLOAT, + nvinfer1::Dims3{1, 1, 1}); + ASSERT_NE(input, nullptr); + + const char* fc_layer_name = "my-fc-layer"; + auto layer = network->addFullyConnected(*input, 1, weights, weights); + ASSERT_NE(layer, nullptr); + layer->setName(fc_layer_name); + + // Check layer names. + EXPECT_THAT(network.get(), + AllOf(LayerNamesNonEmpty(), LayerNamesAreArray({fc_layer_name}))); + + // Add layer with default name and check layer name. + layer = network->addFullyConnected(*input, 1, weights, weights); + EXPECT_THAT(network.get(), AllOf(LayerNamesNonEmpty(), + Not(LayerNamesAreArray({fc_layer_name})))); +} + +} // namespace convert + +} // namespace tensorrt +} // namespace tensorflow + +#endif // GOOGLE_CUDA && GOOGLE_TENSORRT diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..1261e1bf3ed280d88ec14fcc9b2db72c51a8a46a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/BUILD @@ -0,0 +1,1815 @@ +load("@local_config_rocm//rocm:build_defs.bzl", "if_rocm_is_configured") +load("@xla//third_party/rules_python/python:py_library.bzl", "py_library") + +# copybara:uncomment_begin(google-only) +# load("//devtools/deps/check:deps_check.bzl", "check_dependencies") +# copybara:uncomment_end + +load("@xla//xla:xla.default.bzl", "xla_py_proto_library") +load("@xla//xla/service/cpu:build_defs.bzl", "runtime_copts") +load("@xla//xla/tsl/mkl:build_defs.bzl", "mkl_deps") +load("@xla//xla/tsl/platform:build_config_root.bzl", "if_static") +load( + "@xla//xla/tsl/platform/default:cuda_build_defs.bzl", + "if_cuda_is_configured", +) +load("//tensorflow:tensorflow.bzl", "if_google", "if_libtpu", "tf_cc_binary", "tf_cc_test", "tf_copts", "tf_cuda_cc_test", "tf_gen_op_wrapper_py", "tf_openmp_copts") +load("//tensorflow:tensorflow.default.bzl", "cuda_py_strict_test", "filegroup", "get_compatible_with_portable") +load( + "//tensorflow/core/platform:build_config.bzl", + "tf_additional_tensor_coding_deps", + "tf_proto_library", +) +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [":internal"], + licenses = ["notice"], +) + +package_group( + name = "internal", + packages = [ + "//tensorflow/compiler/aot/...", + "//tensorflow/compiler/jit/...", + "//tensorflow/compiler/mlir/...", + "//tensorflow/compiler/tests/...", + "//tensorflow/compiler/tf2xla/...", + "//tensorflow/core/tpu/...", + "//tensorflow/python/compiler/...", + "//tensorflow/python/util/...", + ], +) + +package_group( + name = "friends", + includes = [":internal"], + packages = [ + "//platforms/performance/automl/...", + "//tensorflow/...", + "//tensorflow_federated/cc/core/impl/executors/...", + "//tensorflow_models/...", + "//third_party/deepmind/deepmind_research/density_functional_approximation_dm21/...", + "//third_party/mlir_edge/model_curriculum/iree/...", + "//third_party/mlperf/submissions/training/v0_7/models/...", + "//third_party/py/keras_cv/...", + "//third_party/py/litert_torch/...", + "//third_party/py/orbax/...", + "//third_party/py/tf_keras/...", + "//third_party/sparse_conv/ops/...", + "//waymo/ml/deploy/benchmark/...", + ], +) + +cc_library( + name = "tf2xla_supported_ops_lib", + srcs = ["tf2xla_supported_ops.cc"], + hdrs = ["tf2xla_supported_ops.h"], + visibility = ["//visibility:public"], + deps = [ + ":xla_compiler", + ":xla_op_registry", + "//tensorflow/compiler/tf2xla/kernels:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/strings", + ], +) + +tf_cc_binary( + name = "tf2xla_supported_ops", + srcs = ["tf2xla_supported_ops_main.cc"], + visibility = ["//visibility:public"], + deps = [":tf2xla_supported_ops_lib"], +) + +tf_proto_library( + name = "tf2xla_proto", + srcs = ["tf2xla.proto"], + protodeps = [ + "//tensorflow/core:protos_all", + ], + visibility = ["//visibility:public"], +) + +xla_py_proto_library( + name = "tf2xla_py", + has_services = False, + visibility = ["//visibility:public"], + deps = [":tf2xla_proto"], +) + +tf_proto_library( + name = "host_compute_metadata_proto", + srcs = ["host_compute_metadata.proto"], + protodeps = [ + "//tensorflow/core:protos_all", + ], + visibility = ["//visibility:public"], +) + +cc_library( + name = "graph_compiler_util", + srcs = ["graph_compiler_util.cc"], + hdrs = ["graph_compiler_util.h"], + visibility = [":friends"], + deps = [ + ":functionalize_control_flow", + ":sharding_util", + ":tf2xla_proto_cc", + ":tf2xla_util", + ":xla_compiler", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:graph", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + ], +) + +cc_library( + name = "encoded_buffer_allocation_info", + hdrs = ["encoded_buffer_allocation_info.h"], + visibility = [":friends"], + deps = [ + "@xla//xla/backends/cpu:buffer_allocation_info", + ], +) + +tf_cc_test( + name = "encoded_buffer_allocation_info_test", + srcs = ["encoded_buffer_allocation_info_test.cc"], + deps = [ + ":encoded_buffer_allocation_info", + "@com_google_googletest//:gtest_main", + "@xla//xla/backends/cpu:buffer_allocation_info", + ], +) + +cc_library( + name = "tf2xla", + srcs = ["tf2xla.cc"], + hdrs = ["tf2xla.h"], + visibility = ["//visibility:public"], + deps = [ + ":common", + ":graph_compiler_util", + ":tf2xla_proto_cc", + ":tf2xla_util", + ":xla_compiler", + ":xla_op_registry", + "//tensorflow/compiler/aot:aot_only_var_handle_op", + "//tensorflow/compiler/tf2xla/kernels:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/strings", + "@xla//xla/client", + "@xla//xla/hlo/builder:xla_computation", + ], +) + +cc_library( + name = "mlir_tf2xla", + srcs = ["mlir_tf2xla.cc"], + hdrs = ["tf2xla.h"], + visibility = ["//visibility:public"], + deps = [ + ":tf2xla_proto_cc", + ":tf2xla_util", + ":xla_compiler", + "//tensorflow/compiler/jit", + "//tensorflow/compiler/mlir/tensorflow:device_util", + "//tensorflow/compiler/mlir/tensorflow:import_utils", + "//tensorflow/compiler/mlir/tensorflow:mlir_roundtrip_flags", + "//tensorflow/compiler/mlir/tensorflow/transforms:bridge", + "//tensorflow/compiler/mlir/tensorflow/transforms:tf_dialect_passes", + "//tensorflow/compiler/mlir/tensorflow/translate/tools:parsers", + "//tensorflow/compiler/mlir/tf2xla:compile_mlir_util", + "//tensorflow/compiler/mlir/tf2xla/api/v2:graph_to_tf_executor", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:framework_types_hdr", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:device_set", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:vlog_is_on", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@llvm-project//mlir:IR", + "@tsl//tsl/platform:errors", + "@tsl//tsl/platform:statusor", + "@xla//xla/client", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/tsl/platform:statusor", + ], +) + +# The filegroups below are explicitly used by +# tensorflow/tools/pip_package:build_pip_package to ensure we include the proper +# sources for the XLA AOT CPU runtime; as these are necessary outside of bazel +# when linking tfcompile objects using saved_model_cli (e.g. using the +# tensorflow pip package). The associated .cc files are included in tensorflow +# pip package's xla_aot_runtime_srcs/ subdirectory. All necessary headers are +# also included in the pip package's include/tensorflow/ and include/external/ +# subdirectories. Note however that sometimes additional object files may need +# to be linked when linking aot xla objects, e.g. abseil libraries. See the deps +# attribute of the "xla_compiled_cpu_runtime_standalone" target below for an +# exhaustive list. +filegroup( + name = "xla_compiled_cpu_runtime_hdrs", + srcs = [ + "allocator.h", + "encoded_buffer_allocation_info.h", + "xla_compiled_cpu_function.h", + "//tensorflow/core/kernels:xla_cpu_runtime_hdrs", + "//tensorflow/core/platform:xla_cpu_runtime_srcs", + "@tsl//tsl/platform:xla_cpu_runtime_srcs", + "@xla//xla:cpu_runtime_hdrs", + "@xla//xla/backends/cpu:xla_cpu_runtime_hdrs", + "@xla//xla/service:custom_call_status_hdrs", + "@xla//xla/service/cpu:runtime_hdrs", + "@xla//xla/tsl/concurrency:xla_cpu_runtime_hdrs", + "@xla//xla/tsl/framework:xla_cpu_runtime_hdrs", + "@xla//xla/tsl/framework/fixedpoint:xla_cpu_runtime_hdrs", + "@xla//xla/tsl/lib/math:xla_cpu_runtime_hdrs", + "@xla//xla/tsl/util:xla_cpu_runtime_hdrs", + ], + visibility = [ + "//tensorflow/tools/pip_package:__pkg__", + "//tensorflow/tools/pip_package:__subpackages__", + ], +) + +filegroup( + name = "xla_compiled_cpu_runtime_srcs", + srcs = [ + "allocator.cc", + "xla_compiled_cpu_function.cc", + "//tensorflow/core/kernels:xla_cpu_runtime_srcs", + "//tensorflow/core/platform:xla_cpu_runtime_srcs", + "@tsl//tsl/platform:xla_cpu_runtime_srcs", + "@xla//xla:cpu_runtime_srcs", + "@xla//xla/service:custom_call_status_srcs", + "@xla//xla/service/cpu:runtime_srcs", + "@xla//xla/tsl/concurrency:xla_cpu_runtime_srcs", + ], + visibility = [ + "//tensorflow/tools/pip_package:__pkg__", + "//tensorflow/tools/pip_package:__subpackages__", + ], +) + +# This stand-alone target is used to ensure that we can build tf_library type +# targets against the subset of sources declared in +# xla_compiled_cpu_runtime_{srcs,hdrs}. +# +# The macros in tensorflow/python/tools/tools.bzl produce AOT compiled binaries +# that rely on this target, as do unit tests in tensorflow/python/tools. +# +# See above for the significance of the source filegroups. +cc_library( + name = "xla_compiled_cpu_runtime_standalone", + srcs = [ + ":xla_compiled_cpu_runtime_srcs", + ], + hdrs = [ + ":xla_compiled_cpu_runtime_hdrs", + ], + copts = runtime_copts() + tf_openmp_copts(), + defines = [ + "EIGEN_NEON_GEBP_NR=4", + ], + features = [ + "fully_static_link", + "-parse_headers", + ], + linkstatic = 1, + visibility = [":friends"], + # Note, we specifically removed MKL and multithreaded dependencies so the + # standalone does not require the MKL binary blob or threading libraries. + # + # TODO(ebrevdo): Remove tf_additoinal_tensor_coding_deps in favor of + # absl/strings:cord when we update absl to a newer version. + # + # NOTE!!!!! (b/150412548 for reference) + # DO NOT add dependencies here! + # + # 1) Read first the purpose of this target and the purpose of the + # :xla_compiled_cpu_runtime_{srcs|hrds} targets. + # + # Key point is: this target represents the sources available under the xla_aot_runtime_srcs + # dir in the tensorflow pip package, which enables linking AOT-ed saved modules in customer + # projects, including those not using bazel. So adding a dependency here to fix the tests + # using this target (xla_compiled_cpu_runtime_standalone) defeats the purpose. + # + # 2) Most likely you need to split your dependency into 2 file groups and add them + # to the :xla_compiled_cpu_runtime_{srcs|hrds} targets accordingly. + # + # !!!DO NOT EDIT dependencies - please read the above!!! + deps = [ + "@com_google_absl//absl/base", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/base:dynamic_annotations", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/synchronization", + "@ducc//:fft_wrapper", + "@eigen_archive//:eigen3", + "@llvm-project//mlir:TransformUtils", + "@xla//xla/tsl:empty", + "//tensorflow/core/framework:numeric_types", + "//tensorflow/core/platform:bfloat16", + "//tensorflow/core/platform:float8", + "//tensorflow/core/platform:stringpiece", + # Extra dependencies required for multithreaded runtime objects. + "//tensorflow/core/platform:blocking_counter", + "//tensorflow/core/platform:logging", + "//tensorflow/core/platform:mutex", + "@tsl//tsl/platform:blocking_counter", + "@tsl//tsl/platform:context", + "@tsl//tsl/platform:cord", + "@tsl//tsl/platform:logging", + "@tsl//tsl/platform:ml_dtypes", + "@tsl//tsl/platform:tstring", + "@tsl//tsl/platform:types", + ] + tf_additional_tensor_coding_deps() + mkl_deps(), + alwayslink = 1, +) + +# copybara:uncomment_begin(google-only) +# check_dependencies( +# # Please read the whole comment above the `deps` of xla_compiled_cpu_runtime_standalone before +# # making any change here. +# name = "only_pip_sources_in_xla_lib", +# of = [":xla_compiled_cpu_runtime_standalone"], +# allowed_match_regexp = "|".join([ +# ":xla_compiled_cpu_runtime_standalone", +# "//tensorflow/core/framework:numeric_types", +# "@xla//xla/tsl/framework:numeric_types", +# "@xla//xla/tsl/framework:device_type", +# "@xla//xla/tsl/framework:fixedpoint_types", +# "@tsl//tsl/platform:bfloat16", +# "@tsl//tsl/platform:blocking_counter", +# "@xla//xla/tsl/platform:byte_order", +# "@tsl//tsl/platform:context", +# "@tsl//tsl/platform:cord", +# "@tsl//tsl/platform:env_time", +# "@tsl//tsl/platform:refcount", +# "@tsl//tsl/platform:ml_dtypes", +# "@tsl//tsl/platform:logging", +# "@tsl//tsl/platform:macros", +# "@tsl//tsl/platform:mutex", +# "@tsl//tsl/platform:platform", +# "@tsl//tsl/platform:stringpiece", +# "@tsl//tsl/platform:thread_annotations", +# "@tsl//tsl/platform:tstring", +# "@tsl//tsl/platform:types", +# "@xla//xla/tsl/platform:env_time", +# "@xla//xla/tsl/platform:logging", +# "@xla//xla/tsl/platform:types", +# "@xla//xla/tsl/platform:macros", +# "@xla//xla/tsl/platform/default:context", +# "@xla//xla/tsl/platform/default:cord", +# "@xla//xla/tsl/platform/default:env_time", +# "@xla//xla/tsl/platform/default:types", +# "@xla//xla/tsl/platform/google:context", +# "@xla//xla/tsl/platform/google:cord", +# "@xla//xla/tsl/platform/google:env_time", +# "@xla//xla/tsl/platform/google:types", +# "@xla//xla/tsl/platform/windows:env_time", +# "//tensorflow/core/platform:bfloat16", +# "//tensorflow/core/platform:blocking_counter", +# "//tensorflow/core/platform:byte_order", +# "//tensorflow/core/platform:cord", +# "//tensorflow/core/platform:env_time", +# "//tensorflow/core/platform:float8", +# "//tensorflow/core/platform:logging", +# "//tensorflow/core/platform:macros", +# "//tensorflow/core/platform:mutex", +# "//tensorflow/core/platform:platform", +# "//tensorflow/core/platform:stringpiece", +# "//tensorflow/core/platform:thread_annotations", +# "//tensorflow/core/platform:tstring", +# "//tensorflow/core/platform:types", +# "@xla//xla/tsl:empty", +# ]), +# dont_match_regexp = "|".join(["//tensorflow"]), +# kind = "cc_library", +# ) +# copybara:uncomment_end + +cc_library( + name = "allocator", + srcs = ["allocator.cc"], + hdrs = ["allocator.h"], + compatible_with = get_compatible_with_portable(), + visibility = ["//visibility:public"], + deps = [ + "@com_google_absl//absl/base:dynamic_annotations", + "@com_google_absl//absl/types:span", + "@xla//xla/backends/cpu:alignment", + "@xla//xla/backends/cpu:buffer_allocation_info", + ], +) + +tf_cc_test( + name = "allocator_test", + srcs = ["allocator_test.cc"], + deps = [ + ":allocator", + "//tensorflow/core:framework", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@xla//xla/backends/cpu:alignment", + "@xla//xla/backends/cpu:buffer_allocation_info", + ], +) + +cc_library( + name = "xla_compiled_cpu_function", + srcs = ["xla_compiled_cpu_function.cc"], + hdrs = ["xla_compiled_cpu_function.h"], + compatible_with = get_compatible_with_portable(), + visibility = ["//visibility:public"], + deps = [ + # Keep dependencies to a minimum here; this library is used in every AOT + # binary produced by tfcompile. + ":allocator", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/types:span", + ":encoded_buffer_allocation_info", + "@xla//xla/service:custom_call_status_internal", + "@xla//xla/backends/cpu/runtime:rng_state_lib", + "@xla//xla/backends/cpu:alignment", + "@xla//xla/backends/cpu:buffer_allocation_info", + "@xla//xla:executable_run_options", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/strings:string_view", + ], +) + +cc_library( + name = "xla_compiled_cpu_function_thunks", + srcs = ["xla_compiled_cpu_function_thunks.cc"], + hdrs = ["xla_compiled_cpu_function_thunks.h"], + compatible_with = get_compatible_with_portable(), + visibility = ["//visibility:public"], + deps = [ + ":xla_compiled_cpu_function", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/types:span", + "@xla//xla:executable_run_options", + "@xla//xla/backends/cpu/codegen:aot_compiled_function_library", + "@xla//xla/backends/cpu/nanort:nanort_executable", + "@xla//xla/backends/cpu/runtime:function_library", + "@xla//xla/backends/cpu/runtime/thunk_serdes:all_thunk_serdes", # buildcleaner: keep + "@xla//xla/service:executable", # buildcleaner: keep (b/404179184) + "@xla//xla/service/cpu:cpu_aot_compilation_result", + "@xla//xla/service/cpu:executable_proto_cc", + "@xla//xla/tsl/concurrency:async_value", + "@xla//xla/tsl/platform:env", + ], +) + +cc_library( + name = "xla_compiled_cpu_function_factory", + srcs = ["xla_compiled_cpu_function_factory.cc"], + hdrs = ["xla_compiled_cpu_function_factory.h"], + visibility = ["//visibility:public"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compiled_cpu_function", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + ], +) + +cc_library( + name = "xla_compiled_cpu_function_thunk_factory_registerer", + srcs = ["xla_compiled_cpu_function_thunk_factory_registerer.cc"], + visibility = ["//visibility:public"], + deps = [ + ":xla_compiled_cpu_function_factory", + "//tensorflow/compiler/tf2xla:xla_compiled_cpu_function", + "//tensorflow/compiler/tf2xla:xla_compiled_cpu_function_thunks", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_jit_compiled_cpu_function", + srcs = ["xla_jit_compiled_cpu_function.cc"], + hdrs = ["xla_jit_compiled_cpu_function.h"], + visibility = ["//visibility:public"], + deps = [ + ":encoded_buffer_allocation_info", + ":tf2xla", + ":tf2xla_proto_cc", + ":xla_compiled_cpu_function", + ":xla_compiled_cpu_function_thunks", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:span", + "@tsl//tsl/platform:casts", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/backends/cpu:buffer_allocation_info", + "@xla//xla/backends/cpu:buffer_allocation_info_util", + "@xla//xla/backends/cpu/codegen:compiled_function_library", + "@xla//xla/backends/cpu/runtime/thunk_serdes:all_thunk_serdes", # buildcleaner: keep + "@xla//xla/client:client_library", + "@xla//xla/client:executable_build_options", + "@xla//xla/client:local_client", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/service:platform_util", + "@xla//xla/service/cpu:cpu_aot_compilation_result", + "@xla//xla/service/cpu:executable_proto_cc", + "@xla//xla/stream_executor:platform", + ] + if_libtpu( + if_false = [ + "@xla//xla/service:cpu_plugin", + "@xla//xla/service/cpu:cpu_executable", + ], + if_true = [], + ), +) + +tf_cc_test( + name = "graph_compiler_test", + srcs = ["graph_compiler_test.cc"], + deps = [ + ":graph_compiler_util", + ":tf2xla_proto_cc", + ":xla_compilation_device", + ":xla_compiler", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/lib/monitoring:cell_reader", + "//tensorflow/core/platform:refcount", + "@com_google_googletest//:gtest_main", + ], +) + +cc_library( + name = "xla_compiler", + srcs = [ + "const_analysis.cc", + "graph_compiler.cc", + "xla_compiler.cc", + "xla_cpu_backend.cc", + "xla_op_kernel.cc", + ] + if_cuda_is_configured([ + "xla_gpu_backend.cc", + ]) + if_rocm_is_configured([ + "xla_gpu_backend.cc", + ]), + hdrs = [ + "const_analysis.h", + "graph_compiler.h", + "xla_compiler.h", + "xla_helpers.h", + "xla_op_kernel.h", + "xla_op_registry.h", + ], + copts = tf_copts(), + visibility = [":friends"], + deps = [ + ":common", + ":host_compute_metadata_proto_cc", + ":layout_util", + ":rearrange_function_argument", + ":sharding_util", + ":side_effect_util", + ":tf2xla_util", + ":xla_argument", + ":xla_compilation_device", + ":xla_context", + ":xla_expression", + ":xla_helpers", + ":xla_op_registry", + ":xla_resource", + "//tensorflow/compiler/jit:common", + "//tensorflow/compiler/jit:flags", + "//tensorflow/compiler/jit:shape_inference", + "//tensorflow/compiler/jit:xla_compile_util", + "//tensorflow/compiler/mlir/tensorflow:attribute_utils", + "//tensorflow/compiler/mlir/tf2xla:mlir_bridge_rollout_policy", + "//tensorflow/compiler/mlir/tf2xla/api/v1:compile_mlir_util_no_tf_dialect_passes", + "//tensorflow/compiler/mlir/utils:array_container_utils", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:lib_internal", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/tpu:tpu_defs", + "//tensorflow/core/util:overflow", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/synchronization", + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:span", + "@com_google_absl//absl/types:variant", + "@tsl//tsl/platform:tensor_float_32_hdr_lib", + "@xla//xla:executable_run_options", + "@xla//xla:literal", + "@xla//xla:protobuf_util", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client", + "@xla//xla/client:client_library", + "@xla//xla/client:local_client", + "@xla//xla/core/collectives:clique_id", + "@xla//xla/core/collectives:clique_key", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/ir:hlo", + "@xla//xla/hlo/translate/mhlo_to_hlo:layout_util", + "@xla//xla/service:computation_placer_hdr", + "@xla//xla/service:hlo_proto_cc", + "@xla//xla/service/spmd/shardy:constants", + "@xla//xla/service/spmd/shardy:utils", + "@xla//xla/service/spmd/shardy/stablehlo_round_trip:stablehlo_import", + "@xla//xla/stream_executor:device_memory_allocator", + ] + if_libtpu([ + ":xla_tpu_backend_registration", + ]) + if_static(["@tsl//tsl/platform:tensor_float_32_utils"]), + alwayslink = 1, +) + +cc_library( + name = "xla_compilation_device", + srcs = [ + "xla_compilation_device.cc", + ], + hdrs = [ + "xla_compilation_device.h", + ], + deps = [ + ":common", + ":frontend_attributes_util", + ":sharding_util", + ":xla_context", + ":xla_helpers", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:session_options", + "//tensorflow/core/common_runtime:core_cpu_internal", + "@xla//xla/hlo/builder:xla_builder", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_tpu_backend_registration", + srcs = ["xla_tpu_backend.cc"], + visibility = ["//visibility:public"], + deps = [ + ":xla_op_registry", + "//tensorflow/core/tpu:tpu_defs", + "//tensorflow/core/tpu:tpu_node_device_util", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_context", + srcs = [ + "xla_context.cc", + ], + hdrs = [ + "xla_context.h", + ], + deps = [ + ":common", + ":xla_expression", + ":xla_helpers", + ":xla_resource", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core/common_runtime:core_cpu_internal", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client:client_library", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_op_registry", + srcs = [ + "xla_op_registry.cc", + ], + hdrs = [ + "xla_op_registry.h", + ], + visibility = [":friends"], + deps = [ + ":common", + ":xla_context", + "//tensorflow/compiler/jit:flags", + "//tensorflow/compiler/jit:xla_cluster_util", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:session_options", + "//tensorflow/core/common_runtime:core_cpu_internal", + "//tensorflow/core/common_runtime/next_pluggable_device:next_pluggable_device_factory_hdrs", + "//tensorflow/core/platform:stream_executor_no_cuda", + "//tensorflow/core/tfrt/common:pjrt_util", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:string_view", + "@com_google_absl//absl/types:span", + "@xla//xla:util", + "@xla//xla/client:client_library", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_expression", + srcs = [ + "xla_expression.cc", + ], + hdrs = [ + "xla_expression.h", + ], + deps = [ + ":common", + ":xla_resource", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:optional", + "@xla//xla/client", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_resource", + srcs = [ + "xla_resource.cc", + ], + hdrs = [ + "xla_resource.h", + ], + visibility = [ + ":internal", + "//learning/deepmind/tensorflow/tpufunc:__pkg__", + ], + deps = [ + ":common", + ":sharding_util", + ":xla_helpers", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_helpers", + srcs = [ + "xla_helpers.cc", + ], + hdrs = [ + "xla_helpers.h", + ], + visibility = [":friends"], + deps = [ + ":common", + ":host_compute_metadata_proto_cc", + "//tensorflow/compiler/tf2xla/lib:util", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core/platform:refcount", + "@com_google_absl//absl/container:btree", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/synchronization", + "@com_google_absl//absl/time", + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:span", + "@xla//xla:executable_run_options", + "@xla//xla:literal", + "@xla//xla:literal_util", + "@xla//xla:shape_util", + "@xla//xla/core/collectives:clique_id", + "@xla//xla/core/collectives:clique_key", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/ir:hlo", + "@xla//xla/hlo/translate/mhlo_to_hlo:layout_util", + "@xla//xla/service:computation_placer_hdr", + "@xla//xla/service/gpu:gpu_executable_run_options", + "@xla//xla/stream_executor:stream", + "@xla//xla/stream_executor:stream_executor_h", + ], + alwayslink = 1, +) + +cc_library( + name = "xla_argument", + srcs = [ + "xla_argument.cc", + ], + hdrs = [ + "xla_argument.h", + ], + deps = [ + ":host_compute_metadata_proto_cc", + ":xla_argument_proto_cc", + ":xla_resource", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:span", + "@com_google_absl//absl/types:variant", + "@llvm-project//llvm:Support", + "@xla//xla:shape_util", + "@xla//xla/tsl/platform:statusor", + ], + alwayslink = 1, +) + +tf_cc_test( + name = "xla_argument_test", + srcs = ["xla_argument_test.cc"], + deps = [ + ":xla_argument", + ":xla_argument_proto_cc", + ":xla_resource", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:functional_ops", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core/framework:tensor_testutil", + "@com_google_googletest//:gtest_main", + "@xla//xla:shape_util", + ], +) + +tf_proto_library( + name = "xla_argument_proto", + srcs = ["xla_argument.proto"], + protodeps = [ + "@xla//xla:xla_data_proto", + "//tensorflow/core:protos_all", + ], + visibility = [ + ":friends", + "//tensorflow/compiler:__subpackages__", + ] + if_google([ + "//waymo/ml/deploy:__subpackages__", + ]), +) + +cc_library( + name = "layout_util", + srcs = [ + "layout_util.cc", + ], + hdrs = [ + "layout_util.h", + ], + visibility = [":friends"], + deps = [ + ":common", + ":xla_argument", + ":xla_helpers", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/ir:hlo", + ], + alwayslink = 1, +) + +cc_library( + name = "common", + srcs = [ + "literal_util.cc", + "shape_util.cc", + "type_util.cc", + ], + hdrs = [ + "literal_util.h", + "shape_util.h", + "type_util.h", + ], + visibility = [":friends"], + deps = [ + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + ], +) + +tf_cc_test( + name = "type_util_test", + srcs = ["type_util_test.cc"], + deps = [ + ":common", + "//tensorflow/core:framework_types_hdr", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@com_google_absl//absl/status:statusor", + ], +) + +cc_library( + name = "frontend_attributes_util", + srcs = ["frontend_attributes_util.cc"], + hdrs = ["frontend_attributes_util.h"], + visibility = ["//visibility:public"], + deps = [ + ":tf2xla_defs", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:optional", + "@xla//xla:xla_data_proto_cc", + ], +) + +cc_library( + name = "sharding_util", + srcs = ["sharding_util.cc"], + hdrs = ["sharding_util.h"], + visibility = ["//visibility:public"], + deps = [ + "//tensorflow/compiler/mlir/tensorflow:xla_sharding_util", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla/hlo/builder:sharding_builder", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/ir:hlo_sharding", + "@xla//xla/service/spmd/shardy/stablehlo_round_trip:stablehlo_import", + ], +) + +tf_cc_test( + name = "sharding_util_test", + srcs = ["sharding_util_test.cc"], + deps = [ + ":sharding_util", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "@com_google_googletest//:gtest", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/ir:hlo_sharding", + "@xla//xla/tsl/platform:statusor", + ], +) + +# Internal targets below this point. + +cc_library( + name = "tf2xla_defs", + hdrs = ["tf2xla_defs.h"], + visibility = [":friends"], + deps = [ + "@com_google_absl//absl/strings", + ], +) + +cc_library( + name = "tf2xla_util", + srcs = ["tf2xla_util.cc"], + hdrs = ["tf2xla_util.h"], + visibility = [":friends"], + deps = [ + ":sharding_util", + ":tf2xla_defs", + ":tf2xla_proto_cc", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + ], +) + +tf_cc_test( + name = "tf2xla_util_test", + srcs = ["tf2xla_util_test.cc"], + deps = [ + ":sharding_util", + ":tf2xla_util", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:functional_ops", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:math_ops_op_lib", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + ], +) + +tf_cc_test( + name = "tf2xla_test", + srcs = ["tf2xla_test.cc"], + tags = ["no_cuda_on_cpu_tap"], + deps = [ + ":tf2xla", + ":tf2xla_proto_cc", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@com_google_absl//absl/status:statusor", + "@tsl//tsl/platform:tensor_float_32_hdr_lib", + "@xla//xla:literal", + "@xla//xla:literal_util", + "@xla//xla/client:client_library", + "@xla//xla/client:local_client", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/service:cpu_plugin", + ] + if_static(["@tsl//tsl/platform:tensor_float_32_utils"]), +) + +tf_cc_test( + name = "xla_jit_compiled_cpu_function_test", + srcs = ["xla_jit_compiled_cpu_function_test.cc"], + deps = [ + ":tf2xla_proto_cc", + ":xla_compiled_cpu_function_thunks", + ":xla_jit_compiled_cpu_function", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status:statusor", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client:executable_build_options", + "@xla//xla/hlo/testlib:test", + "@xla//xla/service:compiler", + "@xla//xla/service:platform_util", + "@xla//xla/stream_executor:platform", + "@xla//xla/stream_executor:platform_manager", + ], +) + +tf_cc_test( + name = "xla_compiler_test", + srcs = [ + "xla_compiler_test.cc", + "xla_expression_test.cc", + ], + tags = ["no_cuda_on_cpu_tap"], + deps = [ + ":common", + ":layout_util", + ":side_effect_util", + ":xla_argument", + ":xla_compiler", + ":xla_expression", + ":xla_resource", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:functional_ops", + "//tensorflow/cc:ops", + "//tensorflow/cc:resource_variable_ops", + "//tensorflow/cc:scope", + "//tensorflow/compiler/tf2xla/kernels:xla_ops", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "//tensorflow/core/framework:resource_base", + "//tensorflow/core/framework:tensor_testutil", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/log", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_googletest//:gtest", + "@tsl//tsl/platform:statusor", + "@xla//xla:array", + "@xla//xla:debug_options_flags", + "@xla//xla:literal", + "@xla//xla:literal_util", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client", + "@xla//xla/client:client_library", + "@xla//xla/client:local_client", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/ir:hlo", + "@xla//xla/hlo/ir:hlo_sharding", + "@xla//xla/hlo/testlib:filecheck", + "@xla//xla/service", + "@xla//xla/service:cpu_plugin", + "@xla//xla/service:hlo_module_util", + "@xla//xla/service:hlo_proto_cc", + "@xla//xla/service:hlo_proto_util", + "@xla//xla/tests:literal_test_util", + "@xla//xla/tsl/platform:errors", + "@xla//xla/tsl/platform:statusor", + ], +) + +tf_cc_test( + name = "literal_util_test", + srcs = [ + "literal_util_test.cc", + ], + deps = [ + ":common", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/types:span", + "@com_google_googletest//:gtest_main", + "@xla//xla:literal", + "@xla//xla:literal_util", + "@xla//xla/tsl/protobuf:error_codes_proto_impl_cc", + ], +) + +tf_cc_test( + name = "const_analysis_test", + size = "small", + srcs = ["const_analysis_test.cc"], + deps = [ + ":xla_compiler", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:functional_ops", + "//tensorflow/cc:ops", + "//tensorflow/compiler/jit:flags", + "//tensorflow/compiler/jit:xla_cluster_util", + "//tensorflow/compiler/tf2xla/kernels:xla_ops", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:ops", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) + +cc_library( + name = "light_outside_compilation_kernels_for_test", + testonly = True, + srcs = ["light_outside_compilation_kernels_for_test.cc"], + linkstatic = 1, + deps = [ + ":xla_compiler", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:functional_ops", + "//tensorflow/compiler/tf2xla/kernels:light_outside_compilation", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla/stream_executor:device_memory", + "@xla//xla/stream_executor:stream", + "@xla//xla/tsl/platform:statusor", + ], + alwayslink = 1, +) + +tf_gen_op_wrapper_py( + name = "test_ops_for_light_outside_compilation", + testonly = True, + out = "test_ops_for_light_outside_compilation.py", + extra_py_deps = [ + "//tensorflow/python:pywrap_tfe", + "//tensorflow/python/util:dispatch", + "//tensorflow/python/util:deprecation", + "//tensorflow/python/util:tf_export", + ], + py_lib_rule = py_library, + deps = [ + ":light_outside_compilation_kernels_for_test", + ], +) + +cuda_py_strict_test( + name = "light_outside_compilation_test", + srcs = ["light_outside_compilation_test.py"], + tags = [ + "no_oss", + ], + xla_enable_strict_auto_jit = False, + deps = [ + ":test_ops_for_light_outside_compilation", + "//tensorflow/compiler/mlir/python/mlir_wrapper:filecheck_wrapper", + "//tensorflow/python/eager:context", + "//tensorflow/python/eager:def_function", + "//tensorflow/python/framework:ops", + "//tensorflow/python/framework:test_lib", + "//tensorflow/python/ops:array_ops", + "//tensorflow/python/ops:nn_ops", + "//tensorflow/python/ops:random_ops", + "//tensorflow/python/platform:client_testlib", + "//tensorflow/python/platform:test", + ] + if_google([":light_outside_compilation_kernels_for_test"]), +) + +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/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:graph", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/strings", + "@xla//xla:status_macros", + ], +) + +cc_library( + name = "functionalize_cond", + srcs = [ + "functionalize_cond.cc", + ], + hdrs = [ + "functionalize_cond.h", + ], + deps = [ + ":functionalize_control_flow_util", + ":tf2xla_defs", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:hash", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:status_macros", + ], +) + +cc_library( + name = "functionalize_control_flow", + srcs = [ + "functionalize_control_flow.cc", + ], + hdrs = [ + "functionalize_control_flow.h", + ], + visibility = [":friends"], + deps = [ + ":functionalize_cond", + ":functionalize_control_flow_util", + ":functionalize_while", + ":tf2xla_util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:graph", + "//tensorflow/core:lib", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/types:optional", + "@xla//xla:status_macros", + "@xla//xla:union_find", + ], +) + +cc_library( + name = "mlir_bridge_pass", + srcs = ["mlir_bridge_pass.cc"], + hdrs = ["mlir_bridge_pass.h"], + visibility = [":internal"], + deps = [ + ":tf2xla_defs", + ":xla_op_registry", + "//tensorflow/compiler/jit:flags", + "//tensorflow/compiler/mlir:mlir_graph_optimization_pass", + "//tensorflow/compiler/mlir/tensorflow", + "//tensorflow/compiler/mlir/tensorflow:attribute_utils", + "//tensorflow/compiler/mlir/tensorflow:device_util", + "//tensorflow/compiler/mlir/tensorflow/transforms/host_runtime:lower_cluster_to_runtime_ops", + "//tensorflow/compiler/mlir/tf2xla:mlir_bridge_rollout_policy", + "//tensorflow/compiler/mlir/tf2xla/api/v1:cluster_tf", + "//tensorflow/compiler/mlir/tf2xla/api/v1:tf_dialect_to_executor", + "//tensorflow/compiler/mlir/tf2xla/api/v2:cluster_tf", + "//tensorflow/compiler/mlir/tf2xla/api/v2:tf_dialect_to_executor", + "//tensorflow/compiler/mlir/tf2xla/internal:mlir_bridge_pass_util", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_base", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core/common_runtime:device_set", + "//tensorflow/core/protobuf:for_core_protos_cc", + "//tensorflow/core/tpu:tpu_defs", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/base", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Support", + "@xla//xla/tsl/platform:logging", + ], + alwayslink = 1, +) + +cc_library( + name = "mlir_bridge_pass_registration", + srcs = [ + "mlir_bridge_pass_registration.cc", + ], + visibility = [ + # We define a new TPU device in TFRT to enable TFRT TPU Runtime. + "//learning/brain/tfrt/tf_tpu:__pkg__", + ":internal", + ], + deps = [ + ":mlir_bridge_pass", + "//tensorflow/compiler/mlir:mlir_graph_optimization_pass", + "//tensorflow/compiler/mlir:mlir_graph_optimization_pass_registration", + ], + alwayslink = 1, +) + +cc_library( + name = "rearrange_function_argument", + srcs = [ + "rearrange_function_argument.cc", + ], + hdrs = [ + "rearrange_function_argument.h", + ], + deps = [ + ":tf2xla_util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla:status_macros", + ], +) + +cc_library( + name = "functionalize_control_flow_pass_registration", + srcs = [ + "functionalize_control_flow_pass_registration.cc", + ], + visibility = [":friends"], + deps = [ + ":functionalize_control_flow", + ], + alwayslink = 1, +) + +cc_library( + name = "functionalize_while", + srcs = [ + "functionalize_while.cc", + ], + hdrs = [ + "functionalize_while.h", + ], + deps = [ + ":frontend_attributes_util", + ":functionalize_cond", + ":functionalize_control_flow_util", + ":tf2xla_util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:graph", + "//tensorflow/core:lib", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + "@xla//xla:status_macros", + "@xla//xla:union_find", + ], +) + +tf_cc_test( + name = "functionalize_control_flow_test", + srcs = ["functionalize_control_flow_test.cc"], + deps = [ + ":functionalize_control_flow", + ":test_util", + ":tf2xla_util", + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:cc_ops_internal", + "//tensorflow/cc:function_ops", + "//tensorflow/cc:functional_ops", + "//tensorflow/cc:ops", + "//tensorflow/cc:resource_variable_ops", + "//tensorflow/compiler/tf2xla/cc:xla_ops", + "//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", + "@xla//xla:status_macros", + ], +) + +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/cc:scope", + "//tensorflow/compiler/tf2xla/cc:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:core_cpu_internal", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:ops", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:resource_variable_ops_op_lib", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "//tensorflow/core/platform:test", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/strings", + "@xla//xla:status_macros", + ], +) + +cc_library( + name = "test_util", + testonly = 1, + srcs = ["test_util.cc"], + hdrs = ["test_util.h"], + deps = [ + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@xla//xla:status_macros", + ], +) + +tf_cc_test( + name = "xla_op_registry_test", + srcs = ["xla_op_registry_test.cc"], + deps = [ + ":xla_compiler", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@com_google_absl//absl/log", + ], +) + +cc_library( + name = "resource_operation_table", + srcs = ["resource_operation_table.cc"], + hdrs = ["resource_operation_table.h"], + deps = [ + "//tensorflow/core:lib", + "//tensorflow/core:ops", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/strings", + ], +) + +tf_cc_test( + name = "resource_operation_table_test", + srcs = ["resource_operation_table_test.cc"], + deps = [ + ":resource_operation_table", + ":xla_compiler", + "//tensorflow/compiler/tf2xla/kernels:xla_ops", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/strings", + ], +) + +cc_library( + name = "side_effect_util", + srcs = ["side_effect_util.cc"], + hdrs = ["side_effect_util.h"], + visibility = [":friends"], + deps = [ + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla/tsl/platform:errors", + ], +) + +tf_cuda_cc_test( + name = "fused_batchnorm_reserve_space_test", + size = "medium", + srcs = ["fused_batchnorm_reserve_space_test.cc"], + tags = [ + "no_cuda_asan", # TODO(b/193450885) + ], + deps = [ + "//tensorflow/cc:cc_ops", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/compiler/jit", + "//tensorflow/compiler/jit:flags", + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:framework_internal", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:tensorflow", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/strings", + "@eigen_archive//:eigen3", + ], +) + +cc_library( + name = "mlir_xla_op_kernel", + srcs = ["mlir_xla_op_kernel.cc"], + hdrs = ["mlir_xla_op_kernel.h"], + deps = [ + ":xla_compiler", + ":xla_expression", + "//tensorflow/compiler/jit:xla_compile_util", + "//tensorflow/compiler/mlir/tf2xla/api/v1:compile_mlir_util_no_tf_dialect_passes", + "//tensorflow/compiler/mlir/utils:array_container_utils", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/framework:resource_base", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:refcount", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:IR", + "@tsl//tsl/platform:errors", + "@tsl//tsl/platform:statusor", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +cc_library( + name = "resource_util", + srcs = ["resource_util.cc"], + hdrs = ["resource_util.h"], + visibility = [":friends"], + deps = [ + ":resource_operation_table", + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:function_body", + "//tensorflow/core/common_runtime:function_utils", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/hash", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:status_macros", + ], +) + +tf_cuda_cc_test( + name = "resource_util_test", + size = "small", + srcs = ["resource_util_test.cc"], + deps = [ + ":resource_util", + "//tensorflow/cc:scope", + "//tensorflow/core:framework", + "//tensorflow/core:graph", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core:tensorflow", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + "//tensorflow/core:testlib", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/memory", + ], +) + +filegroup( + name = "tf2xla_opset_hdrs", + srcs = [ + "tf2xla_opset.h", + ], + visibility = ["//tensorflow/python/util:__pkg__"], +) + +cc_library( + name = "tf2xla_opset", + srcs = [ + "tf2xla_opset.cc", + ], + hdrs = ["tf2xla_opset.h"], + visibility = [ + "//tensorflow/python:__pkg__", + "//tensorflow/python/util:__pkg__", + ], + deps = [ + ":tf2xla_util", + ":xla_op_registry", + "//tensorflow/compiler/jit:xla_device", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + ], +) + +tf_cc_test( + name = "tf2xla_opset_test", + srcs = [ + "tf2xla_opset_test.cc", + ], + deps = [ + ":tf2xla_opset", + "//tensorflow/core:test", + "//tensorflow/core:test_main", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator.cc new file mode 100644 index 0000000000000000000000000000000000000000..1eb1ffdc9b2cd3a23920504949f2d5e0589e502a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator.cc @@ -0,0 +1,118 @@ +/* Copyright 2025 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/allocator.h" + +#include +#include +#include + +#include "absl/base/dynamic_annotations.h" +#include "absl/types/span.h" +#include "xla/backends/cpu/alignment.h" +#include "xla/backends/cpu/buffer_allocation_info.h" + +namespace tensorflow { + +namespace { +// Inline memory allocation routines here, because depending on 'base' brings +// in libraries which use c++ streams, which adds considerable code size on +// android. +void* aligned_malloc(size_t size, int minimum_alignment) { +#if defined(__ANDROID__) || defined(OS_ANDROID) || defined(OS_CYGWIN) + return memalign(minimum_alignment, size); +#elif defined(_WIN32) + return _aligned_malloc(size, minimum_alignment); +#else // !__ANDROID__ && !OS_ANDROID && !OS_CYGWIN + void* ptr = nullptr; + // posix_memalign requires that the requested alignment be at least + // sizeof(void*). In this case, fall back on malloc which should return memory + // aligned to at least the size of a pointer. + const int required_alignment = sizeof(void*); + if (minimum_alignment < required_alignment) { + return malloc(size); + } + if (posix_memalign(&ptr, minimum_alignment, size) != 0) { + return nullptr; + } + return ptr; +#endif +} + +void aligned_free(void* aligned_memory) { +#if defined(_WIN32) + _aligned_free(aligned_memory); +#else + free(aligned_memory); +#endif +} + +size_t align_to(size_t n, size_t align) { + return (((n - 1) / align) + 1) * align; +} +} // namespace + +size_t AlignedBufferBytes( + absl::Span buffers, + bool allocate_entry_params) { + size_t total = 0; + for (size_t i = 0; i < buffers.size(); ++i) { + bool should_allocate = + buffers[i].is_temp() || buffers[i].is_result() || + (buffers[i].is_entry_parameter() && allocate_entry_params); + + if (should_allocate) { + total += align_to(buffers[i].size(), xla::cpu::Align()); + } + } + return total; +} + +void* MallocContiguousBuffers( + absl::Span buffers, + bool allocate_entry_params, void** bufs, bool annotate_initialized) { + const size_t total = + tensorflow::AlignedBufferBytes(buffers, allocate_entry_params); + void* contiguous = nullptr; + if (total > 0) { + contiguous = aligned_malloc(total, xla::cpu::Align()); + if (annotate_initialized) { + // Since the memory for temp buffers is written to by JITed code, msan has + // no way of knowing the memory was initialized, so explicitly mark it. + ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(contiguous, total); + } + } + uintptr_t pos = reinterpret_cast(contiguous); + for (size_t i = 0; i < buffers.size(); ++i) { + bool should_allocate = + buffers[i].is_temp() || buffers[i].is_result() || + (buffers[i].is_entry_parameter() && allocate_entry_params); + if (should_allocate) { + bufs[i] = reinterpret_cast(pos); + pos += align_to(buffers[i].size(), xla::cpu::Align()); + } else { + bufs[i] = nullptr; + } + } + return contiguous; +} + +void FreeContiguous(void* contiguous) { + if (contiguous != nullptr) { + aligned_free(contiguous); + } +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator.h new file mode 100644 index 0000000000000000000000000000000000000000..398089da099b615e3e8184f318edeac55ee81a29 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator.h @@ -0,0 +1,56 @@ +/* Copyright 2025 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_ALLOCATOR_H_ +#define TENSORFLOW_COMPILER_TF2XLA_ALLOCATOR_H_ + +#include + +#include "absl/types/span.h" +#include "xla/backends/cpu/buffer_allocation_info.h" + +namespace tensorflow { + +// 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 Align() byte boundaries. +size_t AlignedBufferBytes( + absl::Span buffers, + bool allocate_entry_params); + +// MallocContiguousBuffers allocates buffers for use by the entry point +// 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( + absl::Span buffers, + bool allocate_entry_params, void** bufs, bool annotate_initialized); + +// FreeContiguous frees the contiguous block of memory allocated by +// MallocContiguousBuffers. +void FreeContiguous(void* contiguous); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_ALLOCATOR_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..6eb6e568b4351db31e6fa3e36340642b486b779f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/allocator_test.cc @@ -0,0 +1,165 @@ +/* Copyright 2025 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/allocator.h" + +#include +#include +#include +#include +#include + +#include "xla/backends/cpu/alignment.h" +#include "xla/backends/cpu/buffer_allocation_info.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { + +using ::xla::cpu::BufferAllocationInfo; + +TEST(AllocatorTest, 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. + // The tfcompile runtime also has a requirement that comes from the xla + // generated code, on the relation: buffer_size >= 16 ? 2 * sizeof(void*) : 8 + // So any value that we choose must abide by that constraint as well. + EXPECT_EQ(xla::cpu::Align(), Allocator::kAllocatorAlignment); + EXPECT_LE(xla::cpu::MinAlign(), Allocator::kAllocatorAlignment); +} + +std::vector SizesToBufferAllocationInfos( + const intptr_t* sizes, size_t n) { + std::vector 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 indicate the + // the current slot does not need an allocation. + int64_t on_stack_buffer_size = 4; + return BufferAllocationInfo::ThreadLocal(on_stack_buffer_size); + } + return BufferAllocationInfo::Temp(size); + }); + return buffer_infos; +} + +// Simple wrappers to make writing tests more ergonomic. + +size_t AlignedBufferBytesFromSizes(const intptr_t* sizes, size_t n) { + std::vector buffer_infos = + SizesToBufferAllocationInfos(sizes, n); + return tensorflow::AlignedBufferBytes(buffer_infos, + /*allocate_entry_params=*/false); +} + +void* MallocContiguousBuffersFromSizes(const intptr_t* sizes, size_t n, + void** bufs, bool annotate_initialized) { + std::vector buffer_infos = + SizesToBufferAllocationInfos(sizes, n); + return tensorflow::MallocContiguousBuffers(buffer_infos, + /*allocate_entry_params=*/false, + bufs, annotate_initialized); +} + +TEST(AllocatorTest, AlignedBufferBytes) { + EXPECT_EQ(AlignedBufferBytesFromSizes(nullptr, 0), 0); + + static constexpr intptr_t sizesA[1] = {-1}; + EXPECT_EQ(AlignedBufferBytesFromSizes(sizesA, 1), 0); + + static constexpr intptr_t sizesB[1] = {3}; + EXPECT_EQ(AlignedBufferBytesFromSizes(sizesB, 1), 64); + + static constexpr intptr_t sizesC[1] = {32}; + EXPECT_EQ(AlignedBufferBytesFromSizes(sizesC, 1), 64); + + static constexpr intptr_t sizesD[7] = {1, -1, 32, -1, 64, 2, 3}; + EXPECT_EQ(AlignedBufferBytesFromSizes(sizesD, 7), 320); +} + +void* add_ptr(void* base, uintptr_t delta) { + return reinterpret_cast(reinterpret_cast(base) + delta); +} + +// To test MallocContiguousBuffers and FreeContiguous, we just check for +// expected nullptrs, and write to each byte of allocated memory. We rely on +// the leak checker to tell us if there's an inconsistency between malloc and +// free. We also check the contiguous property. +TEST(AllocatorTest, MallocFreeContiguousBuffers) { + // Test empty sizes. + void* base = MallocContiguousBuffersFromSizes(nullptr, 0, nullptr, false); + EXPECT_EQ(base, nullptr); + FreeContiguous(base); + + // Test non-empty sizes with 0 sum. + static constexpr intptr_t sizesA[1] = {-1}; + void* bufA[1]; + base = MallocContiguousBuffersFromSizes(sizesA, 1, bufA, false); + EXPECT_EQ(base, nullptr); + EXPECT_EQ(bufA[0], nullptr); + FreeContiguous(base); + + // Test non-empty sizes with non-0 sum. + static constexpr intptr_t sizesB[1] = {3}; + void* bufB[1]; + base = MallocContiguousBuffersFromSizes(sizesB, 1, bufB, false); + EXPECT_NE(base, nullptr); + EXPECT_EQ(bufB[0], add_ptr(base, 0)); + char* bufB0_bytes = static_cast(bufB[0]); + bufB0_bytes[0] = 'A'; + bufB0_bytes[1] = 'B'; + bufB0_bytes[2] = 'C'; + FreeContiguous(base); + + // Test non-empty sizes with non-0 sum, and annotate_initialized. + static constexpr intptr_t sizesC[1] = {3}; + void* bufC[1]; + base = MallocContiguousBuffersFromSizes(sizesC, 1, bufC, true); + EXPECT_NE(base, nullptr); + EXPECT_EQ(bufC[0], add_ptr(base, 0)); + char* bufC0_bytes = static_cast(bufC[0]); + bufC0_bytes[0] = 'A'; + bufC0_bytes[1] = 'B'; + bufC0_bytes[2] = 'C'; + FreeContiguous(base); + + // Test mixed sizes. + static constexpr intptr_t sizesD[7] = {1, -1, 32, -1, 64, 2, 3}; + void* bufD[7]; + base = MallocContiguousBuffersFromSizes(sizesD, 7, bufD, false); + EXPECT_NE(base, nullptr); + EXPECT_EQ(bufD[0], add_ptr(base, 0)); + EXPECT_EQ(bufD[1], nullptr); + EXPECT_EQ(bufD[2], add_ptr(base, 64)); + EXPECT_EQ(bufD[3], nullptr); + EXPECT_EQ(bufD[4], add_ptr(base, 128)); + EXPECT_EQ(bufD[5], add_ptr(base, 192)); + EXPECT_EQ(bufD[6], add_ptr(base, 256)); + for (int i = 0; i < 7; ++i) { + const intptr_t size = sizesD[i]; + if (size != -1) { + char* bufD_bytes = static_cast(bufD[i]); + for (size_t j = 0; j < size; ++j) { + bufD_bytes[j] = 'A' + j; + } + } + } + FreeContiguous(base); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/cc/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/cc/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..4f66dc4a33dc99e80869624e82e5b585c6559283 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/cc/BUILD @@ -0,0 +1,53 @@ +load("//tensorflow:tensorflow.default.bzl", "tf_gen_op_wrapper_cc") +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//tensorflow/compiler/tf2xla:friends"], + licenses = ["notice"], +) + +tf_gen_op_wrapper_cc( + name = "xla_ops_gen", + out_ops_file = "ops/xla_ops", + deps = ["//tensorflow/compiler/tf2xla/ops:xla_ops"], +) + +cc_library( + name = "xla_ops", + srcs = ["ops/xla_ops.cc"], + hdrs = ["ops/xla_ops.h"], + deps = [ + "//tensorflow/cc:const_op", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + ], +) + +tf_gen_op_wrapper_cc( + name = "xla_jit_op_gen", + include_internal_ops = 1, + out_ops_file = "ops/xla_jit_ops", + deps = ["//tensorflow/compiler/jit/ops:xla_ops"], +) + +cc_library( + name = "xla_jit_ops", + srcs = ["ops/xla_jit_ops.cc"], + hdrs = ["ops/xla_jit_ops.h"], + deps = [ + "//tensorflow/cc:const_op", + "//tensorflow/cc:ops", + "//tensorflow/cc:scope", + "//tensorflow/compiler/jit/ops:xla_ops", + "//tensorflow/core:core_cpu", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis.cc new file mode 100644 index 0000000000000000000000000000000000000000..8f941cde691624f8fe14cb5fad7b055dc28b198e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis.cc @@ -0,0 +1,308 @@ +/* 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/const_analysis.h" + +#include +#include + +#include "absl/algorithm/container.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/status_macros.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +namespace { + +absl::Status GetFunctionBody(FunctionLibraryRuntime* flib_runtime, + const NodeDef& node, + absl::string_view func_attr_name, + const FunctionBody** fbody) { + NameAttrList name_attr_list; + TF_RETURN_IF_ERROR(GetNodeAttr(node, func_attr_name, &name_attr_list)); + FunctionLibraryRuntime::Handle func_handle; + TF_RETURN_IF_ERROR(flib_runtime->Instantiate( + name_attr_list.name(), AttrSlice(&name_attr_list.attr()), &func_handle)); + *fbody = flib_runtime->GetFunctionBody(func_handle); + return absl::OkStatus(); +} + +absl::Status GetFunctionBodies(FunctionLibraryRuntime* flib_runtime, + const NodeDef& node, + absl::string_view func_list_attr_name, + std::vector* fbodies) { + std::vector name_attr_lists; + TF_RETURN_IF_ERROR(GetNodeAttr(node, func_list_attr_name, &name_attr_lists)); + for (const NameAttrList& name_attr_list : name_attr_lists) { + FunctionLibraryRuntime::Handle func_handle; + TF_RETURN_IF_ERROR(flib_runtime->Instantiate( + name_attr_list.name(), AttrSlice(&name_attr_list.attr()), + &func_handle)); + fbodies->push_back(flib_runtime->GetFunctionBody(func_handle)); + } + return absl::OkStatus(); +} + +absl::Status CondConstInputIndices( + absl::Span branch_bodies, + std::vector* const_input_idxs, FunctionLibraryRuntime* flib_runtime) { + TF_RET_CHECK(!branch_bodies.empty()); + TF_RET_CHECK(branch_bodies[0] != nullptr); + int num_inputs = + branch_bodies[0]->record->fdef().signature().input_arg_size(); + // Stores indices of the "branch function" inputs that are expected to be + // compile time constants. + std::vector compile_time_const_arg_indices(num_inputs); + for (auto fbody : branch_bodies) { + TF_RET_CHECK(fbody != nullptr); + TF_RETURN_IF_ERROR(BackwardsConstAnalysis( + *(fbody->graph), &compile_time_const_arg_indices, + /*compile_time_const_nodes=*/nullptr, flib_runtime)); + } + for (int i = 0, end = compile_time_const_arg_indices.size(); i < end; i++) { + if (compile_time_const_arg_indices[i]) { + // The 0th input is the pred or branch index, which is not passed to the + // branches. So the i'th input of a branch function corresponds to the + // i + 1'th input of the If/Case op. + const_input_idxs->push_back(i + 1); + } + } + return absl::OkStatus(); +} + +absl::Status GetCompileTimeConstInputs(const NodeDef& node, + const OpKernel* op_kernel, + const OpDef* op_def, + std::vector* const_input_idxs, + FunctionLibraryRuntime* flib_runtime) { + DCHECK(op_def != nullptr || op_kernel != nullptr); + if (node.op() == "While" || node.op() == "StatelessWhile") { + // For While nodes, recurse into the body and cond graphs. + const FunctionBody* fcond = nullptr; + const FunctionBody* fbody = nullptr; + TF_RETURN_IF_ERROR(GetFunctionBody(flib_runtime, node, "cond", &fcond)); + TF_RETURN_IF_ERROR(GetFunctionBody(flib_runtime, node, "body", &fbody)); + TF_RET_CHECK(fcond); + TF_RET_CHECK(fbody); + int num_inputs = fbody->record->fdef().signature().input_arg_size(); + + // Stores which of the loop inputs are expected to be compile time + // constants. + std::vector compile_time_const_arg_indices(num_inputs); + TF_RETURN_IF_ERROR(BackwardsConstAnalysis( + *(fcond->graph), &compile_time_const_arg_indices, + /*compile_time_const_nodes=*/nullptr, flib_runtime)); + TF_RETURN_IF_ERROR(BackwardsConstAnalysis( + *(fbody->graph), &compile_time_const_arg_indices, + /*compile_time_const_nodes=*/nullptr, flib_runtime)); + for (int i = 0; i < num_inputs; i++) { + if (compile_time_const_arg_indices[i]) { + // Check that this input is actually a loop invariant. + TF_ASSIGN_OR_RETURN( + bool is_loop_invariant, + IsLoopInvariant(fbody, i, + flib_runtime->GetFunctionLibraryDefinition())); + if (is_loop_invariant) { + const_input_idxs->push_back(i); + } else { + // TODO(b/178546817): Verify that it's OK and raise an error if we are + // using this branch from jit_compile=True. + Node* arg_i = fbody->arg_nodes[i]; + Node* ret_i = fbody->ret_nodes[i]; + VLOG(1) << "Argument " << i << " to while-loop " << node.name() + << " has to be constant, but it's not a loop invariant, " + "cluster compilation likely to fail at compile time: " + << arg_i->DebugString() << " vs. " << ret_i->DebugString(); + VLOG(1) << node.ShortDebugString(); + } + } + } + return absl::OkStatus(); + } else if (node.op() == "If" || node.op() == "StatelessIf") { + const FunctionBody* fthen = nullptr; + const FunctionBody* felse = nullptr; + TF_RETURN_IF_ERROR( + GetFunctionBody(flib_runtime, node, "then_branch", &fthen)); + TF_RETURN_IF_ERROR( + GetFunctionBody(flib_runtime, node, "else_branch", &felse)); + return CondConstInputIndices({fthen, felse}, const_input_idxs, + flib_runtime); + } else if (node.op() == "Case" || node.op() == "StatelessCase") { + std::vector branch_bodies; + TF_RETURN_IF_ERROR( + GetFunctionBodies(flib_runtime, node, "branches", &branch_bodies)); + return CondConstInputIndices(branch_bodies, const_input_idxs, flib_runtime); + } else if (node.op() == "PartitionedCall" || + node.op() == "StatefulPartitionedCall") { + const FunctionBody* fbody; + TF_RETURN_IF_ERROR(GetFunctionBody(flib_runtime, node, "f", &fbody)); + int num_inputs = fbody->record->fdef().signature().input_arg_size(); + std::vector compile_time_const_arg_indices(num_inputs); + TF_RETURN_IF_ERROR(BackwardsConstAnalysis( + *(fbody->graph), &compile_time_const_arg_indices, + /*compile_time_const_nodes=*/nullptr, flib_runtime)); + for (int i = 0; i < num_inputs; i++) { + if (compile_time_const_arg_indices[i]) { + const_input_idxs->push_back(i); + } + } + return absl::OkStatus(); + } else if (op_def != nullptr) { + return XlaOpRegistry::CompileTimeConstantInputs(node, *op_def, + const_input_idxs); + } else { + return XlaOpRegistry::CompileTimeConstantInputs(*op_kernel, + const_input_idxs); + } +} + +absl::Status GetCompileTimeConstInputs(const Node* node, + std::vector* const_input_idxs, + FunctionLibraryRuntime* flib_runtime) { + return GetCompileTimeConstInputs(node->def(), /*op_kernel=*/nullptr, + &node->op_def(), const_input_idxs, + flib_runtime); +} + +} // namespace + +// Backwards dataflow analysis that finds arguments to a graph that must be +// compile-time constants. +absl::Status BackwardsConstAnalysis( + const Graph& g, std::vector* compile_time_const_arg_indices, + std::vector* compile_time_const_nodes, + FunctionLibraryRuntime* flib_runtime, + std::function edge_filter_input) { + if (!compile_time_const_nodes && g.GetConstArgIndicesCache().has_value() && + !edge_filter_input) { + VLOG(5) << "Using cached argument indices on graph " << &g; + *compile_time_const_arg_indices = g.GetConstArgIndicesCache().value(); + return absl::OkStatus(); + } + auto edge_filter = [&](const Edge& e) { + return edge_filter_input ? edge_filter_input(e) : true; + }; + + std::vector compile_time_const_nodes_impl; + if (compile_time_const_nodes) { + CHECK_EQ(compile_time_const_nodes->size(), g.num_node_ids()); + } else { + compile_time_const_nodes_impl.resize(g.num_node_ids()); + compile_time_const_nodes = &compile_time_const_nodes_impl; + } + + absl::Status status; + auto visit = [&](Node* node) { + if (!status.ok()) return; + + // If this is a metadata-only op, don't propagate the const requirement. + if (XlaOpRegistry::IsMetadataOp(node->type_string())) { + VLOG(3) << "must-be-const node is metadata op: " << node->name(); + return; + } + + // If this node must be const, and it isn't a metadata op, then all of its + // parents must be const. + if ((*compile_time_const_nodes)[node->id()]) { + VLOG(3) << "marking consts for must-be-const node " << node->name(); + if (node->type_string() == "_Arg") { + int index; + status = GetNodeAttr(node->attrs(), "index", &index); + if (!status.ok()) return; + if (compile_time_const_arg_indices) { + (*compile_time_const_arg_indices)[index] = true; + } + VLOG(3) << " const _Arg " << index << ": " << node->name(); + return; + } + for (const Edge* pred : node->in_edges()) { + if (!pred->IsControlEdge() && edge_filter(*pred)) { + // If the src node of the `pred` is an IdentityN/While do not mark it + // as a compile-time const. Only mark the corresponding input to the + // IdentityN/While node as a const. XLA IdentityN op simply forwards + // its inputs so this is safe; loop-invariance is checked elsewhere. + while (edge_filter(*pred) && IsConstTraversableOpType(pred->src())) { + status = pred->src()->input_edge(pred->src_output(), &pred); + if (!status.ok()) return; + } + if (edge_filter(*pred)) { + VLOG(4) << " " << pred->src()->name() << " must be const (is " + << pred->src()->type_string() << ")"; + (*compile_time_const_nodes)[pred->src()->id()] = true; + } + } + } + return; + } + + // Mark any compile-time constant operator arguments as const. + std::vector const_input_idxs; + status = GetCompileTimeConstInputs(node, &const_input_idxs, flib_runtime); + + if (!status.ok() || const_input_idxs.empty()) { + return; + } + + VLOG(3) << "marking consts for must-be-const inputs of " << node->name(); + for (Edge const* edge : node->in_edges()) { + if (!edge->IsControlEdge() && + absl::c_binary_search(const_input_idxs, edge->dst_input()) && + edge_filter(*edge)) { + // Do not mark IdentityN / While nodes as compile-time const. + // If the src node of the `pred` is an IdentityN do not mark it as a + // compile-time const. Only mark the corresponding input to the + // IdentityN/While node as a const. XLA IdentityN op simply forwards its + // inputs so this is safe; loop invariance is checked elsewhere. + while (edge_filter(*edge) && IsConstTraversableOpType(edge->src())) { + status = edge->src()->input_edge(edge->src_output(), &edge); + if (!status.ok()) return; + } + if (edge_filter(*edge)) { + VLOG(4) << " input " << edge->dst_input() << ": " + << edge->src()->name() << " must be const (is " + << edge->src()->type_string() << ")"; + (*compile_time_const_nodes)[edge->src()->id()] = true; + } + } + } + }; + + // Post-order traversal visits nodes in reverse topological order for an + // acyclic graph. + DFS(g, /*enter=*/{}, /*leave=*/visit, NodeComparatorName{}, + [](const Edge& edge) { return !edge.src()->IsNextIteration(); }); + if (compile_time_const_arg_indices && !edge_filter_input) { + VLOG(5) << "Setting the cache on the graph: " << &g; + g.GetConstArgIndicesCache() = *compile_time_const_arg_indices; + } + return status; +} + +absl::Status GetCompileTimeConstInputs(const OpKernel* op_kernel, + std::vector* const_input_idxs, + FunctionLibraryRuntime* flib_runtime) { + return GetCompileTimeConstInputs(op_kernel->def(), op_kernel, + /*op_def=*/nullptr, const_input_idxs, + flib_runtime); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..c762f9f0bdada926efb02387b566dae7074be37a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis.h @@ -0,0 +1,51 @@ +/* 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_CONST_ANALYSIS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_CONST_ANALYSIS_H_ + +#include + +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Backwards dataflow analysis that finds nodes in a graph that must be +// compile-time constants for us to be able to lower the graph to XLA. +// +// The indices of the arguments to `graph` that must be constant are returned in +// `compile_time_const_arg_indices`, if `compile_time_const_arg_indices` is not +// null. +// +// The ids of the nodes in `graph` that must be constant are returned in +// `compile_time_const_nodes`, if `compile_time_const_nodes` is not null. +// +// If `edge_filter` is non-null, only propagate const-ness along edges for which +// `edge_filter` returns true. +absl::Status BackwardsConstAnalysis( + const Graph& g, std::vector* compile_time_const_arg_indices, + std::vector* compile_time_const_nodes, + FunctionLibraryRuntime* flib_runtime, + std::function edge_filter_input = nullptr); + +// Given an op kernel and function library runtime, return all the indices of +// inputs that need to be compile time constant. +absl::Status GetCompileTimeConstInputs(const OpKernel* op_kernel, + std::vector* const_input_idxs, + FunctionLibraryRuntime* flib_runtime); +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_CONST_ANALYSIS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a32d6f99d5a4cdf8c849641b489f57da15f18907 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/const_analysis_test.cc @@ -0,0 +1,227 @@ +/* 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 the backward const analysis. + +#include "tensorflow/compiler/tf2xla/const_analysis.h" + +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/ops/function_ops.h" +#include "tensorflow/cc/ops/functional_ops.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/compiler/jit/xla_cluster_util.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { +namespace { + +TEST(ConstAnalysisTest, Basics) { + Scope root = Scope::NewRootScope(); + + auto arg0 = ops::_Arg(root.WithOpName("Arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(root.WithOpName("Arg1"), DT_INT32, 1); + auto arg2 = ops::_Arg(root.WithOpName("Arg2"), DT_INT32, 2); + auto arg3 = ops::_Arg(root.WithOpName("Arg3"), DT_INT32, 3); + auto a = ops::Shape(root, arg0); + auto b = ops::Add(root, a, arg1); + auto c = ops::Reshape(root, arg2, b); + auto d = ops::Mul(root, c, ops::Sum(root, arg3, arg3)); + + FixupSourceAndSinkEdges(root.graph()); + + std::vector const_args(4, false); + std::vector const_nodes(root.graph()->num_node_ids(), false); + TF_ASSERT_OK(BackwardsConstAnalysis(*root.graph(), &const_args, &const_nodes, + /*flib_runtime=*/nullptr)); + + // Arg 0 doesn't need to be constant since the graph only uses its shape. + // Arg 1 must be constant because it flows to the shape argument of a Reshape. + // Arg 2 is used only as the value input to a Reshape and need not be const. + // Arg 3 is used as the reduction-indices argument to Sum and must be const. + EXPECT_EQ(const_args, std::vector({false, true, false, true})); + + EXPECT_FALSE(const_nodes[arg0.node()->id()]); + EXPECT_TRUE(const_nodes[arg1.node()->id()]); + EXPECT_FALSE(const_nodes[arg2.node()->id()]); + EXPECT_TRUE(const_nodes[arg3.node()->id()]); +} + +// Regression test for a case where the backward const analysis did +// not visit nodes in topological order. +TEST(ConstAnalysisTest, TopologicalOrder) { + for (bool order : {false, true}) { + Scope root = Scope::NewRootScope(); + + auto arg0 = ops::_Arg(root.WithOpName("Arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(root.WithOpName("Arg1"), DT_INT32, 1); + auto arg2 = ops::_Arg(root.WithOpName("Arg2"), DT_INT32, 2); + auto a = ops::Reshape(root, arg0, arg1); + auto b = ops::Reshape(root, arg2, a); + if (order) { + // Consider both orders for arguments to the Sum so we aren't sensitive + // to the DFS traversal order. + std::swap(a, b); + } + auto c = ops::Add(root, a, b); + + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(root.ToGraph(&graph)); + + std::vector const_args(3, false); + TF_ASSERT_OK(BackwardsConstAnalysis(graph, &const_args, + /*compile_time_const_nodes=*/nullptr, + /*flib_runtime=*/nullptr)); + + EXPECT_EQ(const_args, std::vector({true, true, false})); + } +} + +void TestFunctionCall(bool is_stateful_partitioned_call) { + FunctionDef callee = FunctionDefHelper::Define( + "Callee", {"t:float", "shape:int32"}, {"result:float"}, {}, + {{{"result"}, "Reshape", {"t", "shape"}, {{"T", DT_FLOAT}}}}); + + FunctionDefLibrary flib; + *flib.add_function() = callee; + FunctionLibraryDefinition flib_def(OpRegistry::Global(), flib); + + Scope root = Scope::NewRootScope().ExitOnError(); + + auto arg0 = ops::_Arg(root.WithOpName("tensor"), DT_FLOAT, 0); + auto arg1 = ops::_Arg(root.WithOpName("shape"), DT_INT32, 1); + + NameAttrList call_attrs; + call_attrs.set_name("Callee"); + if (is_stateful_partitioned_call) { + ops::StatefulPartitionedCall b(root.WithOpName("Call"), + {Output(arg0), Output(arg1)}, {DT_FLOAT}, + call_attrs); + } else { + ops::PartitionedCall b(root.WithOpName("Call"), + {Output(arg0), Output(arg1)}, {DT_FLOAT}, + call_attrs); + } + + Graph graph(&flib_def); + TF_ASSERT_OK(root.ToGraph(&graph)); + + OptimizerOptions opts; + std::unique_ptr pflr( + new ProcessFunctionLibraryRuntime(nullptr, Env::Default(), + /*config=*/nullptr, + TF_GRAPH_DEF_VERSION, &flib_def, opts)); + FunctionLibraryRuntime* lib_runtime = + pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); + + std::vector const_args(2, false); + TF_ASSERT_OK(BackwardsConstAnalysis(graph, &const_args, + /*compile_time_const_nodes=*/nullptr, + lib_runtime)); + + EXPECT_EQ(const_args, std::vector({false, true})); +} + +TEST(ConstAnalysisTest, PartitionedCall) { + TestFunctionCall(/*is_stateful_partitioned_call=*/false); +} + +TEST(ConstAnalysisTest, StatefulPartitionedCall) { + TestFunctionCall(/*is_stateful_partitioned_call=*/true); +} + +TEST(ConstAnalysisTest, DontFollowControlDependencies) { + Scope root = Scope::NewRootScope(); + + Output arg0 = ops::_Arg(root.WithOpName("Arg0"), DT_INT32, 0); + Output arg1 = ops::_Arg(root.WithOpName("Arg1"), DT_INT32, 1); + Output c1 = + ops::Const(root.WithOpName("c1").WithControlDependencies(arg0), 1, {1}); + Output add = ops::Add(root, arg1, c1); + Output reshape = ops::Reshape(root, arg1, add); + + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(root.ToGraph(&graph)); + + std::vector const_args(2, false); + TF_ASSERT_OK(BackwardsConstAnalysis(graph, &const_args, + /*compile_time_const_nodes=*/nullptr, + /*flib_runtime=*/nullptr)); + + EXPECT_EQ(const_args, std::vector({false, true})); +} + +TEST(ConstAnalysisTest, RespectExplicitAttr_0) { + Scope root = Scope::NewRootScope(); + + Output arg0 = ops::_Arg(root.WithOpName("Arg0"), DT_INT32, 0); + Output arg1 = ops::_Arg(root.WithOpName("Arg1"), DT_INT32, 1); + Output c1 = + ops::Const(root.WithOpName("c1").WithControlDependencies(arg0), 1, {1}); + Output add = ops::Add(root, arg1, c1); + + // Force const analysis to pretend that the shape argument to `reshape` does + // not need to be a constant. + Output reshape = ops::Reshape(root, arg1, add); + reshape.node()->AddAttr(kXlaCompileTimeConstantInputsAttr, + std::vector()); + + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(root.ToGraph(&graph)); + + std::vector const_args(2, false); + TF_ASSERT_OK(BackwardsConstAnalysis(graph, &const_args, + /*compile_time_const_nodes=*/nullptr, + /*flib_runtime=*/nullptr)); + + EXPECT_EQ(const_args, std::vector({false, false})); +} + +TEST(ConstAnalysisTest, RespectExplicitAttr_1) { + Scope root = Scope::NewRootScope(); + + Output arg0 = ops::_Arg(root.WithOpName("Arg0"), DT_INT32, 0); + Output c1 = + ops::Const(root.WithOpName("c1").WithControlDependencies(arg0), 1, {1}); + Output add = ops::Add(root, arg0, c1); + + // Force const analysis to pretend that the first argument to `add` needs to + // be a constant. + std::vector add_constant_inputs; + add_constant_inputs.push_back("x"); + add.node()->AddAttr(kXlaCompileTimeConstantInputsAttr, add_constant_inputs); + + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(root.ToGraph(&graph)); + + std::vector const_args(1, false); + TF_ASSERT_OK(BackwardsConstAnalysis(graph, &const_args, + /*compile_time_const_nodes=*/nullptr, + /*flib_runtime=*/nullptr)); + + EXPECT_EQ(const_args, std::vector({true})); +} + +static bool Initialized = [] { + tensorflow::GetXlaDeviceFlags()->tf_xla_enable_xla_devices = true; + return true; +}(); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/encoded_buffer_allocation_info.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/encoded_buffer_allocation_info.h new file mode 100644 index 0000000000000000000000000000000000000000..4e6da8a3d2dcf6179d9431ab41ccfb19d8d5cdfe --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/encoded_buffer_allocation_info.h @@ -0,0 +1,99 @@ +/* Copyright 2025 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_ENCODED_BUFFER_ALLOCATION_INFO_H_ +#define TENSORFLOW_COMPILER_TF2XLA_ENCODED_BUFFER_ALLOCATION_INFO_H_ + +#include + +#include "xla/backends/cpu/buffer_allocation_info.h" + +namespace xla { +namespace cpu { + +// Encoded version of `BufferAllocationInfo`, which can be used to reconstruct +// the `BufferAllocationInfo` later. It's used in the AOT compiler, to +// represent buffer allocation info as a lightweight struct. +struct EncodedBufferAllocationInfo { + EncodedBufferAllocationInfo(uint64_t packed_kind_and_size, + uint32_t entry_param_number, + uint32_t result_number) + : packed_kind_and_size(packed_kind_and_size), + entry_param_number(entry_param_number), + result_number(result_number) {} + + // Encodes BufferAllocationInfo into the struct that can be used to + // reconstruct the BufferAllocationInfo later using the constructor. We need + // this because we use BufferAllocationInfo in places where using protocol + // buffers would negatively impact binary size. + explicit EncodedBufferAllocationInfo( + const BufferAllocationInfo& buffer_info) { + packed_kind_and_size = Pack(buffer_info.kind(), buffer_info.size()); + entry_param_number = buffer_info.is_entry_parameter() + ? buffer_info.entry_parameter_number() + : -1; + result_number = buffer_info.is_result() ? buffer_info.result_number() : -1; + } + + explicit operator BufferAllocationInfo() const { + auto kind = UnpackKind(packed_kind_and_size); + auto size = UnpackSize(packed_kind_and_size); + int32_t entry_param_number = static_cast(this->entry_param_number); + int32_t result_number = static_cast(this->result_number); + + switch (kind) { + case BufferAllocationInfo::Kind::kConstant: + return BufferAllocationInfo::Constant(size); + case BufferAllocationInfo::Kind::kTemp: + return BufferAllocationInfo::Temp(size); + case BufferAllocationInfo::Kind::kParameter: + if (entry_param_number >= 0 && result_number >= 0) { + return BufferAllocationInfo::InOutParameter(size, entry_param_number, + result_number); + } + if (entry_param_number >= 0) { + return BufferAllocationInfo::EntryParameter(size, entry_param_number); + } + return BufferAllocationInfo::Result(size, result_number); + case BufferAllocationInfo::Kind::kThreadLocal: + return BufferAllocationInfo::ThreadLocal(size); + } + } + + static uint64_t Pack(BufferAllocationInfo::Kind kind, uint64_t size) { + return (static_cast(size) << 2) | static_cast(kind); + } + + static constexpr BufferAllocationInfo::Kind UnpackKind(uint64_t packed) { + return static_cast((packed << 62) >> 62); + } + + static constexpr uint64_t UnpackSize(uint64_t packed) { return packed >> 2; } + + uint64_t packed_kind_and_size = 0; + uint32_t entry_param_number = -1; + uint32_t result_number = -1; +}; +} // namespace cpu + +// TODO(ezhulenev): This is a temporary hack to keep `tfcompile` code working. +namespace cpu_function_runtime { +using BufferInfo = ::xla::cpu::BufferAllocationInfo; +using EncodedBufferInfo = ::xla::cpu::EncodedBufferAllocationInfo; +} // namespace cpu_function_runtime + +} // namespace xla + +#endif // TENSORFLOW_COMPILER_TF2XLA_ENCODED_BUFFER_ALLOCATION_INFO_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/encoded_buffer_allocation_info_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/encoded_buffer_allocation_info_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..7307fd51274a83d617ae01128691a42895480df0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/encoded_buffer_allocation_info_test.cc @@ -0,0 +1,42 @@ +/* Copyright 2025 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/encoded_buffer_allocation_info.h" + +#include +#include "xla/backends/cpu/buffer_allocation_info.h" + +namespace xla::cpu { +namespace { + +TEST(EncodedBufferAllocationInfoTest, RoundTrip) { + auto round_trip = [](const BufferAllocationInfo& buffer_info) { + EncodedBufferAllocationInfo encoded(buffer_info); + BufferAllocationInfo round_trip(encoded); + ASSERT_EQ(round_trip, buffer_info); + }; + + round_trip(BufferAllocationInfo::Temp(0)); + round_trip(BufferAllocationInfo::Temp(4)); + round_trip(BufferAllocationInfo::ThreadLocal(0)); + round_trip(BufferAllocationInfo::ThreadLocal(4)); + round_trip(BufferAllocationInfo::Constant(0)); + round_trip(BufferAllocationInfo::Constant(4)); + round_trip(BufferAllocationInfo::EntryParameter(0, 4)); + round_trip(BufferAllocationInfo::EntryParameter(4, 0)); +} + +} // namespace +} // namespace xla::cpu diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/frontend_attributes_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/frontend_attributes_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..f5e23c31f1d1bb7e8ddef3f145c04d51e6299469 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/frontend_attributes_util.cc @@ -0,0 +1,39 @@ +/* Copyright 2019 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/frontend_attributes_util.h" + +#include "tensorflow/compiler/tf2xla/tf2xla_defs.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +absl::StatusOr> +GetFrontendAttributesFromAttrSlice(const AttrSlice& attrs) { + const AttrValue* attr = attrs.Find(kXlaFrontendAttributesAttrName); + if (attr == nullptr) { + return absl::StatusOr>(std::nullopt); + } + xla::FrontendAttributes attributes; + if (!attributes.ParseFromString(attr->s())) { + return absl::InvalidArgumentError( + "Experimental _XlaFrontendAttributes attribute was not a valid encoded " + "xla::FrontendAttributes proto."); + } + return std::optional(attributes); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/frontend_attributes_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/frontend_attributes_util.h new file mode 100644 index 0000000000000000000000000000000000000000..8b36c72f09735bc2cf64ae8cf9d1b03faa1fbc85 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/frontend_attributes_util.h @@ -0,0 +1,36 @@ +/* Copyright 2019 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_FRONTEND_ATTRIBUTES_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_FRONTEND_ATTRIBUTES_UTIL_H_ + +#include + +#include "absl/types/optional.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Return the FrontendAttributes stored in the AttrSlice if there are some. +// +// Return an InvalidArgument error if some attributes are present but +// cannot be parsed. +absl::StatusOr> +GetFrontendAttributesFromAttrSlice(const AttrSlice& attrs); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_FRONTEND_ATTRIBUTES_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond.cc new file mode 100644 index 0000000000000000000000000000000000000000..b2ed31e36d749de60f4a19efb968fcb34374dc2b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond.cc @@ -0,0 +1,1640 @@ +/* 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 +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla_defs.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/common_runtime/shape_refiner.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#include "tensorflow/core/framework/node_def_builder.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/versions.pb.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/graph/graph_node_util.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/hash.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { +namespace functionalize_cond { + +bool AncestorNode::operator<(const AncestorNode& other) const { + return (output_tensor.node->id() < other.output_tensor.node->id()) || + (output_tensor.node->id() == other.output_tensor.node->id() && + output_tensor.index < other.output_tensor.index) || + (output_tensor.node->id() == other.output_tensor.node->id() && + output_tensor.index == other.output_tensor.index && + type < other.type); +} + +bool AncestorNode::operator==(const AncestorNode& other) const { + return output_tensor.node->id() == other.output_tensor.node->id() && + output_tensor.index == other.output_tensor.index && type == other.type; +} + +size_t AncestorNode::Hash::operator()(const AncestorNode& ancestor) const { + size_t h = std::hash()(ancestor.output_tensor.node->id()); + h = Hash64Combine(h, std::hash()(ancestor.output_tensor.index)); + return Hash64Combine(h, std::hash()(static_cast(ancestor.type))); +} + +typedef std::tuple + ClusterTuple; + +struct ClusterTupleLessThan { + bool operator()(const ClusterTuple& a, const ClusterTuple& b) const { + if (std::tie(std::get<0>(a), std::get<1>(a)) < + std::tie(std::get<0>(b), std::get<1>(b))) { + return true; + } else if (std::tie(std::get<0>(a), std::get<1>(a)) == + std::tie(std::get<0>(b), std::get<1>(b))) { + return StateMap::OutputTensorLess()(std::get<2>(a), std::get<2>(b)); + } else { + return false; + } + } +}; + +// TODO(jpienaar): Move to OutputTensor. +std::string DebugString(const OutputTensor& tensor) { + return absl::StrCat(tensor.node->name(), ":", tensor.index); +} + +std::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"; + } +} + +std::string DebugString(StateMap::CondId cond_state) { + if (cond_state == nullptr || cond_state->empty()) return "{}"; + using value_type = StateMap::CondState::value_type; + return absl::StrCat( + "{", + absl::StrJoin(*cond_state, ", ", + [](std::string* output, const value_type& pred_branch) { + const OutputTensor& pred = pred_branch.first; + const BranchType& branch = pred_branch.second; + if (branch == BranchType::kNeither) + absl::StrAppend(output, "d"); + else + absl::StrAppend(output, "s(", DebugString(pred), ",", + Branch_Name(branch), ")"); + }), + "}"); +} + +// Returns the predicate of a switch. +absl::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 absl::OkStatus(); +} + +absl::Status GetSwitchValue(const Node& switch_node, OutputTensor* val) { + const Edge* val_edge; + TF_RETURN_IF_ERROR(switch_node.input_edge(0, &val_edge)); + *val = OutputTensor(val_edge->src(), val_edge->src_output()); + return absl::OkStatus(); +} + +bool StateMap::OutputTensorLess::operator()(const OutputTensor& lhs, + const OutputTensor& rhs) const { + return (lhs.node->id() < rhs.node->id()) || + (lhs.node->id() == rhs.node->id() && lhs.index < rhs.index); +} + +struct CondStateLess { + bool operator()(const StateMap::CondState::value_type& lhs, + const StateMap::CondState::value_type& rhs) const { + if (StateMap::OutputTensorLess().operator()(lhs.first, rhs.first)) + return true; + if (lhs.first.node->id() == rhs.first.node->id() && + lhs.first.index == rhs.first.index) + return lhs.second < rhs.second; + return false; + } +}; + +StateMap::StateMap(Graph* graph) { + node_to_condid_map_.resize(graph->num_node_ids()); + node_to_ancestorid_map_.resize(graph->num_node_ids()); + // Initialize the dead state (empty state is designated with a nullptr). + dead_id_ = GetCondId( + {std::make_pair(OutputTensor(nullptr, -1), BranchType::kNeither)}); +} + +bool StateMap::IsDead(StateMap::CondId id) const { return id == dead_id_; } + +bool StateMap::IsEmpty(StateMap::CondId id) const { return id == nullptr; } + +size_t StateMap::Hash::operator()(const StateMap::CondState& map) const { + if (map.empty()) return 0; + // Compute hash of the front element. + auto it = map.begin(); + size_t h = Hash64Combine(OutputTensor::Hash()(it->first), + hash()(it->second)); + for (++it; it != map.end(); ++it) { + // Combine the has with the different elements in the map. + h = Hash64Combine(h, Hash64Combine(OutputTensor::Hash()(it->first), + hash()(it->second))); + } + return h; +} + +size_t StateMap::Hash::operator()(const StateMap::AncestorState& map) const { + if (map.empty()) return 0; + // Compute hash of the front element. + auto it = map.begin(); + size_t h = AncestorNode::Hash()(*it); + for (++it; it != map.end(); ++it) { + // Combine the has with the different elements in the map. + h = Hash64Combine(h, AncestorNode::Hash()(*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) {} + + std::string ToString() const { + return absl::StrCat("src=", src->name(), ":", src_output, + " switches=", NodesToString(switches)); + } + + Node* src; + int src_output; + std::array branch_copy; + std::vector switches; +}; +using CondArgNodes = std::vector; + +std::string DebugString(const CondArgNodes& nodes) { + return absl::StrCat( + "[", + absl::StrJoin(nodes, ", ", + [](std::string* output, const CondArgNode& node) { + absl::StrAppend(output, node.ToString()); + }), + "]"); +} + +StateMap::CondId StateMap::LookupCondId(const Node* node) const { + const int64_t map_size = node_to_condid_map_.size(); + if (node->id() < map_size) return node_to_condid_map_[node->id()]; + return added_node_condid_mapping_.at(node->id()); +} + +StateMap::CondId StateMap::GetCondId(const StateMap::CondState& state) { + if (state.empty()) return nullptr; + return &*condstate_set_.insert(state).first; +} + +void StateMap::ResetCondId(const Node* node, StateMap::CondId id) { + const int64_t map_size = node_to_condid_map_.size(); + if (node->id() < map_size) + node_to_condid_map_[node->id()] = id; + else + added_node_condid_mapping_[node->id()] = id; +} + +StateMap::AncestorId StateMap::LookupAncestorId(const Node* node) const { + const int64_t map_size = node_to_ancestorid_map_.size(); + if (node->id() < map_size) return node_to_ancestorid_map_[node->id()]; + return added_node_ancestorid_mapping_.at(node->id()); +} + +StateMap::AncestorId StateMap::GetAncestorId( + const StateMap::AncestorState& state) { + if (state.empty()) return nullptr; + return &*ancestorstate_set_.insert(state).first; +} + +void StateMap::ResetAncestorId(const Node* node, StateMap::AncestorId id) { + const int64_t map_size = node_to_ancestorid_map_.size(); + if (node->id() < map_size) + node_to_ancestorid_map_[node->id()] = id; + else + added_node_ancestorid_mapping_[node->id()] = id; +} + +void StateMap::MarkDead(const Node* node) { ResetCondId(node, dead_id_); } + +std::string StateMap::CondStateToString(const Node* node) const { + return CondStateToString(LookupCondId(node)); +} + +std::string StateMap::CondStateToString(StateMap::CondId id) const { + return DebugString(id); +} + +std::string StateMap::AncestorStateToString(const Node* node) const { + if (auto id = LookupAncestorId(node)) { + return absl::StrCat( + "{", + absl::StrJoin(*id, ",", + [](std::string* output, const AncestorNode& ancestor) { + absl::StrAppend(output, + ancestor.output_tensor.node->name(), + ":", ancestor.output_tensor.index); + }), + "}"); + } + return "{}"; +} + +FunctionalizeCond::FunctionalizeCond(Graph* graph, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter) + : state_map_(graph), + library_(library), + graph_(graph), + node_filter_(node_filter) {} + +// Class representing the merge/switch nodes that will become a conditional. +class Conditional { + public: + Conditional(OutputTensor predicate, FunctionalizeCond* parent, + StateMap* cond_state_map, const ShapeRefiner& refiner); + + // Adds merge node that is part of this conditional. + absl::Status AddMerge(Node* m); + + // Constructs an If node from the merge nodes. + absl::Status BuildAndReplace( + Graph* graph, FunctionLibraryDefinition* library, + std::unordered_map* merge_to_replacement); + + 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. + absl::Status ExtractBodies(Graph* graph); + + // Builds the arguments that are the input to the If. + absl::Status BuildArgumentNodes(); + + // Builds the If node for the extracted bodies with the given predicate. + absl::Status BuildIfNode(Graph* graph, FunctionLibraryDefinition* library); + + // Adds input edges to If node. + absl::Status AddInputEdges( + Graph* graph, + const std::unordered_map& merge_to_replacement); + + // Adds output edges from If node. + // Record new output tensor for all Merge nodes in 'merge_to_replacement'. + absl::Status AddOutputEdges( + Graph* graph, + std::unordered_map* merge_to_replacement); + + // Adds switch node that is part of this conditional. + absl::Status AddSwitch(Node* s); + + // Adds a switch node along the edge and rewire the edge to go via the switch. + absl::Status AddSwitchNodeAlongEdge(const Edge* edge, BranchType branch, + Graph* graph); + + // Internal name of conditional. The name is based on the first merge node + // added. + std::string name() const; + + // The FunctionalizeCond instance that created this. + FunctionalizeCond* parent_; + + // Mapping between nodes and their cond state. + StateMap* state_map_; + + // The predicate of the conditional. + OutputTensor predicate_; + + // Shape refiner of ops in the graph. + const ShapeRefiner& refiner_; + + // 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 switches_; + + // Merge nodes in graph that are part of this conditional. + std::set merges_; + + // Vector of control inputs from outside the conditional to a node inside. + std::vector external_control_inputs_; + std::vector external_control_outputs_; + + // Graphs corresponding to the then and else branch. + std::array, 2> bodies_; + + // Maps from graph_ to the branch body's graph. + std::array, 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, + StateMap* cond_state_map, const ShapeRefiner& refiner) + : parent_(parent), + state_map_(cond_state_map), + predicate_(predicate), + refiner_(refiner) {} + +absl::Status Conditional::AddMerge(Node* m) { + merges_.insert(m); + return absl::OkStatus(); +} + +absl::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 absl::InvalidArgumentError(absl::StrCat( + "Merge nodes ", NodesToString(merges_), + " directly dominated by switch nodes with different predicates (", + DebugString(switch_predicate_), " vs ", DebugString(predicate), ").")); + } + switches_.insert(s); + parent_->AddSwitchId(s->id()); + return absl::OkStatus(); +} + +absl::Status Conditional::BuildArgumentNodes() { + VLOG(1) << "Build function arguments"; + struct Hash { + size_t operator()(const std::pair& item) const { + return Hash64Combine(hash()(item.first), + std::hash()(item.second)); + } + }; + + std::unordered_map, int, Hash> input_index; + for (Node* switch_node : switches_) { + const Edge* e; + TF_RETURN_IF_ERROR(switch_node->input_edge(0, &e)); + std::pair 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(branch); + TF_RETURN_IF_ERROR( + NodeBuilder(absl::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(branch)][m->id()]->in_edges()) { + if (!e->IsControlEdge()) { + has_input = true; + break; + } + } + if (!has_input) { + return absl::InternalError( + absl::StrCat("Failed to functionalize control flow with merge ", + FormatNodeForError(*m), " that doesn't have input on ", + Branch_Name(branch), " branch.")); + } + } + } + + return absl::OkStatus(); +} + +absl::Status Conditional::AddSwitchNodeAlongEdge(const Edge* edge, + BranchType branch, + Graph* graph) { + // Previously we had edge: + // src:src_output ---- edge ----> dst:dst_input + // post this we have (in graph) + // src:src_output --> switch --- new_edge --> dst:dst_input + + // TODO(jpienaar): One could keep a map caching the extra switch nodes added + // to avoid adding another switch to feed a value for which a switch was + // already added. + Node* switch_node; + Node* src = edge->src(); + int src_output = edge->src_output(); + TF_RETURN_IF_ERROR( + NodeBuilder(graph->NewName(absl::StrCat(src->name(), "_added_switch")), + "Switch") + .Input(src, src_output) + .Input(const_cast(predicate_.node), predicate_.index) + .Finalize(graph, &switch_node)); + state_map_->ResetCondId(switch_node, state_map_->LookupCondId(src)); + state_map_->ResetAncestorId(switch_node, state_map_->LookupAncestorId(src)); + + Node* dst = edge->dst(); + int dst_input = edge->dst_input(); + graph->RemoveEdge(edge); + graph->AddEdge(switch_node, static_cast(branch), dst, dst_input); + return AddSwitch(switch_node); +} + +absl::Status Conditional::ExtractBodies(Graph* graph) { + VLOG(2) << "Extracting bodies for " << name(); + for (auto b : {BranchType::kElseBranch, BranchType::kThenBranch}) { + bodies_[static_cast(b)] = + std::make_unique(graph->op_registry()); + } + + auto find_branch = [&](const Edge* e) { + const auto& id = state_map_->LookupCondId(e->src()); + return IsSwitch(e->src()) ? BranchType(e->src_output()) + : state_map_->FindBranchOf(id, predicate_); + }; + + std::array, 2> stacks; + VLOG(5) << "Merges: " << NodesToString(merges_); + for (Node* m : merges_) { + VLOG(5) << "For merge: " << m->DebugString() << " " + << 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) + << ") for predicate " << DebugString(predicate_) << " [" + << DebugString(state_map_->LookupCondId(e->src())) << "]."; + 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(branch)].push_back(src); + } + } + } + + for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) { + int branch_index = static_cast(branch); + auto output = bodies_[branch_index].get(); + auto& stack = stacks[branch_index]; + VLOG(5) << "In branch: " << Branch_Name(branch) << " " + << NodesToString(stack); + std::vector 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 exiting scope. + for (const Edge* e : n->out_edges()) { + Node* dst = e->dst(); + if (IsMerge(dst)) continue; + Node* src = e->src(); + + auto dst_id = state_map_->LookupCondId(dst); + auto src_id = state_map_->LookupCondId(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) << absl::InvalidArgumentError(absl::StrCat( + "Graph contains node ", FormatNodeForError(*src), + " that feeds into node ", FormatNodeForError(*dst), + " but these nodes are in different control contexts (", + DebugString(src_id), " vs ", DebugString(dst_id), + " (detected during out edge testing)")); + } + } + } + } + + // Copying incoming edges to dst node. Iterate over a copy of the edges + // as they could be mutated during iteration. + std::vector in_edges(n->in_edges().begin(), + n->in_edges().end()); + // Sort in_edges to make sure nodes are copied in a deterministic order. + std::sort( + in_edges.begin(), in_edges.end(), [](const Edge* a, const Edge* b) { + int a_src_output = a->src_output(), b_src_output = b->src_output(); + absl::string_view a_name(a->src()->name()), + b_name(b->src()->name()); + return std::tie(a_src_output, a_name) < + std::tie(b_src_output, b_name); + }); + for (const Edge* e : 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 = state_map_->LookupCondId(src); + auto dst_id = state_map_->LookupCondId(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()) { + // Here we have a control flow edge between src and dst that are not + // in the same context. This is an external control dependency except + // for one case: where the only difference between CondId of e->src() + // and CondId of e->dst() is that e->src() has {PRED, kNeither} and + // e->dst() has {PRED, kThenBranch/kElseBranch}. This happens in + // gradients code for tf.cond(), where e->src() is a control pivot + // node for a branch and e->dst() is a data node in that branch. + bool is_external_control_input = true; + if (!state_map_->IsEmpty(src_id) && !state_map_->IsEmpty(dst_id)) { + std::vector diff; + std::set_symmetric_difference( + src_id->begin(), src_id->end(), dst_id->begin(), dst_id->end(), + std::back_inserter(diff), CondStateLess()); + if (diff.size() == 2 && diff[0].first == diff[1].first && + (diff[0].second == BranchType::kNeither || + diff[1].second == BranchType::kNeither)) { + auto src_branch = src_id->find(diff[0].first); + if (src_branch != src_id->end() && + src_branch->second == BranchType::kNeither) { + is_external_control_input = false; + } + } + } + if (is_external_control_input) { + 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 by for + // * constant nodes copy them; + // * non-constant nodes, insert a switch along the edge; + if (IsConstant(src)) { + // Check if constant node was added already. It is possible to have + // multiple uses of a constant node. + if (node_map.at(src->id()) == nullptr) { + node_map.at(src->id()) = output->CopyNode(src); + } + } else { + StateMap::CondState state = *dst_id; + state.erase(predicate_); + if (state_map_->GetCondId(state) == src_id) { + TF_RETURN_IF_ERROR(AddSwitchNodeAlongEdge(e, branch, graph)); + continue; + } else { + return absl::InvalidArgumentError(absl::StrCat( + "Graph contains node ", FormatNodeForError(*src), + " that feeds into node ", FormatNodeForError(*dst), + " 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(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 + // Switch node, which is handled separately. + for (auto e : m->in_edges()) { + if (e->IsControlEdge()) continue; + int branch_index = static_cast(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 absl::OkStatus(); +} + +absl::Status Conditional::BuildIfNode(Graph* graph, + FunctionLibraryDefinition* library) { + VLOG(2) << "Build cond function for " << name(); + NodeDebugInfo debug_info((*merges_.begin())->def()); + NodeDefBuilder builder(name(), "If", library, &debug_info); + const std::string branch_name[] = {"else_branch", "then_branch"}; + for (auto branch : {BranchType::kElseBranch, BranchType::kThenBranch}) { + int branch_index = static_cast(branch); + + NameAttrList body_name; + body_name.set_name(library->UniqueFunctionName( + absl::StrCat("_functionalize_if_", branch_name[branch_index], "_"))); + + VLOG(3) << "FunctionalizeControlFlow (" << branch_name[branch_index] + << "): " + << 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 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; + std::vector output_shapes; + output_shapes.reserve(merges_.size()); + for (const Node* merge : merges_) { + DataType dtype = merge->output_type(0); + TensorShapeProto shape; + if (auto* shape_ctx = refiner_.GetContext(merge)) { + shape_inference::ShapeHandle handle; + shape_ctx->ShapeHandleToProto(shape_ctx->output(0), &shape); + } + out_type.push_back(dtype); + output_shapes.push_back(shape); + } + builder.Attr("Tout", out_type); + VLOG(3) << "Build output type: " << DataTypeVectorString(out_type); + builder.Attr("output_shapes", output_shapes); + VLOG(3) << "Build output shapes: " + << PartialTensorShapeUtils::PartialShapeListString(output_shapes); + + builder.Attr("Tcond", DT_BOOL); + // Add some internal attributes which need to be propagated. + for (absl::string_view attr_name : kAttrsToPropagate) { + std::string attr_val; + if (GetNodeAttr(predicate_.node->def(), attr_name, &attr_val).ok()) { + builder.Attr(attr_name, attr_val); + } + } + 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(predicate_.index))); + // ... 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(), predicate_)); + + return absl::OkStatus(); +} + +absl::Status Conditional::AddInputEdges( + Graph* graph, + const std::unordered_map& merge_to_replacement) { + VLOG(2) << "AddInputEdges for " << if_node_->name(); + int index = 0; + // Add predicate input. + if (predicate_.node->IsMerge()) { + // If the predicate is a Merge node, we should not use Merge output as + // predicate. Instead, we should use the corresponding If output in + // 'merge_to_replacement'. Otherwise, this Conditional's If node is still + // connected to the predicate Merge node; and when we call + // DeleteReachableAndDeadNodes(), the predicate Merge node and this + // Conditional's If node will be removed. + auto iter = merge_to_replacement.find(predicate_.node); + if (iter == merge_to_replacement.end()) { + return absl::InternalError(absl::StrCat( + "Cannot find replacement for Merge node ", predicate_.node->name())); + } + graph->AddEdge(iter->second.node, iter->second.index, if_node_, index++); + } else { + graph->AddEdge(const_cast(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 absl::OkStatus(); +} + +absl::Status Conditional::AddOutputEdges( + Graph* graph, + std::unordered_map* merge_to_replacement) { + 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 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 absl::UnimplementedError( + absl::StrCat("Output of index (", edge->src_output(), + ") of merge node ", FormatNodeForError(*node))); + } + + 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); + } + } + + // Record corresponding output tensor in 'merge_to_replacement'. + (*merge_to_replacement)[node] = OutputTensor{if_node_, i}; + + ++i; + } + for (Node* n : external_control_outputs_) { + graph->AddControlEdge(if_node_, n); + } + + return absl::OkStatus(); +} + +absl::Status Conditional::BuildAndReplace( + Graph* graph, FunctionLibraryDefinition* library, + std::unordered_map* merge_to_replacement) { + VLOG(1) << "Build If and replace merge nodes " + << NodesToString(this->merges_); + if (replaced_) return absl::OkStatus(); + + 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(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, *merge_to_replacement)); + TF_RETURN_IF_ERROR(AddOutputEdges(graph, merge_to_replacement)); + TF_RETURN_IF_ERROR(parent_->PropagateUpdatedState(if_node_)); + + // 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 absl::OkStatus(); +} + +std::string Conditional::name() const { + CHECK(!merges_.empty()); + return absl::StrCat((*merges_.begin())->name(), "_if"); +} + +absl::Status FunctionalizeCond::AddIdentityNode(const Node* replacee, + Node* if_node, int port) { + NodeBuilder id_builder(replacee->name(), "Identity"); + id_builder.Input(if_node, port); + std::string outside_compilation; + if (GetNodeAttr(if_node->def(), kXlaOutsideCompilationAttr, + &outside_compilation) + .ok()) { + id_builder.Attr(kXlaOutsideCompilationAttr, outside_compilation); + } + Node* id; + TF_RETURN_IF_ERROR(id_builder.Finalize(graph_, &id)); + state_map_.ResetCondId(id, state_map_.LookupCondId(if_node)); + state_map_.ResetAncestorId(id, state_map_.LookupAncestorId(if_node)); + return absl::OkStatus(); +} + +absl::StatusOr FunctionalizeCond::AddIfNode( + const NodeDef& def, const Node* replacee, const OutputTensor& predicate) { + TF_ASSIGN_OR_RETURN(Node * ret, graph_->AddNode(def)); + VLOG(1) << "Adding If for " << replacee->name(); + StateMap::CondId id = state_map_.LookupCondId(replacee); + if (id) { + StateMap::CondState state = *id; + state.erase(predicate); + state_map_.ResetCondId(ret, state_map_.GetCondId(state)); + } else { + state_map_.ResetCondId(ret, nullptr); + } + + state_map_.ResetAncestorId(ret, state_map_.LookupAncestorId(replacee)); + + return ret; +} + +absl::Status FunctionalizeCond::PropagateUpdatedState(const Node* replacee) { + VLOG(2) << "Propagating update state for " << replacee->name() << " " + << 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 rev_topo_order; + GetPostOrder(*graph_, &rev_topo_order, NodeComparatorID()); + + // All the outputs of the new node could potentially be updated. + std::unordered_set 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; + StateMap::CondId old_state = state_map_.LookupCondId(n); + state_map_.ResetCondId(n, nullptr); + TF_RETURN_IF_ERROR(DetermineCondState(n)); + if (state_map_.LookupCondId(n) != old_state) { + for (auto out : n->out_nodes()) + if (out->IsOp()) changed.insert(out); + } + changed.erase(n); + } + } + return absl::OkStatus(); +} + +// 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; +} + +BranchType StateMap::FindBranchOf(CondId id, OutputTensor predicate) const { + if (IsEmpty(id)) return BranchType::kNeither; + const CondState& nodes = *id; + auto it = nodes.find(predicate); + if (it == nodes.end()) return BranchType::kNeither; + return it->second; +} + +absl::StatusOr FunctionalizeCond::JoinCondStatesNonMerge( + StateMap::CondId src, StateMap::CondId dst) { + VLOG(5) << "Joining src=" << DebugString(src) << " [" << src + << "] and dst=" << DebugString(dst) << " [" << dst << "]"; + + if (state_map_.IsEmpty(dst) || state_map_.IsDead(src)) return src; + if (state_map_.IsDead(dst) || state_map_.IsEmpty(src)) return dst; + + // Nothing to do if the CondState is the same. + if (src == dst) return src; + + StateMap::CondState both = *src; + for (const auto& kv : *dst) { + auto it = both.find(kv.first); + if (it == both.end()) { + both.insert(kv); + } else { + if (it->second != kv.second) { + if (it->second == BranchType::kNeither) { + // BranchType for 'src' is kNeither. Use the BranchType in 'dst'. + it->second = kv.second; + } else if (kv.second == BranchType::kNeither) { + // BranchType for 'dst' is kNeither. Use the BranchType in 'src'. + // No need to change it->second. + } else { + return absl::InvalidArgumentError(absl::StrCat( + "Graph contains node with inputs predicated on incompatible " + "predicates: ", + DebugString(src), " and ", DebugString(dst))); + } + } + } + } + return state_map_.GetCondId(both); +} + +absl::StatusOr FunctionalizeCond::JoinCondStatesMerge( + Node* merge, StateMap::CondId src, StateMap::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 an 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 (state_map_.IsEmpty(dst)) return src; + if (state_map_.IsEmpty(src)) { + return absl::InternalError( + absl::StrCat("Merge node ", merge->name(), + " has input that's not in any CondContext.")); + } + + if (state_map_.IsDead(src)) return src; + if (state_map_.IsDead(dst)) return dst; + + std::vector diff; + StateMap::CondState merged; + std::set_symmetric_difference(src->begin(), src->end(), dst->begin(), + dst->end(), std::back_inserter(diff), + CondStateLess()); + std::set_intersection(src->begin(), src->end(), dst->begin(), dst->end(), + std::inserter(merged, merged.begin()), CondStateLess()); + + // Update mapping from merge node to predicate. + if (diff.size() == 2) { + auto pred = diff[0].first; + bool different_branches = (diff[0].second != diff[1].second) && + (diff[0].second == BranchType::kThenBranch || + diff[0].second == BranchType::kElseBranch) && + (diff[1].second == BranchType::kThenBranch || + diff[1].second == BranchType::kElseBranch); + if (!(pred == diff[1].first) || !different_branches) + return absl::InvalidArgumentError( + "Unable to determine predicate for merge node"); + merge_to_predicate_[merge] = pred; + } else { + return absl::InvalidArgumentError(absl::StrCat( + "Merge of two inputs that differ on more than one predicate ", + DebugString(src), " and ", DebugString(dst))); + } + + return state_map_.GetCondId(merged); +} + +StateMap::CondId FunctionalizeCond::StateAlongEdge(const Edge* e) { + Node* src = e->src(); + StateMap::CondId id = state_map_.LookupCondId(e->src()); + + // Dead nodes only propagate dead state. + if (state_map_.IsDead(id)) return id; + + if (IsSwitch(src)) { + StateMap::CondState state; + if (id != nullptr) state = *id; + OutputTensor predicate; + CHECK_OK(GetSwitchPredicate(*src, &predicate)); + if (e->IsControlEdge()) { + // In gradients of tf.cond(), in each branch, we have a NoOp node as + // control pivot. These NoOp nodes have control dependency from Switch + // node. If we don't record this into CondState, branches might have + // incorrect CondState (e.g. if the branch only has a Const data node). + // We set it to kNeither because there is no way to tell whether it's + // for true branch or false branch. This node's descendents might have + // other incoming edges with defined BranchType, and we correctly handle + // merging kNeither with other defined BranchType in StateAlongEdge(). + state[predicate] = BranchType::kNeither; + } else { + state[predicate] = BranchType(e->src_output()); + } + return state_map_.GetCondId(state); + } + return id; +} + +absl::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 (state_map_.IsDead(state_map_.LookupCondId(dst))) return absl::OkStatus(); + + int data_inputs = 0; + for (auto e : dst->in_edges()) { + Node* src = e->src(); + VLOG(5) << "Processing forward flow for merge: " << e->DebugString() << " " + << state_map_.CondStateToString(src); + if (!src->IsOp()) continue; + if (!e->IsControlEdge()) ++data_inputs; + + StateMap::CondId prop = StateAlongEdge(e); + auto id_or = JoinCondStatesMerge(dst, prop, state_map_.LookupCondId(dst)); + TF_RETURN_WITH_CONTEXT_IF_ERROR(id_or.status(), "for node ", + FormatNodeForError(*dst)); + state_map_.ResetCondId(dst, id_or.value()); + } + + // Incomplete Merge nodes are not supported. + if (data_inputs != 2) { + return absl::UnimplementedError(absl::StrCat( + dst->name(), " only has ", data_inputs, + " inputs, while only merge nodes with two inputs supported.")); + } + return absl::OkStatus(); +} + +absl::Status FunctionalizeCond::DetermineCondStateNonMerge(Node* dst) { + // Handle non-merge join. + for (auto e : dst->in_edges()) { + VLOG(4) << "Processing forward flow for: " << e->DebugString() << " " + << state_map_.CondStateToString(dst); + Node* src = e->src(); + if (!src->IsOp()) continue; + + // Joining the state between the current and propagated state. + StateMap::CondId prop = StateAlongEdge(e); + auto id_or = JoinCondStatesNonMerge(prop, state_map_.LookupCondId(dst)); + TF_RETURN_WITH_CONTEXT_IF_ERROR(id_or.status(), "for node ", + FormatNodeForError(*dst)); + state_map_.ResetCondId(dst, id_or.value()); + } + return absl::OkStatus(); +} + +absl::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 (!state_map_.IsDead(state_map_.LookupCondId(node))) + return absl::OkStatus(); + + 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 = state_map_.LookupCondId(src); + if (!state_map_.IsDead(src_id)) { + non_dead_edge = e; + break; + } + } + + if (non_dead_edge == nullptr) { + return absl::InvalidArgumentError(absl::StrCat( + "Merge node ", FormatNodeForError(*node), " has no non-dead inputs.")); + } + state_map_.MarkDead(node); + 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 absl::OkStatus(); +} + +absl::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. + StateMap::CondId dst_id = state_map_.LookupCondId(node); + if (state_map_.IsDead(dst_id)) return absl::OkStatus(); + + BranchType b; + OutputTensor pred; + TF_RETURN_IF_ERROR(GetSwitchPredicate(*node, &pred)); + + // Determine if we are already on a branch where the switch predicate is + // true/false. Consider both the data and predicate to determine if the + // node is redundant (skipping over identity node). + b = state_map_.FindBranchOf(dst_id, pred); + if (b != BranchType::kThenBranch && b != BranchType::kElseBranch) { + OutputTensor val; + const Edge* e; + TF_RETURN_IF_ERROR(node->input_edge(0, &e)); + val = OutputTensor(e->src(), e->src_output()); + while (IsIdentity(val.node)) { + TF_RETURN_IF_ERROR(val.node->input_edge(0, &e)); + val = OutputTensor(e->src(), e->src_output()); + } + b = state_map_.FindBranchOf(dst_id, val); + if (b != BranchType::kThenBranch && b != BranchType::kElseBranch) + return absl::OkStatus(); + } + + VLOG(5) << "Redundant switch " << node->name() << " " << Branch_Name(b) << " " + << DebugString(dst_id); + 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_node, dst_id, + state_map_.LookupCondId(dst_node)); + TF_RETURN_WITH_CONTEXT_IF_ERROR(id_or.status(), "for node ", + FormatNodeForError(*dst_node)); + state_map_.ResetCondId(dst_node, id_or.value()); + } else { + auto id_or = + JoinCondStatesNonMerge(dst_id, state_map_.LookupCondId(dst_node)); + TF_RETURN_IF_ERROR(id_or.status()); + state_map_.ResetCondId(dst_node, id_or.value()); + } + } else if (BranchType(switch_branch) != b) { + state_map_.MarkDead(dst_node); + continue; + } + graph_->AddEdge( + val_node, + switch_branch == Graph::kControlSlot ? Graph::kControlSlot : val_port, + dst_node, dst_input); + } + return absl::OkStatus(); +} + +absl::Status FunctionalizeCond::DetermineStates( + std::vector 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)); + TF_RETURN_IF_ERROR(DetermineAncestorState(dst)); + if (IsSwitch(dst)) TF_RETURN_IF_ERROR(RemoveRedundantSwitch(dst)); + if (IsMerge(dst)) TF_RETURN_IF_ERROR(RemoveRedundantMerge(dst)); + + VLOG(5) << dst->name() << " :: " << state_map_.CondStateToString(dst) + << " @ " << state_map_.AncestorStateToString(dst); + if (VLOG_IS_ON(10)) DumpGraphWithCondState("it"); + } + return absl::OkStatus(); +} + +absl::Status FunctionalizeCond::DetermineAncestorState(Node* dst) { + StateMap::AncestorId id = nullptr; + StateMap::AncestorState state; + + auto insert = [&](StateMap::AncestorId id, Node* src) { + auto other_id = state_map_.LookupAncestorId(src); + if (other_id != id && other_id != nullptr) { + state.insert(other_id->begin(), other_id->end()); + } + if (IsMerge(src)) { + state.insert({{src, 0}, AncestorNode::AncestorNodeType::kMerge}); + } else if (IsSwitch(src)) { + OutputTensor pred; + // For dead switch nodes, GetSwitchPredicate() will fail, and we use + // the switch node directly as ancestor. + if (GetSwitchPredicate(*src, &pred).ok()) { + state.insert({pred, AncestorNode::AncestorNodeType::kPred}); + } else { + state.insert({{src, 0}, AncestorNode::AncestorNodeType::kSwitch}); + } + } + return state_map_.GetAncestorId(state); + }; + + // Compute the union of all the switch/merge nodes that affects the input of + // dst. + for (auto e : dst->in_edges()) { + Node* src = e->src(); + id = insert(id, src); + } + state_map_.ResetAncestorId(dst, id); + return absl::OkStatus(); +} + +void FunctionalizeCond::DeleteReachableAndDeadNodes( + const std::vector& merge_order) { + // 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::deque delete_nodes; + std::vector deleted(graph_->num_node_ids(), false); + // Don't try to delete source or sink nodes. + deleted[graph_->kSourceId] = true; + deleted[graph_->kSinkId] = true; + + // All remaining switch nodes that were not excluded from functionalization + // according to `node_filter_` are not reachable from a merge node and + // removed. This is to account for dead switch nodes. + for (int s_id : switch_ids_) { + Node* s = graph_->FindNodeId(s_id); + if (s == nullptr) continue; + for (const Edge* e : s->out_edges()) { + // Control outputs of switch nodes (which are unconditionally executed if + // the switch is) are not removed as they need not be part of a + // conditional. + if (!e->IsControlEdge()) delete_nodes.push_back(e->dst()->id()); + } + // Only remove switch node if we have functionalized the corresponding + // condition before (according to `node_filter_`). + if (!node_filter_ || node_filter_(s)) { + VLOG(2) << "Removing obsolete switch node " << s->name(); + deleted[s_id] = true; + graph_->RemoveNode(s); + } + } + + // All merge nodes that were not excluded from functionalization according to + // `node_filter_` should have been transformed at this point and we remove + // them from the graph here. + for (Node* m : merge_order) { + for (const Edge* e : m->out_edges()) { + // Similar to control outputs of switch nodes don't remove control + // outputs of merge nodes. + // TODO(jpienaar): Check cases where output edges still exist here vs + // being removed in AddOutputEdges. + if (!e->IsControlEdge()) delete_nodes.push_back(e->dst()->id()); + } + // Only remove merge node if we have functionalized the corresponding + // condition before (according to `node_filter_`). + if (!node_filter_ || node_filter_(m)) { + VLOG(2) << "Removing obsolete merge node " << m->name(); + deleted[m->id()] = true; + graph_->RemoveNode(m); + } + } + + // Enqueue all the dead nodes. + for (Node* n : graph_->nodes()) { + if (state_map_.IsDead(state_map_.LookupCondId(n))) { + delete_nodes.push_back(n->id()); + } + } + // Remove dead nodes and nodes that are reachable from dead nodes. + 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()); + } + VLOG(2) << "Removing obsolete node " << d->name(); + deleted[d_id] = true; + graph_->RemoveNode(d); + } +} + +void FunctionalizeCond::SortMergeNodes(std::vector* merge_order) { + // Sort merge nodes by nesting depth. + using sort_pair = std::pair; + std::vector 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; + StateMap::CondId id = state_map_.LookupCondId(merge); + int depth = id != nullptr ? id->size() : 0; + 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); + } +} + +absl::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 + // AncestorState from the innermost to the outermost into IfOps; + // Note: In the above only nodes that feed into a merge node will be + // considered for functionalization. + // Note: Nodes for which `node_filter_` returns false are excluded. + + // 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 rev_topo_order; + std::vector merge_order; + DFS(*graph_, nullptr, [&](Node* n) { + // Only collect switch and merge nodes that are not filtered out, those form + // the conditions that will be functionalized. + if (!node_filter_ || node_filter_(n)) { + if (IsSwitch(n)) { + AddSwitchId(n->id()); + } + if (IsMerge(n)) { + merge_order.push_back(n); + } + } + // Collect all other nodes here, independent of `node_filter_`, because they + // might belong to a condition that should be functionalized. + 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); + DeleteReachableAndDeadNodes(merge_order); + return absl::OkStatus(); + } + + TF_RETURN_IF_ERROR(DetermineStates(std::move(rev_topo_order))); + if (VLOG_IS_ON(4)) DumpGraphWithCondState("id"); + + // Determine the shapes of the ops in the graph. + ShapeRefiner shape_refiner{graph_->versions().producer(), + graph_->op_registry()}; + std::vector nodes; + GetReversePostOrder(*graph_, &nodes, NodeComparatorID()); + for (auto node : nodes) { + if (!shape_refiner.AddNode(node).ok()) { + LOG(WARNING) << "Couldn't deduce shape for " << node->name(); + } + } + + // Sort the merge nodes from innermost outwards. + SortMergeNodes(&merge_order); + + // Cluster merge nodes by (CondId, AncestorId, predicate) in order of + // nesting. (CondId, AncestorId) is not enough, e.g. + // pred1 = array_ops.placeholder(dtypes.bool, name='pred1') + // pred2 = array_ops.placeholder(dtypes.bool, name='pred2') + // cond1 = cond.cond(pred1, ...) + // cond2 = cond.cond(pred2, ...) + // cond3 = cond.cond(pred1, use cond1 and cond2) + // cond4 = cond.cond(pred2, use cond1 and cond2) + // cond3 and cond4 have the same (CondId, AncestorId), but they should not + // be merged into one "If" node (because they have different predicates). + std::deque> merge_clusters; + std::map merge_cluster_index; + for (Node* merge : merge_order) { + auto cond_id = state_map_.LookupCondId(merge); + if (state_map_.IsDead(cond_id)) continue; + + auto predicate = merge_to_predicate_.find(merge); + if (predicate == merge_to_predicate_.end()) { + return absl::InternalError( + absl::StrCat("Cannot find predicate for Merge node ", merge->name())); + } + + ClusterTuple key = std::make_tuple( + cond_id, state_map_.LookupAncestorId(merge), predicate->second); + auto idx = merge_cluster_index.find(key); + if (idx == merge_cluster_index.end()) { + merge_cluster_index[key] = merge_clusters.size(); + merge_clusters.push_back({merge}); + } else { + merge_clusters[idx->second].emplace_back(merge); + } + } + + // Extract the conditionals from inner most to outer most. Extracting from + // innermost to outermost enables the extraction pass to stop once it + // encounters a Switch node instead of having to keep track of Switch/Merge + // nodes seen. + for (const auto& cluster : merge_clusters) { + // Construct a Conditional with the predicate of the merge. + Conditional cond(merge_to_predicate_.at(cluster.front()), this, &state_map_, + shape_refiner); + for (Node* merge : cluster) TF_RETURN_IF_ERROR(cond.AddMerge(merge)); + TF_RETURN_IF_ERROR( + cond.BuildAndReplace(graph_, library_, &merge_to_replacement_)); + + if (VLOG_IS_ON(4)) DumpGraphWithCondState("after_extract"); + } + + DeleteReachableAndDeadNodes(merge_order); + + return absl::OkStatus(); +} + +void FunctionalizeCond::DumpGraphWithCondState(const std::string& name) { + const char* const kCondGroupDebugAttr = "_XlaFunctionalizeCondGroup"; + + for (Node* n : graph_->nodes()) { + n->ClearAttr(kCondGroupDebugAttr); + n->AddAttr(kCondGroupDebugAttr, + absl::StrCat(state_map_.CondStateToString(n), "_", + state_map_.AncestorStateToString(n))); + } + LOG(INFO) << "FunctionalizeControlFlow (" << name << "): " + << DumpGraphToFile(absl::StrCat("functionalize_cond_", name), + *graph_, library_); +} + +void FunctionalizeCond::AddSwitchId(int switch_id) { + switch_ids_.push_back(switch_id); +} + +absl::Status FunctionalizeCond::Functionalize( + Graph* graph, FunctionLibraryDefinition* library, + const NodeFilter& node_filter) { + VLOG(1) << "FunctionalizeCond::Functionalize"; + FunctionalizeCond fc(graph, library, node_filter); + return fc.FunctionalizeInternal(); +} + +} // namespace functionalize_cond + +absl::Status FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library, + const NodeFilter& node_filter) { + // 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, + node_filter); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond.h new file mode 100644 index 0000000000000000000000000000000000000000..782f2a621f1a43f5dce363579815f6fff70011da --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond.h @@ -0,0 +1,291 @@ +/* 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 + +#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h" +#include "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. +// +// If `node_filter` is defined, then only conditions for whose nodes +// `node_filter` returns true are functionalized. +// +// Preconditions: +// a) Same as for `FunctionalizeControlFlow` (see comment there). +// b) While loops must have been functionalized before according to +// `node_filter` (e.g., by calling `FunctionalizeWhileLoop` with the same +// filter before calling this function). +absl::Status FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library, + const NodeFilter& node_filter = {}); + +// 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, +}; + +// When we keep track of which switch/merge node's feed into a node, we record +// 1) predicate for non-dead switch node, +// 2) the switch node itself for dead switch node, +// 3) the merge node itself for merge node. +// Case 1) is an optimization. With this optimization, if there are nodes from +// different switch nodes but those switch nodes have the same predicate, the +// nodes will still have same AncestorState, and they will be clustered into a +// single "If". +struct AncestorNode { + enum class AncestorNodeType { + kPred = 0, + kSwitch = 1, + kMerge = 2, + }; + + OutputTensor output_tensor; + AncestorNodeType type; + + // Compare two AncestorNodes by (node id, index, type). + bool operator<(const AncestorNode& other) const; + bool operator==(const AncestorNode& other) const; + + struct Hash { + size_t operator()(const AncestorNode&) const; + }; +}; + +// StateMap is responsible for mapping from each graph Node to +// * a CondState, where each CondState is a map from predicate to branch (i,e., +// what predicates have to hold or not hold). +// * a AncestorState, where each AncestorState is a set of switch/merge nodes +// that are an ancestor of the node in the graph; +// For efficiency, this class interns the CondState (AncestorState), so that +// CondState (AncestorState) equality comparisons are simply pointer +// comparisons. +class StateMap { + public: + explicit StateMap(Graph* graph); + + // Compare two OutputTensors by (node id, index). + struct OutputTensorLess { + bool operator()(const OutputTensor& lhs, const OutputTensor& rhs) const; + }; + + // A node in the graph is executed when multiple conditions hold. Keep track + // of the predicates that must hold for a node to execute. + using CondState = std::map; + + // Every unique ID is mapped to a CondState. + using CondId = const CondState*; + + // Keep track of which switch/merge node's feed into a node's values. + using AncestorState = std::set; + + // Every unique ID is mapped to a AncestorState. + using AncestorId = const AncestorState*; + + // Returns the CondId for a given node. + CondId LookupCondId(const Node* node) const; + + // Returns the unique CondId for CondState. + CondId GetCondId(const CondState& state); + + // Resets the CondId for a given node. + void ResetCondId(const Node* node, CondId id); + + // Returns the AncestorId for a given node. + AncestorId LookupAncestorId(const Node* node) const; + + // Returns the unique AncestorId for CondState. + AncestorId GetAncestorId(const AncestorState& state); + + // Resets the AncestorId for a given node. + void ResetAncestorId(const Node* node, AncestorId id); + + // Marks `node` as dead. + void MarkDead(const Node* node); + + // Determine branch execution of CondState. + BranchType FindBranchOf(CondId id, OutputTensor predicate) const; + + // Returns textual representation of node's CondState. + std::string CondStateToString(const Node* node) const; + std::string CondStateToString(CondId id) const; + + // Returns textual representation of node's AncestorState. + std::string AncestorStateToString(const Node* node) 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; + + private: + // Hash for CondState and AncestorState. + struct Hash { + size_t operator()(const CondState& map) const; + size_t operator()(const AncestorState& map) 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_set_; + + // Mapping from Node id to CondId. + std::vector 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 added_node_condid_mapping_; + + // AncestorId variants of the CondId members. + std::unordered_set ancestorstate_set_; + std::vector node_to_ancestorid_map_; + std::unordered_map added_node_ancestorid_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: + // See comment for function `FunctionalizeCond`. + static absl::Status Functionalize(Graph* graph, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter); + + // Build identity node with the same name as the merge that will be replaced + // in case the output is fetched/colocated. + absl::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. + absl::StatusOr AddIfNode(const NodeDef& def, const Node* replacee, + const OutputTensor& predicate); + + // Propagates the state of a newly inserted node. + absl::Status PropagateUpdatedState(const Node* replacee); + + // Dump graph with the CondState annotated. + void DumpGraphWithCondState(const std::string& name); + + // Adds `switch_id` to the list of Switch node ids. + void AddSwitchId(int switch_id); + + private: + FunctionalizeCond(Graph* graph, FunctionLibraryDefinition* library, + const NodeFilter& node_filter); + + // Performs the actual cond functionalization. Iterate over groups of merge + // nodes (linked by common predicates & ancestor IDs), from innermost to + // outermost, and extract into If nodes. + absl::Status FunctionalizeInternal(); + + // Returns the forward flow state propagated along edge `e`. + // This may modify state_map_. + StateMap::CondId StateAlongEdge(const Edge* e); + + // Determines the CondState and AncestorState of all the nodes in the given + // vector where the input is expected in reverse topological order. + // This populates the state_map_. + absl::Status DetermineStates(std::vector rev_topo_order); + + // Determine the CondState for a given node using the incoming edges + // to the node. Note: it is expected that this node's CondState is only + // determined once its input's CondState is. + absl::Status DetermineCondState(Node* dst) { + if (IsMerge(dst)) return DetermineCondStateMerge(dst); + return DetermineCondStateNonMerge(dst); + } + + // Helper functions for DetermineCondState. + absl::Status DetermineCondStateNonMerge(Node* dst); + absl::Status DetermineCondStateMerge(Node* dst); + + // 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 state_map_. + absl::StatusOr JoinCondStatesMerge(Node* merge, + StateMap::CondId src, + StateMap::CondId dst); + absl::StatusOr JoinCondStatesNonMerge(StateMap::CondId src, + StateMap::CondId dst); + + // Determines which switch/merge nodes are ancestors of this node. + absl::Status DetermineAncestorState(Node* dst); + + // Checks if a merge node is redundant and if so removes it from the graph. + absl::Status RemoveRedundantMerge(Node* node); + + // Checks if a switch node is redundant and if so removes it from the graph. + absl::Status RemoveRedundantSwitch(Node* node); + + // Sorts merge nodes (in reverse topological order) in order of increasing + // nesting depth. + void SortMergeNodes(std::vector* merge_order); + + // Deletes all nodes in/consumers reachable from switch/merge nodes that were + // extracted. + void DeleteReachableAndDeadNodes(const std::vector& merge_order); + + // Member used to unique the CondState to a unique CondId (AncestorState to a + // unique AncestorId) and keep track of CondState/CondId + // (AncestorState/AncestorId) per Node. + StateMap state_map_; + + // Mapping from merge nodes to predicate. + std::unordered_map merge_to_predicate_; + + // Mapping from merge nodes to corresponding If node outputs. + std::unordered_map merge_to_replacement_; + + FunctionLibraryDefinition* library_; + Graph* graph_; + + friend class FunctionalizeCondTest; + + std::vector switch_ids_; + + // Controls which nodes are skipped for functionalization. + NodeFilter node_filter_ = {}; +}; + +} // namespace functionalize_cond + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_COND_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..afdf878a8611cfa1426f1db14c494d2a47cc9e9a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_cond_test.cc @@ -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. +==============================================================================*/ + +// Tests for the backward const analysis. + +#include "tensorflow/compiler/tf2xla/functionalize_cond.h" + +#include "absl/container/flat_hash_set.h" +#include "absl/strings/string_view.h" +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/array_ops.h" +#include "tensorflow/cc/ops/const_op.h" +#include "tensorflow/cc/ops/control_flow_ops.h" +#include "tensorflow/cc/ops/function_ops.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/core/framework/types.pb.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(), NodeFilter{})); + } + + StateMap::CondId GetUniqueId(const StateMap::StateMap::CondState& state) { + return fc_->state_map_.GetCondId(state); + } + + std::string GetString(const StateMap::StateMap::CondId id) { + return fc_->state_map_.CondStateToString(id); + } + + absl::StatusOr JoinCondStatesNonMerge( + StateMap::CondId src, StateMap::CondId dst) { + return fc_->JoinCondStatesNonMerge(src, dst); + } + + absl::StatusOr JoinCondStatesMerge(Node* n, + StateMap::CondId src, + StateMap::CondId dst) { + return fc_->JoinCondStatesMerge(n, src, dst); + } + + FunctionDefLibrary fdef_lib_; + std::unique_ptr fc_; + std::unique_ptr flib_def_; + std::unique_ptr graph_; +}; + +namespace { + +TEST_F(FunctionalizeCondTest, JoinCondStates) { + Tensor pred_tensor(DT_BOOL, TensorShape()); + pred_tensor.flat().setZero(); + Node* pred = test::graph::Constant(graph_.get(), pred_tensor, "pred"); + Tensor val_tensor(DT_INT32, TensorShape()); + val_tensor.flat().setZero(); + Node* val = test::graph::Constant(graph_.get(), val_tensor, "val"); + Node* m = test::graph::Merge(graph_.get(), val, val); + + StateMap::CondId then_branch; + { + StateMap::CondState ss; + ss.insert(std::make_pair(OutputTensor(pred, 0), BranchType::kThenBranch)); + then_branch = GetUniqueId(ss); + } + StateMap::CondId else_branch; + { + StateMap::CondState ss; + ss.insert(std::make_pair(OutputTensor(pred, 0), BranchType::kElseBranch)); + else_branch = GetUniqueId(ss); + } + + // An non-merge op with inputs from then and else branch. + absl::Status status = + JoinCondStatesNonMerge(then_branch, else_branch).status(); + EXPECT_TRUE(absl::IsInvalidArgument(status)); + + // Merge between then and else branch. + auto joined_or = JoinCondStatesMerge(m, then_branch, else_branch); + TF_EXPECT_OK(joined_or.status()); + StateMap::CondId joined = joined_or.value(); + + // 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()); +} + +TEST_F(FunctionalizeCondTest, JoinCondStatesMergeWithInputNotInCondContext) { + Tensor val_tensor(DT_INT32, TensorShape()); + val_tensor.flat().setZero(); + Node* val = test::graph::Constant(graph_.get(), val_tensor, "val"); + Node* m = test::graph::Merge(graph_.get(), val, val); + + StateMap::CondState cond_state; + auto joined_or = JoinCondStatesMerge(m, /*src=*/nullptr, &cond_state); + EXPECT_FALSE(joined_or.ok()); +} + +TEST(FunctionalizeCond, DuplicateConstNodes) { + Scope root = Scope::NewRootScope().ExitOnError(); + auto const_op = ops::Const(root.WithOpName("const"), 1); + auto arg_0_op = ops::_Arg(root.WithOpName("arg_0"), DT_BOOL, 0); + auto arg_1_op = ops::_Arg(root.WithOpName("arg_1"), DT_INT32, 1); + auto switch_op = ops::Switch(root.WithOpName("switch"), arg_1_op, arg_0_op); + auto identity_n_false_op = + ops::IdentityN(root.WithOpName("identity_n_0"), + {switch_op.output_false, const_op, const_op}); + auto identity_n_true_op = + ops::IdentityN(root.WithOpName("identity_n_1"), + {switch_op.output_true, const_op, const_op}); + auto merge_op = ops::Merge( + root.WithOpName("merge"), + {identity_n_false_op.output.front(), identity_n_true_op.output.front()}); + GraphDef graph_def; + TF_ASSERT_OK(root.ToGraphDef(&graph_def)); + + Graph graph(OpRegistry::Global()); + GraphConstructorOptions options; + TF_EXPECT_OK(ConvertGraphDefToGraph(options, graph_def, &graph)); + + FunctionDefLibrary fdef_lib; + FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); + + auto status = tensorflow::FunctionalizeCond(&graph, &flib_def); + TF_ASSERT_OK(status); + + FunctionDefLibrary flib_def_proto = flib_def.ToProto(); + for (const auto& fdef : flib_def_proto.function()) { + absl::flat_hash_set node_names; + for (const auto& node : fdef.node_def()) { + EXPECT_TRUE(node_names.insert(node.name()).second) + << node.op() << " with duplicate node name '" << node.name() + << "' found."; + } + } +} + +} // namespace +} // namespace functionalize_cond +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow.cc new file mode 100644 index 0000000000000000000000000000000000000000..c9af6f30e51eb25ffd03fc4356dd444062d3e996 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow.cc @@ -0,0 +1,397 @@ +/* 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.h" + +#include +#include +#include +#include +#include + +#include "absl/memory/memory.h" +#include "absl/types/optional.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 "xla/status_macros.h" +#include "xla/union_find.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/common_runtime/graph_optimizer.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.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/core/errors.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/public/session_options.h" +#include "tensorflow/core/public/version.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { + +// Helper functions for functionalizing control flow in functions. + +// Maps function name to +// - new function name, if the function body was functionalized +// - std::nullopt, if not +using FuncMap = std::map>; +using FuncMapIter = + std::map>::const_iterator; + +// Returns whether function has been processed before. +bool FunctionHasBeenProcessed(FuncMapIter func_iter, const FuncMap* func_map) { + return func_iter != func_map->end(); +} + +// Returns whether function has been modified (i.e., functionalized) before. +bool FunctionHasBeenModified(FuncMapIter func_iter) { + return func_iter->second.has_value(); +} + +// Returns a name for the new functionalized version of a function. +std::string GetNewFunctionName( + const std::string& func_name, Node* n, + AssociatedFunctionInfo::AssociatedFunctionType func_type, + FunctionLibraryDefinition* fld) { + // For SymbolicGradient, `func_name` is always "SymbolicGradient" which + // is not very informative. Use node name instead. + return ( + func_type == + AssociatedFunctionInfo::AssociatedFunctionType::kSymbolicGradient + ? fld->UniqueFunctionName(absl::StrCat(n->name(), "_f15n_")) + : fld->UniqueFunctionName(absl::StrCat(func_name, "_f15n_"))); +} + +// Returns name to which a modified function has been mapped. +const std::string& GetMappedFunctionName(FuncMapIter func_iter) { + DCHECK(func_iter->second.has_value()); + return func_iter->second.value(); +} + +// Updates `func_map` with function given by `canonicalized_name`. +void UpdateFunctionMap(FuncMap* func_map, const std::string& canonicalized_name, + const std::string& new_func_name, + bool function_modified) { + // If function was modified store its new name, otherwise add empty entry to + // record that function has been processed and does not need to be rewritten. + (*func_map)[canonicalized_name] = + function_modified ? std::make_optional(new_func_name) : std::nullopt; +} + +// Adds new function def to graph's function library if necessary. +absl::Status AddFunctionDefToGraphLibrary( + const std::string& func_name, + const AssociatedFunctionInfo& associated_function, Graph* graph, + FunctionLibraryDefinition* fld) { + const OpRegistrationData* op_reg_data; + // We have to be careful with adding the function def since there are three + // different `OpRegistryInterface`s involved here: + // `fld`, `graph->flib_def()` and `graph->flib_def().default_registry()`. + // We have already added the function def to `fld` before calling this + // function but for the subsequent `RewriteAssociatedFunction` call we need + // the function def to be in one of the other two registries, otherwise + // `RewriteAssociatedFunction` will fail for the `kFunctionCallNode` case + // because it cannot find the associated function def. + // On the other hand, we should not add the function def if it is already + // contained in one of the last two registries, this would lead to errors when + // the function def is already in one registry and we try to add it to the + // other one (if we try to add it to the same it's fine). This can happen in + // cases where one of the last two registries is identical to `fld` (which we + // already updated). + // Therefore, before adding the function def we have to check if it's already + // contained in either `graph->flib_def()` or + // `graph->flib_def().default_registry()` which is done in the following line + // (we have to use `LookUp` instead of `Contains` or `Find` because the latter + // both don't check the default registry). + if (graph->flib_def().LookUp(func_name, &op_reg_data).ok()) + return absl::OkStatus(); + + const FunctionDef* new_fdef = fld->Find(func_name); + DCHECK(new_fdef != nullptr); + FunctionDefLibrary fdef_lib; + *(fdef_lib.add_function()) = *new_fdef; + return graph->AddFunctionLibrary(fdef_lib); +} + +// Functionalizes function given by `func_name`. Update `func_map` accordingly. +absl::Status FunctionalizeControlFlowForFunction( + const std::string& func_name, const std::string& new_func_name, + const protobuf::Map& attrs, + FunctionLibraryDefinition* fld, FunctionLibraryRuntime* flr, + FuncMap* func_map, bool* function_modified, + const NodeFilter& node_filter = {}); + +// Functionalizes all functions that are (directly or indirectly) associated to +// any node in `graph`. Adds processed functions to `func_map`. +absl::Status FunctionalizeControlFlowForNodeAssociatedFunctions( + FuncMap* func_map, Graph* graph, FunctionLibraryDefinition* fld, + FunctionLibraryRuntime* flr, bool* any_function_modified, + const NodeFilter& node_filter) { + std::vector>> + nodes_to_associated_functions; + for (auto* n : graph->nodes()) { + auto associated_functions = GetAssociatedFunctions(*n, fld); + if (!associated_functions.empty()) { + nodes_to_associated_functions.push_back({n, associated_functions}); + } + } + for (const auto& pair : nodes_to_associated_functions) { + Node* n = pair.first; + auto associated_functions = pair.second; + for (auto& associated_function : associated_functions) { + // Note that if `n` is a function call node, then potential calls of + // `RewriteAssociatedFunction` below might delete `n` and create a new + // node instead, making `n` an invalid pointer. That's fine because in + // that case `n` only has one associated function, so this loop has only + // one iteration and we don't use `n` again after the rewrite. + // The invariant is guaranteed by `GetAssociatedFunctions` and confirmed + // below. + DCHECK(associated_function.type() != + AssociatedFunctionInfo::kFunctionCallNode || + associated_functions.size() == 1); + + // Process one node-function-pair. + std::string func_name = associated_function.func_name(); + std::string canonicalized_name = + Canonicalize(func_name, AttrSlice(&associated_function.attrs())); + auto func_iter = func_map->find(canonicalized_name); + std::string new_func_name; + if (FunctionHasBeenProcessed(func_iter, func_map)) { + if (FunctionHasBeenModified(func_iter)) { + *any_function_modified = true; + new_func_name = GetMappedFunctionName(func_iter); + TF_RETURN_IF_ERROR(RewriteAssociatedFunction( + graph, n, fld, associated_function, new_func_name)); + } + continue; + } + // Function is processed for the first time. + bool function_modified = false; + new_func_name = + GetNewFunctionName(func_name, n, associated_function.type(), fld); + // Perform functionalization for current function. + TF_RETURN_IF_ERROR(FunctionalizeControlFlowForFunction( + func_name, new_func_name, associated_function.attrs(), fld, flr, + func_map, &function_modified, node_filter)); + UpdateFunctionMap(func_map, canonicalized_name, new_func_name, + function_modified); + if (function_modified) { + *any_function_modified = true; + TF_RETURN_IF_ERROR(AddFunctionDefToGraphLibrary( + new_func_name, associated_function, graph, fld)); + TF_RETURN_IF_ERROR(RewriteAssociatedFunction( + graph, n, fld, associated_function, new_func_name)); + } + } + } + return absl::OkStatus(); +} + +absl::Status FunctionalizeControlFlowForFunction( + const std::string& func_name, const std::string& new_func_name, + const protobuf::Map& attrs, + FunctionLibraryDefinition* fld, FunctionLibraryRuntime* flr, + FuncMap* func_map, bool* function_modified, const NodeFilter& node_filter) { + *function_modified = false; + + // Convert the function to a graph. + FunctionLibraryRuntime::Handle handle; + TF_RETURN_IF_ERROR(flr->Instantiate(func_name, AttrSlice(&attrs), &handle)); + absl::Status ret_status = absl::OkStatus(); + auto cleanup_handle = gtl::MakeCleanup([&]() { + auto s = flr->ReleaseHandle(handle); + if (!s.ok()) { + ret_status.Update(s); + } + }); + const FunctionBody* body = flr->GetFunctionBody(handle); + Graph* g = body->graph; + + // Check if the graph has Switch or Merge node. + bool has_switch_or_merge = false; + for (Node* n : body->graph->nodes()) { + // Skip nodes that are filtered out. + if (node_filter && !node_filter(n)) continue; + if (n->type_string() == "Switch" || n->type_string() == "Merge") { + has_switch_or_merge = true; + break; + } + } + // Before functionalizing control flow in `g` we functionalize control flow + // in functions (directly or indirectly) associated with nodes in `g`. + TF_RETURN_IF_ERROR(FunctionalizeControlFlowForNodeAssociatedFunctions( + func_map, g, fld, flr, function_modified, node_filter)); + + if (has_switch_or_merge) { + *function_modified = true; + + // Functionalize the function body. + if (VLOG_IS_ON(4)) { + DumpGraphToFile( + absl::StrCat("functionalize_control_flow_before_fdef_", func_name), + *g, fld); + } + TF_RETURN_IF_ERROR(FunctionalizeControlFlow(g, fld, node_filter)); + if (VLOG_IS_ON(4)) { + DumpGraphToFile( + absl::StrCat("functionalize_control_flow_after_fdef_", func_name), *g, + fld); + } + } + if (*function_modified) { + // Add rewritten FunctionDef into library. + FunctionDef functionalized_fdef; + TF_RETURN_IF_ERROR( + GraphToFunctionDef(*g, new_func_name, &functionalized_fdef)); + if (func_name == new_func_name) { + VLOG(2) << "Replacing function " << func_name; + TF_RETURN_IF_ERROR( + fld->ReplaceFunction(new_func_name, functionalized_fdef)); + } else { + VLOG(2) << "Adding function " << new_func_name; + TF_RETURN_IF_ERROR(fld->AddFunctionDef(functionalized_fdef)); + } + } + + return ret_status; +} + +absl::Status FunctionalizeControlFlow(Graph* graph, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter, + bool include_functions) { + VLOG(2) << "FunctionalizeControlFlow (initial): " + << DumpGraphToFile("functionalize_initial", *graph, library); + + if (include_functions) { + // Functionalize control flow in functions that are (directly or indirectly) + // associated with a node in `graph`. + auto pflr = std::make_unique( + /*device_mgr=*/nullptr, tensorflow::Env::Default(), + /*config=*/nullptr, TF_GRAPH_DEF_VERSION, library, + tensorflow::OptimizerOptions()); + // `pflr` has only one `FunctionLibraryRuntime`, for `kDefaultFLRDevice` + // (because we constructed it with `device_mgr = nullptr`). + FunctionLibraryRuntime* flr = + pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); + + FuncMap func_map; + bool modified = false; + TF_RETURN_IF_ERROR(FunctionalizeControlFlowForNodeAssociatedFunctions( + &func_map, graph, library, flr, &modified, node_filter)); + } + // Functionalize and remove while loops from graph. + TF_RETURN_IF_ERROR(FunctionalizeWhileLoop(graph, library, node_filter)); + + // 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(graph, library, node_filter)); + + VLOG(2) << "FunctionalizeControlFlow (final): " + << DumpGraphToFile("functionalize_final", *graph, library); + + return absl::OkStatus(); +} + +absl::Status FunctionalizeControlFlowForGraphDef( + GraphDef* graph_def, FunctionLibraryDefinition* library, + const NodeFilter& node_filter, bool include_functions) { + FunctionDefLibrary function_lib = graph_def->library(); + Graph graph(OpRegistry::Global()); + + TF_RETURN_IF_ERROR(ConvertGraphDefToGraph({}, *graph_def, &graph)); + TF_RETURN_IF_ERROR(FunctionalizeControlFlow(&graph, library, node_filter, + include_functions)); + graph.ToGraphDef(graph_def); + std::swap(*graph_def->mutable_library(), function_lib); + return absl::OkStatus(); +} + +absl::Status FunctionalizeControlFlowForXlaPass::Run( + const GraphOptimizationPassOptions& options) { + Graph* graph = options.graph->get(); + if (VLOG_IS_ON(4)) { + DumpGraphToFile("functionalize_control_flow_before", *graph, + options.flib_def); + } + const auto* config = &options.session_options->config; + std::unique_ptr pflr( + new ProcessFunctionLibraryRuntime( + /*device_mgr=*/nullptr, options.session_options->env, config, + TF_GRAPH_DEF_VERSION, options.flib_def, + config->graph_options().optimizer_options())); + FunctionLibraryRuntime* flr = + pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); + + // Find XLA compile ops and its corresponding FunctionDef. + // TPUCompile op is not in the map because graph rewriting might happen + // multiple times, and we want to avoid functionalize it again. + static std::map* kNodeTypeToFunctionAttrMapping = + new std::map{ + // _TPUReplicate ops are generated by EncapsulateTPUComputationsPass. + {"_TPUReplicate", "computation"}, + // XlaLaunch ops are generated by EncapsulateXlaComputationsPass. + {"XlaLaunch", "function"}, + }; + FuncMap func_map; + bool fld_modified = false; + for (Node* n : graph->nodes()) { + auto it = kNodeTypeToFunctionAttrMapping->find(n->type_string()); + if (it == kNodeTypeToFunctionAttrMapping->end()) { + continue; + } + const std::string func_attr = it->second; + NameAttrList func; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), func_attr, &func)); + VLOG(2) << "Graph has node " << n->type_string() + << ". Corresponding function: " << func.name(); + std::string new_func_name = options.flib_def->UniqueFunctionName( + absl::StrCat(func.name(), "_f15n_")); + bool modified; + TF_RETURN_IF_ERROR(FunctionalizeControlFlowForFunction( + func.name(), new_func_name, func.attr(), options.flib_def, flr, + &func_map, &modified)); + if (modified) { + n->ClearAttr(func_attr); + func.set_name(new_func_name); + n->AddAttr(func_attr, func); + fld_modified = true; + } + } + + // TODO(ylc, endlessroad): Change this to "if (fld_modified")" + if (false) { + if (VLOG_IS_ON(4)) { + DumpGraphToFile("functionalize_control_flow_before_prune", *graph, + options.flib_def); + } + TF_RETURN_IF_ERROR( + PruneUnreachableFunctionsFromGraph(*graph, options.flib_def)); + } + + if (VLOG_IS_ON(4)) { + DumpGraphToFile("functionalize_control_flow_after", *graph, + options.flib_def); + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow.h new file mode 100644 index 0000000000000000000000000000000000000000..85bc9fd6cad341f83f11999488f331b1aaf334f2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow.h @@ -0,0 +1,76 @@ +/* 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_H_ +#define TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_H_ + +#include "tensorflow/compiler/tf2xla/functionalize_control_flow_util.h" +#include "xla/status_macros.h" +#include "tensorflow/core/common_runtime/optimization_registry.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { + +const char kFunctionalizeControlFlowFailureMessage[] = + "Failed to functionalize Control Flow V1 ops. Consider using Control " + "Flow V2 ops instead. See " + "https://www.tensorflow.org/api_docs/python/tf/" + "compat/v1/enable_control_flow_v2."; + +// Transformation that converts tf.while_loop() loops into functional While +// operators and tf.cond() conditionals into function If operators, suitable for +// XLA compilation. +// +// If `node_filter` is defined, then only loops and conditions for whose +// nodes `node_filter` returns true are functionalized. + +// If `include_functions` is true, then loops and conditions inside of functions +// that are associated with nodes in `graph` (e.g., a function called from a +// node in `graph`) are also functionalized, otherwise they are not. +// This also handles transitive cases, e.g., a function body will be +// functionalized when it is called in another function that is called by some +// node in `graph` (and so on). The node filter also applies here. +// +// Precondition: +// For any node in a loop or condition for which `node_filter` returns true, +// all nodes inside of the same loop or condition must also return true +// (including nodes in other nested loops and conditions inside of that loop or +// condition). +// This means that a "not to be functionalized" loop or condition is not allowed +// inside a "to be functionalized" loop or condition. +// +// The user of this function is responsible for using a node filter that +// satisfies the above conditions. +absl::Status FunctionalizeControlFlow(Graph* graph, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter = {}, + bool include_functions = false); + +absl::Status FunctionalizeControlFlowForGraphDef( + GraphDef* graph_def, FunctionLibraryDefinition* library, + const NodeFilter& node_filter = {}, bool include_functions = false); + +// Rewrites the graph by turning V1 control flow structure +// (Switch/Merge/etc.) into V2 control flow structure (If/While), only modifies +// functions that will be executed by XLA. +class FunctionalizeControlFlowForXlaPass : public GraphOptimizationPass { + public: + absl::Status Run(const GraphOptimizationPassOptions& options) override; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_pass_registration.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_pass_registration.cc new file mode 100644 index 0000000000000000000000000000000000000000..09ed29fadd65079b6574efddabe7d05f4da6beec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_pass_registration.cc @@ -0,0 +1,25 @@ +/* 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/tf2xla/functionalize_control_flow.h" + +namespace tensorflow { + +// This pass is required for some AOT backends and all JIT backends, so this +// file exists as a separate lib and will be linked to both AOT and JIT. +REGISTER_OPTIMIZATION(OptimizationPassRegistry::PRE_PLACEMENT, 37, + FunctionalizeControlFlowForXlaPass); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e2c25fc359efac593451d7c29c9a1d1af7d372ec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_test.cc @@ -0,0 +1,1337 @@ +/* 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.h" + +#include + +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/ops/control_flow_ops_internal.h" +#include "tensorflow/cc/ops/function_ops.h" +#include "tensorflow/cc/ops/functional_ops.h" +#include "tensorflow/cc/ops/resource_variable_ops.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/compiler/tf2xla/cc/ops/xla_ops.h" +#include "tensorflow/compiler/tf2xla/test_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "xla/status_macros.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/graph/graph_def_builder.h" +#include "tensorflow/core/graph/validate.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/public/version.h" +#include "tensorflow/core/util/dump_graph.h" +#include "tensorflow/core/util/equal_graph_def.h" + +namespace tensorflow { +namespace { + +// Returns the names of the "then" and "else" functions for the If node in a +// graph. +absl::Status FindIfThenAndElse(const GraphDef& graph, std::string* op_name, + NameAttrList* then_fn, NameAttrList* else_fn) { + for (const NodeDef& node : graph.node()) { + if (node.op() == "If") { + *op_name = node.name(); + const NameAttrList* result; + TF_RETURN_IF_ERROR(GetNodeAttr(node, "then_branch", &result)); + *then_fn = *result; + TF_RETURN_IF_ERROR(GetNodeAttr(node, "else_branch", &result)); + *else_fn = *result; + return absl::OkStatus(); + } + } + return absl::NotFoundError("No If node found in graph"); +} + +// Graph: +// x = array_ops.placeholder(dtypes.int32) +// y = array_ops.placeholder(dtypes.int32) +// z = cond.cond( +// math_ops.less(y, x), lambda: math_ops.multiply(y, 17), +// lambda: math_ops.add(x, 23)) +// +// Tests different node filters and functionalization inside of a function. +class ConditionalTestFixture + : public ::testing::TestWithParam> { + protected: + void SetUp() override { + restrict_to_tpu_nodes_ = std::get<0>(GetParam()); + wrap_condition_in_function_ = std::get<1>(GetParam()); + } + void RunTest(); + + private: + void BuildCondGraph(Graph* cond_graph); + void CheckGraphDef(const GraphDef& graph_def, + const FunctionLibraryDefinition& library); + + bool restrict_to_tpu_nodes_ = false; + bool wrap_condition_in_function_ = false; +}; + +TEST_P(ConditionalTestFixture, ConditionalTests) { RunTest(); } + +INSTANTIATE_TEST_SUITE_P( + FunctionalizeControlFlow, ConditionalTestFixture, + ::testing::Combine(::testing::Bool(), ::testing::Bool()), + [](const ::testing::TestParamInfo& + info) { + bool restrict_to_tpu_nodes = std::get<0>(info.param); + bool wrap_cond_in_function = std::get<1>(info.param); + std::string name = + absl::StrCat(restrict_to_tpu_nodes ? "with_filter" : "without_filter", + wrap_cond_in_function ? "_in_function" : "_in_graph"); + return name; + }); + +void ConditionalTestFixture::BuildCondGraph(Graph* cond_graph) { + { + 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"), less, less); + + auto identity_t = + ops::Identity(scope.WithOpName("cond/Identity"), switch_1.output_true); + auto seventeen = ops::Const( + scope.WithOpName("cond").WithControlDependencies(identity_t), 17); + auto switch_2 = ops::Switch(scope.WithOpName("cond/Switch"), y, less); + auto mul = ops::Multiply(scope.WithOpName("cond/Mul"), switch_2.output_true, + seventeen); + + auto identity_f = + ops::Identity(scope.WithOpName("cond/Identity"), switch_1.output_false); + auto twenty_three = ops::Const( + scope.WithOpName("cond").WithControlDependencies(identity_f), 23); + auto switch_3 = ops::Switch(scope.WithOpName("cond/Switch"), x, less); + auto add = ops::Add(scope.WithOpName("cond/false/add"), + switch_3.output_false, twenty_three); + + auto merge = ops::Merge(scope.WithOpName("cond/Merge"), + std::initializer_list{add, mul}); + + TF_EXPECT_OK(scope.ToGraph(cond_graph)); + + // Set all attributes that need propagation for all nodes. This is to test + // if propagation works. Note that this includes `_tpu_replicate`. + for (Node* n : cond_graph->nodes()) { + std::string dummy_value = "value"; + for (absl::string_view attr_name : kAttrsToPropagate) { + n->AddAttr(std::string(attr_name), dummy_value); + } + } + } +} + +void ConditionalTestFixture::CheckGraphDef( + const GraphDef& graph_def, const FunctionLibraryDefinition& library) { + std::string op_name; + NameAttrList then_fn; + NameAttrList else_fn; + TF_EXPECT_OK(FindIfThenAndElse(graph_def, &op_name, &then_fn, &else_fn)); + InstantiationResultForTest else_result; + TF_EXPECT_OK( + InstantiateFunctionForTest(else_fn.name(), library, &else_result)); + + // Outer graph + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto y = ops::Placeholder(scope.WithOpName("y"), DT_INT32); + auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32); + auto less = ops::Less(scope.WithOpName("cond/Less"), y, x); + auto if_op = + ops::If(scope.WithOpName(op_name), less, + std::initializer_list{less, y, x}, {DT_INT32}, then_fn, + else_fn, ops::If::OutputShapes({PartialTensorShape()})); + auto id = ops::Identity(scope.WithOpName("cond/Merge"), if_op.output[0]); + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + TF_EXPECT_GRAPH_EQ(expected, graph_def); + } + + // then body. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg_0 = ops::_Arg(scope.WithOpName("arg0"), DT_BOOL, 0); + auto arg_1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto arg_2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2); + auto identity = ops::Identity(scope.WithOpName("cond/Identity"), arg_0); + auto cond = ops::Const( + scope.WithOpName("cond").WithControlDependencies(identity), 17); + auto mul = ops::Mul(scope.WithOpName("cond/Mul"), arg_1, cond); + auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), mul, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK(InstantiateFunctionForTest(then_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types); + EXPECT_EQ((DataTypeVector{DT_BOOL, DT_INT32, DT_INT32}), result.arg_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + + // else body. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg_0 = ops::_Arg(scope.WithOpName("arg0"), DT_BOOL, 0); + auto arg_1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto arg_2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2); + auto identity = ops::Identity(scope.WithOpName("cond/Identity_1"), arg_0); + auto cond_1 = ops::Const( + scope.WithOpName("cond_1").WithControlDependencies(identity), 23); + auto add = ops::Add(scope.WithOpName("cond/false/add"), arg_2, cond_1); + auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK(InstantiateFunctionForTest(else_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types); + EXPECT_EQ((DataTypeVector{DT_BOOL, DT_INT32, DT_INT32}), result.arg_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + + // Check that internal attributes were correctly propagated to `If` node + // (such attributes are ignored in the above graph equality check). + for (const NodeDef& node : graph_def.node()) { + if (node.op() == "If") { + for (absl::string_view attr_name : kAttrsToPropagate) { + std::string attr_val; + TF_EXPECT_OK(GetNodeAttr(node, attr_name, &attr_val)); + EXPECT_EQ(attr_val, "value"); + } + } + } + } +} + +void ConditionalTestFixture::RunTest() { + Graph graph(OpRegistry::Global()); + if (wrap_condition_in_function_) { + // Wrap condition in a function which is called from `graph`. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + + Graph cond_graph(OpRegistry::Global()); + BuildCondGraph(&cond_graph); + + FunctionDef cond_fdef; + TF_ASSERT_OK(GraphToFunctionDef(cond_graph, "cond_fn", &cond_fdef)); + + FunctionDefLibrary fdef_lib; + *(fdef_lib.add_function()) = cond_fdef; + TF_ASSERT_OK(scope.graph()->AddFunctionLibrary(fdef_lib)); + NodeDef cond_fn; + cond_fn.set_name("cond_node"); + cond_fn.set_op("cond_fn"); + *(cond_fn.add_input()) = "source"; + absl::Status status; + scope.graph()->AddNode(cond_fn, &status); + TF_ASSERT_OK(status); + TF_ASSERT_OK(scope.ToGraph(&graph)); + } else { + // Build condition in `graph`. + BuildCondGraph(&graph); + } + FunctionLibraryDefinition library(graph.flib_def()); + // If `restrict_to_tpu_nodes_` is true let filter function return true for + // `_tpu_replicate` nodes. + NodeFilter node_filter = + restrict_to_tpu_nodes_ + ? [](const Node* n) { return n->attrs().Find("_tpu_replicate"); } + : NodeFilter{}; + + GraphDef optimized_graph_def; + graph.ToGraphDef(&optimized_graph_def); + TF_ASSERT_OK(FunctionalizeControlFlowForGraphDef( + &optimized_graph_def, &library, node_filter, + /*include_functions=*/wrap_condition_in_function_)); + TF_ASSERT_OK(FunctionalizeControlFlow( + &graph, &library, node_filter, + /*include_functions=*/wrap_condition_in_function_)); + + if (wrap_condition_in_function_) { + // Check if function body was functionalized. + auto pflr = std::make_unique( + /*device_mgr=*/nullptr, tensorflow::Env::Default(), + /*config=*/nullptr, TF_GRAPH_DEF_VERSION, &library, + tensorflow::OptimizerOptions()); + FunctionLibraryRuntime* flr = + pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); + FunctionLibraryRuntime::Handle handle; + + // Functionalized function name is the type string of `cond_node`. + std::string func_name; + for (Node* n : graph.nodes()) { + if (n->name() == "cond_node") { + func_name = n->type_string(); + break; + } + } + TF_ASSERT_OK(flr->Instantiate(func_name, AttrSlice(), &handle)); + const FunctionBody* body = flr->GetFunctionBody(handle); + GraphDef graph_def; + body->graph->ToGraphDef(&graph_def); + CheckGraphDef(graph_def, library); + } else { + // Check if graphs were functionalized. + CheckGraphDef(optimized_graph_def, library); + GraphDef converted_graph_def; + graph.ToGraphDef(&converted_graph_def); + CheckGraphDef(converted_graph_def, library); + } +} + +// Returns the names of the "cond" and "body" functions for the While node +// in a graph. +absl::Status FindWhileCondAndBody(const GraphDef& graph, NameAttrList* cond, + NameAttrList* body) { + for (const NodeDef& node : graph.node()) { + if (node.op() == "While") { + const NameAttrList* result; + TF_RETURN_IF_ERROR(GetNodeAttr(node, "cond", &result)); + *cond = *result; + TF_RETURN_IF_ERROR(GetNodeAttr(node, "body", &result)); + *body = *result; + return absl::OkStatus(); + } + } + return absl::NotFoundError("No While node found in graph"); +} + +// Graph: +// x = array_ops.placeholder(dtypes.int32) +// y = control_flow_ops.while_loop(lambda i: i < 10, lambda i: i + 1, [x]) +TEST(FunctionalizeControlFlow, OneLoopVar) { + Graph graph(OpRegistry::Global()); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + + auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32); + + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto enter = + ops::internal::Enter(scope.WithOpName("while/Enter"), source, "aloop"); + // Add an unused Enter node. These should be ignored. + auto enter2 = + ops::internal::Enter(scope.WithOpName("while/Enter2"), source, "aloop"); + auto merge = ops::Merge(scope.WithOpName("while/Merge"), + std::initializer_list{enter, dummy}); + auto ten = ops::Const( + scope.WithOpName("while/Less/y").WithControlDependencies(merge.output), + 10); + auto less = ops::Less(scope.WithOpName("while/Less"), merge.output, ten); + auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less); + auto switch_ = + ops::Switch(scope.WithOpName("while/Switch"), merge.output, loop_cond); + auto exit = ops::internal::Exit(scope.WithOpName("while/Exit"), + switch_.output_false); + auto identity = + ops::Identity(scope.WithOpName("while/Identity"), switch_.output_true); + auto one = ops::Const( + scope.WithOpName("while/add/y").WithControlDependencies(identity), 1); + auto add = ops::Add(scope.WithOpName("while/add"), identity, one); + auto next_iteration = + ops::NextIteration(scope.WithOpName("while/NextIteration"), add); + + auto sink = ops::Identity(scope.WithOpName("sink"), exit); + + // Remove the dummy node and add the loop backedge. + scope.graph()->RemoveNode(dummy.node()); + scope.graph()->AddEdge(next_iteration.node(), 0, merge.output.node(), 1); + + TF_EXPECT_OK(scope.ToGraph(&graph)); + } + + // Regression test: control edges from an Enter node to the graph sink should + // be ignored. + for (Node* n : graph.nodes()) { + if (n->name() == "while/Enter") { + graph.AddControlEdge(n, graph.sink_node()); + } + } + + FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary()); + GraphDef optimized_graph_def; + graph.ToGraphDef(&optimized_graph_def); + TF_ASSERT_OK( + FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library)); + TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library)); + GraphDef converted_graph_def; + graph.ToGraphDef(&converted_graph_def); + + for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) { + NameAttrList cond_fn, body_fn; + TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn)); + + // Outer graph + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto while_op = + ops::While(scope.WithOpName("while/LoopCond"), + std::initializer_list{source}, cond_fn, body_fn); + auto sink = ops::Identity(scope.WithOpName("sink"), while_op[0]); + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + TF_EXPECT_GRAPH_EQ(expected, graph_def); + } + + // Condition graph + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto ten = ops::Const( + scope.WithOpName("while/Less/y").WithControlDependencies(arg), 10); + auto less = ops::Less(scope.WithOpName("while/Less"), arg, ten); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(cond_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types); + EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + + // Body graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto identity = ops::Identity(scope.WithOpName("while/Identity"), arg); + auto one = ops::Const( + scope.WithOpName("while/add/y").WithControlDependencies(identity), 1); + auto add = ops::Add(scope.WithOpName("while/add"), identity, one); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(body_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types); + EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + } +} + +FunctionDef GetNoinlineFunctionDef() { + FunctionDef fdef = FunctionDefHelper::Create( + "increment_fn", {"x:int32"}, {"add:int32"}, {}, + { + {{"add/y"}, "Const", {}, {{"dtype", DT_INT32}}}, + {{"add_0"}, "Add", {"x", "add/y:output:0"}, {{"T", DT_INT32}}}, + }, + {{"add", "add_0:z:0"}}); + (*fdef.mutable_attr())["_noinline"].set_b(true); + return fdef; +} + +// @function.Defun(noinline=True) +// def increment_fn(x): +// return [x + 1] +// Define the above function, and add it to the given graph. It's used as the +// while loop body in NoinlineLoopBody test. +absl::Status AddNoinlineFunctionToGraph(const std::string& node_name, + Graph* graph) { + FunctionDefLibrary fdef_lib; + *(fdef_lib.add_function()) = GetNoinlineFunctionDef(); + TF_RETURN_IF_ERROR(graph->AddFunctionLibrary(fdef_lib)); + NodeDef increment_fn; + increment_fn.set_name(node_name); + increment_fn.set_op("increment_fn"); + *increment_fn.add_input() = "while/Identity"; + *increment_fn.add_input() = "^while/Identity"; + absl::Status status; + graph->AddNode(increment_fn, &status); + return status; +} + +// Graph: +// x = array_ops.placeholder(dtypes.int32) +// y = control_flow_ops.while_loop(lambda i: i < 10, increment_fn, [x]) +TEST(FunctionalizeControlFlow, NoinlineLoopBody) { + const std::string& noinline_node_name = "while/increment_fn"; + Graph graph(OpRegistry::Global()); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32); + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto enter = ops::internal::Enter(scope.WithOpName("while/Enter"), source, + "while/while_context"); + auto merge = ops::Merge(scope.WithOpName("while/Merge"), + std::initializer_list{enter, dummy}); + auto ten = ops::Const( + scope.WithOpName("while/Less/y").WithControlDependencies(merge.output), + 10); + auto less = ops::Less(scope.WithOpName("while/Less"), merge.output, ten); + auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less); + auto switch_ = + ops::Switch(scope.WithOpName("while/Switch"), merge.output, loop_cond); + auto exit = ops::internal::Exit(scope.WithOpName("while/Exit"), + switch_.output_false); + auto identity = + ops::Identity(scope.WithOpName("while/Identity"), switch_.output_true); + + TF_ASSERT_OK(AddNoinlineFunctionToGraph(noinline_node_name, scope.graph())); + + NodeDef next_iter; + next_iter.set_name("while/NextIteration"); + next_iter.set_op("NextIteration"); + *next_iter.add_input() = noinline_node_name; + (*next_iter.mutable_attr())["T"].set_type(DT_INT32); + + absl::Status status; + Node* n = scope.graph()->AddNode(next_iter, &status); + TF_ASSERT_OK(status); + + // Remove the dummy node and add the loop backedge. + scope.graph()->RemoveNode(dummy.node()); + scope.graph()->AddEdge(n, 0, merge.output.node(), 1); + TF_ASSERT_OK(scope.ToGraph(&graph)); + } + + FunctionLibraryDefinition library(graph.flib_def()); + GraphDef optimized_graph_def; + graph.ToGraphDef(&optimized_graph_def); + + *(optimized_graph_def.mutable_library()->add_function()) = + GetNoinlineFunctionDef(); + + TF_ASSERT_OK( + FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library)); + TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library)); + GraphDef converted_graph_def; + graph.ToGraphDef(&converted_graph_def); + + for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) { + NameAttrList cond_fn, body_fn; + TF_ASSERT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn)); + + // Outer graph + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto while_op = + ops::While(scope.WithOpName("while/LoopCond"), + std::initializer_list{source}, cond_fn, body_fn); + GraphDef expected; + TF_ASSERT_OK(scope.ToGraphDef(&expected)); + TF_EXPECT_GRAPH_EQ(expected, graph_def); + } + + // Body graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + TF_ASSERT_OK( + AddNoinlineFunctionToGraph(noinline_node_name, scope.graph())); + auto identity = ops::Identity(scope.WithOpName("while/Identity"), arg); + NodeDef retval; + retval.set_name("retval0_RetVal"); + retval.set_op(FunctionLibraryDefinition::kRetOp); + *retval.add_input() = noinline_node_name; + (*retval.mutable_attr())["T"].set_type(DT_INT32); + (*retval.mutable_attr())["index"].set_i(0); + absl::Status status; + scope.graph()->AddNode(retval, &status); + TF_ASSERT_OK(status); + + GraphDef expected; + TF_ASSERT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + // Verify that increment_fn has been copied to library. + TF_EXPECT_OK( + InstantiateFunctionForTest(body_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types); + EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types); + // Ignore the function library when comparing the graphs. + expected.clear_library(); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + } +} + +TEST(FunctionalizeControlFlow, MissingFunctionDefInLibrary) { + const std::string& noinline_node_name = "while/increment_fn"; + Graph graph(OpRegistry::Global()); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto identity = ops::Identity(scope.WithOpName("while/Identity"), source); + TF_ASSERT_OK(AddNoinlineFunctionToGraph(noinline_node_name, scope.graph())); + TF_ASSERT_OK(scope.ToGraph(&graph)); + } + + FunctionLibraryDefinition library(graph.flib_def()); + GraphDef graph_def; + graph.ToGraphDef(&graph_def); + graph_def.clear_library(); + + absl::Status status = + FunctionalizeControlFlowForGraphDef(&graph_def, &library); + EXPECT_EQ(tensorflow::error::NOT_FOUND, status.code()); +} + +// Tests functionalizing OneLoopVar where the loop value is not used post the +// loop. +// Graph: +// x = array_ops.placeholder(dtypes.int32) +// control_flow_ops.while_loop(lambda i: i < 10, lambda i: i + 1, [x]) +TEST(FunctionalizeControlFlow, OneLoopVarWithoutExit) { + Graph graph(OpRegistry::Global()); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + + auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32); + + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto enter = + ops::internal::Enter(scope.WithOpName("while/Enter"), source, "aloop"); + auto merge = ops::Merge(scope.WithOpName("while/Merge"), + std::initializer_list{enter, dummy}); + auto ten = ops::Const( + scope.WithOpName("while/Less/y").WithControlDependencies(merge.output), + 10); + auto less = ops::Less(scope.WithOpName("while/Less"), merge.output, ten); + auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less); + auto switch_ = + ops::Switch(scope.WithOpName("while/Switch"), merge.output, loop_cond); + auto identity = + ops::Identity(scope.WithOpName("while/Identity"), switch_.output_true); + auto one = ops::Const( + scope.WithOpName("while/add/y").WithControlDependencies(identity), 1); + auto add = ops::Add(scope.WithOpName("while/add"), identity, one); + auto next_iteration = + ops::NextIteration(scope.WithOpName("while/NextIteration"), add); + + // Remove the dummy node and add the loop backedge. + scope.graph()->RemoveNode(dummy.node()); + scope.graph()->AddEdge(next_iteration.node(), 0, merge.output.node(), 1); + + TF_EXPECT_OK(scope.ToGraph(&graph)); + } + + FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary()); + GraphDef optimized_graph_def; + graph.ToGraphDef(&optimized_graph_def); + TF_ASSERT_OK( + FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library)); + TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library)); + GraphDef converted_graph_def; + graph.ToGraphDef(&converted_graph_def); + + for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) { + NameAttrList cond_fn, body_fn; + TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn)); + + // Outer graph + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto source = ops::Placeholder(scope.WithOpName("source"), DT_INT32); + auto while_op = + ops::While(scope.WithOpName("while/LoopCond"), + std::initializer_list{source}, cond_fn, body_fn); + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + TF_EXPECT_GRAPH_EQ(expected, graph_def); + } + + // Condition graph + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto ten = ops::Const( + scope.WithOpName("while/Less/y").WithControlDependencies(arg), 10); + auto less = ops::Less(scope.WithOpName("while/Less"), arg, ten); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(cond_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types); + EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + + // Body graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto identity = ops::Identity(scope.WithOpName("while/Identity"), arg); + auto one = ops::Const( + scope.WithOpName("while/add/y").WithControlDependencies(identity), 1); + auto add = ops::Add(scope.WithOpName("while/add"), identity, one); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(body_fn.name(), library, &result)); + + EXPECT_EQ(DataTypeVector{DT_INT32}, result.arg_types); + EXPECT_EQ(DataTypeVector{DT_INT32}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + } +} + +// Graph: +// x = array_ops.placeholder(dtypes.int32) +// y = array_ops.placeholder(dtypes.int32) +// cond = lambda (i, j): i + 3 < 10 +// body = lambda (i, j): (i < 10, j * 2) +// z = control_flow_ops.while_loop(cond, body, [x, y]) +TEST(FunctionalizeControlFlow, TwoLoopVars) { + Graph graph(OpRegistry::Global()); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + + auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32); + + auto x = ops::Placeholder(scope.WithOpName("Placeholder/x"), DT_INT32); + auto y = ops::Placeholder(scope.WithOpName("Placeholder/y"), DT_INT32); + auto enter_x = + ops::internal::Enter(scope.WithOpName("while/Enter/x"), x, "aloop"); + auto enter_y = + ops::internal::Enter(scope.WithOpName("while/Enter/y"), y, "aloop"); + auto merge_x = ops::Merge(scope.WithOpName("while/Merge/x"), + std::initializer_list{enter_x, dummy}); + auto merge_y = ops::Merge(scope.WithOpName("while/Merge/y"), + std::initializer_list{enter_y, dummy}); + + // Loop condition + auto three = + ops::Const(scope.WithOpName("while/cond/three") + .WithControlDependencies(merge_x.output), + 3); + auto cond_add = + ops::Add(scope.WithOpName("while/cond/Add"), merge_x.output, three); + auto ten = ops::Const(scope.WithOpName("while/cond/ten") + .WithControlDependencies(merge_x.output), + 10); + auto less = ops::Less(scope.WithOpName("while/cond/Less"), cond_add, ten); + auto loop_cond = ops::LoopCond(scope.WithOpName("while/LoopCond"), less); + + auto switch_x = ops::Switch(scope.WithOpName("while/Switch/x"), + merge_x.output, loop_cond); + auto switch_y = ops::Switch(scope.WithOpName("while/Switch/y"), + merge_y.output, loop_cond); + + auto exit_x = ops::internal::Exit(scope.WithOpName("while/Exit/x"), + switch_x.output_false); + auto exit_y = ops::internal::Exit(scope.WithOpName("while/Exit/y"), + switch_y.output_false); + + auto identity_x = ops::Identity(scope.WithOpName("while/Identity/x"), + switch_x.output_true); + auto identity_y = ops::Identity(scope.WithOpName("while/Identity/y"), + switch_y.output_true); + + auto one = ops::Const( + scope.WithOpName("while/add/one").WithControlDependencies(identity_x), + 1); + auto two = ops::Const( + scope.WithOpName("while/mul/two").WithControlDependencies(identity_x), + 2); + + auto add = ops::Add(scope.WithOpName("while/add"), identity_x, one); + auto mul = ops::Add(scope.WithOpName("while/mul"), identity_y, two); + auto next_iteration_x = + ops::NextIteration(scope.WithOpName("while/NextIteration/x"), add); + auto next_iteration_y = + ops::NextIteration(scope.WithOpName("while/NextIteration/y"), mul); + + auto sink_x = ops::Identity(scope.WithOpName("sink_x"), exit_x); + auto sink_y = ops::Identity(scope.WithOpName("sink_y"), exit_y); + + // Remove the dummy node and add the loop backedges. + scope.graph()->RemoveNode(dummy.node()); + scope.graph()->AddEdge(next_iteration_x.node(), 0, merge_x.output.node(), + 1); + scope.graph()->AddEdge(next_iteration_y.node(), 0, merge_y.output.node(), + 1); + + TF_EXPECT_OK(scope.ToGraph(&graph)); + } + + FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary()); + GraphDef optimized_graph_def; + graph.ToGraphDef(&optimized_graph_def); + TF_ASSERT_OK( + FunctionalizeControlFlowForGraphDef(&optimized_graph_def, &library)); + TF_ASSERT_OK(FunctionalizeControlFlow(&graph, &library)); + GraphDef converted_graph_def; + graph.ToGraphDef(&converted_graph_def); + + for (const GraphDef& graph_def : {optimized_graph_def, converted_graph_def}) { + NameAttrList cond_fn, body_fn; + TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &cond_fn, &body_fn)); + + // Outer graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto x = ops::Placeholder(scope.WithOpName("Placeholder/x"), DT_INT32); + auto y = ops::Placeholder(scope.WithOpName("Placeholder/y"), DT_INT32); + auto while_op = + ops::While(scope.WithOpName("while/LoopCond"), + std::initializer_list{x, y}, cond_fn, body_fn); + auto sink_x = ops::Identity(scope.WithOpName("sink_x"), while_op[0]); + auto sink_y = ops::Identity(scope.WithOpName("sink_y"), while_op[1]); + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + TF_EXPECT_GRAPH_EQ(expected, graph_def); + } + + // Condition graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto three = + ops::Const(scope.WithOpName("while/cond/three") + .WithControlDependencies(arg0.output), + 3); + auto cond_add = + ops::Add(scope.WithOpName("while/cond/Add"), arg0.output, three); + auto ten = ops::Const(scope.WithOpName("while/cond/ten") + .WithControlDependencies(arg0.output), + 10); + auto less = ops::Less(scope.WithOpName("while/cond/Less"), cond_add, ten); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(cond_fn.name(), library, &result)); + + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32}), result.arg_types); + EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + + // Body graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + + auto identity_x = + ops::Identity(scope.WithOpName("while/Identity/x"), arg0); + auto identity_y = + ops::Identity(scope.WithOpName("while/Identity/y"), arg1); + + auto one = ops::Const( + scope.WithOpName("while/add/one").WithControlDependencies(identity_x), + 1); + auto two = ops::Const( + scope.WithOpName("while/mul/two").WithControlDependencies(identity_x), + 2); + + auto add = ops::Add(scope.WithOpName("while/add"), identity_x, one); + auto mul = ops::Add(scope.WithOpName("while/mul"), identity_y, two); + auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add, 0); + auto retval1 = ops::_Retval(scope.WithOpName("retval1_RetVal"), mul, 1); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(body_fn.name(), library, &result)); + + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32}), result.arg_types); + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32}), result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + } +} + +// More complex example with nesting, loop-invariant arguments, and resource +// variables. Used for multiple tests with different node filters. +class ComplexTestFixture + : public ::testing::TestWithParam> { + protected: + void SetUp() override { + restrict_to_tpu_nodes_ = std::get<0>(GetParam()); + mark_inner_loop_tpu_ = std::get<1>(GetParam()); + mark_outer_loop_tpu_ = std::get<2>(GetParam()); + } + void RunTest(); + + private: + void CheckOuterNodesFunctionalized(const GraphDef& graph_def, + const FunctionLibraryDefinition& library, + NameAttrList& inner_cond_fn, + NameAttrList& inner_body_fn); + void CheckInnerNodesFunctionalized(const GraphDef& graph_def, + const FunctionLibraryDefinition& library, + const NameAttrList& inner_cond_fn, + const NameAttrList& inner_body_fn); + + bool restrict_to_tpu_nodes_ = false; + bool mark_inner_loop_tpu_ = false; + bool mark_outer_loop_tpu_ = false; +}; + +TEST_P(ComplexTestFixture, ComplexTests) { RunTest(); } + +INSTANTIATE_TEST_SUITE_P( + FunctionalizeControlFlow, ComplexTestFixture, + ::testing::Combine(::testing::Bool(), ::testing::Bool(), ::testing::Bool()), + [](const ::testing::TestParamInfo& info) { + bool restrict_to_tpu_nodes = std::get<0>(info.param); + bool mark_inner_loop_tpu = std::get<1>(info.param); + bool mark_outer_loop_tpu = std::get<2>(info.param); + + std::string node_string; + if (mark_inner_loop_tpu && mark_outer_loop_tpu) + node_string = "both_loops_tpu"; + else if (!mark_inner_loop_tpu && !mark_outer_loop_tpu) + node_string = "no_loop_tpu"; + else + node_string = mark_inner_loop_tpu ? "inner_loop_tpu" : "outer_loop_tpu"; + + std::string name = absl::StrCat( + restrict_to_tpu_nodes ? "restricted_" : "unrestricted_", node_string); + return name; + }); + +void ComplexTestFixture::RunTest() { + // Graph: + // + // accum = resource_variable_ops.ResourceVariable(1) + // x = array_ops.placeholder(2, dtype=dtypes.int32) + // y = 3 + x + // + // def inner_body(j, k): + // add = state_ops.assign_add(accum, k * j + x) + // with ops.control_dependencies([add]): + // return [j + 1, k] + // + // def body(i): + // m = control_flow_ops.while_loop(lambda j, k: j < 5, inner_body, + // [1, y], name="inner") + // with ops.control_dependencies(m): + // return [i + 1] + // + // z = control_flow_ops.while_loop(lambda i: i < 10, body, [0], name="outer") + Graph graph(OpRegistry::Global()); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + + auto dummy = ops::Placeholder(scope.WithOpName("Dummy"), DT_INT32); + + auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32); + auto three = ops::Const(scope.WithOpName("three"), 3); + auto y = ops::Add(scope.WithOpName("y"), x, three); + + auto var = ops::VarHandleOp(scope.WithOpName("Variable"), DT_INT32, + TensorShape({})); + + // Outer loop + auto zero = ops::Const(scope.WithOpName("outer/Const"), 0); + auto enter_i = + ops::internal::Enter(scope.WithOpName("outer/Enter_i"), zero, "outer"); + auto merge_i = ops::Merge(scope.WithOpName("outer/Merge_i"), + std::initializer_list{enter_i, dummy}); + auto ten = ops::Const(scope.WithOpName("outer/Less/y") + .WithControlDependencies(merge_i.output), + 10); + auto less_i = + ops::Less(scope.WithOpName("outer/Less_i"), merge_i.output, ten); + auto outer_loop_cond = + ops::LoopCond(scope.WithOpName("outer/LoopCond"), less_i); + auto switch_i = ops::Switch(scope.WithOpName("outer/Switch"), + merge_i.output, outer_loop_cond); + auto exit_i = ops::internal::Exit(scope.WithOpName("outer/Exit"), + switch_i.output_false); + auto identity_i = + ops::Identity(scope.WithOpName("outer/Identity"), switch_i.output_true); + + auto enter_x_outer = + ops::internal::Enter(scope.WithOpName("outer/Enter_x"), x, "outer", + ops::internal::Enter::Attrs().IsConstant(true)); + auto enter_k_outer = + ops::internal::Enter(scope.WithOpName("outer/Enter_k"), y, "outer", + ops::internal::Enter::Attrs().IsConstant(true)); + auto enter_var_outer = + ops::internal::Enter(scope.WithOpName("outer/Enter_var"), var, "outer", + ops::internal::Enter::Attrs().IsConstant(true)); + + // Inner loop + auto one_j = ops::Const( + scope.WithOpName("outer/j").WithControlDependencies(identity_i), 1); + auto enter_j = ops::internal::Enter(scope.WithOpName("outer/inner/Enter_j"), + one_j, "inner"); + auto enter_k = + ops::internal::Enter(scope.WithOpName("outer/inner/Enter_k") + .WithControlDependencies(identity_i), + enter_k_outer, "inner"); + auto enter_x = ops::internal::Enter( + scope.WithOpName("outer/inner/Enter_x"), enter_x_outer, "inner", + ops::internal::Enter::Attrs().IsConstant(true)); + auto enter_var = ops::internal::Enter( + scope.WithOpName("outer/inner/Enter_var"), enter_var_outer, "inner", + ops::internal::Enter::Attrs().IsConstant(true)); + + auto merge_j = ops::Merge(scope.WithOpName("outer/inner/Merge_j"), + std::initializer_list{enter_j, dummy}); + auto merge_k = ops::Merge(scope.WithOpName("outer/inner/Merge_k"), + std::initializer_list{enter_k, dummy}); + + auto five = + ops::Const(scope.WithOpName("outer/inner/Five") + .WithControlDependencies(merge_j.output), + 5); + auto less_j = + ops::Less(scope.WithOpName("outer/inner/Less_j"), merge_j.output, five); + auto loop_cond = + ops::LoopCond(scope.WithOpName("outer/inner/LoopCond"), less_j); + + auto switch_j = ops::Switch(scope.WithOpName("outer/inner/Switch_j"), + merge_j.output, loop_cond); + auto switch_k = ops::Switch(scope.WithOpName("outer/inner/Switch_k"), + merge_k.output, loop_cond); + auto exit_j = ops::internal::Exit(scope.WithOpName("outer/inner/Exit_j"), + switch_j.output_false); + auto exit_k = ops::internal::Exit(scope.WithOpName("outer/inner/Exit_k"), + switch_k.output_false); + auto identity_j = ops::Identity(scope.WithOpName("outer/inner/Identity_j"), + switch_j.output_true); + auto identity_k = ops::Identity(scope.WithOpName("outer/inner/Identity_k"), + switch_k.output_true); + + // Variable update + auto mul_jk = + ops::Mul(scope.WithOpName("outer/inner/mul"), identity_j, identity_k); + auto add_jkx = + ops::Add(scope.WithOpName("outer/inner/add"), mul_jk, enter_x); + auto assign = ops::AssignAddVariableOp( + scope.WithOpName("outer/inner/assign_add"), enter_var, add_jkx); + + auto one = ops::Const( + scope.WithOpName("outer/inner/One") + .WithControlDependencies( + absl::Span{assign.operation}), + 1); + auto add_j = + ops::Add(scope.WithOpName("outer/inner/add_j"), identity_j, one); + + auto next_iteration_j = ops::NextIteration( + scope.WithOpName("outer/inner/NextIteration_j"), add_j); + auto next_iteration_k = ops::NextIteration( + scope.WithOpName("outer/inner/NextIteration_k"), identity_k); + + // Body and backedge for outer loop. + auto one_outer = ops::Const( + scope.WithOpName("outer/add/y").WithControlDependencies(identity_i), 1); + auto add_i = + ops::Add(scope.WithOpName("outer/add") + .WithControlDependencies(absl::Span{ + exit_j.output.op(), exit_k.output.op()}), + identity_i, one_outer); + auto next_iteration_i = + ops::NextIteration(scope.WithOpName("outer/NextIteration"), add_i); + + auto sink = ops::Identity(scope.WithOpName("sink"), exit_i); + + // Remove the dummy node and add the loop backedge. + scope.graph()->RemoveNode(dummy.node()); + scope.graph()->AddEdge(next_iteration_i.node(), 0, merge_i.output.node(), + 1); + scope.graph()->AddEdge(next_iteration_j.node(), 0, merge_j.output.node(), + 1); + scope.graph()->AddEdge(next_iteration_k.node(), 0, merge_k.output.node(), + 1); + + TF_EXPECT_OK(scope.ToGraph(&graph)); + } + // Add '_tpu_replicate' attributes as specified. + for (Node* n : graph.nodes()) { + std::string name = n->name(); + bool is_inner_node = name.find("outer/inner/") != std::string::npos; + bool is_outer_node = + !is_inner_node && name.find("outer/") != std::string::npos; + if ((is_inner_node && mark_inner_loop_tpu_) || + (is_outer_node && mark_outer_loop_tpu_)) { + n->AddAttr("_tpu_replicate", "cluster"); + } + } + + FunctionLibraryDefinition library(OpRegistry::Global(), FunctionDefLibrary()); + GraphDef orig_graph_def, optimized_graph_def; + graph.ToGraphDef(&orig_graph_def); + optimized_graph_def = orig_graph_def; + // If `restrict_to_tpu_nodes_` is true let filter function return true for + // `_tpu_replicate` nodes, otherwise don't set filter. + NodeFilter node_filter = + restrict_to_tpu_nodes_ + ? [](const Node* n) { return n->attrs().Find("_tpu_replicate"); } + : NodeFilter{}; + + absl::Status status1 = FunctionalizeControlFlowForGraphDef( + &optimized_graph_def, &library, node_filter); + absl::Status status2 = + FunctionalizeControlFlow(&graph, &library, node_filter); + ASSERT_EQ(status1, status2); + if (restrict_to_tpu_nodes_ && mark_outer_loop_tpu_ && !mark_inner_loop_tpu_) { + // This case violates the precondition of `FunctionalizeControlFlow`, we + // expect an internal error. + ASSERT_EQ(absl::IsInternal(status1), true); + return; + } else { + // Supported cases, no error expected. + TF_ASSERT_OK(status1); + } + + GraphDef optimized_converted_graph_def; + graph.ToGraphDef(&optimized_converted_graph_def); + for (const GraphDef& graph_def : + {optimized_graph_def, optimized_converted_graph_def}) { + NameAttrList inner_cond_fn, inner_body_fn; + if (!restrict_to_tpu_nodes_ || + (restrict_to_tpu_nodes_ && mark_outer_loop_tpu_ && + mark_inner_loop_tpu_)) { + // We expect that both inner and outer nodes have been functionalized. + CheckOuterNodesFunctionalized(graph_def, library, inner_cond_fn, + inner_body_fn); + CheckInnerNodesFunctionalized(graph_def, library, inner_cond_fn, + inner_body_fn); + } else /*restrict_to_tpu_nodes_ == true*/ { + if (!mark_outer_loop_tpu_ && !mark_inner_loop_tpu_) { + // Graph has no TPU nodes so we expect no functionalization. + TF_EXPECT_GRAPH_EQ(orig_graph_def, graph_def); + } else if (!mark_outer_loop_tpu_ && mark_inner_loop_tpu_) { + // We expect that only inner nodes have been functionalized. + TF_EXPECT_OK( + FindWhileCondAndBody(graph_def, &inner_cond_fn, &inner_body_fn)); + CheckInnerNodesFunctionalized(graph_def, library, inner_cond_fn, + inner_body_fn); + } + } + } +} + +void ComplexTestFixture::CheckOuterNodesFunctionalized( + const GraphDef& graph_def, const FunctionLibraryDefinition& library, + NameAttrList& inner_cond_fn, NameAttrList& inner_body_fn) { + NameAttrList outer_cond_fn, outer_body_fn; + TF_EXPECT_OK(FindWhileCondAndBody(graph_def, &outer_cond_fn, &outer_body_fn)); + + // Outer graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto x = ops::Placeholder(scope.WithOpName("x"), DT_INT32); + auto three = ops::Const(scope.WithOpName("three"), 3); + auto y = ops::Add(scope.WithOpName("y"), x, three); + + auto var = ops::VarHandleOp(scope.WithOpName("Variable"), DT_INT32, + TensorShape({})); + + auto zero = ops::Const(scope.WithOpName("outer/Const"), 0); + + auto while_op = ops::While(scope.WithOpName("outer/LoopCond"), + std::initializer_list{zero, y, x, var}, + outer_cond_fn, outer_body_fn); + auto sink = ops::Identity(scope.WithOpName("sink"), while_op[0]); + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + TF_EXPECT_GRAPH_EQ(expected, graph_def); + } + + // Outer condition graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2); + auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3); + + auto ten = ops::Const( + scope.WithOpName("outer/Less/y").WithControlDependencies(arg0.output), + 10); + auto less = ops::Less(scope.WithOpName("outer/Less_i"), arg0, ten); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(outer_cond_fn.name(), library, &result)); + + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}), + result.arg_types); + EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + + // Outer body graph. + { + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(outer_body_fn.name(), library, &result)); + + // Find the inner condition and body names. + TF_EXPECT_OK( + FindWhileCondAndBody(result.gdef, &inner_cond_fn, &inner_body_fn)); + + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2); + auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3); + + auto identity_i = ops::Identity(scope.WithOpName("outer/Identity"), arg0); + auto one_j = ops::Const( + scope.WithOpName("outer/j").WithControlDependencies(identity_i), 1); + auto while_op = + ops::While(scope.WithOpName("outer/inner/LoopCond"), + std::initializer_list{one_j, arg1, arg2, arg3}, + inner_cond_fn, inner_body_fn); + + auto one_outer = ops::Const( + scope.WithOpName("outer/add/y").WithControlDependencies(identity_i), 1); + auto add_i = + ops::Add(scope.WithOpName("outer/add") + .WithControlDependencies(absl::Span{ + while_op[0].op(), while_op[1].op()}), + identity_i, one_outer); + + auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add_i, 0); + auto retval1 = ops::_Retval(scope.WithOpName("retval1_RetVal"), arg1, 1); + auto retval2 = ops::_Retval(scope.WithOpName("retval2_RetVal"), arg2, 2); + auto retval3 = ops::_Retval(scope.WithOpName("retval3_RetVal"), arg3, 3); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}), + result.arg_types); + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}), + result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } +} + +void ComplexTestFixture::CheckInnerNodesFunctionalized( + const GraphDef& graph_def, const FunctionLibraryDefinition& library, + const NameAttrList& inner_cond_fn, const NameAttrList& inner_body_fn) { + // Inner condition graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2); + auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3); + + auto five = ops::Const( + scope.WithOpName("outer/inner/Five").WithControlDependencies(arg0), 5); + auto less_j = ops::Less(scope.WithOpName("outer/inner/Less_j"), arg0, five); + auto retval = ops::_Retval(scope.WithOpName("retval0_RetVal"), less_j, 0); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(inner_cond_fn.name(), library, &result)); + + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}), + result.arg_types); + EXPECT_EQ(DataTypeVector{DT_BOOL}, result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } + + // Inner body graph. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_INT32, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_INT32, 2); + auto arg3 = ops::_Arg(scope.WithOpName("arg3"), DT_RESOURCE, 3); + + auto identity_j = + ops::Identity(scope.WithOpName("outer/inner/Identity_j"), arg0); + auto identity_k = + ops::Identity(scope.WithOpName("outer/inner/Identity_k"), arg1); + + auto mul_jk = + ops::Mul(scope.WithOpName("outer/inner/mul"), identity_j, identity_k); + auto add_jkx = ops::Add(scope.WithOpName("outer/inner/add"), mul_jk, arg2); + auto assign = ops::AssignAddVariableOp( + scope.WithOpName("outer/inner/assign_add"), arg3, add_jkx); + + auto one = ops::Const( + scope.WithOpName("outer/inner/One") + .WithControlDependencies( + absl::Span{assign.operation}), + 1); + auto add_j = + ops::Add(scope.WithOpName("outer/inner/add_j"), identity_j, one); + + auto retval0 = ops::_Retval(scope.WithOpName("retval0_RetVal"), add_j, 0); + auto retval1 = + ops::_Retval(scope.WithOpName("retval1_RetVal"), identity_k, 1); + auto retval2 = ops::_Retval(scope.WithOpName("retval2_RetVal"), arg2, 2); + auto retval3 = ops::_Retval(scope.WithOpName("retval3_RetVal"), arg3, 3); + + GraphDef expected; + TF_EXPECT_OK(scope.ToGraphDef(&expected)); + + InstantiationResultForTest result; + TF_EXPECT_OK( + InstantiateFunctionForTest(inner_body_fn.name(), library, &result)); + + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}), + result.arg_types); + EXPECT_EQ((DataTypeVector{DT_INT32, DT_INT32, DT_INT32, DT_RESOURCE}), + result.ret_types); + TF_EXPECT_GRAPH_EQ(expected, result.gdef); + } +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee5d028f2991e2d15342ad23235bd419df5901f1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_util.cc @@ -0,0 +1,106 @@ +/* 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" +#include "tensorflow/core/graph/graph_node_util.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()); +} + +absl::StatusOr BuildRetvalNode(Graph* graph, DataType type, int index) { + const char* const kRetValOp = "_Retval"; + NodeDef ret_def; + ret_def.set_op(kRetValOp); + ret_def.set_name(absl::StrCat(kRetValOp, index)); + AddNodeAttr("T", type, &ret_def); + AddNodeAttr("index", index, &ret_def); + return graph->AddNode(ret_def); +} + +absl::Status ExtractWhileLoopFrames( + const std::vector& cf_info, const Graph* graph, + std::unordered_map* frames, + const NodeFilter& node_filter) { + 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); + + WhileLoopFrame& frame = (*frames)[cf.frame_name]; + WhileLoopFrame* 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)) { + WhileLoopArg 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); + if (node->IsControlFlow() && node_filter && !node_filter(node)) { + frame.should_be_functionalized = false; + } + } + + return absl::OkStatus(); +} + +// Check that the graph has no cycle containing the given node. +absl::Status CheckNodeNotInCycle(const Node* node, const int num_nodes) { + std::vector ready; + ready.push_back(node); + std::vector 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 absl::InternalError( + absl::StrCat("Detected a cycle: ", FormatNodeForError(*node), " (", + node->def().op(), ") feeds into itself.")); + } else if (!visited[out->dst()->id()]) { + ready.push_back(out->dst()); + } + } + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h new file mode 100644 index 0000000000000000000000000000000000000000..73c5bd6bf6725afeaa28ff13ccf792a819f6ffe3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_control_flow_util.h @@ -0,0 +1,111 @@ +/* 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 "absl/strings/str_join.h" +#include "xla/status_macros.h" +#include "tensorflow/core/graph/control_flow.h" +#include "tensorflow/core/graph/graph.h" + +// Utility functions shared between functionalize cond and while +// or used by other graph optimization passes. + +namespace tensorflow { + +using NodeFilter = std::function; + +// Information about a loop argument. +struct WhileLoopArg { + // 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 WhileLoopFrame { + std::string name; + + // Pointer to the parent frame. The root frame has a pointer to itself. + WhileLoopFrame* parent = nullptr; + int num_children = 0; + + // Arguments to this loop. + std::vector 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 nodes; + + // After `ExtractWhileLoopFrames` this is true if for all control flow nodes + // of this frame `node_filter` returns true, i.e., the frame should be + // functionalized, and false otherwise. + bool should_be_functionalized = true; +}; + +// Extracts v1 while loops within a graph and creates a map of +// . +// If `node_filter` is defined, then we keep track of frames that should be +// functionalized according to the filter (see comment for +// `FunctionalizeControlFlow` for more details about node filters). +absl::Status ExtractWhileLoopFrames( + const std::vector& cf_info, const Graph* graph, + std::unordered_map* frames, + const NodeFilter& node_filter = {}); + +// Check that the graph has no cycle containing the given node. +absl::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. +absl::StatusOr AddNodeDefToGraph(const NodeDef& node_def, Graph* graph); + +// Build a retval node of given type and index. +absl::StatusOr BuildRetvalNode(Graph* graph, DataType type, int index); + +// Returns a textual representation of the names of the nodes in the input. +template +std::string NodesToString(const T& nodes) { + return absl::StrCat("{", + absl::StrJoin(nodes, ",", + [](std::string* output, const Node* node) { + absl::StrAppend(output, node->name()); + }), + "}"); +} + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_CONTROL_FLOW_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_while.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_while.cc new file mode 100644 index 0000000000000000000000000000000000000000..7a8f52978c4cf71ef4bff09666ecd0eaa9006685 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_while.cc @@ -0,0 +1,575 @@ +/* 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 +#include +#include +#include +#include + +#include "absl/memory/memory.h" +#include "absl/strings/match.h" +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2xla/frontend_attributes_util.h" +#include "tensorflow/compiler/tf2xla/functionalize_cond.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "xla/status_macros.h" +#include "xla/union_find.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/strings/strcat.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { +namespace { + +// 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. +absl::Status CopySubgraph(const Graph& graph, const WhileLoopFrame* frame, + std::vector stack, + const std::vector& squash_src_outputs, + std::vector* node_map, Graph* output) { + VLOG(3) << "Stack: " << NodesToString(stack); + std::vector 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; + + // Sort "n->in_edges()" to make sure nodes are copied in a deterministic + // order. + std::vector sorted_edges(n->in_edges().begin(), + n->in_edges().end()); + std::sort(sorted_edges.begin(), sorted_edges.end(), + [](const Edge* a, const Edge* b) { + int a_src_output = a->src_output(), + b_src_output = b->src_output(); + absl::string_view a_name(a->src()->name()), + b_name(b->src()->name()); + return std::tie(a_src_output, a_name) < + std::tie(b_src_output, b_name); + }); + for (const Edge* e : sorted_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 absl::InternalError(absl::StrCat( + "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 absl::OkStatus(); +} + +absl::StatusOr BuildArgNode(Graph* graph, DataType type, int index) { + const char* const kArgOp = "_Arg"; + NodeDef arg_def; + NodeDefBuilder builder(absl::StrCat(kArgOp, index), kArgOp); + builder.Attr("T", type); + builder.Attr("index", index); + TF_RETURN_IF_ERROR(builder.Finalize(&arg_def)); + return graph->AddNode(arg_def); +} + +// Builds a graph for the loop condition. +absl::Status BuildLoopCondition(const Graph& graph, WhileLoopFrame* frame, + std::unique_ptr* cond_output) { + VLOG(2) << "Building loop condition for " << frame->name; + *cond_output = std::make_unique(graph.op_registry()); + Graph* output = cond_output->get(); + + // Map from nodes in the original graph to the condition graph. + std::vector node_map(graph.num_node_ids(), nullptr); + std::vector squash_src_outputs(graph.num_node_ids(), false); + + // Build one _Arg node for each Enter node. + for (int i = 0, end = frame->args.size(); i < end; ++i) { + const WhileLoopArg& 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. +absl::Status BuildLoopBody(const Graph& graph, WhileLoopFrame* frame, + DataTypeVector* arg_types, + std::unique_ptr* body_output) { + VLOG(2) << "Building loop body for " << frame->name; + *body_output = std::make_unique(graph.op_registry()); + Graph* output = body_output->get(); + + // Map from nodes in the original graph to the body graph. + std::vector node_map(graph.num_node_ids(), nullptr); + std::vector squash_src_outputs(graph.num_node_ids(), false); + + // Build one _Arg node for each Enter node. + std::vector next_iterations; + next_iterations.reserve(frame->args.size()); + arg_types->reserve(frame->args.size()); + for (int i = 0, end = frame->args.size(); i < end; ++i) { + const WhileLoopArg& 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)); + 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. + if (dtype == DT_RESOURCE) { + // DT_RESOURCE arguments should always be loop-invariant in the graphs + // generated from TF. + return absl::UnimplementedError(absl::StrCat( + "Loop-varying DT_RESOURCE Enter node ", arg.enter->name(), + " is currently not", " supported.")); + } + 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 absl::OkStatus(); +} + +absl::Status FunctionalizeLoop(Graph* graph, WhileLoopFrame* frame, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter) { + if (node_filter && !frame->should_be_functionalized) { + VLOG(2) << "Skipping functionalization for frame " << frame->name + << " because it has control flow nodes that are filtered out by " + "the specified node filter."; + return absl::OkStatus(); + } + VLOG(2) << "Frame " << frame->name << " before: " + << 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 args; + args.reserve(frame->args.size()); + for (const WhileLoopArg& arg : frame->args) { + if (arg.is_loop_invariant) { + args.push_back(arg); + } else { + std::vector edges(arg.enter->out_edges().begin(), + arg.enter->out_edges().end()); + for (int i = 0, end = edges.size(); i < end; ++i) { + if (edges[i]->IsControlEdge() && edges[i]->dst()->IsSink()) { + continue; + } + TF_RET_CHECK(!edges[i]->IsControlEdge()) << edges[i]->src()->name(); + WhileLoopArg 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 WhileLoopArg& a, const WhileLoopArg& b) { + return NodeCmpByNameResourcesLast()(a.enter, b.enter); + }); + + if (frame->loop_cond == nullptr) { + return absl::InvalidArgumentError( + absl::StrCat("Loop ", frame->name, " has no LoopCond node")); + } + + // Find the set of Switch nodes that are successors of the LoopCond. + std::unordered_set 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 (WhileLoopArg& 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 absl::InternalError(absl::StrCat( + "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 absl::InternalError(absl::StrCat( + "Enter node for loop-varying argument ", + FormatNodeForError(*arg.enter), " has zero successors")); + } + arg.merge = enter_merge->dst(); + if (!IsMerge(arg.merge)) { + return absl::InvalidArgumentError(absl::StrCat( + "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 absl::InvalidArgumentError(absl::StrCat( + "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 absl::InvalidArgumentError(absl::StrCat( + "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 absl::InvalidArgumentError( + absl::StrCat("Duplicate Switch successors to ", + FormatNodeForError(*arg.merge))); + } + arg.switch_node = edge->dst(); + } + } + if (arg.switch_node == nullptr) { + return absl::InvalidArgumentError(absl::StrCat( + "Missing Switch successor to ", FormatNodeForError(*arg.merge))); + } + // 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 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 absl::InvalidArgumentError( + absl::StrCat("Duplicate Exit successors to ", + FormatNodeForError(*arg.switch_node))); + } + arg.exit = edge->dst(); + } else { + if (!IsIdentity(edge->dst())) { + return absl::UnimplementedError( + absl::StrCat("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. Notice that we call + // FunctionalizeCond() on cond_graph and body_graph because we might have + // unfunctionalized "if" in cond_graph and body_graph. Functionalize them + // before they are encapsulated in FunctionDef. + std::unique_ptr cond_graph; + TF_RETURN_IF_ERROR(BuildLoopCondition(*graph, frame, &cond_graph)); + FixupSourceAndSinkEdges(cond_graph.get()); + TF_RETURN_IF_ERROR(FunctionalizeCond(cond_graph.get(), library, node_filter)); + DataTypeVector arg_types; + std::unique_ptr body_graph; + TF_RETURN_IF_ERROR(BuildLoopBody(*graph, frame, &arg_types, &body_graph)); + FixupSourceAndSinkEdges(body_graph.get()); + TF_RETURN_IF_ERROR(FunctionalizeCond(body_graph.get(), library, node_filter)); + + VLOG(2) << "Frame " << frame->name << " condition: " + << DumpGraphToFile("loop_condition", *cond_graph, library) + << " body: " << DumpGraphToFile("loop_body", *body_graph); + + NameAttrList cond_name; + cond_name.set_name(library->UniqueFunctionName("_functionalize_cond_")); + NameAttrList body_name; + body_name.set_name(library->UniqueFunctionName("_functionalize_body_")); + 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)); + + // Builds a While operator. + NodeDef while_def; + NodeDefBuilder builder(frame->loop_cond->name(), "While", library); + builder.Attr("T", arg_types); + builder.Attr("cond", cond_name); + builder.Attr("body", body_name); + // Add some internal attributes which need to be propagated. + for (absl::string_view attr_name : kAttrsToPropagate) { + std::string attr_val; + if (GetNodeAttr(frame->loop_cond->def(), attr_name, &attr_val).ok()) { + builder.Attr(attr_name, attr_val); + } + } + std::vector inputs; + for (int i = 0, end = frame->args.size(); i < end; ++i) { + const WhileLoopArg& 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, graph->AddNode(while_def)); + + // Copies edges to the Enter nodes and from the Exit nodes onto the While. + for (int i = 0, end = frame->args.size(); i < end; ++i) { + const WhileLoopArg& 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 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) { + VLOG(2) << "Removing obsolete node " << node->name(); + graph->RemoveNode(node); + } + frame->nodes.clear(); + frame->parent->nodes.insert(while_node); + + VLOG(2) << "Frame " << frame->name << " after: " + << DumpGraphToFile("functionalize_after", *graph, library); + + return absl::OkStatus(); +} +} // namespace + +absl::Status FunctionalizeWhileLoop(Graph* graph, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter) { + // 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 cf_info; + std::vector unreachable_nodes; + TF_RETURN_IF_ERROR(BuildControlFlowInfo(graph, &cf_info, &unreachable_nodes)); + if (!unreachable_nodes.empty()) { + return absl::InvalidArgumentError(absl::StrCat( + "The following nodes are unreachable from the source in the graph: ", + errors::FormatNodeNamesForError(unreachable_nodes))); + } + + // Builds Frames, indexed by name. + std::unordered_map frames; + TF_RETURN_IF_ERROR( + ExtractWhileLoopFrames(cf_info, graph, &frames, node_filter)); + + // Adds frames with no children (i.e., the innermost frames) to a worklist. + std::deque worklist; + for (auto& frame : frames) { + if (frame.second.num_children == 0) { + worklist.push_back(&frame.second); + } + } + + // Eliminate loops from innermost to outermost. Note that the precondition for + // `node_filter` in `FunctionalizeControlFlow` makes sure that this approach + // works. + while (!worklist.empty()) { + WhileLoopFrame* frame = worklist.front(); + worklist.pop_front(); + if (frame->parent == frame) { + // Skip the root frame. + continue; + } + + TF_RETURN_IF_ERROR(FunctionalizeLoop(graph, frame, library, node_filter)); + + // 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); + } + } + + if (!node_filter) { + // There should be no cycle at this point, since while loops have been + // removed from graph. Check that the newly added While nodes don't feed + // into themselves. + for (const Node* node : graph->op_nodes()) { + if (node->def().op() == "While") { + TF_RETURN_WITH_CONTEXT_IF_ERROR( + CheckNodeNotInCycle(node, graph->num_node_ids()), + "Functionalizing loop failed."); + } + } + } + + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_while.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_while.h new file mode 100644 index 0000000000000000000000000000000000000000..c037b1cf48112562346ad845fc49d98bf57f1f65 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/functionalize_while.h @@ -0,0 +1,40 @@ +/* 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/compiler/tf2xla/functionalize_control_flow_util.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. +// +// If `node_filter` is defined, then only loops for whose nodes `node_filter` +// returns true are functionalized. +// +// Preconditions: +// Same as for `FunctionalizeControlFlow` (see comment there). +absl::Status FunctionalizeWhileLoop(Graph* graph, + FunctionLibraryDefinition* library, + const NodeFilter& node_filter = {}); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_FUNCTIONALIZE_WHILE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/fused_batchnorm_reserve_space_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/fused_batchnorm_reserve_space_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..b6ca5ecc3ad614d85525a3cfc7350c938f51f96d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/fused_batchnorm_reserve_space_test.cc @@ -0,0 +1,150 @@ +/* Copyright 2019 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 +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_cat.h" +#include "unsupported/Eigen/CXX11/Tensor" // from @eigen_archive +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/array_ops.h" +#include "tensorflow/cc/ops/const_op.h" +#include "tensorflow/cc/ops/nn_ops.h" +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/public/session.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { +namespace { +absl::Status GetTestDevice(Session* session, std::string* test_device) { + std::vector devices; + TF_RETURN_IF_ERROR(session->ListDevices(&devices)); + + bool found_cpu = absl::c_any_of(devices, [&](const DeviceAttributes& device) { + return device.device_type() == "CPU"; + }); + + bool found_gpu = absl::c_any_of(devices, [&](const DeviceAttributes& device) { + return device.device_type() == "GPU"; + }); + + if (!found_gpu && !found_cpu) { + return absl::InternalError("Expected at least one CPU or GPU!"); + } + + *test_device = found_gpu ? "GPU" : "CPU"; + VLOG(2) << "Using test device " << *test_device; + return absl::OkStatus(); +} + +void FillZeros(Tensor* tensor) { + auto flat = tensor->flat(); + for (int i = 0; i < flat.size(); i++) { + flat.data()[i] = 0.0f; + } +} + +// This tests check that the implementation outputs from FusedBatchnorm +// training, reserve_space_{1|2}, are what we assume them to be in the TF/XLA +// lowering. +// +// If this test starts failing then it doesn't indicate that TF/cudnn have +// violated their contract, but it indicates that we need to update the TF/XLA +// lowering for FusedBatchnorm training to match the new implementation defined +// behavior. +TEST(FusedBatchnormReserveSpaceTest, Test) { + using ::tensorflow::ops::Const; + using ::tensorflow::ops::FusedBatchNorm; + + std::unique_ptr session( + tensorflow::NewSession(tensorflow::SessionOptions{})); + + std::string test_device; + TF_ASSERT_OK(GetTestDevice(session.get(), &test_device)); + + Scope root = tensorflow::Scope::NewRootScope(); + Output input = ops::Placeholder(root.WithOpName("input"), DT_FLOAT); + + Tensor scale_data(DT_FLOAT, TensorShape({10})); + FillZeros(&scale_data); + Output scale = + Const(root.WithOpName("scale"), Input::Initializer(scale_data)); + + Tensor offset_data(DT_FLOAT, TensorShape({10})); + FillZeros(&offset_data); + Output offset = + Const(root.WithOpName("offset"), Input::Initializer(offset_data)); + + Tensor mean_data(DT_FLOAT, TensorShape({0})); + Output mean = Const(root.WithOpName("offset"), Input::Initializer(mean_data)); + + Tensor variance_data(DT_FLOAT, TensorShape({0})); + Output variance = + Const(root.WithOpName("variance"), Input::Initializer(variance_data)); + + std::string tf_device = absl::StrCat("/device:", test_device, ":0"); + std::string xla_device = absl::StrCat("/device:XLA_", test_device, ":0"); + + FusedBatchNorm fused_batch_norm_tf( + root.WithOpName("fused_batch_norm_tf").WithDevice(tf_device), input, + scale, offset, mean, variance, FusedBatchNorm::Attrs{}.IsTraining(true)); + FusedBatchNorm fused_batch_norm_xla( + root.WithOpName("fused_batch_norm_xla").WithDevice(xla_device), input, + scale, offset, mean, variance, FusedBatchNorm::Attrs{}.IsTraining(true)); + + tensorflow::GraphDef graph; + TF_ASSERT_OK(root.ToGraphDef(&graph)); + + TF_ASSERT_OK(session->Create(graph)); + + Tensor input_data(DT_FLOAT, TensorShape({10, 10, 10, 10})); + auto flat_input = input_data.flat(); + for (int i = 0; i < flat_input.size(); i++) { + flat_input.data()[i] = (i - 5) / 1000.0f; + } + + std::vector results; + TF_ASSERT_OK(session->Run({{"input", input_data}}, + {fused_batch_norm_tf.reserve_space_1.name(), + fused_batch_norm_xla.reserve_space_1.name(), + fused_batch_norm_tf.reserve_space_2.name(), + fused_batch_norm_xla.reserve_space_2.name()}, + {}, &results)); + + test::ExpectClose(results[0], results[1], /*atol=*/1e-4); + test::ExpectClose(results[2], results[3], /*atol=*/1e-4); +} + +static bool Initialized = [] { + tensorflow::GetXlaDeviceFlags()->tf_xla_enable_xla_devices = true; + return true; +}(); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/g3doc/cpu_supported_ops.md b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/g3doc/cpu_supported_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..6917fa6f9fd67285a341530aaff75729413603ad --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/g3doc/cpu_supported_ops.md @@ -0,0 +1,280 @@ +**Supported operators for device: XLA_CPU_JIT** + +Operator | Type Constraint +------------------------------------- | --------------- +`Abs` | `T={double,float,int32,int64}` +`Acos` | `T={complex64,double,float,int32,int64}` +`Acosh` | `T={complex64,double,float}` +`Add` | `T={complex64,double,float,int32,int64}` +`AddN` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`AdjustContrastv2` | +`AdjustHue` | +`AdjustSaturation` | +`All` | `Tidx={int32,int64}` +`Angle` | `Tout={double,float}`
`T={complex64}` +`Any` | `Tidx={int32,int64}` +`ApproximateEqual` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`ArgMax` | `Tidx={int32,int64}`
`output_type={int32,int64}`
`T={float}` +`ArgMin` | `Tidx={int32,int64}`
`output_type={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`Asin` | `T={complex64,double,float,int32,int64}` +`Asinh` | `T={complex64,double,float}` +`AssignAddVariableOp` | `dtype={complex64,double,float,int32,int64,uint32,uint64}` +`AssignSubVariableOp` | `dtype={complex64,double,float,int32,int64,uint32,uint64}` +`AssignVariableOp` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Atan` | `T={complex64,double,float,int32,int64}` +`Atan2` | `T={double,float}` +`Atanh` | `T={complex64,double,float}` +`AvgPool` | `T={double,float}` +`AvgPool3D` | `T={double,float}` +`AvgPool3DGrad` | `T={double,float}` +`AvgPoolGrad` | `T={double,float}` +`BatchMatMul` | `T={complex64,double,float,int32}` +`BatchToSpace` | `Tidx={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`BatchToSpaceND` | `Tcrops={int32,int64}`
`Tblock_shape={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`BiasAdd` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`BiasAddGrad` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`BiasAddV1` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`BitwiseAnd` | `T={int32,int64,uint32,uint64}` +`BitwiseOr` | `T={int32,int64,uint32,uint64}` +`BroadcastArgs` | `T={int32,int64}` +`BroadcastGradientArgs` | `T={int32,int64}` +`Cast` | `DstT={bool,complex64,double,float,int32,int64,uint32,uint64}`
`SrcT={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Ceil` | `T={double,float}` +`Cholesky` | `T={double,float}` +`Complex` | `Tout={complex64}`
`T={double,float}` +`ComplexAbs` | `Tout={double,float}`
`T={complex64}` +`Concat` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ConcatOffset` | +`ConcatV2` | `Tidx={int32}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Conj` | `T={complex64}` +`Const` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ControlTrigger` | +`Conv2D` | `T={float}` +`Conv2DBackpropFilter` | `T={float}` +`Conv2DBackpropInput` | `T={float}` +`Conv3D` | `T={double,float}` +`Conv3DBackpropFilterV2` | `T={double,float}` +`Conv3DBackpropInputV2` | `T={double,float}` +`Cos` | `T={complex64,double,float}` +`Cosh` | `T={complex64,double,float}` +`Cross` | `T={double,float,int32,int64,uint32,uint64}` +`Cumprod` | `Tidx={int32,int64}`
`T={float}` +`Cumsum` | `Tidx={int32,int64}`
`T={float}` +`DepthToSpace` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`DepthwiseConv2dNative` | `T={double,float}` +`DepthwiseConv2dNativeBackpropFilter` | `T={double,float}` +`DepthwiseConv2dNativeBackpropInput` | `T={double,float}` +`Diag` | `T={complex64,double,float,int32,int64}` +`DiagPart` | `T={complex64,double,float,int32,int64}` +`Div` | `T={complex64,double,float,int32,int64}` +`DynamicStitch` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Elu` | `T={double,float}` +`EluGrad` | `T={double,float}` +`Equal` | `T={bool,complex64,double,float,int32,int64}` +`Exp` | `T={complex64,double,float}` +`ExpandDims` | `Tdim={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Expm1` | `T={complex64,double,float}` +`ExtractImagePatches` | `T={double,float,int32,int64,uint32,uint64}` +`FFT` | +`FFT2D` | +`FFT3D` | +`FakeQuantWithMinMaxArgs` | +`FakeQuantWithMinMaxArgsGradient` | +`FakeQuantWithMinMaxVars` | +`FakeQuantWithMinMaxVarsGradient` | +`Fill` | `index_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Floor` | `T={double,float}` +`FloorDiv` | `T={complex64,double,float,int32,int64}` +`FloorMod` | `T={double,float,int32,int64}` +`FusedBatchNorm` | `T={float}` +`FusedBatchNormGrad` | `T={float}` +`FusedBatchNormGradV2` | `U={float}`
`T={float}` +`FusedBatchNormV2` | `U={float}`
`T={float}` +`Gather` | `Tindices={int32,int64}`
`Tparams={bool,complex64,double,float,int32,int64,uint32,uint64}` +`GatherNd` | `Tindices={int32,int64}`
`Tparams={bool,complex64,double,float,int32,int64,uint32,uint64}` +`GatherV2` | `Taxis={int32,int64}`
`Tindices={int32,int64}`
`Tparams={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Greater` | `T={double,float,int32,int64,uint32,uint64}` +`GreaterEqual` | `T={double,float,int32,int64,uint32,uint64}` +`HSVToRGB` | `T={double,float}` +`IFFT` | +`IFFT2D` | +`IFFT3D` | +`IRFFT` | +`IRFFT2D` | +`IRFFT3D` | +`Identity` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`IdentityN` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Imag` | `Tout={double,float}`
`T={complex64}` +`Inv` | `T={complex64,double,float,int32,int64}` +`Invert` | `T={int32,int64,uint32,uint64}` +`InvertPermutation` | `T={int32}` +`IsFinite` | `T={double,float}` +`IsInf` | `T={double,float}` +`IsNan` | `T={double,float}` +`L2Loss` | `T={double,float}` +`LRN` | `T={float}` +`LRNGrad` | `T={float}` +`LeftShift` | `T={int32,int64,uint32,uint64}` +`Less` | `T={double,float,int32,int64,uint32,uint64}` +`LessEqual` | `T={double,float,int32,int64,uint32,uint64}` +`LinSpace` | `Tidx={int32,int64}`
`T={double,float}` +`Log` | `T={complex64,double,float}` +`Log1p` | `T={complex64,double,float}` +`LogSoftmax` | `T={double,float}` +`LogicalAnd` | +`LogicalNot` | +`LogicalOr` | +`MatMul` | `T={complex64,double,float}` +`MatrixBandPart` | `Tindex={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixDiag` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixDiagPart` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixSetDiag` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixTriangularSolve` | `T={complex64,double,float}` +`Max` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`MaxPool` | `T={double,float,int32,int64}` +`MaxPool3D` | `T={float}` +`MaxPool3DGrad` | `TInput={float}`
`T={float}` +`MaxPoolGrad` | `T={double,float,int32,int64,uint32,uint64}` +`MaxPoolGradGrad` | `T={float}` +`MaxPoolGradGradV2` | `T={float}` +`MaxPoolGradV2` | `T={double,float,int32,int64,uint32,uint64}` +`MaxPoolV2` | `T={double,float,int32,int64}` +`Maximum` | `T={double,float,int32,int64}` +`Mean` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`Min` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`Minimum` | `T={double,float,int32,int64}` +`MirrorPad` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Mod` | `T={double,float,int32,int64}` +`Mul` | `T={complex64,double,float,int32,int64}` +`Multinomial` | `output_dtype={int32,int64}`
`T={double,float,int32,int64,uint32,uint64}` +`Neg` | `T={complex64,double,float,int32,int64}` +`NoOp` | +`NotEqual` | `T={bool,complex64,double,float,int32,int64}` +`OneHot` | `TI={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`OnesLike` | `T={bool,complex64,double,float,int32,int64}` +`Pack` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Pad` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`PadV2` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ParallelDynamicStitch` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Pow` | `T={complex64,double,float,int32,int64}` +`PreventGradient` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Prod` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`QuantizeAndDequantizeV2` | `T={double,float}` +`RFFT` | +`RFFT2D` | +`RFFT3D` | +`RGBToHSV` | `T={double,float}` +`RandomStandardNormal` | `dtype={float}` +`RandomUniform` | `T={int32,int64}`
`dtype={double,float}` +`RandomUniformInt` | `T={int32,int64}`
`Tout={int32,int64}` +`Range` | `Tidx={double,float,int32,int64}` +`Rank` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ReadVariableOp` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Real` | `Tout={double,float}`
`T={complex64}` +`RealDiv` | `T={complex64,double,float,int32,int64}` +`Reciprocal` | `T={complex64,double,float,int32,int64}` +`ReciprocalGrad` | `T={complex64,double,float}` +`Relu` | `T={double,float,int32,int64,uint32,uint64}` +`Relu6` | `T={double,float,int32,int64,uint32,uint64}` +`Relu6Grad` | `T={double,float,int32,int64,uint32,uint64}` +`ReluGrad` | `T={double,float,int32,int64,uint32,uint64}` +`Reshape` | `Tshape={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ResizeBilinear` | `T={double,float,int32,int64}` +`ResizeBilinearGrad` | `T={double,float}` +`ResourceApplyAdagrad` | `T={double,float}` +`ResourceApplyAdam` | `T={double,float}` +`ResourceApplyFtrl` | `T={double,float}` +`ResourceApplyFtrlV2` | `T={double,float}` +`ResourceApplyGradientDescent` | `T={double,float}` +`ResourceApplyMomentum` | `T={double,float}` +`ResourceApplyRMSProp` | `T={double,float}` +`ResourceGather` | `Tindices={int32,int64}`
`dtype={complex64,double,float,int32,int64,uint32,uint64}` +`ResourceStridedSliceAssign` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Reverse` | `T={bool,complex64,double,float,int32,int64}` +`ReverseSequence` | `Tlen={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ReverseV2` | `T={bool,complex64,double,float,int32,int64}`
`Tidx={int32,int64}` +`RightShift` | `T={int32,int64,uint32,uint64}` +`Rint` | `T={double,float}` +`Round` | `T={complex64,double,float,int32,int64}` +`Rsqrt` | `T={complex64,double,float}` +`RsqrtGrad` | `T={complex64,double,float}` +`ScatterNd` | `Tindices={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Select` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Selu` | `T={double,float}` +`SeluGrad` | `T={double,float}` +`Shape` | `out_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ShapeN` | `out_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Sigmoid` | `T={complex64,double,float}` +`SigmoidGrad` | `T={complex64,double,float}` +`Sign` | `T={complex64,double,float,int32,int64}` +`Sin` | `T={complex64,double,float}` +`Sinh` | `T={complex64,double,float}` +`Size` | `out_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Slice` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Snapshot` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Softmax` | `T={double,float}` +`SoftmaxCrossEntropyWithLogits` | `T={double,float}` +`Softplus` | `T={double,float,int32,int64,uint32,uint64}` +`SoftplusGrad` | `T={double,float,int32,int64,uint32,uint64}` +`Softsign` | `T={double,float,int32,int64,uint32,uint64}` +`SoftsignGrad` | `T={double,float,int32,int64,uint32,uint64}` +`SpaceToBatch` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SpaceToBatchND` | `Tblock_shape={int32,int64}`
`Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SpaceToDepth` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SparseMatMul` | `Tb={float}`
`Ta={float}` +`SparseSoftmaxCrossEntropyWithLogits` | `Tlabels={int32,int64}`
`T={double,float}` +`Split` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SplitV` | `Tlen={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Sqrt` | `T={complex64,double,float}` +`SqrtGrad` | `T={complex64,double,float}` +`Square` | `T={complex64,double,float,int32,int64}` +`SquaredDifference` | `T={complex64,double,float,int32,int64}` +`Squeeze` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StackCloseV2` | +`StackPopV2` | `elem_type={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StackPushV2` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StackV2` | `elem_type={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StatelessRandomNormal` | `Tseed={int32}`
`T={int32,int64}`
`dtype={float}` +`StatelessRandomUniform` | `Tseed={int32}`
`T={int32,int64}`
`dtype={float}` +`StopGradient` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StridedSlice` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StridedSliceGrad` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Sub` | `T={complex64,double,float,int32,int64}` +`Sum` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`SymbolicGradient` | `Tout={bool,complex64,double,float,int32,int64,uint32,uint64}`
`Tin={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Tan` | `T={complex64,double,float,int32,int64}` +`Tanh` | `T={complex64,double,float}` +`TanhGrad` | `T={complex64,double,float}` +`TensorArrayCloseV3` | +`TensorArrayConcatV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayGatherV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayGradV3` | +`TensorArrayReadV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayScatterV3` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArraySizeV3` | +`TensorArraySplitV3` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayWriteV3` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Tile` | `Tmultiples={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Transpose` | `Tperm={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TruncateDiv` | `T={complex64,complex128,double,float,half,bfloat16,int8,int16,int32,int64,uint8,uint16,uint32,uint64}` +`TruncateMod` | `T={double,float,int32,int64}` +`TruncatedNormal` | `T={int32,int64}`
`dtype={double,float}` +`Unpack` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`UnsortedSegmentSum` | `Tnumsegments={int32,int64}`
`Tindices={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`VarIsInitializedOp` | +`VariableShape` | `out_type={int32,int64}` +`XlaWhile` | `T={bool,complex64,double,float,int32,int64,resource,uint32,uint64}` +`ZerosLike` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_Arg` | `T={bool,complex64,double,float,int32,int64,resource,uint32,uint64}` +`_ArrayToList` | `out_types={bool,complex64,double,float,int32,int64,uint32,uint64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_ListToArray` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}`
`Tin={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_Retval` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_XLARecv` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_XLASend` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` + +To regenerate this table, run: + +```shell +bazel run -c opt -- tensorflow/compiler/tf2xla:tf2xla_supported_ops --device=XLA_CPU_JIT +``` diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/g3doc/gpu_supported_ops.md b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/g3doc/gpu_supported_ops.md new file mode 100644 index 0000000000000000000000000000000000000000..7b9a635b692e88326cd314828b63a1f58d47694a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/g3doc/gpu_supported_ops.md @@ -0,0 +1,276 @@ +**Supported operators for device: XLA_GPU_JIT** + +Operator | Type Constraint +------------------------------------- | --------------- +`Abs` | `T={double,float,int32,int64}` +`Acos` | `T={complex64,double,float,int32,int64}` +`Acosh` | `T={complex64,double,float}` +`Add` | `T={complex64,double,float,int32,int64}` +`AddN` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`AdjustContrastv2` | +`AdjustHue` | +`AdjustSaturation` | +`All` | `Tidx={int32,int64}` +`Angle` | `Tout={double,float}`
`T={complex64}` +`Any` | `Tidx={int32,int64}` +`ApproximateEqual` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`ArgMax` | `Tidx={int32,int64}`
`output_type={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`ArgMin` | `Tidx={int32,int64}`
`output_type={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`Asin` | `T={complex64,double,float,int32,int64}` +`Asinh` | `T={complex64,double,float}` +`AssignAddVariableOp` | `dtype={complex64,double,float,int32,int64,uint32,uint64}` +`AssignSubVariableOp` | `dtype={complex64,double,float,int32,int64,uint32,uint64}` +`AssignVariableOp` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Atan` | `T={complex64,double,float,int32,int64}` +`Atan2` | `T={double,float}` +`Atanh` | `T={complex64,double,float}` +`AvgPool` | `T={double,float}` +`AvgPool3D` | `T={double,float}` +`AvgPool3DGrad` | `T={double,float}` +`AvgPoolGrad` | `T={double,float}` +`BatchMatMul` | `T={complex64,double,float,int32}` +`BatchToSpace` | `Tidx={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`BatchToSpaceND` | `Tcrops={int32,int64}`
`Tblock_shape={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`BiasAdd` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`BiasAddGrad` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`BiasAddV1` | `T={complex64,double,float,int32,int64,uint32,uint64}` +`BitwiseAnd` | `T={int32,int64,uint32,uint64}` +`BitwiseOr` | `T={int32,int64,uint32,uint64}` +`BroadcastArgs` | `T={int32,int64}` +`BroadcastGradientArgs` | `T={int32,int64}` +`Cast` | `DstT={bool,complex64,double,float,int32,int64,uint32,uint64}`
`SrcT={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Ceil` | `T={double,float}` +`Cholesky` | `T={double,float}` +`Complex` | `Tout={complex64}`
`T={double,float}` +`ComplexAbs` | `Tout={double,float}`
`T={complex64}` +`Concat` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ConcatOffset` | +`ConcatV2` | `Tidx={int32}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Conj` | `T={complex64}` +`Const` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ControlTrigger` | +`Conv2D` | `T={float}` +`Conv2DBackpropFilter` | `T={float}` +`Conv2DBackpropInput` | `T={float}` +`Conv3D` | `T={double,float}` +`Conv3DBackpropFilterV2` | `T={double,float}` +`Conv3DBackpropInputV2` | `T={double,float}` +`Cos` | `T={complex64,double,float}` +`Cosh` | `T={complex64,double,float}` +`Cross` | `T={double,float,int32,int64,uint32,uint64}` +`Cumprod` | `Tidx={int32,int64}`
`T={float}` +`Cumsum` | `Tidx={int32,int64}`
`T={float}` +`DepthToSpace` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`DepthwiseConv2dNative` | `T={double,float}` +`DepthwiseConv2dNativeBackpropFilter` | `T={double,float}` +`DepthwiseConv2dNativeBackpropInput` | `T={double,float}` +`Diag` | `T={complex64,double,float,int32,int64}` +`DiagPart` | `T={complex64,double,float,int32,int64}` +`Div` | `T={complex64,double,float,int32,int64}` +`DynamicStitch` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Elu` | `T={double,float}` +`EluGrad` | `T={double,float}` +`Equal` | `T={bool,complex64,double,float,int32,int64}` +`Exp` | `T={complex64,double,float}` +`ExpandDims` | `Tdim={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Expm1` | `T={complex64,double,float}` +`ExtractImagePatches` | `T={double,float,int32,int64,uint32,uint64}` +`FFT` | +`FFT2D` | +`FFT3D` | +`FakeQuantWithMinMaxArgs` | +`FakeQuantWithMinMaxArgsGradient` | +`FakeQuantWithMinMaxVars` | +`FakeQuantWithMinMaxVarsGradient` | +`Fill` | `index_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Floor` | `T={double,float}` +`FloorDiv` | `T={complex64,double,float,int32,int64}` +`FloorMod` | `T={double,float,int32,int64}` +`FusedBatchNorm` | `T={float}` +`FusedBatchNormGrad` | `T={float}` +`FusedBatchNormGradV2` | `U={float}`
`T={float}` +`FusedBatchNormV2` | `U={float}`
`T={float}` +`Gather` | `Tindices={int32,int64}`
`Tparams={bool,complex64,double,float,int32,int64,uint32,uint64}` +`GatherNd` | `Tindices={int32,int64}`
`Tparams={bool,complex64,double,float,int32,int64,uint32,uint64}` +`GatherV2` | `Taxis={int32,int64}`
`Tindices={int32,int64}`
`Tparams={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Greater` | `T={double,float,int32,int64,uint32,uint64}` +`GreaterEqual` | `T={double,float,int32,int64,uint32,uint64}` +`HSVToRGB` | `T={double,float}` +`IFFT` | +`IFFT2D` | +`IFFT3D` | +`IRFFT` | +`IRFFT2D` | +`IRFFT3D` | +`Identity` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`IdentityN` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Imag` | `Tout={double,float}`
`T={complex64}` +`Inv` | `T={complex64,double,float,int32,int64}` +`Invert` | `T={int32,int64,uint32,uint64}` +`InvertPermutation` | `T={int32}` +`IsFinite` | `T={double,float}` +`IsInf` | `T={double,float}` +`IsNan` | `T={double,float}` +`L2Loss` | `T={double,float}` +`LRN` | `T={float}` +`LRNGrad` | `T={float}` +`LeftShift` | `T={int32,int64,uint32,uint64}` +`Less` | `T={double,float,int32,int64,uint32,uint64}` +`LessEqual` | `T={double,float,int32,int64,uint32,uint64}` +`LinSpace` | `Tidx={int32,int64}`
`T={double,float}` +`Log` | `T={complex64,double,float}` +`Log1p` | `T={complex64,double,float}` +`LogSoftmax` | `T={double,float}` +`LogicalAnd` | +`LogicalNot` | +`LogicalOr` | +`MatMul` | `T={complex64,double,float}` +`MatrixBandPart` | `Tindex={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixDiag` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixDiagPart` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixSetDiag` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`MatrixTriangularSolve` | `T={complex64,double,float}` +`Max` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`MaxPool` | `T={double,float,int32,int64}` +`MaxPool3D` | `T={float}` +`MaxPool3DGrad` | `TInput={float}`
`T={float}` +`MaxPoolGrad` | `T={double,float,int32,int64,uint32,uint64}` +`MaxPoolGradGrad` | `T={float}` +`MaxPoolGradGradV2` | `T={float}` +`MaxPoolGradV2` | `T={double,float,int32,int64,uint32,uint64}` +`MaxPoolV2` | `T={double,float,int32,int64}` +`Maximum` | `T={double,float,int32,int64}` +`Mean` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`Min` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`Minimum` | `T={double,float,int32,int64}` +`MirrorPad` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Mod` | `T={double,float,int32,int64}` +`Mul` | `T={complex64,double,float,int32,int64}` +`Multinomial` | `output_dtype={int32,int64}`
`T={double,float,int32,int64,uint32,uint64}` +`Neg` | `T={complex64,double,float,int32,int64}` +`NoOp` | +`NotEqual` | `T={bool,complex64,double,float,int32,int64}` +`OneHot` | `TI={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`OnesLike` | `T={bool,complex64,double,float,int32,int64}` +`Pack` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Pad` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`PadV2` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ParallelDynamicStitch` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Pow` | `T={complex64,double,float,int32,int64}` +`PreventGradient` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Prod` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`QuantizeAndDequantizeV2` | `T={double,float}` +`RFFT` | +`RFFT2D` | +`RFFT3D` | +`RGBToHSV` | `T={double,float}` +`Range` | `Tidx={double,float,int32,int64}` +`Rank` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ReadVariableOp` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Real` | `Tout={double,float}`
`T={complex64}` +`RealDiv` | `T={complex64,double,float,int32,int64}` +`Reciprocal` | `T={complex64,double,float,int32,int64}` +`ReciprocalGrad` | `T={complex64,double,float}` +`Relu` | `T={double,float,int32,int64,uint32,uint64}` +`Relu6` | `T={double,float,int32,int64,uint32,uint64}` +`Relu6Grad` | `T={double,float,int32,int64,uint32,uint64}` +`ReluGrad` | `T={double,float,int32,int64,uint32,uint64}` +`Reshape` | `Tshape={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ResizeBilinear` | `T={double,float,int32,int64}` +`ResizeBilinearGrad` | `T={double,float}` +`ResourceApplyAdagrad` | `T={double,float}` +`ResourceApplyAdam` | `T={double,float}` +`ResourceApplyFtrl` | `T={double,float}` +`ResourceApplyFtrlV2` | `T={double,float}` +`ResourceApplyGradientDescent` | `T={double,float}` +`ResourceApplyMomentum` | `T={double,float}` +`ResourceApplyRMSProp` | `T={double,float}` +`ResourceGather` | `Tindices={int32,int64}`
`dtype={complex64,double,float,int32,int64,uint32,uint64}` +`ResourceStridedSliceAssign` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Reverse` | `T={bool,complex64,double,float,int32,int64}` +`ReverseSequence` | `Tlen={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ReverseV2` | `T={bool,complex64,double,float,int32,int64}`
`Tidx={int32,int64}` +`RightShift` | `T={int32,int64,uint32,uint64}` +`Rint` | `T={double,float}` +`Round` | `T={complex64,double,float,int32,int64}` +`Rsqrt` | `T={complex64,double,float}` +`RsqrtGrad` | `T={complex64,double,float}` +`ScatterNd` | `Tindices={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Select` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Selu` | `T={double,float}` +`SeluGrad` | `T={double,float}` +`Shape` | `out_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`ShapeN` | `out_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Sigmoid` | `T={complex64,double,float}` +`SigmoidGrad` | `T={complex64,double,float}` +`Sign` | `T={complex64,double,float,int32,int64}` +`Sin` | `T={complex64,double,float}` +`Sinh` | `T={complex64,double,float}` +`Size` | `out_type={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Slice` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Snapshot` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Softmax` | `T={double,float}` +`SoftmaxCrossEntropyWithLogits` | `T={double,float}` +`Softplus` | `T={double,float,int32,int64,uint32,uint64}` +`SoftplusGrad` | `T={double,float,int32,int64,uint32,uint64}` +`Softsign` | `T={double,float,int32,int64,uint32,uint64}` +`SoftsignGrad` | `T={double,float,int32,int64,uint32,uint64}` +`SpaceToBatch` | `Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SpaceToBatchND` | `Tblock_shape={int32,int64}`
`Tpaddings={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SpaceToDepth` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SparseMatMul` | `Tb={float}`
`Ta={float}` +`SparseSoftmaxCrossEntropyWithLogits` | `Tlabels={int32,int64}`
`T={double,float}` +`Split` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`SplitV` | `Tlen={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Sqrt` | `T={complex64,double,float}` +`SqrtGrad` | `T={complex64,double,float}` +`Square` | `T={complex64,double,float,int32,int64}` +`SquaredDifference` | `T={complex64,double,float,int32,int64}` +`Squeeze` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StackCloseV2` | +`StackPopV2` | `elem_type={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StackPushV2` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StackV2` | `elem_type={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StatelessRandomNormal` | `Tseed={int32}`
`T={int32,int64}`
`dtype={float}` +`StatelessRandomUniform` | `Tseed={int32}`
`T={int32,int64}`
`dtype={float}` +`StopGradient` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StridedSlice` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`StridedSliceGrad` | `Index={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Sub` | `T={complex64,double,float,int32,int64}` +`Sum` | `Tidx={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`SymbolicGradient` | `Tout={bool,complex64,double,float,int32,int64,uint32,uint64}`
`Tin={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Tan` | `T={complex64,double,float,int32,int64}` +`Tanh` | `T={complex64,double,float}` +`TanhGrad` | `T={complex64,double,float}` +`TensorArrayCloseV3` | +`TensorArrayConcatV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayGatherV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayGradV3` | +`TensorArrayReadV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayScatterV3` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArraySizeV3` | +`TensorArraySplitV3` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayV3` | `dtype={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TensorArrayWriteV3` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Tile` | `Tmultiples={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`Transpose` | `Tperm={int32,int64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`TruncateDiv` | `T={complex64,complex128,double,float,half,bfloat16,int8,int16,int32,int64,uint8,uint16,uint32,uint64}` +`TruncateMod` | `T={double,float,int32,int64}` +`Unpack` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`UnsortedSegmentSum` | `Tnumsegments={int32,int64}`
`Tindices={int32,int64}`
`T={complex64,double,float,int32,int64,uint32,uint64}` +`VarIsInitializedOp` | +`VariableShape` | `out_type={int32,int64}` +`XlaWhile` | `T={bool,complex64,double,float,int32,int64,resource,uint32,uint64}` +`ZerosLike` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_Arg` | `T={bool,complex64,double,float,int32,int64,resource,uint32,uint64}` +`_ArrayToList` | `out_types={bool,complex64,double,float,int32,int64,uint32,uint64}`
`T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_ListToArray` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}`
`Tin={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_Retval` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_XLARecv` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` +`_XLASend` | `T={bool,complex64,double,float,int32,int64,uint32,uint64}` + +To regenerate this table, run: + +```shell +bazel run -c opt -- tensorflow/compiler/tf2xla:tf2xla_supported_ops --device=XLA_GPU_JIT +``` diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler.cc new file mode 100644 index 0000000000000000000000000000000000000000..18032e94e9a682e4ee524b8cf71b34f4b69acc8f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler.cc @@ -0,0 +1,358 @@ +/* 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/graph_compiler.h" + +#include +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/const_analysis.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/client/client_library.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/executor.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/common_runtime/graph_optimizer.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/attr_value_util.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/graph/validate.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/lib/hash/hash.h" +#include "tensorflow/core/lib/monitoring/counter.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/public/version.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { + +auto* graph_compiler_failed_compilation_op_count = + tensorflow::monitoring::Counter<1>::New( + /*metric_name=*/ + "/tensorflow/core/tf2xla/graph_compilation_failed_op_count", + /*metric_description=*/"Records an op that failed to compile", + /*metric_label=*/"op_name"); + +namespace { +absl::Status PrepareArguments( + XlaOpKernelContext* ctx, Graph* graph, + const std::vector& expressions, + const NameAttrList& func, std::vector* args) { + auto client = ctx->compiler()->client(); + std::vector arg_must_be_compile_time_constant(expressions.size()); + + TF_RETURN_IF_ERROR(BackwardsConstAnalysis( + *graph, &arg_must_be_compile_time_constant, + /*compile_time_const_nodes=*/nullptr, ctx->function_library())); + + args->resize(expressions.size()); + for (int i = 0, end = args->size(); i < end; ++i) { + XlaCompiler::Argument& arg = (*args)[i]; + arg.type = ctx->input_type(i); + arg.shape = ctx->InputShape(i); + + switch (expressions[i]->kind()) { + case XlaExpression::Kind::kConstant: + arg.kind = XlaCompiler::Argument::kConstant; + arg.constant_value = *expressions[i]->constant_value(); + break; + case XlaExpression::Kind::kXlaOp: + if (arg_must_be_compile_time_constant[i]) { + TF_ASSIGN_OR_RETURN(std::optional value, + expressions[i]->ResolveConstant(client)); + if (value.has_value()) { + arg.kind = XlaCompiler::Argument::kConstant; + arg.constant_value = *value; + } else { + arg.kind = XlaCompiler::Argument::kParameter; + } + + } else { + arg.kind = XlaCompiler::Argument::kParameter; + } + break; + case XlaExpression::Kind::kResource: { + XlaResource* resource = expressions[i]->resource(); + XlaCompiler::PopulateArgumentFromResource(*resource, &arg); + break; + } + case XlaExpression::Kind::kTensorList: { + arg.kind = XlaCompiler::Argument::kTensorList; + const xla::XlaOp& tensor_list = expressions[i]->handle(); + arg.shape = tensor_list.builder()->GetShape(tensor_list).value(); + break; + } + case XlaExpression::Kind::kInvalid: + return absl::InvalidArgumentError("Invalid function argument"); + } + } + return absl::OkStatus(); +} +} // namespace +absl::Status GraphCompiler::Compile() { + // Check that the graph has no illegal cycles. + TF_RETURN_IF_ERROR(graph::ValidateGraphHasNoCycle(*graph_)); + // Maintain a mapping from node id to node outputs. + using NodeOutputs = std::vector; + std::vector output_registry(graph_->num_node_ids()); + auto output_registry_cleanup = gtl::MakeCleanup([&output_registry] { + for (const NodeOutputs& outputs : output_registry) { + for (const TensorValue& value : outputs) { + CHECK(!value.is_ref()); + delete value.tensor; + } + } + }); + + // XLA requires determinism, generate a stable ordering from DFS. + std::vector topo_sorted_nodes; + GetReversePostOrder(*graph_, &topo_sorted_nodes, + /*stable_comparator=*/NodeComparatorName()); + + OpKernelContext::Params params; + PartiallySetupParams(¶ms); + + for (Node* n : topo_sorted_nodes) { + OpKernel* op_kernel_raw = nullptr; + // The kernel is not actually run for functional ops, we just need it + // for metadata. + absl::Status s = flib_->CreateKernel(n->properties(), &op_kernel_raw); + // Transfer ownership of the kernel to a local smart pointer. + std::unique_ptr op_kernel(op_kernel_raw); + + if (!s.ok()) { + s = AttachDef(s, *n); + LOG(ERROR) << "Executor failed to create kernel. " << s; + return s; + } + + TF_RET_CHECK(!n->IsRecv() && !n->IsSend() && !n->IsSwitch()) + << "Not supported node: " << n->DebugString(); + params.op_kernel = op_kernel.get(); + absl::InlinedVector output_attr(n->num_outputs()); + params.output_attr_array = output_attr.data(); + + // tensor_inputs_ is a buffer reused across graph traversal. We clean up and + // reinitialize the buffer before we visit a new node. + tensor_inputs_.clear(); + tensor_inputs_.resize(n->num_inputs()); + + // Set up inputs from outputs of previous nodes. + for (auto* e : n->in_edges()) { + if (e->IsControlEdge()) continue; + const Node* src = e->src(); + const int output_registry_size = output_registry.size(); + TF_RET_CHECK(src->id() < output_registry_size); + const NodeOutputs& src_outputs = output_registry[src->id()]; + + tensor_inputs_.at(e->dst_input()) = src_outputs.at(e->src_output()); + } + params.inputs = tensor_inputs_; + + OpKernelContext op_context(¶ms, n->num_outputs()); + VLOG(3) << "Translating " << params.op_kernel->name(); + if (IsFunctionCall(*flib_->GetFunctionLibraryDefinition(), *n)) { + TF_RETURN_IF_ERROR(CompileFunctionalNode(n, &op_context)); + } else { + device_->Compute(CHECK_NOTNULL(params.op_kernel), &op_context); + absl::Status s = op_context.status(); + if (!s.ok()) { + graph_compiler_failed_compilation_op_count + ->GetCell(params.op_kernel->def().op()) + ->IncrementBy(1); + return AttachDef(s, n->def()); + } + } + + // Set up outputs. Also check if outputs from the previous computation is + // valid. + NodeOutputs& outputs = output_registry[n->id()]; + outputs.resize(n->num_outputs()); + for (int o = 0; o < n->num_outputs(); ++o) { + outputs[o] = op_context.release_output(o); + if (outputs[o].tensor == nullptr) { + return absl::InternalError(absl::StrCat("Missing xla_context ", o, + "-th output from ", + FormatNodeForError(*n))); + } + } + } + return absl::OkStatus(); +} + +namespace { + +absl::Status GetFunctionNameAndAttr(const FunctionLibraryRuntime& flib, + const Node& node, NameAttrList* func) { + if (node.IsPartitionedCall()) { + const AttrValue* attr_value; + TF_RETURN_IF_ERROR( + node.attrs().Find(FunctionLibraryDefinition::kFuncAttr, &attr_value)); + if (!attr_value->has_func()) { + return absl::InvalidArgumentError( + absl::StrCat("The attribute value for attribute 'f' in node ", + node.DebugString(), " does not have 'func' field set")); + } + *func = attr_value->func(); + return absl::OkStatus(); + } + + if (flib.GetFunctionLibraryDefinition()->Find(node.def().op())) { + func->set_name(node.type_string()); + } else { + func->set_name(FunctionLibraryDefinition::kGradientOp); + } + *func->mutable_attr() = node.def().attr(); + return absl::OkStatus(); +} + +} // namespace + +absl::Status GraphCompiler::CompileFunctionalNode(Node* n, + OpKernelContext* op_context) { + TF_RET_CHECK(IsFunctionCall(*flib_->GetFunctionLibraryDefinition(), *n)); + // For functional nodes, compile them using compiler from the context and call + // into the functions. + XlaOpKernelContext xla_op_context(op_context); + + XlaContext& context = XlaContext::Get(op_context); + auto* b = context.builder(); + + XlaCompiler* compiler = xla_op_context.compiler(); + + NameAttrList func; + TF_RETURN_IF_ERROR(GetFunctionNameAndAttr(*flib_, *n, &func)); + + std::vector expressions; + + for (auto tensor : tensor_inputs_) { + auto expression = + reinterpret_cast(tensor->tensor_data().data()); + expressions.push_back(expression); + } + + // Prepare the arguments and compile the function. + std::vector arguments; + const FunctionBody* fbody; + TF_RETURN_IF_ERROR(compiler->FindFunctionBody(func, &fbody)); + + auto graph = compiler->GetGraph(fbody); + + TF_RETURN_IF_ERROR(PrepareArguments(&xla_op_context, graph.get(), expressions, + func, &arguments)); + + bool add_token_input_output = + func.attr().find(kXlaTokenInputNodesAttrName) != func.attr().end(); + + XlaCompiler::CompileOptions compile_options; + compile_options.is_entry_computation = false; + compile_options.add_token_input_output = add_token_input_output; + XlaCompiler::CompilationResult result; + TF_RETURN_IF_ERROR( + compiler->CompileFunction(compile_options, func, arguments, &result)); + + TF_RET_CHECK(arguments.size() == expressions.size()); + + std::vector handles; + for (int64_t i = 0, end = expressions.size(); i < end; ++i) { + if (arguments[i].kind == XlaCompiler::Argument::kConstant) { + continue; + } + if (arguments[i].kind == XlaCompiler::Argument::kResource) { + handles.push_back(expressions[i]->resource()->value()); + } else { + handles.push_back(expressions[i]->handle()); + } + } + if (add_token_input_output) { + std::vector token_input_nodes; + TF_RETURN_IF_ERROR(GetNodeAttr(AttrSlice(&func.attr()), + kXlaTokenInputNodesAttrName, + &token_input_nodes)); + std::vector token_inputs; + for (const std::string& node_name : token_input_nodes) { + auto token_or = compiler->GetNodeToken(node_name); + TF_RETURN_IF_ERROR(token_or.status()); + token_inputs.push_back(std::move(token_or).value()); + } + xla::XlaOp token_input = xla::AfterAll(b, token_inputs); + handles.push_back(token_input); + } + + auto output_handle = xla::Call(b, *result.computation, handles); + // The output handle of `Call` computation is a tuple type. Unzip it so + // that it can fit into future computations. + int computation_output = 0; + for (int64_t i = 0; i < n->num_outputs(); ++i) { + if (result.outputs[i].is_constant) { + xla_op_context.SetConstantOutput(i, result.outputs[i].constant_value); + } else { + if (result.outputs[i].is_tensor_list) { + xla_op_context.SetTensorListOutput( + i, xla::GetTupleElement(output_handle, computation_output)); + } else { + xla_op_context.SetOutput( + i, xla::GetTupleElement(output_handle, computation_output)); + } + ++computation_output; + } + } + + for (int64_t i = 0, end = result.resource_updates.size(); i < end; i++) { + if (result.resource_updates[i].modified) { + XlaResource* resource = + expressions[result.resource_updates[i].input_index]->resource(); + xla::XlaOp updated_value = + xla::GetTupleElement(output_handle, i + n->num_outputs()); + TF_RETURN_IF_ERROR(resource->SetValue(updated_value)); + } + } + + if (add_token_input_output) { + std::string node_name; + if (!GetNodeAttr(n->attrs(), kXlaOriginalOutsideCompilationNodeName, + &node_name) + .ok()) + node_name = n->name(); + TF_RETURN_IF_ERROR(compiler->SetNodeToken( + node_name, xla::GetTupleElement(output_handle, computation_output))); + } + return b->first_error(); +} + +void GraphCompiler::PartiallySetupParams(OpKernelContext::Params* params) { + params->device = device_; + params->step_container = step_container_; + params->resource_manager = device_->resource_manager(); + params->function_library = flib_; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..9eac8dccb55e3c21e87d115a994ee1dcb1df803b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler.h @@ -0,0 +1,92 @@ +/* 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_GRAPH_COMPILER_H_ +#define TENSORFLOW_COMPILER_TF2XLA_GRAPH_COMPILER_H_ + +#include "tensorflow/compiler/tf2xla/xla_compilation_device.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "xla/client/local_client.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/notification.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { + +// GraphCompiler compiles the graph in topological order in the current +// thread. It also resolves the nondeterminism in the graph by enforcing a +// total order on all inputs to a node. This abstraction helps us create the +// same XLA computation given two structurally equivalent TensorFlow graphs. +// If a function call is visited during the graph traversal, it is then +// compiled through the xla_context into a computation and a `Call` operation +// is inserted to call into that computation. +// +// Note: GraphCompiler was created to remove our dependency to TF Executor in +// the history. There are still some todos so that we can completely decouple +// from Executor. +// +// TODO(yunxing): Remove usage of XlaCompilationDevice. +// +// TODO(yunxing): Remove the hack that wraps XlaExpression within a tensor now +// that we don't use TF Executor to pass around a tensor. +// +// TODO(yunxing): Make XlaOpkernel not a subclass of OpKernel so that it can +// handle a XlaExpression directly instead of a Tensor. This may require our own +// op registration infrastructure instead of FunctionLibraryRuntime. +class GraphCompiler { + public: + GraphCompiler(XlaCompilationDevice* device, Graph* graph, + FunctionLibraryRuntime* flib, + ScopedStepContainer* step_container) + : device_(device), + graph_(graph), + flib_(flib), + step_container_(step_container) {} + + // Compiles the graph. The results are written in xla_context stored in the + // resource_manager of the 'XlaCompilationDevice' that's passed into the + // constructor. + absl::Status Compile(); + + private: + // Partially sets params. This partially set params can be reused + // across multiple nodes visit. + void PartiallySetupParams(OpKernelContext::Params* params); + + // Compiles a functional node and writes result to OpkernelContext. A + // functional node represents a defined computation and should be compiled + // using `compiler_`. + absl::Status CompileFunctionalNode(Node* n, OpKernelContext* op_context); + + XlaCompilationDevice* device_; + Graph* graph_; + FunctionLibraryRuntime* flib_; + ScopedStepContainer* step_container_; + // A buffer to hold tensor inputs to a node, this is reused across the graph + // traversal. + absl::InlinedVector tensor_inputs_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_GRAPH_COMPILER_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d2845e9134774e729f4be4c21c5a501ca15c7bf --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_test.cc @@ -0,0 +1,152 @@ +/* Copyright 2023 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/graph_compiler.h" + +#include + +#include +#include +#include "tensorflow/compiler/tf2xla/graph_compiler_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/xla_compilation_device.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/attr_value_util.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/lib/monitoring/cell_reader.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/public/session_options.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { +namespace { + +using ::tensorflow::monitoring::testing::CellReader; + +constexpr char kOpCompilationFailureStreamz[] = + "/tensorflow/core/tf2xla/graph_compilation_failed_op_count"; + +class DummyOp : public XlaOpKernel { + public: + explicit DummyOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override {} +}; + +REGISTER_KERNEL_BUILDER(Name("NoOp").Device(DEVICE_DEFAULT), DummyOp); +REGISTER_KERNEL_BUILDER(Name("NoOp").Device("XLA_TPU_JIT"), DummyOp); +REGISTER_KERNEL_BUILDER(Name("NoOp").Device("XLA_CPU_JIT"), DummyOp); + +class MockAlwaysFailsOp : public XlaOpKernel { + public: + explicit MockAlwaysFailsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + ctx->CtxFailure(__FILE__, __LINE__, + absl::InvalidArgumentError("MockBroken")); + } +}; + +REGISTER_OP("MockAlwaysFails") + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +A test only Op that always fails to compile. +)doc"); + +REGISTER_KERNEL_BUILDER(Name("MockAlwaysFails").Device(DEVICE_DEFAULT), + MockAlwaysFailsOp); +REGISTER_KERNEL_BUILDER(Name("MockAlwaysFails").Device("XLA_CPU_JIT"), + MockAlwaysFailsOp); +REGISTER_KERNEL_BUILDER(Name("MockAlwaysFails").Device("XLA_TPU_JIT"), + MockAlwaysFailsOp); +REGISTER_XLA_OP(Name("MockAlwaysFails").CompilationOnly(), MockAlwaysFailsOp); + +class GraphCompilerTest : public ::testing::Test { + public: + void SetUp() override { + device_ = new tensorflow::XlaCompilationDevice( + tensorflow::SessionOptions(), tensorflow::DeviceType("XLA_TPU_JIT")); + device_mgr_ = std::make_unique(absl::WrapUnique(device_)); + } + + absl::Status RunGraphCompiler(Graph& graph) { + ProcessFunctionLibraryRuntime runtime( + device_mgr_.get(), Env::Default(), nullptr, TF_GRAPH_DEF_VERSION, + &graph.flib_def(), OptimizerOptions()); + + xla::XlaBuilder builder("test_builder"); + XlaCompiler::Options options; + options.device_type = "XLA_TPU_JIT"; + + XlaCompiler xla_compiler(options); + + // Resource cleanup is messy, see the LINT.ThenChange for comments. + // LINT.IfChange + XlaContext* xla_context = new XlaContext(&xla_compiler, &builder, &graph); + core::ScopedUnref context_unref(xla_context); + xla_context->Ref(); + + auto step_container = std::make_unique( + 0, [this](const std::string& name) { + absl::Status status = + this->device_->resource_manager()->Cleanup(name); + }); + auto container_status = step_container->Create( + device_->resource_manager(), XlaContext::kXlaContextResourceName, + xla_context); + + GraphCompiler graph_compiler( + device_, &graph, runtime.GetFLR(device_->name()), step_container.get()); + + return graph_compiler.Compile(); + // LINT.ThenChange(//tensorflow/compiler/tf2xla/xla_compiler.cc:ExecuteGraph) + } + + protected: + XlaCompilationDevice* device_; // Owned by device_mgr_ + std::unique_ptr device_mgr_; +}; + +TEST_F(GraphCompilerTest, CompilesGraph) { + Graph graph(OpRegistry::Global()); + + EXPECT_TRUE(RunGraphCompiler(graph).ok()); +} + +TEST_F(GraphCompilerTest, RecordsStreamzFailedCompilationNode) { + Graph graph(OpRegistry::Global()); + Node* mock_fail; + ASSERT_TRUE(NodeBuilder("mock_fail", "MockAlwaysFails") + .Finalize(&graph, &mock_fail) + .ok()); + graph.AddControlEdge(graph.source_node(), mock_fail); + graph.AddControlEdge(mock_fail, graph.sink_node()); + + CellReader op_reader(kOpCompilationFailureStreamz); + + EXPECT_FALSE(RunGraphCompiler(graph).ok()); + + EXPECT_EQ(op_reader.Delta("MockAlwaysFails"), 1); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..3475b513b43ae1b60b997e6ae366ea5bf9b34965 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_util.cc @@ -0,0 +1,318 @@ +/* Copyright 2019 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/graph_compiler_util.h" + +#include +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/functionalize_control_flow.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/graph_def_util.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/versions.pb.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { + +namespace { + +const char* const kFeedIdAttr = "_feed_id"; +const char* const kFetchIdAttr = "_fetch_id"; +const char* const kShapeAttr = "_shape"; +const char* const kDebugNameAttr = "_debug_name"; + +typedef std::unordered_map NodeMap; + +// Each feed id identifies the positional output of some node, which may consist +// of multiple edges. AddPlaceholdersForFeeds has already replaced each fed +// tensor with a placeholder. For each feed tensor, replaces all edges so they +// point from a new _Arg node instead. The newly created _Arg nodes are added to +// `arg_nodes`. +absl::Status AddArgNodes( + Graph* graph, const NodeMap& node_map, + const protobuf::RepeatedPtrField& feeds, + const std::unordered_map& feed_remapping, + std::unordered_set* arg_nodes) { + for (int arg_index = 0; arg_index < feeds.size(); ++arg_index) { + const tf2xla::Feed& feed = feeds[arg_index]; + // All feeds have been replaced by placeholders. + const int output_index = 0; + + const std::string key = TensorIdToString(feed.id()); + const auto remap_it = feed_remapping.find(key); + auto node_it = node_map.find(remap_it->second); + if (node_it == node_map.end()) { + // Strip off the aot_feed_#/ prefix. + absl::string_view name(remap_it->second); + const auto index = name.find('/'); + if (index > 0) name.remove_prefix(index + 1); + return absl::InvalidArgumentError( + absl::StrCat("Node is fed but not needed for fetching: ", name)); + } + const Node* feed_node = node_it->second; + + // TODO(toddw): Invoke shape inference in AddPlaceholdersForFeeds and add a + // "_shape" attr if we can determine it. That way the graph will be + // initialized with whatever shapes we can infer, while the user can still + // explicitly specify or override them. + Node* arg_node = nullptr; + TF_RETURN_IF_ERROR( + NodeBuilder( + absl::StrCat("_arg_", arg_index), + FunctionLibraryDefinition::FunctionLibraryDefinition::kArgOp) + .Attr("T", BaseType(feed_node->output_type(output_index))) + .Attr("index", arg_index) + .Attr(kFeedIdAttr, TensorIdToString(feed.id())) + .Attr(kShapeAttr, TensorShape(feed.shape())) + .Attr(kDebugNameAttr, feed.name()) + .Finalize(graph, &arg_node)); + arg_nodes->insert(arg_node); + + // Collects out-edges from the feed node that have a matching edge index; + // these will be replaced with edges from the arg node instead. + // + // We must collect the edges first and process them in a second pass, since + // removing the edge from the graph invalidates feed_node->out_edges. + std::vector feed_edges; + for (const Edge* edge : feed_node->out_edges()) { + if (edge->src_output() == output_index) { + feed_edges.push_back(edge); + } + } + for (const Edge* edge : feed_edges) { + graph->AddEdge(arg_node, 0, edge->dst(), edge->dst_input()); + graph->RemoveEdge(edge); + } + } + return absl::OkStatus(); +} + +// Each fetch id identifies the positional output of some node. For each fetch +// node, adds a new _Retval node instead, and adds the node to `retval_nodes`. +absl::Status AddRetvalNodes( + Graph* graph, const NodeMap& node_map, + const protobuf::RepeatedPtrField& fetches, + std::unordered_set* retval_nodes) { + for (int ret_index = 0; ret_index < fetches.size(); ++ret_index) { + const tf2xla::TensorId& id = fetches[ret_index].id(); + auto it = node_map.find(id.node_name()); + if (it == node_map.end()) { + return absl::NotFoundError( + absl::StrCat("Can't find fetch id: ", TensorIdToString(id))); + } + Node* fetch_node = it->second; + if (id.output_index() >= fetch_node->num_outputs()) { + return absl::InvalidArgumentError(absl::StrCat( + "Invalid fetch id: ", TensorIdToString(id), + ", output index should be < ", fetch_node->num_outputs())); + } + // Connects fetch_node -> retval_node. + Node* retval_node = nullptr; + TF_RETURN_IF_ERROR( + NodeBuilder(absl::StrCat("_retval_", ret_index), + FunctionLibraryDefinition::kRetOp) + .Input(fetch_node, id.output_index()) + .Attr("T", BaseType(fetch_node->output_type(id.output_index()))) + .Attr("index", ret_index) + .Attr(kFetchIdAttr, TensorIdToString(id)) + .Finalize(graph, &retval_node)); + retval_nodes->insert(retval_node); + } + return absl::OkStatus(); +} + +// RewriteAndPruneGraph identifies input and output edges (named by the feed and +// fetch ids respectively), and rewrites the edges so that inputs flow from _Arg +// nodes, and outputs flow to _Retval nodes. This allows the symbolic graph +// execution to know the input and output args for the generated function. +absl::Status RewriteAndPruneGraph( + Graph* graph, const tf2xla::Config& config, + const std::unordered_map& feed_remapping) { + NodeMap node_map; + for (Node* n : graph->nodes()) { + node_map[n->name()] = n; + } + std::unordered_set nodes_to_keep; + TF_RETURN_IF_ERROR(AddArgNodes(graph, node_map, config.feed(), feed_remapping, + &nodes_to_keep)); + TF_RETURN_IF_ERROR( + AddRetvalNodes(graph, node_map, config.fetch(), &nodes_to_keep)); + VLOG(2) << "Post rewrite: " << DumpGraphToFile("tf2xla_post_rewrite", *graph); + PruneForReverseReachability(graph, std::move(nodes_to_keep)); + FixupSourceAndSinkEdges(graph); + VLOG(2) << "Post prune: " << DumpGraphToFile("tfcompile_post_prune", *graph); + // Sanity-check, to make sure the feeds and fetches still exist post-pruning. + std::set missing_feeds, missing_fetches; + for (const tf2xla::Feed& feed : config.feed()) { + missing_feeds.insert(TensorIdToString(feed.id())); + } + for (const tf2xla::Fetch& fetch : config.fetch()) { + missing_fetches.insert(TensorIdToString(fetch.id())); + } + for (const Node* n : graph->op_nodes()) { + if (n->type_string() == FunctionLibraryDefinition::kArgOp) { + std::string feed_id; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), kFeedIdAttr, &feed_id)); + if (missing_feeds.erase(feed_id) == 0) { + return absl::AbortedError( + absl::StrCat(FunctionLibraryDefinition::kArgOp, + " node found with unknown feed id: ", feed_id)); + } + } else if (n->type_string() == FunctionLibraryDefinition::kRetOp) { + std::string fetch_id; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), kFetchIdAttr, &fetch_id)); + if (missing_fetches.erase(fetch_id) == 0) { + return absl::AbortedError( + absl::StrCat(FunctionLibraryDefinition::kRetOp, + " node found with unknown fetch id: ", fetch_id)); + } + } + } + if (!missing_feeds.empty() || !missing_fetches.empty()) { + return absl::AbortedError(absl::StrCat( + "Post graph-pruning", + ", missing feeds: ", absl::StrJoin(missing_feeds, ", "), + ", missing fetches: ", absl::StrJoin(missing_fetches, ", "))); + } + return absl::OkStatus(); +} + +// CollectArgNodes collects _Arg nodes from the graph, and performs basic +// sanity-checking to ensure the index and type attributes of each node are +// initialized correctly. +absl::Status CollectArgNodes(const Graph& graph, + std::vector* arg_nodes) { + std::map indexed_arg_nodes; + for (Node* n : graph.nodes()) { + if (n->type_string() == FunctionLibraryDefinition::kArgOp) { + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); + auto insert_result = indexed_arg_nodes.insert({index, n}); + if (!insert_result.second) { + const Node* dup = insert_result.first->second; + return absl::InvalidArgumentError(absl::StrCat( + "Multiple ", FunctionLibraryDefinition::kArgOp, + " nodes with index ", index, ", ", FormatNodeForError(*n), " and ", + FormatNodeForError(*dup))); + } + } + } + arg_nodes->clear(); + for (const auto& index_node : indexed_arg_nodes) { + const int arg_nodes_size = arg_nodes->size(); + if (index_node.first != arg_nodes_size) { + return absl::InvalidArgumentError(absl::StrCat( + "Expected ", FunctionLibraryDefinition::kArgOp, " node with index ", + arg_nodes->size(), ", but got index ", index_node.first)); + } + arg_nodes->push_back(index_node.second); + } + return absl::OkStatus(); +} + +} // namespace + +absl::Status CreateXlaArgs(const Graph& graph, + std::vector* xla_args) { + std::vector arg_nodes; + TF_RETURN_IF_ERROR(CollectArgNodes(graph, &arg_nodes)); + for (const Node* node : arg_nodes) { + XlaCompiler::Argument arg; + arg.kind = XlaCompiler::Argument::kParameter; + TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), "T", &arg.type)); + TensorShape shape; + TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), kShapeAttr, &shape)); + arg.shape = shape; + TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), kDebugNameAttr, &arg.name)); + xla_args->push_back(arg); + } + return absl::OkStatus(); +} + +void PopulateXlaArgs(const tf2xla::Config& config, + std::vector* xla_args) { + // Populate arguments with resource variables from the config. The variables + // get turned into inputs and outputs. + for (const tf2xla::Variable& variable : config.variable()) { + XlaCompiler::Argument arg; + arg.type = variable.type(); + arg.kind = XlaCompiler::Argument::kResource; + arg.shape = variable.shape(); + arg.name = variable.node_name(); + arg.resource_kind = XlaResource::kVariable; + arg.initialized = true; + xla_args->push_back(std::move(arg)); + } +} + +absl::Status InitGraph(const GraphDef& graph_def, const tf2xla::Config& config, + std::unique_ptr* graph) { + TF_RETURN_IF_ERROR(ValidateConfig(config)); + + FunctionLibraryDefinition flib_def(OpRegistry::Global(), graph_def.library()); + std::unique_ptr g(new Graph(flib_def)); + + // Replace references to fed tensors with references to newly added + // placeholders. + GraphDef first_copy_def = graph_def; + + // Maps from name:port of a feed to the name:port of the placeholder to use. + std::unordered_map feed_remapping; + TF_RETURN_IF_ERROR(AddPlaceholdersForFeeds(config, g->op_registry(), + &feed_remapping, &first_copy_def)); + + // Prune the GraphDef first so that unknown ops that we aren't compiling get + // filtered out. + GraphDef second_copy_def; + // Add the placeholder nodes as "fetches" in prune_config, such that they will + // be preserved in PruneGraphDefInto. + auto prune_config = config; + for (const auto& entry : feed_remapping) { + auto ph = prune_config.add_fetch(); + *ph->mutable_id()->mutable_node_name() = entry.second; + ph->mutable_id()->set_output_index(0); + } + TF_RETURN_IF_ERROR( + PruneGraphDefInto(prune_config, first_copy_def, &second_copy_def)); + + TF_RETURN_IF_ERROR(AddDefaultAttrsToGraphDef( + &second_copy_def, *g->op_registry(), /*node_offset=*/0)); + + TF_RETURN_IF_ERROR(ConvertGraphDefToGraph( + GraphConstructorOptions(), std::move(second_copy_def), g.get())); + TF_RETURN_IF_ERROR(RewriteAndPruneGraph(g.get(), config, feed_remapping)); + + // Functionalize control flow. + TF_RETURN_IF_ERROR(FunctionalizeControlFlow(g.get(), &flib_def)); + // After control flow functionalization, we might have more FunctionDef's + // (then/else branch, loop body). Add them to the graph. + TF_RETURN_IF_ERROR(g->AddFunctionLibrary(flib_def.ToProto())); + + *graph = std::move(g); + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_util.h new file mode 100644 index 0000000000000000000000000000000000000000..25046a4f7dd23ab1dd6f77f5b029969ddf2a5015 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/graph_compiler_util.h @@ -0,0 +1,51 @@ +/* Copyright 2019 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_GRAPH_COMPILER_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_GRAPH_COMPILER_UTIL_H_ + +#include + +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "xla/status_macros.h" +#include "tensorflow/core/framework/graph.pb.h" + +namespace tensorflow { + +// Fills in xla_args from the corresponding _Arg nodes in the graph. +absl::Status CreateXlaArgs(const Graph& graph, + std::vector* xla_args); + +// Populate xla_args for the given XLA config. +void PopulateXlaArgs(const tf2xla::Config& config, + std::vector* xla_args); + +// InitGraph creates a graph based on the graph_def, that may then be converted +// to an xla::XlaComputation via ConvertGraphToXla. +// +// The graph is rewritten with _Arg and _Retval nodes, representing the inputs +// and outputs of the function that will be compiled. Each feed id causes a new +// _Arg node to be created, where we first collect all existing edges pointing +// from the named node's output index, and then rewrite them to point from that +// _Arg node instead. Each fetch id causes a new _Retval node to be created, +// with a new edge pointing from the named node's output index to that _Retval +// node. +absl::Status InitGraph(const GraphDef& graph_def, const tf2xla::Config& config, + std::unique_ptr* graph); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_GRAPH_COMPILER_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/host_compute_metadata.proto b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/host_compute_metadata.proto new file mode 100644 index 0000000000000000000000000000000000000000..459313b0e7bee41096bc2586ea9d9285c35abdec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/host_compute_metadata.proto @@ -0,0 +1,40 @@ +syntax = "proto3"; + +package tensorflow.tf2xla; + +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "Tf2XlaProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.tf2xla"; + +// TensorMetadata indicates the type and shape of a Tensor that is +// part of a host compute transfer. +message TensorMetadata { + DataType type = 1; + TensorShapeProto shape = 2; + int64 channel_id = 3; +} + +// HostTransferMetadata describes a transfer either from host to device +// or device to host. It has a key that is unique to the computation, +// and metadata about the list of tensors being transferred. +message HostTransferMetadata { + // The key used to identify this transfer. + string key = 1; + + // For each Tensor being transferred, its type and shape. + repeated TensorMetadata metadata = 2; +} + +// HostComputeMetadata describes all the sends and recvs +// from all host compute transfer ops in a computation. +message HostComputeMetadata { + // Metadata about each device_to_host transfer + repeated HostTransferMetadata device_to_host = 1; + + // Metadata about each host_to_device transfer + repeated HostTransferMetadata host_to_device = 2; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..ab7a4ab80ce9fd98f9a97b81d40559bfaa38cae8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/BUILD @@ -0,0 +1,3529 @@ +load( + "@xla//xla/tsl:tsl.bzl", + "check_deps", +) +load("@xla//xla/tsl/platform:build_config_root.bzl", "if_static") +load( + "//tensorflow:tensorflow.bzl", + "tf_cc_test", + "tf_cuda_library", +) +load("//tensorflow:tensorflow.default.bzl", "tf_kernel_library") +load( + "//tensorflow/core/platform:build_config.bzl", + "tf_additional_all_protos", + "tf_proto_library", +) +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [ + "//tensorflow/compiler/tf2xla:internal", + "//third_party/cloud_tpu/inference_converter:__subpackages__", + "//third_party/py/orbax:__subpackages__", + ], + licenses = ["notice"], +) + +check_deps( + name = "xla_ops_check_deps", + disallowed_deps = [ + "@xla//xla/service/cpu:cpu_compiler", + "@xla//xla/service/gpu:gpu_compiler", + ], + deps = [":xla_ops"], +) + +cc_library( + name = "xla_ops", + tags = ["optonly"], + visibility = ["//visibility:public"], + deps = [ + ":aggregate_ops", + ":all_reduce_op", + ":approx_topk_op", + ":arg_op", + ":batch_matmul_op", + ":batch_norm_op", + ":batchtospace_op", + ":bcast_ops", + ":beta_op", + ":bias_ops", + ":binary_ops", + ":bincount_op", + ":broadcast_to_op", + ":bucketize_op", + ":case_op", + ":cast_op", + ":categorical_op", + ":cholesky_op", + ":clip_by_value_op", + ":concat_op", + ":const_op", + ":conv_ops", + ":cross_op", + ":cwise_ops", + ":data_format_ops", + ":depthtospace_op", + ":dequantize_op", + ":device_index_op", + ":diag_op", + ":dynamic_partition_op", + ":dynamic_slice_ops", + ":dynamic_stitch_op", + ":einsum_op", + ":elu_op", + ":empty_op", + ":ensure_shape_op", + ":extract_image_patches_op", + ":fake_param_op", + ":fake_quantize_ops", + ":fft_ops", + ":fill_op", + ":function_ops", + ":fused_conv_ops", + ":gather_op", + ":gather_scatter_ops", + ":identity_op", + ":if_op", + ":image_ops", + ":image_resize_ops", + ":in_topk_op", + ":index_ops", + ":l2loss_op", + ":listdiff_op", + ":lower_upper_bound_ops", + ":lrn_ops", + ":matmul_op", + ":matrix_band_part_op", + ":matrix_diag_ops", + ":matrix_inverse_op", + ":matrix_solve_op", + ":matrix_triangular_solve_op", + ":mirror_pad_op", + ":next_after_op", + ":no_op", + ":one_hot_op", + ":pack_op", + ":pad_op", + ":pooling_ops", + ":qr_op", + ":quantize_and_dequantize_op", + ":random_ops", + ":random_ops_util", + ":reduce_window_op", + ":reduction_ops", + ":reduction_ops_common", + ":relu_op", + ":replica_id_op", + ":reshape_op", + ":retval_op", + ":reverse_op", + ":reverse_sequence_op", + ":roll_op", + ":scan_ops", + ":scatter_nd_op", + ":segment_reduction_ops", + ":select_op", + ":sendrecv_ops", + ":sequence_ops", + ":shape_op", + ":shape_util", + ":sharding_op", + ":sharding_util_ops", + ":slice_op", + ":softmax_op", + ":sort_ops", + ":spacetobatch_op", + ":spacetodepth_op", + ":sparse_to_dense_op", + ":split_op", + ":spmd_manual_sharding_ops", + ":stack_ops", + ":stateful_random_ops", + ":stateless_random_ops", + ":stateless_random_ops_v2", + ":stochastic_cast_op", + ":strided_slice_op", + ":tensor_array_ops", + ":tensor_list_ops", + ":tile_ops", + ":to_bool_op", + ":topk_op", + ":training_ops", + ":transpose_op", + ":tridiagonal_ops", + ":unary_ops", + ":unary_ops_composition", + ":uniform_quantized_ops", + ":unique_op", + ":unpack_op", + ":variable_ops", + ":where_op", + ":while_op", + ":xla_broadcast_helper_op", + ":xla_call_module_op", + ":xla_conv_op", + ":xla_custom_call_op", + ":xla_custom_call_v2_op", + ":xla_dequantize_op", + ":xla_dot_op", + ":xla_optimization_barrier_op", + ":xla_pad_op", + ":xla_reduce_op", + ":xla_reduce_precision_op", + ":xla_select_and_scatter_op", + ":xla_self_adjoint_eig_op", + ":xla_svd_op", + ], +) + +tf_cuda_library( + name = "light_outside_compilation", + srcs = ["light_outside_compilation.cc"], + hdrs = ["light_outside_compilation.h"], + visibility = ["//visibility:public"], + deps = [ + ":callback_proto_cc", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/core:framework", + "//tensorflow/core:gpu_runtime", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:process_state", + "//tensorflow/core/platform:env", + "//tensorflow/core/platform:refcount", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/cleanup", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/memory", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/synchronization", + "@com_google_absl//absl/types:span", + "@tsl//tsl/platform:fingerprint", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/service:custom_call_status", + "@xla//xla/service:custom_call_target_registry", + "@xla//xla/service:hlo_proto_cc", + "@xla//xla/stream_executor:device_memory", + "@xla//xla/stream_executor:platform", + "@xla//xla/stream_executor:platform_manager", + "@xla//xla/stream_executor:stream", + "@xla//xla/stream_executor:stream_executor_h", + "@xla//xla/stream_executor:stream_finder", + "@xla//xla/tsl/lib/strings:proto_serialization", + "@xla//xla/tsl/platform:errors", + "@xla//xla/tsl/platform:statusor", + ], + alwayslink = 1, +) + +# A separate cc_library for resampler_ops is needed because resampler is in +# contrib/, and thus the declaration of resampler cannot be pulled into the deps +# of xla_ops. Therefore, resampler_ops is its own cc_library target, and its +# corresponding tf_kernel_library is defined in contrib/resampler/BUILD. +cc_library( + name = "resampler_ops", + srcs = ["resampler_ops.cc"], + hdrs = ["resampler_ops.h"], + visibility = ["//visibility:public"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + ], + alwayslink = 1, +) + +# See note on resampler_ops target for why this is also a seprate op. +cc_library( + name = "resampler_addon_ops", + srcs = ["resampler_addon_ops.cc"], + visibility = ["//visibility:public"], + deps = [ + ":resampler_ops", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/core:protos_all_cc", + ], + alwayslink = 1, +) + +cc_library( + name = "conv_op_helpers", + srcs = ["conv_op_helpers.cc"], + hdrs = ["conv_op_helpers.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/framework:bounds_check", + "//tensorflow/core/kernels:conv_grad_shape_utils", + "//tensorflow/core/platform:statusor", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@tsl//tsl/platform:tensor_float_32_hdr_lib", + "@xla//xla:literal_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + ] + if_static(["@tsl//tsl/platform:tensor_float_32_utils"]), +) + +cc_library( + name = "tensor_list_utils", + srcs = ["tensor_list_utils.cc"], + hdrs = ["tensor_list_utils.h"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_expression", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@xla//xla:literal_util", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +cc_library( + name = "if_while_utils", + srcs = ["if_while_utils.cc"], + hdrs = ["if_while_utils.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_expression", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:function_body", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@xla//xla:literal", + "@xla//xla/hlo/builder:value_inference", + ], +) + +cc_library( + name = "xla_call_module_loader", + srcs = ["xla_call_module_loader.cc"], + hdrs = ["xla_call_module_loader.h"], + deps = [ + "//tensorflow/compiler/jit:flags", + "//tensorflow/compiler/mlir/tensorflow:dump_mlir_util", + "//tensorflow/compiler/mlir/tensorflow:error_util", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/log:vlog_is_on", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Parser", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:Support", + "@llvm-project//mlir:Transforms", + "@shardy//shardy/dialect/sdy/ir:dialect", + "@shardy//shardy/dialect/sdy/transforms/import:passes", + "@stablehlo//:chlo_ops", + "@stablehlo//:stablehlo_ops", + "@stablehlo//:stablehlo_passes", + "@stablehlo//:stablehlo_passes_optimization", + "@stablehlo//:stablehlo_serialization", + "@stablehlo//:vhlo_ops", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/translate:stablehlo", + "@xla//xla/mlir/utils:type_util", + "@xla//xla/python:refine_polymorphic_shapes", + "@xla//xla/service:hlo_proto_cc", + "@xla//xla/service/spmd/shardy/sdy_round_trip:pipelines", + "@xla//xla/tsl/platform:errors", + "@xla//xla/tsl/platform:statusor", + ], +) + +tf_kernel_library( + name = "xla_call_module_op", + srcs = ["xla_call_module_op.cc"], + deps = [ + ":xla_call_module_loader", + "//tensorflow/compiler/mlir/tensorflow:convert_type", + "//tensorflow/compiler/mlir/tensorflow:dump_mlir_util", + "//tensorflow/compiler/tf2xla:side_effect_util", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:types", + "//tensorflow/core/tpu:tpu_defs", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@llvm-project//llvm:Support", + "@llvm-project//mlir:FuncDialect", + "@llvm-project//mlir:FuncExtensions", + "@llvm-project//mlir:IR", + "@llvm-project//mlir:Pass", + "@llvm-project//mlir:Support", + "@stablehlo//:stablehlo_ops", + "@xla//xla:debug_options_flags", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/ir:hlo", + "@xla//xla/hlo/translate:stablehlo", + "@xla//xla/hlo/translate/mhlo_to_hlo:type_to_shape", + "@xla//xla/service:hlo_module_config", + "@xla//xla/service/spmd/shardy/stablehlo_round_trip:stablehlo_import", + "@xla//xla/tsl/framework/mlir:status_scoped_diagnostic_handler", + "@xla//xla/tsl/platform:errors", + "@xla//xla/tsl/platform:statusor", + ], +) + +tf_kernel_library( + name = "while_op", + srcs = ["while_op.cc"], + hdrs = ["while_op.h"], + deps = [ + ":if_while_utils", + ":tensor_list_utils", + "//tensorflow/compiler/tf2xla:side_effect_util", + "//tensorflow/compiler/tf2xla:tf2xla_util", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:shape_tree", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:tuple", + "@xla//xla/tsl/platform:errors", + "@xla//xla/tsl/platform:statusor", + ], +) + +tf_kernel_library( + name = "if_op", + srcs = ["if_op.cc"], + hdrs = ["if_op.h"], + deps = [ + ":if_while_utils", + "//tensorflow/compiler/tf2xla:side_effect_util", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/common_runtime:function_body", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:vlog_is_on", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + "@xla//xla/tsl/platform:errors", + ], +) + +tf_kernel_library( + name = "case_op", + srcs = ["case_op.cc"], + hdrs = ["case_op.h"], + deps = [ + ":if_while_utils", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:side_effect_util", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:vlog_is_on", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + ], +) + +# Kernels that have a dummy (no-op) implementation. +tf_kernel_library( + name = "xla_dummy_ops", + srcs = [ + "assert_op.cc", + "check_numerics_op.cc", + ], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/core:array_ops_op_lib", + "//tensorflow/core:lib", + "//tensorflow/core:logging_ops_op_lib", + "@com_google_absl//absl/log", + ], + alwayslink = 1, +) + +tf_proto_library( + name = "callback_proto", + srcs = ["callback.proto"], + protodeps = tf_additional_all_protos(), +) + +cc_library( + name = "rng_converter_utils", + srcs = ["rng_converter_utils.cc"], + hdrs = ["rng_converter_utils.h"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/core:framework", + "@com_google_absl//absl/strings:string_view", + "@xla//xla:xla_data_proto_cc", + ], +) + +tf_kernel_library( + name = "xla_dot_op", + srcs = ["xla_dot_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "training_ops", + srcs = ["training_ops.cc"], + deps = [ + ":cwise_ops", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "batch_matmul_op", + srcs = ["batch_matmul_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:protos_all_cc", + "@tsl//tsl/platform:tensor_float_32_hdr_lib", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder/lib:math", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "softmax_op", + srcs = ["softmax_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "in_topk_op", + srcs = ["in_topk_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:sorting", + ], +) + +tf_kernel_library( + name = "unary_ops_composition", + srcs = ["unary_ops_composition.cc"], + deps = [ + ":cwise_ops", + ":elu_op", + ":relu_op", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "topk_op", + srcs = ["topk_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status:statusor", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:sorting", + ], +) + +tf_kernel_library( + name = "tensor_array_ops", + srcs = ["tensor_array_ops.cc"], + deps = [ + ":gather_op", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:status_macros", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "tile_ops", + srcs = ["tile_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/types:span", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "strided_slice_op", + srcs = ["strided_slice_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/types:span", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + ], +) + +tf_kernel_library( + name = "xla_broadcast_helper_op", + srcs = ["xla_broadcast_helper_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_svd_op", + srcs = ["xla_svd_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:slicing", + "@xla//xla/hlo/builder/lib:svd", + ], +) + +tf_kernel_library( + name = "reduction_ops", + srcs = ["reduction_ops.cc"], + hdrs = ["reduction_ops.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/status", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "batchtospace_op", + srcs = ["batchtospace_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "spmd_manual_sharding_ops", + srcs = ["spmd_manual_sharding_ops.cc"], + deps = [ + "//tensorflow/compiler/mlir/tensorflow:xla_sharding_util", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:types", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "fused_conv_ops", + srcs = ["fused_conv_ops.cc"], + deps = [ + ":conv_op_helpers", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "matrix_band_part_op", + srcs = ["matrix_band_part_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + ], +) + +tf_kernel_library( + name = "clip_by_value_op", + srcs = ["clip_by_value_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "sharding_util_ops", + srcs = ["sharding_util_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "sort_ops", + srcs = ["sort_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:comparators", + ], +) + +tf_kernel_library( + name = "matrix_inverse_op", + srcs = ["matrix_inverse_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:matrix", + "@xla//xla/hlo/builder/lib:qr", + ], +) + +tf_kernel_library( + name = "reduce_window_op", + srcs = ["reduce_window_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + ], +) + +tf_kernel_library( + name = "pad_op", + srcs = ["pad_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@xla//xla:literal", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "function_ops", + srcs = ["function_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + ], +) + +tf_kernel_library( + name = "sparse_to_dense_op", + srcs = ["sparse_to_dense_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:scatter", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "reverse_op", + srcs = ["reverse_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/container:inlined_vector", + "@xla//xla:literal", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "random_ops", + srcs = ["random_ops.cc"], + deps = [ + ":gather_op", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/lib:random", + "//tensorflow/compiler/tf2xla/lib:util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status:statusor", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:comparators", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + "@xla//xla/hlo/builder/lib:loops", + "@xla//xla/tsl/platform:statusor", + ], +) + +tf_kernel_library( + name = "gather_op", + srcs = ["gather_op.cc"], + hdrs = ["gather_op_helpers.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:optional", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client:client_library", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:slicing", + ], +) + +tf_kernel_library( + name = "segment_reduction_ops", + srcs = ["segment_reduction_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:scatter", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "dynamic_partition_op", + srcs = ["dynamic_partition_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core/tpu:tpu_defs", + "@com_google_absl//absl/algorithm:container", + "@xla//xla:comparison_util", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:comparators", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "transpose_op", + srcs = ["transpose_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:scatter", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/status", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "identity_op", + srcs = ["identity_op.cc"], + deps = [ + ":tensor_list_utils", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log:check", + ], +) + +tf_kernel_library( + name = "tensor_list_ops", + srcs = ["tensor_list_ops.cc"], + deps = [ + ":gather_op", + ":tensor_list_utils", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "cross_op", + srcs = ["cross_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "next_after_op", + srcs = ["next_after_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "stochastic_cast_op", + srcs = ["stochastic_cast_op.cc"], + deps = [ + ":random_ops_util", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/kernels:stochastic_cast_op_header", + "@com_google_absl//absl/status:statusor", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "select_op", + srcs = ["select_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/algorithm:container", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "l2loss_op", + srcs = ["l2loss_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "arg_op", + srcs = ["arg_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "shape_util", + srcs = ["shape_util.cc"], + hdrs = ["shape_util.h"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/status", + ], +) + +tf_kernel_library( + name = "to_bool_op", + srcs = ["to_bool_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/status", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "mirror_pad_op", + srcs = ["mirror_pad_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status:statusor", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "xla_reduce_op", + srcs = ["xla_reduce_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + ], +) + +tf_kernel_library( + name = "qr_op", + srcs = ["qr_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:qr", + ], +) + +tf_kernel_library( + name = "slice_op", + srcs = ["slice_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/types:span", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + ], +) + +tf_kernel_library( + name = "pack_op", + srcs = ["pack_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla:literal_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "all_reduce_op", + srcs = ["all_reduce_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "sharding_op", + srcs = ["sharding_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:sharding_util", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@xla//xla:sharding_op_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "concat_op", + srcs = ["concat_op.cc"], + deps = [ + ":shape_util", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "scan_ops", + srcs = ["scan_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + ], +) + +tf_kernel_library( + name = "image_resize_ops", + srcs = ["image_resize_ops.cc"], + hdrs = ["image_resize_ops.h"], + deps = [ + "//tensorflow/compiler/jit:xla_activity_listener", + "//tensorflow/compiler/jit:xla_activity_proto_cc", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/types:span", + "@xla//xla:array4d", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "spacetobatch_op", + srcs = ["spacetobatch_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/util:overflow", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/types:span", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "lrn_ops", + srcs = ["lrn_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@xla//xla/hlo/builder:padding", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "binary_ops", + srcs = ["binary_ops.cc"], + deps = [ + ":cwise_ops", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/client:client_library", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "roll_op", + srcs = ["roll_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:slicing", + ], +) + +tf_kernel_library( + name = "random_ops_util", + srcs = ["random_ops_util.cc"], + hdrs = ["random_ops_util.h"], + deps = [ + ":rng_converter_utils", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/kernels:stateless_random_ops_v2_header", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:prng", + ], +) + +tf_kernel_library( + name = "unary_ops", + srcs = ["unary_ops.cc"], + deps = [ + ":cwise_ops", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/status:statusor", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + "@xla//xla/tsl/platform:statusor", + ], +) + +tf_kernel_library( + name = "cwise_ops", + srcs = ["cwise_ops.cc"], + hdrs = ["cwise_ops.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla/client:client_library", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "matrix_triangular_solve_op", + srcs = ["matrix_triangular_solve_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "relu_op", + srcs = ["relu_op.cc"], + hdrs = ["relu_op.h"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@xla//xla:literal", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "reduction_ops_common", + srcs = ["reduction_ops_common.cc"], + deps = [ + ":reduction_ops", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + ], +) + +tf_kernel_library( + name = "bucketize_op", + srcs = ["bucketize_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + ], +) + +tf_kernel_library( + name = "depthtospace_op", + srcs = ["depthtospace_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:data_format", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_optimization_barrier_op", + srcs = ["xla_optimization_barrier_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + ], +) + +tf_kernel_library( + name = "matmul_op", + srcs = ["matmul_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@tsl//tsl/platform:tensor_float_32_hdr_lib", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "matrix_solve_op", + srcs = ["matrix_solve_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:matrix", + "@xla//xla/hlo/builder/lib:qr", + ], +) + +tf_kernel_library( + name = "categorical_op", + srcs = ["categorical_op.cc"], + deps = [ + ":random_ops_util", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:prng", + ], +) + +tf_kernel_library( + name = "dynamic_stitch_op", + srcs = ["dynamic_stitch_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "beta_op", + srcs = ["beta_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:status_macros", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:loops", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "unique_op", + srcs = ["unique_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:optional", + "@com_google_absl//absl/types:span", + "@xla//xla:comparison_util", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:comparators", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "reshape_op", + srcs = ["reshape_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/log", + "@xla//xla:literal", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "pooling_ops", + srcs = ["pooling_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:padding", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:pooling", + ], +) + +tf_kernel_library( + name = "data_format_ops", + srcs = ["data_format_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:slicing", + ], +) + +tf_kernel_library( + name = "xla_dequantize_op", + srcs = ["xla_dequantize_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:types", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:quantize", + ], +) + +tf_kernel_library( + name = "const_op", + srcs = ["const_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "shape_op", + srcs = ["shape_op.cc"], + deps = [ + ":shape_util", + ":tensor_list_utils", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla:literal_util", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "image_ops", + srcs = ["image_ops.cc"], + deps = [ + ":gather_op", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:comparators", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + "@xla//xla/hlo/builder/lib:loops", + "@xla//xla/hlo/builder/lib:sorting", + ], +) + +tf_kernel_library( + name = "retval_op", + srcs = ["retval_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@xla//xla:status_macros", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_custom_call_v2_op", + srcs = ["xla_custom_call_v2_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/service:hlo_proto_cc", + ], +) + +tf_kernel_library( + name = "listdiff_op", + srcs = ["listdiff_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:flat_hash_set", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "sendrecv_ops", + srcs = ["sendrecv_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:types", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "conv_ops", + srcs = ["conv_ops.cc"], + deps = [ + ":conv_op_helpers", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:literal_util", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "dequantize_op", + srcs = ["dequantize_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "ensure_shape_op", + srcs = ["ensure_shape_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "where_op", + srcs = ["where_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:comparators", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + ], +) + +tf_kernel_library( + name = "stack_ops", + srcs = ["stack_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_reduce_precision_op", + srcs = ["xla_reduce_precision_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + ], +) + +tf_kernel_library( + name = "diag_op", + srcs = ["diag_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:matrix", + "@xla//xla/hlo/builder/lib:pooling", + ], +) + +tf_kernel_library( + name = "index_ops", + srcs = ["index_ops.cc"], + hdrs = ["index_ops.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + ], +) + +tf_kernel_library( + name = "lower_upper_bound_ops", + srcs = ["lower_upper_bound_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/status", + "@xla//xla:comparison_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "spacetodepth_op", + srcs = ["spacetodepth_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:data_format", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/types:span", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "empty_op", + srcs = ["empty_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "bincount_op", + srcs = ["bincount_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:comparators", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "tridiagonal_ops", + srcs = ["tridiagonal_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla/hlo/builder/lib:slicing", + "@xla//xla/hlo/builder/lib:tridiagonal", + ], +) + +tf_kernel_library( + name = "device_index_op", + srcs = ["device_index_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/container:flat_hash_map", + "@com_google_absl//absl/strings", + "@xla//xla/client:client_library", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "bcast_ops", + srcs = ["bcast_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal", + "@xla//xla/hlo/builder:value_inference", + ], +) + +tf_kernel_library( + name = "aggregate_ops", + srcs = ["aggregate_ops.cc"], + deps = [ + ":tensor_list_utils", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:lib", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "split_op", + srcs = ["split_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla:shape_util", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "replica_id_op", + srcs = ["replica_id_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "bias_ops", + srcs = ["bias_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_select_and_scatter_op", + srcs = ["xla_select_and_scatter_op.cc"], + deps = [ + ":while_op", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + ], +) + +tf_kernel_library( + name = "stateless_random_ops_v2", + srcs = ["stateless_random_ops_v2.cc"], + deps = [ + ":random_ops_util", + ":rng_converter_utils", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:random", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/kernels:stateless_random_ops_v2_header", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:string_view", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:dynamic_shaped_ops", + "@xla//xla/hlo/builder/lib:prng", + ], +) + +tf_kernel_library( + name = "approx_topk_op", + srcs = ["approx_topk_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/tpu:tpu_defs", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:str_format", + "@com_google_absl//absl/types:span", + "@xla//xla:literal_util", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:approx_topk", + ], +) + +tf_kernel_library( + name = "stateful_random_ops", + srcs = ["stateful_random_ops.cc"], + deps = [ + ":random_ops_util", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:random", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/kernels:stateful_random_ops_header", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:prng", + ], +) + +tf_kernel_library( + name = "no_op", + srcs = ["no_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + ], +) + +tf_kernel_library( + name = "xla_conv_op", + srcs = ["xla_conv_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "@xla//xla:xla_data_proto_cc", + ], +) + +tf_kernel_library( + name = "broadcast_to_op", + srcs = ["broadcast_to_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:lib", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "sequence_ops", + srcs = ["sequence_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/status:statusor", + "@xla//xla:literal", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "variable_ops", + srcs = ["variable_ops.cc"], + deps = [ + ":gather_op", + ":shape_util", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:scatter", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/kernels:resource_variable_util", + "//tensorflow/core/kernels:scatter_nd_util", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:types", + "@com_google_absl//absl/status", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:slicing", + "@xla//xla/tsl/platform:errors", + ], +) + +tf_kernel_library( + name = "matrix_diag_ops", + srcs = ["matrix_diag_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@eigen_archive//:eigen3", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "reverse_sequence_op", + srcs = ["reverse_sequence_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "xla_custom_call_op", + srcs = ["xla_custom_call_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/log:check", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_self_adjoint_eig_op", + srcs = ["xla_self_adjoint_eig_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla/hlo/builder/lib:self_adjoint_eig", + ], +) + +tf_kernel_library( + name = "cast_op", + srcs = ["cast_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/lib:util", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "dynamic_slice_ops", + srcs = ["dynamic_slice_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log:check", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "fft_ops", + srcs = ["fft_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:literal_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "xla_pad_op", + srcs = ["xla_pad_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "one_hot_op", + srcs = ["one_hot_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:types", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "unpack_op", + srcs = ["unpack_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "elu_op", + srcs = ["elu_op.cc"], + hdrs = ["elu_op.h"], + deps = [ + ":cwise_ops", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@xla//xla:literal", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_kernel_library( + name = "batch_norm_op", + srcs = ["batch_norm_op.cc"], + deps = [ + ":relu_op", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "extract_image_patches_op", + srcs = ["extract_image_patches_op.cc"], + deps = [ + ":conv_op_helpers", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "scatter_nd_op", + srcs = ["scatter_nd_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:scatter", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "@com_google_absl//absl/status", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "fill_op", + srcs = ["fill_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:value_inference", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "stateless_random_ops", + srcs = ["stateless_random_ops.cc"], + deps = [ + ":random_ops_util", + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/lib:broadcast", + "//tensorflow/compiler/tf2xla/lib:random", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/strings:string_view", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:prng", + ], +) + +tf_kernel_library( + name = "gather_scatter_ops", + srcs = ["gather_scatter_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + ], +) + +tf_kernel_library( + name = "einsum_op", + srcs = ["einsum_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "cholesky_op", + srcs = ["cholesky_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:matrix", + ], +) + +tf_kernel_library( + name = "quantize_and_dequantize_op", + srcs = ["quantize_and_dequantize_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + "@xla//xla/hlo/builder/lib:arithmetic", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +tf_kernel_library( + name = "fake_quantize_ops", + srcs = ["fake_quantize_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:arithmetic", + ], +) + +tf_kernel_library( + name = "fake_param_op", + srcs = ["fake_param_op.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/compiler/tf2xla:xla_compilation_device", + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_context", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/compiler/tf2xla:xla_resource", + "//tensorflow/compiler/tf2xla/ops:xla_ops", + "//tensorflow/core:framework", + "//tensorflow/core:protos_all_cc", + "@xla//xla/hlo/builder/lib:constants", + ], +) + +tf_cc_test( + name = "rng_converter_utils_test", + srcs = ["rng_converter_utils_test.cc"], + deps = [ + ":rng_converter_utils", + "//tensorflow/compiler/tf2xla:xla_op_registry", + "//tensorflow/core:framework", + "@com_google_googletest//:gtest_main", + "@xla//xla:xla_data_proto_cc", + ], +) + +tf_kernel_library( + name = "uniform_quantized_ops", + srcs = ["uniform_quantized_ops.cc"], + deps = [ + "//tensorflow/compiler/tf2xla:mlir_xla_op_kernel", + "//tensorflow/compiler/tf2xla:xla_op_registry", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/aggregate_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/aggregate_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..1fc866aa6c49ddcec96e77dbf534f69d782421f5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/aggregate_ops.cc @@ -0,0 +1,101 @@ +/* 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 "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +namespace { + +class AddNOp : public XlaOpKernel { + public: + explicit AddNOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + if (!ctx->ValidateInputsAreSameShape(this)) return; + + OP_REQUIRES( + ctx, ctx->num_inputs() >= 1, + absl::InvalidArgumentError("AddN requires at least one argument")); + + XlaExpression::Kind kind = ctx->InputExpression(0).kind(); + xla::XlaOp sum; + switch (kind) { + case XlaExpression::Kind::kTensorList: { + // Check that all TensorLists are initialized. + for (int i = 1; i < ctx->num_inputs(); ++i) { + xla::XlaOp list = ctx->Input(i); + bool is_initialized; + OP_REQUIRES_OK(ctx, IsTensorListInitialized(list, &is_initialized)); + OP_REQUIRES(ctx, is_initialized, + absl::InvalidArgumentError(absl::StrCat( + "TensorList input #", i, + " for AddN op is an uninitialized list"))); + } + // Nested TensorList is not supported. + bool is_nested_list; + OP_REQUIRES_OK(ctx, IsNestedTensorList(ctx->Input(0), &is_nested_list)); + OP_REQUIRES(ctx, !is_nested_list, + absl::UnimplementedError( + "Nested TensorList is not supported for AddN op")); + + OP_REQUIRES_OK(ctx, GetTensorListBuffer(ctx->Input(0), &sum)); + xla::Shape sum_shape; + OP_REQUIRES_OK(ctx, + GetTensorListBufferShape(ctx->Input(0), &sum_shape)); + for (int i = 1; i < ctx->num_inputs(); ++i) { + xla::XlaOp operand; + OP_REQUIRES_OK(ctx, GetTensorListBuffer(ctx->Input(i), &operand)); + // Check that the shapes match. + xla::Shape operand_shape; + OP_REQUIRES_OK( + ctx, GetTensorListBufferShape(ctx->Input(i), &operand_shape)); + OP_REQUIRES( + ctx, sum_shape.dimensions() == operand_shape.dimensions(), + absl::InvalidArgumentError(absl::StrCat( + "TensorList arguments to AddN must all have the same ", + "shape.\n", "Expected: ", sum_shape.ToString(), "\n", + "Found: ", operand_shape.ToString()))); + sum = xla::Add(sum, operand); + } + xla::XlaOp push_index; + OP_REQUIRES_OK(ctx, GetTensorListPushIndex(ctx->Input(0), &push_index)); + OP_REQUIRES_OK(ctx, BuildNonNestedTensorList(sum, push_index, &sum)); + ctx->SetTensorListOutput(0, sum); + break; + } + default: + sum = ctx->Input(0); + for (int i = 1; i < ctx->num_inputs(); ++i) { + sum = xla::Add(sum, ctx->Input(i)); + } + ctx->SetOutput(0, sum); + } + } + + private: + AddNOp(const AddNOp&) = delete; + void operator=(const AddNOp&) = delete; +}; + +REGISTER_XLA_OP(Name("AddN").AllowVariantTypes(), AddNOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/all_reduce_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/all_reduce_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..72a9e62c8f414680170b9776ce5191c342081673 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/all_reduce_op.cc @@ -0,0 +1,127 @@ +/* Copyright 2021 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 +#include +#include + +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { + +class CollectiveReduceV2Op : public XlaOpKernel { + public: + explicit CollectiveReduceV2Op(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("merge_op", &merge_op_name_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("final_op", &final_op_name_)); + OP_REQUIRES_OK(ctx, + ctx->GetAttr("communication_hint", &communication_hint_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + int64_t group_key, group_size; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("group_key", &group_key)); + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntScalar("group_size", &group_size)); + OP_REQUIRES(ctx, + communication_hint_ == "nccl" || communication_hint_ == "auto", + absl::InvalidArgumentError(absl::StrCat( + "Only compiling NCCL/auto collective is supported, got: ", + communication_hint_))); + + // Store all traversed collective configurations, and generate channel_id + // for the collective. + absl::StatusOr channel_id = + ctx->xla_context()->RecordCollectiveInfo(group_key, group_size); + OP_REQUIRES_OK(ctx, channel_id.status()); + + DataType dtype = XlaHelpers::SumAccumulationType(ctx->input_type(0)); + OP_REQUIRES(ctx, merge_op_name_ == "Add" || merge_op_name_ == "Mul", + absl::InvalidArgumentError( + absl::StrCat("Only Add and Mul reduction supported " + "for tf2xla all-reduce lowering, got: ", + merge_op_name_))); + const xla::XlaComputation* reducer = [&] { + if (merge_op_name_ == "Add") { + return ctx->GetOrCreateAdd(dtype); + } + CHECK_EQ(merge_op_name_, "Mul"); + return ctx->GetOrCreateMul(dtype); + }(); + + OP_REQUIRES(ctx, final_op_name_ == "Id", + absl::InvalidArgumentError( + "Only 'Id' is supported as a final operation " + "for all-reduce tf2xla lowering")); + VLOG(2) << "Emitting xla::AllReduce on channel " << *channel_id + << " for Op " << ctx->op_kernel().name() + << " group_size=" << group_size << " group_key=" << group_key; + xla::ChannelHandle channel_handle; + channel_handle.set_type(xla::ChannelHandle::DEVICE_TO_DEVICE); + channel_handle.set_handle(*channel_id); + std::vector replica_groups(1); + for (int64_t i = 0; i < group_size; i++) { + replica_groups[0].add_replica_ids(i); + } + ctx->SetOutput(0, xla::AllReduce(ctx->Input(0), *reducer, replica_groups, + channel_handle)); + } + + private: + DataType dtype_ = DT_INVALID; + std::string merge_op_name_; + std::string final_op_name_; + std::string communication_hint_; + + CollectiveReduceV2Op(const CollectiveReduceV2Op&) = delete; + void operator=(const CollectiveReduceV2Op&) = delete; +}; + +REGISTER_XLA_OP(Name("CollectiveReduceV2") + .CompileTimeConstantInput("group_key") + .CompileTimeConstantInput("group_size"), + CollectiveReduceV2Op); + +REGISTER_XLA_OP(Name("CollectiveAssignGroupV2") + .CompileTimeConstantInput("group_assignment"), + MlirXlaOpKernel); + +REGISTER_XLA_OP(Name("XlaReduceScatter") + .CompileTimeConstantInput("group_assignment") + .CompileTimeConstantInput("scatter_dimension"), + MlirXlaOpKernel); + +REGISTER_XLA_OP( + Name("XlaAllReduce").CompileTimeConstantInput("group_assignment"), + MlirXlaOpKernel); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/approx_topk_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/approx_topk_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..9f5570b763dd3f28968eb35c5d0e4cb58780677c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/approx_topk_op.cc @@ -0,0 +1,168 @@ +/* Copyright 2022 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 +#include + +#include "absl/strings/str_format.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/lib/approx_topk.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/literal_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/tpu/tpu_defs.h" +namespace tensorflow { +namespace { + +xla::XlaComputation ComparatorBuilder(xla::XlaBuilder* builder, + xla::PrimitiveType op_type, + bool is_max_k) { + auto p0 = xla::Parameter(builder, 0, xla::ShapeUtil::MakeScalarShape(op_type), + "v0"); + auto p1 = xla::Parameter(builder, 1, xla::ShapeUtil::MakeScalarShape(op_type), + "v1"); + xla::Parameter(builder, 2, xla::ShapeUtil::MakeScalarShape(xla::S32), "a2"); + xla::Parameter(builder, 3, xla::ShapeUtil::MakeScalarShape(xla::S32), "a3"); + if (is_max_k) { + xla::Gt(p0, p1); + } else { + xla::Lt(p0, p1); + } + return builder->BuildAndNoteError(); +} + +class ApproxTopKOpBase : public XlaOpKernel { + public: + explicit ApproxTopKOpBase(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + // k is static instead of dynamic. + // This is required for deriving the approximation algorithm. + OP_REQUIRES_OK(ctx, ctx->GetAttr("k", &k_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("reduction_dimension", &reduction_dim_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("recall_target", &recall_target_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("is_max_k", &is_max_k_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("reduction_input_size_override", + &reduction_input_size_override_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("aggregate_to_topk", &aggregate_to_topk_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::Shape op_shape = ctx->InputXlaShape(0).value(); + xla::PrimitiveType op_type = op_shape.element_type(); + + int64_t reduction_dim = reduction_dim_; + if (reduction_dim < 0) { + // Reverse index. + reduction_dim += op_shape.dimensions().size(); + } + auto cmp_builder = ctx->builder()->CreateSubBuilder( + absl::StrFormat("top_k_%s_comparator", is_max_k_ ? "gt" : "lt")); + xla::XlaComputation comparator = + ComparatorBuilder(cmp_builder.get(), op_type, is_max_k_); + + xla::XlaOp init_val = xla::ConstantLiteral( + ctx->builder(), is_max_k_ ? xla::LiteralUtil::MinValue(op_type) + : xla::LiteralUtil::MaxValue(op_type)); + xla::XlaOp init_arg = xla::ConstantR0(ctx->builder(), -1); + xla::XlaOp iota = xla::Iota( + ctx->builder(), + xla::ShapeUtil::MakeShapeWithType(op_shape.dimensions()), + reduction_dim); + xla::XlaOp output_tuple = ApproxTopKFn( + ctx->builder(), {ctx->Input(0), iota}, {init_val, init_arg}, k_, + reduction_dim, comparator, recall_target_, aggregate_to_topk_, + reduction_input_size_override_); + ctx->SetOutput(0, xla::GetTupleElement(output_tuple, 0)); + ctx->SetOutput(1, xla::GetTupleElement(output_tuple, 1)); + } + + protected: + virtual xla::XlaOp ApproxTopKFn( + xla::XlaBuilder* builder, absl::Span operands, + absl::Span init_values, int64_t top_k, + int64_t reduction_dim, const xla::XlaComputation& comparator, + float recall_target, bool aggregate_to_topk, + int64_t reduction_input_size_override) const = 0; + + private: + int64_t k_; + int64_t reduction_dim_; + float recall_target_; + bool is_max_k_; + int64_t reduction_input_size_override_; + bool aggregate_to_topk_; + + ApproxTopKOpBase(const ApproxTopKOpBase&) = delete; + void operator=(const ApproxTopKOpBase&) = delete; +}; + +class TpuApproxTopKOp : public ApproxTopKOpBase { + public: + explicit TpuApproxTopKOp(OpKernelConstruction* ctx) : ApproxTopKOpBase(ctx) {} + + protected: + xla::XlaOp ApproxTopKFn( + xla::XlaBuilder* builder, absl::Span operands, + absl::Span init_values, int64_t top_k, + int64_t reduction_dim, const xla::XlaComputation& comparator, + float recall_target, bool aggregate_to_topk, + int64_t reduction_input_size_override) const override { + return xla::ApproxTopK(builder, operands, init_values, top_k, reduction_dim, + comparator, recall_target, aggregate_to_topk, + reduction_input_size_override); + } +}; + +class FallbackApproxTopKOp : public ApproxTopKOpBase { + public: + explicit FallbackApproxTopKOp(OpKernelConstruction* ctx) + : ApproxTopKOpBase(ctx) {} + + protected: + xla::XlaOp ApproxTopKFn( + xla::XlaBuilder* builder, absl::Span operands, + absl::Span init_values, int64_t top_k, + int64_t reduction_dim, const xla::XlaComputation& comparator, + float recall_target, bool aggregate_to_topk, + int64_t reduction_input_size_override) const override { + return xla::ApproxTopKFallback( + builder, operands, init_values, top_k, reduction_dim, comparator, + recall_target, aggregate_to_topk, reduction_input_size_override); + } +}; + +// Register for TPU +REGISTER_XLA_OP(Name("ApproxTopK") + .Device(absl::Span{ + DEVICE_TPU, DEVICE_TPU_XLA_JIT}) + .TypeConstraint("T", {DT_FLOAT, DT_HALF, DT_BFLOAT16}), + TpuApproxTopKOp); + +// Register for all registered devices except for TPU since it is already +// registered. +REGISTER_XLA_OP( + Name("ApproxTopK").TypeConstraint("T", {DT_FLOAT, DT_HALF, DT_BFLOAT16}), + FallbackApproxTopKOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/arg_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/arg_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..aece970db8a0e672842ac75adacc1a1ec5f55117 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/arg_op.cc @@ -0,0 +1,125 @@ +/* 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 + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_compilation_device.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +// This OpKernel implements the _Arg Op for XLA JIT devices. It +// associates its output with one of the arguments to a +// subcomputation. +class XlaArgOp : public XlaOpKernel { + public: + explicit XlaArgOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("index", &index_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + // If 'frame' is non-null, this is a function call inside an outer JIT + // compilation. Use the usual implementation of _Arg. + auto frame = ctx->call_frame(); + if (frame != nullptr) { + const Tensor* val; + OP_REQUIRES_OK(ctx, frame->GetArg(index_, &val)); + // Types that cannot be copied using memcpy (like DT_STRING) are wrapped + // in a DT_UINT8 and hence the type mismatches. Skip the test in such + // cases. See XlaOpKernelContext::SetOutputExpression for details. + if (DataTypeCanUseMemcpy(dtype_)) { + OP_REQUIRES(ctx, val->dtype() == dtype_, + absl::InvalidArgumentError(absl::StrCat( + "Type mismatch: actual ", DataTypeString(val->dtype()), + " vs. expect ", DataTypeString(dtype_)))); + } + // Forwards the argument from the frame. + ctx->op_kernel_context()->set_output(0, *val); + return; + } + + const XlaExpression& arg = ctx->xla_context()->args()[index_]; + OP_REQUIRES( + ctx, arg.kind() != XlaExpression::Kind::kInvalid, + absl::InvalidArgumentError("Invalid/missing argument expression")); + if (ctx->expected_output_dtype(0) == DT_VARIANT) { + ctx->SetTensorListOutput(0, arg.handle()); + } else if (arg.value_bound().has_value()) { + // The argument has a bound attached to it, call SetBound op on the + // argument. + xla::XlaBuilder* builder = ctx->builder(); + auto input_op = arg.AsXlaOp(builder); + + // We pass two pieces of information to SetBound: + // Bound - The upper-bounds of the argument's values. + // + // Dynamism - Whether or not each individual value is dynamic. If this + // is false, it means value with same tensor index in the argument is + // static, and it's upper-bound is same as lower-bound and also same as + // the static value itself. + // + // E.g.,: + // When we have an argument `arg` with shape s32[3], bound = [1, 2, 3] and + // dynamism = [false, false, true] + // + // We know that: + // arg[0] is a static value, its value is 1 + // arg[1] is a static value, its value is 2 + // arg[2] is a dynamic value, its value is unknown at compile time, but + // its upper-bound is known to be 3. + // + // Note that `arg` is still considered dynamic as long as one element + // inside is dynamic, therefore the argument node can't be constant folded + // into a constant node. + xla::Literal bound = HostTensorToLiteral(*arg.value_bound()).value(); + xla::Literal dynamism = + HostTensorToLiteral(*arg.value_dynamism()).value(); + xla::Literal tuple = xla::LiteralUtil::MakeTupleOwned( + std::move(bound), std::move(dynamism)); + ctx->SetOutput(0, xla::CustomCall(builder, "SetBound", {input_op}, + builder->GetShape(input_op).value(), "", + false, {}, &tuple)); + return; + } else { + ctx->SetOutputExpression(0, arg); + } + } + + private: + int index_; + DataType dtype_; + + XlaArgOp(const XlaArgOp&) = delete; + void operator=(const XlaArgOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("_Arg").AllowResourceTypes().AllowVariantTypes().CompilationOnly(), + XlaArgOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/assert_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/assert_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..b8690b68b81136af0d9595824ccf75bb28c0034b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/assert_op.cc @@ -0,0 +1,51 @@ +/* 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 "absl/log/log.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/mutex.h" + +namespace tensorflow { + +namespace { + +// This TensorFlow op supports the Assert primitive. +class AssertOp : public XlaOpKernel { + public: + explicit AssertOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + ~AssertOp() override = default; + + void Compile(XlaOpKernelContext* ctx) override { + static mutex mu(tensorflow::LINKER_INITIALIZED); + static int log_counter = 0; + + mutex_lock l(mu); + if (log_counter < 20) { + ++log_counter; + LOG(WARNING) << "Ignoring Assert operator " << name(); + } + } + + private: + AssertOp(const AssertOp&) = delete; + void operator=(const AssertOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Assert").CompilationOnly(), AssertOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batch_matmul_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batch_matmul_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..9cfbe7457812088daba3ca549420e17c9b8120d0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batch_matmul_op.cc @@ -0,0 +1,74 @@ +/* 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 + +#include "tensorflow/compiler/tf2xla/lib/util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tsl/platform/tensor_float_32_utils.h" + +namespace tensorflow { +namespace { + +class BatchMatMulOp : public XlaOpKernel { + public: + explicit BatchMatMulOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("adj_x", &adj_x_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("adj_y", &adj_y_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("grad_x", &grad_x_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("grad_y", &grad_y_)); + + if (ctx->HasAttr("Tout")) { + DataType output_type; + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tout", &output_type)); + + xla::PrimitiveType xla_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(output_type, &xla_type)); + preferred_element_type_.emplace(xla_type); + } + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::PrecisionConfig::Precision precision = + tsl::tensor_float_32_execution_enabled() + ? xla::PrecisionConfig::DEFAULT + : xla::PrecisionConfig::HIGHEST; + auto result = + xla::BatchDot(MaybeConjugate(ctx->Input(0), adj_x_), adj_x_, + MaybeConjugate(ctx->Input(1), adj_y_), adj_y_, precision, + preferred_element_type_, grad_x_, grad_y_); + ctx->SetOutput(0, result); + } + + private: + bool adj_x_; + bool adj_y_; + bool grad_x_; + bool grad_y_; + std::optional preferred_element_type_; +}; + +REGISTER_XLA_OP(Name("BatchMatMul"), BatchMatMulOp); +REGISTER_XLA_OP(Name("BatchMatMulV2"), BatchMatMulOp); +REGISTER_XLA_OP(Name("BatchMatMulV3"), BatchMatMulOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batch_norm_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batch_norm_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..64c841fbb77e7ea7d9c959be8035c0049774d896 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batch_norm_op.cc @@ -0,0 +1,366 @@ +/* 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. +==============================================================================*/ + +// XLA implementation of BatchNorm operations. +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/relu_op.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +class FusedBatchNormOp : public XlaOpKernel { + public: + explicit FusedBatchNormOp(OpKernelConstruction* ctx) + : FusedBatchNormOp(ctx, false) {} + + FusedBatchNormOp(OpKernelConstruction* ctx, bool is_batch_norm_ex) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("epsilon", &epsilon_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("is_training", &is_training_)); + OP_REQUIRES_OK( + ctx, ctx->GetAttr("exponential_avg_factor", &exponential_avg_factor_)); + std::string data_format_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); + OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_), + absl::InvalidArgumentError( + absl::StrCat("Invalid data format: ", data_format_str))); + + if (is_batch_norm_ex) { + int num_side_inputs; + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_side_inputs", &num_side_inputs)); + OP_REQUIRES(ctx, num_side_inputs >= 0 && num_side_inputs <= 1, + absl::InvalidArgumentError( + "FusedBatchNormEx supports at most 1 side input.")); + add_side_input_ = (num_side_inputs == 1); + std::string activation_mode; + OP_REQUIRES_OK(ctx, ctx->GetAttr("activation_mode", &activation_mode)); + OP_REQUIRES(ctx, + activation_mode == "Identity" || activation_mode == "Relu", + absl::InvalidArgumentError(absl::StrCat( + "Unsupported FusedBatchNormEx activation mode: ", + activation_mode))); + apply_relu_ = (activation_mode == "Relu"); + } else { + add_side_input_ = false; + apply_relu_ = false; + } + is_on_gpu_ = ctx->device_type().type_string() == DEVICE_GPU_XLA_JIT; + } + + void Compile(XlaOpKernelContext* ctx) override { CompileImpl(ctx); } + + protected: + virtual void CompileImpl(XlaOpKernelContext* ctx) { + xla::XlaBuilder* const b = ctx->builder(); + xla::PrimitiveType input_type; + OP_REQUIRES_OK(ctx, + DataTypeToPrimitiveType(ctx->input_type(0), &input_type)); + xla::PrimitiveType scale_type; + OP_REQUIRES_OK(ctx, + DataTypeToPrimitiveType(ctx->input_type(1), &scale_type)); + + xla::XlaOp input = ctx->Input(0); + TensorShape input_shape = ctx->InputShape(0); + + int feature_index = + GetTensorFeatureDimIndex(input_shape.dims(), data_format_); + + // TODO(b/69928690): support mixed precision in the XLA batch normalization + // operators. As a workaround, cast everything to the statistics type (which + // may be more precise than the input type). + input = xla::ConvertElementType(input, scale_type); + + if (is_training_) { + xla::XlaOp output = xla::BatchNormTraining( + input, ctx->Input(1), ctx->Input(2), epsilon_, feature_index); + + // In training mode, outputs the normalized value as well as the + // calculated mean and variance. Optionally we add side input and apply + // relu activation. + xla::XlaOp converted = + xla::ConvertElementType(xla::GetTupleElement(output, 0), input_type); + if (add_side_input_ && apply_relu_) { + ctx->SetOutput(0, xla::Relu(xla::Add(ctx->Input(5), converted))); + } else if (apply_relu_) { + ctx->SetOutput(0, xla::Relu(converted)); + } else { + ctx->SetOutput(0, converted); + } + + xla::XlaOp variance = xla::GetTupleElement(output, 2); + // Apply Bessel's correction. + int total_input_size = ctx->InputShape(0).num_elements(); + int total_scale_size = ctx->InputShape(1).num_elements(); + int sample_size = + total_scale_size > 0 ? total_input_size / total_scale_size : 0; + int sample_size_minus_one = std::max(1, sample_size - 1); + double factor = static_cast(sample_size) / + static_cast(sample_size_minus_one); + + constexpr int kVarianceOutputIndex = 2; + xla::XlaOp corrected = + xla::Mul(variance, xla::ScalarLike(variance, factor)); + if (input_shape.num_elements() == 0) { + auto status_or_output_shape = b->GetShape(corrected); + OP_REQUIRES_OK(ctx, status_or_output_shape.status()); + ctx->SetOutput(1, xla::GetTupleElement(output, 1)); + ctx->SetOutput( + kVarianceOutputIndex, + xla::Broadcast( + xla::NanValue(b, ctx->output_xla_type(kVarianceOutputIndex)), + status_or_output_shape.value().dimensions())); + + } else { + if (exponential_avg_factor_ == 1.0f) { + ctx->SetOutput(1, xla::GetTupleElement(output, 1)); + ctx->SetOutput(2, corrected); + } else { + xla::XlaOp old_mean = ctx->Input(3); + xla::XlaOp alpha = + xla::ScalarLike(old_mean, 1.0f - exponential_avg_factor_); + xla::XlaOp beta = xla::ScalarLike(old_mean, exponential_avg_factor_); + // new_running_mean = alpha * old_mean + beta * batch_mean. + xla::XlaOp new_running_mean = + xla::Add(xla::Mul(old_mean, alpha), + xla::Mul(xla::GetTupleElement(output, 1), beta)); + ctx->SetOutput(1, new_running_mean); + + xla::XlaOp old_variance = ctx->Input(4); + xla::XlaOp new_running_variance = xla::Add( + xla::Mul(old_variance, alpha), xla::Mul(corrected, beta)); + // new_running_variance = alpha * old_variance + beta * + // batch_variance. + ctx->SetOutput(2, new_running_variance); + } + } + + // Output 3 and 4 for "FusedBatchNorm" are currently marked as "reserved + // space 1 & 2". They are used to pass the per-batch mean and + // variance to the gradient. Here we maintain the same behavior by setting + // them to the mean and variance calculated by BatchNormTraining. + ctx->SetOutput(3, xla::GetTupleElement(output, 1)); + if (is_on_gpu_) { + // The last two outputs from the FusedBatchNorm training TensorFlow GPU + // op are implementation defined. For now we rely on the in-practice + // behavior of the op: + // output 3 is the mean + // output 4 is rsqrt(variance + epsilon) + ctx->SetOutput(4, xla::Rsqrt(xla::Add( + variance, xla::ScalarLike(variance, epsilon_)))); + } else { + ctx->SetOutput(4, variance); + } + } else { + xla::XlaOp output = xla::BatchNormInference( + input, ctx->Input(1), ctx->Input(2), ctx->Input(3), ctx->Input(4), + epsilon_, feature_index); + + xla::XlaOp converted = xla::ConvertElementType(output, input_type); + if (add_side_input_ && apply_relu_) { + ctx->SetOutput(0, xla::Relu(xla::Add(ctx->Input(5), converted))); + } else if (apply_relu_) { + ctx->SetOutput(0, xla::Relu(converted)); + } else { + ctx->SetOutput(0, converted); + } + + // Directly send input to output as mean and variance in inference mode. + ctx->SetOutput(1, ctx->Input(3)); + ctx->SetOutput(2, ctx->Input(4)); + ctx->SetOutput(3, ctx->Input(3)); + ctx->SetOutput(4, ctx->Input(4)); + } + } + + private: + float epsilon_; + TensorFormat data_format_; + bool is_training_; + float exponential_avg_factor_; + bool add_side_input_; + bool apply_relu_; + bool is_on_gpu_; +}; + +class FusedBatchNormOpV3 : public FusedBatchNormOp { + public: + explicit FusedBatchNormOpV3(OpKernelConstruction* ctx) + : FusedBatchNormOp(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + FusedBatchNormOp::CompileImpl(ctx); + if (!ctx->status().ok()) { + return; + } + ctx->SetConstantOutput(5, Tensor()); + } +}; + +class FusedBatchNormOpEx : public FusedBatchNormOp { + public: + explicit FusedBatchNormOpEx(OpKernelConstruction* ctx) + : FusedBatchNormOp(ctx, /*is_batch_norm_ex=*/true) {} + + void Compile(XlaOpKernelContext* ctx) override { + FusedBatchNormOp::CompileImpl(ctx); + if (!ctx->status().ok()) { + return; + } + ctx->SetConstantOutput(5, Tensor()); + } +}; + +REGISTER_XLA_OP(Name("FusedBatchNorm"), FusedBatchNormOp); +REGISTER_XLA_OP(Name("FusedBatchNormV2"), FusedBatchNormOp); +REGISTER_XLA_OP(Name("FusedBatchNormV3"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("_FusedBatchNormEx"), FusedBatchNormOpEx); + +class FusedBatchNormGradOp : public XlaOpKernel { + public: + explicit FusedBatchNormGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("epsilon", &epsilon_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("is_training", &is_training_)); + std::string data_format_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); + OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_), + absl::InvalidArgumentError( + absl::StrCat("Invalid data format: ", data_format_str))); + is_on_gpu_ = ctx->device_type().type_string() == DEVICE_GPU_XLA_JIT; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* const b = ctx->builder(); + DataType input_dtype = ctx->input_type(0); + DataType scale_dtype = ctx->input_type(2); + + // TODO(b/69928690): support mixed precision in the XLA batch normalization + // operators. For now, cast everything to the statistics type (which + // may be more precise than the input type). + auto grad_backprop = + XlaHelpers::ConvertElementType(ctx->Input(0), scale_dtype); + auto activations = + XlaHelpers::ConvertElementType(ctx->Input(1), scale_dtype); + auto scale = ctx->Input(2); + auto mean = ctx->Input(3); + auto var = ctx->Input(4); + + const int input_dims = ctx->InputShape(0).dims(); + const int feature_index = + GetTensorFeatureDimIndex(input_dims, data_format_); + + xla::XlaOp x_backprop; + xla::XlaOp scale_backprop; + xla::XlaOp offset_backprop; + if (is_training_) { + if (is_on_gpu_) { + // The last two inputs to the FusedBatchNormGrad training TensorFlow GPU + // op are implementation defined. For now we rely on the in-practice + // behavior of the op: input 3 is the mean input 4 is rsqrt(variance + + // epsilon) + // + // The XLA op expects: + // input 3 is the mean + // input 4 is the variance + // + // so we adjust input 4 here. + xla::XlaOp one = xla::ScalarLike(var, 1.0f); + xla::XlaOp epsilon = xla::ScalarLike(var, epsilon_); + var = xla::Sub(one / (var * var), epsilon); + } + + xla::XlaOp output = + xla::BatchNormGrad(activations, scale, mean, var, grad_backprop, + epsilon_, feature_index); + + x_backprop = xla::GetTupleElement(output, 0); + scale_backprop = xla::GetTupleElement(output, 1); + offset_backprop = xla::GetTupleElement(output, 2); + } else { + // Reduce over all dimensions except the feature dim. + std::vector reduction_dims(input_dims - 1); + std::iota(reduction_dims.begin(), reduction_dims.begin() + feature_index, + 0); + std::iota(reduction_dims.begin() + feature_index, reduction_dims.end(), + feature_index + 1); + // offset_backprop = sum(y_backprop) + // scale_backprop = y_backprop * ((x - pop_mean) * rsqrt(pop_var + + // epsilon)) + // x_backprop = y_backprop * (scale * rsqrt(pop_var + epsilon)) + const DataType accumulation_type = + XlaHelpers::SumAccumulationType(scale_dtype); + auto converted = + XlaHelpers::ConvertElementType(grad_backprop, accumulation_type); + auto reduce = + xla::Reduce(converted, XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), reduction_dims); + offset_backprop = XlaHelpers::ConvertElementType(reduce, scale_dtype); + + // scratch1 = rsqrt(pop_var + epsilon) + auto epsilon = XlaHelpers::FloatLiteral(b, scale_dtype, epsilon_); + auto scratch1 = xla::Rsqrt(xla::Add(var, epsilon)); + + // scratch2 = sum(y_backprop * (x - mean)) + auto mul = + xla::Mul(grad_backprop, xla::Sub(activations, mean, {feature_index})); + converted = XlaHelpers::ConvertElementType(mul, accumulation_type); + reduce = + xla::Reduce(converted, XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), reduction_dims); + auto scratch2 = XlaHelpers::ConvertElementType(reduce, scale_dtype); + + x_backprop = + xla::Mul(grad_backprop, xla::Mul(scratch1, scale), {feature_index}); + scale_backprop = xla::Mul(scratch1, scratch2); + } + + ctx->SetOutput(0, XlaHelpers::ConvertElementType(x_backprop, input_dtype)); + ctx->SetOutput(1, scale_backprop); + ctx->SetOutput(2, offset_backprop); + ctx->SetConstantOutput(3, Tensor()); + ctx->SetConstantOutput(4, Tensor()); + } + + private: + TensorFormat data_format_; + float epsilon_; + bool is_training_; + bool is_on_gpu_; +}; + +REGISTER_XLA_OP(Name("FusedBatchNormGrad"), FusedBatchNormGradOp); +REGISTER_XLA_OP(Name("FusedBatchNormGradV2"), FusedBatchNormGradOp); +REGISTER_XLA_OP(Name("FusedBatchNormGradV3"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batchtospace_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batchtospace_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..4b992092f1e654db1734bbebbdf750cd5c5c7f1c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/batchtospace_op.cc @@ -0,0 +1,200 @@ +/* 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 +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +void BatchToSpace(XlaOpKernelContext* ctx, const xla::XlaOp input, + DataType input_dtype, const TensorShape& input_tensor_shape, + absl::Span block_shape, + const xla::Literal& crops) { + const int input_rank = input_tensor_shape.dims(); + const absl::InlinedVector input_shape = + input_tensor_shape.dim_sizes(); + const int block_rank = block_shape.size(); + + OP_REQUIRES(ctx, input_rank >= 1 + block_rank, + absl::InvalidArgumentError( + absl::StrCat("input rank should be >= ", 1 + block_rank, + " instead of ", input_rank))); + absl::Span remainder_shape(input_shape); + remainder_shape.remove_prefix(1 + block_rank); + + OP_REQUIRES( + ctx, + crops.shape().dimensions().size() == 2 && + block_rank == xla::ShapeUtil::GetDimension(crops.shape(), 0) && + 2 == xla::ShapeUtil::GetDimension(crops.shape(), 1), + absl::InvalidArgumentError(absl::StrCat( + "crops should have shape [", block_rank, ", 2] instead of ", + xla::ShapeUtil::HumanString(crops.shape())))); + + const int64_t batch_size = input_shape[0]; + + // Compute the product of the block_shape values. + int64_t block_num_elems = 1; + for (int i = 0; i < block_rank; ++i) { + block_num_elems *= block_shape[i]; + } + OP_REQUIRES(ctx, block_num_elems > 0, + absl::InvalidArgumentError( + "The product of the block dimensions must be positive")); + + // 1. Reshape `input` to `reshaped` of shape: + // [block_shape[0], ..., block_shape[M-1], + // batch / prod(block_shape), + // input_shape[1], ..., input_shape[N-1]] + + OP_REQUIRES(ctx, batch_size % block_num_elems == 0, + absl::InvalidArgumentError( + absl::StrCat("Input batch dimension (", batch_size, + ") is not divisible by product of block sizes (", + block_num_elems, ")"))); + std::vector reshaped_shape(input_rank + block_rank); + std::copy(block_shape.begin(), block_shape.end(), reshaped_shape.begin()); + reshaped_shape[block_rank] = batch_size / block_num_elems; + std::copy(input_shape.begin() + 1, input_shape.end(), + reshaped_shape.begin() + block_rank + 1); + xla::XlaOp reshaped = xla::Reshape(input, reshaped_shape); + + // 2. Permute dimensions of `reshaped` to produce `permuted` of shape + // [batch / prod(block_shape), + // + // input_shape[1], block_shape[0], + // ..., + // input_shape[M], block_shape[M-1], + // + // input_shape[M+1], ..., input_shape[N-1]] + std::vector permutation(reshaped_shape.size()); + permutation[0] = block_rank; + for (int i = 0; i < block_rank; ++i) { + permutation[1 + 2 * i] = block_rank + 1 + i; + permutation[1 + 2 * i + 1] = i; + } + std::iota(permutation.begin() + 1 + block_rank * 2, permutation.end(), + 1 + block_rank * 2); + xla::XlaOp permuted = xla::Transpose(reshaped, permutation); + + // 3. Reshape `permuted` to produce `reshaped_permuted` of shape + // [batch / prod(block_shape), + // + // input_shape[1] * block_shape[0], + // ..., + // input_shape[M] * block_shape[M-1], + // + // input_shape[M+1], + // ..., + // input_shape[N-1]] + std::vector reshaped_permuted_shape(input_rank); + reshaped_permuted_shape[0] = batch_size / block_num_elems; + for (int i = 0; i < block_rank; ++i) { + reshaped_permuted_shape[1 + i] = block_shape[i] * input_shape[1 + i]; + } + std::copy(remainder_shape.begin(), remainder_shape.end(), + reshaped_permuted_shape.begin() + 1 + block_rank); + + xla::XlaOp reshaped_permuted = + xla::Reshape(permuted, reshaped_permuted_shape); + + // 4. Crop the start and end of dimensions `[1, ..., M]` of + // `reshaped_permuted` according to `crops` to produce the output of shape: + // [batch / prod(block_shape), + // + // input_shape[1] * block_shape[0] - crops[0,0] - crops[0,1], + // ..., + // input_shape[M] * block_shape[M-1] - crops[M-1,0] - crops[M-1,1], + // + // input_shape[M+1], ..., input_shape[N-1]] + std::vector start_indices(input_rank, 0); + std::vector end_indices = reshaped_permuted_shape; + std::vector strides(input_rank, 1); + for (int i = 0; i < block_rank; ++i) { + int64_t crop_start = crops.Get({i, 0}); + int64_t crop_end = crops.Get({i, 1}); + OP_REQUIRES(ctx, crop_start >= 0 && crop_end >= 0, + absl::InvalidArgumentError("Crops must be non-negative")); + start_indices[1 + i] = crop_start; + end_indices[1 + i] -= crop_end; + OP_REQUIRES( + ctx, start_indices[1 + i] <= end_indices[1 + i], + absl::InvalidArgumentError(absl::StrCat( + "Cropped size must be non-negative: start: ", crop_start, + " end: ", crop_end, " size ", reshaped_permuted_shape[1 + i]))); + } + xla::XlaOp output = + xla::Slice(reshaped_permuted, start_indices, end_indices, strides); + ctx->SetOutput(0, output); +} + +class BatchToSpaceNDOp : public XlaOpKernel { + public: + explicit BatchToSpaceNDOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + std::vector block_shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &block_shape)); + + xla::Literal crops; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal(2, &crops)); + + BatchToSpace(ctx, ctx->Input(0), input_type(0), ctx->InputShape(0), + block_shape, crops); + } +}; +REGISTER_XLA_OP(Name("BatchToSpaceND") + .CompileTimeConstantInput("block_shape") + .CompileTimeConstantInput("crops"), + BatchToSpaceNDOp); + +class BatchToSpaceOp : public XlaOpKernel { + public: + explicit BatchToSpaceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("block_size", &block_size_)); + OP_REQUIRES(ctx, block_size_ > 1, + absl::InvalidArgumentError( + absl::StrCat("Block size should be > 1: ", block_size_))); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::Literal crops; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal(1, &crops)); + + BatchToSpace(ctx, ctx->Input(0), input_type(0), ctx->InputShape(0), + {block_size_, block_size_}, crops); + } + + private: + int block_size_; +}; +REGISTER_XLA_OP(Name("BatchToSpace").CompileTimeConstantInput("crops"), + BatchToSpaceOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bcast_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bcast_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..d3896bb1595070d349e2185cd90b1f6781dfeaac --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bcast_ops.cc @@ -0,0 +1,156 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Ops for broadcasting used in gradient +// code. + +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/literal.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/bcast.h" + +namespace tensorflow { +namespace { + +// Given shapes of two tensors, computes the broadcast shape. +class BCastArgsOp : public XlaOpKernel { + public: + explicit BCastArgsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + } + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES( + ctx, ctx->num_inputs() == 2, + absl::UnimplementedError("Broadcast for n-ary operations (n > 2)")); + absl::InlinedVector shapes; + for (int i = 0; i < ctx->num_inputs(); ++i) { + const TensorShape in_shape = ctx->InputShape(i); + OP_REQUIRES( + ctx, TensorShapeUtils::IsVector(in_shape), + absl::InvalidArgumentError(absl::StrCat( + "In[", i, "] must be a vector.", in_shape.DebugString()))); + std::vector shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector( + i, &shape, xla::ValueInferenceMode::kUpperBound)); + shapes.push_back(BCast::Vec(shape.begin(), shape.end())); + } + BCast bcast(shapes[0], shapes[1]); + OP_REQUIRES(ctx, bcast.IsValid(), + absl::InvalidArgumentError(absl::StrCat( + "Incompatible shapes: [", absl::StrJoin(shapes[0], ","), + "] vs. [", absl::StrJoin(shapes[1], ","), "]"))); + + DataType val_type = ctx->expected_output_dtype(0); + const int64_t len = bcast.output_shape().size(); + Tensor output(val_type, TensorShape({len})); + for (int64_t i = 0; i < len; ++i) { + if (val_type == DT_INT32) { + output.flat()(i) = + static_cast(bcast.output_shape()[i]); + } else { + output.flat()(i) = + static_cast(bcast.output_shape()[i]); + } + } + ctx->SetConstantOutput(0, output); + } + + private: + BCastArgsOp(const BCastArgsOp&) = delete; + void operator=(const BCastArgsOp&) = delete; +}; +REGISTER_XLA_OP(Name("BroadcastArgs") + .CompileTimeConstantInput("s0") + .CompileTimeConstantInput("s1"), + BCastArgsOp); + +// Given shapes of two tensors, computes the reduction indices for the +// gradient computation. +// +// TODO(zhifengc): +// 1. Adds support for n-ary (n >= 2). +class BCastGradArgsOp : public XlaOpKernel { + public: + explicit BCastGradArgsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + } + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES( + ctx, ctx->num_inputs() == 2, + absl::UnimplementedError("Broadcast for n-ary operations (n > 2)")); + + absl::InlinedVector shapes; + for (int i = 0; i < ctx->num_inputs(); ++i) { + const TensorShape in_shape = ctx->InputShape(i); + OP_REQUIRES( + ctx, TensorShapeUtils::IsVector(in_shape), + absl::InvalidArgumentError(absl::StrCat( + "In[", i, "] must be a vector.", in_shape.DebugString()))); + std::vector vec; + // Technically we don't need to infer the upper-bound here. However the + // forward path uses the upperbound as bounded shape so we need backward + // path to use the same shape to decide the reduction indices. + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector( + i, &vec, xla::ValueInferenceMode::kUpperBound)); + + shapes.push_back(BCast::Vec(vec.begin(), vec.end())); + } + BCast bcast(shapes[0], shapes[1]); + OP_REQUIRES(ctx, bcast.IsValid(), + absl::InvalidArgumentError(absl::StrCat( + "Incompatible shapes: [", absl::StrJoin(shapes[0], ","), + "] vs. [", absl::StrJoin(shapes[1], ","), "]"))); + Output(ctx, 0, bcast.grad_x_reduce_idx()); + Output(ctx, 1, bcast.grad_y_reduce_idx()); + } + + private: + void Output(XlaOpKernelContext* ctx, int idx, const BCast::Vec& v) { + const int64_t len = v.size(); + DataType val_type = ctx->expected_output_dtype(idx); + Tensor constant(val_type, TensorShape({len})); + for (int64_t i = 0; i < len; ++i) { + if (val_type == DT_INT32) { + constant.flat()(i) = static_cast(v[i]); + } else { + constant.flat()(i) = static_cast(v[i]); + } + } + ctx->SetConstantOutput(idx, constant); + } + + BCastGradArgsOp(const BCastGradArgsOp&) = delete; + void operator=(const BCastGradArgsOp&) = delete; +}; + +REGISTER_XLA_OP(Name("BroadcastGradientArgs") + .CompileTimeConstantInput("s0") + .CompileTimeConstantInput("s1"), + BCastGradArgsOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/beta_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/beta_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..55f7a7fd2c1bf3f98122b265b4cdb84b788d0a50 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/beta_op.cc @@ -0,0 +1,82 @@ +/* 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 "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/loops.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/status_macros.h" + +namespace tensorflow { +namespace { + +class BetaincOp : public XlaOpKernel { + public: + explicit BetaincOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape& a_shape = ctx->InputShape(0); + const TensorShape& b_shape = ctx->InputShape(1); + const TensorShape& x_shape = ctx->InputShape(2); + if (a_shape.dims() > 0 && b_shape.dims() > 0) { + OP_REQUIRES(ctx, a_shape == b_shape, + absl::InvalidArgumentError(absl::StrCat( + "Shapes of a and b are inconsistent: ", + a_shape.DebugString(), " vs. ", b_shape.DebugString()))); + } + if (a_shape.dims() > 0 && x_shape.dims() > 0) { + OP_REQUIRES(ctx, a_shape == x_shape, + absl::InvalidArgumentError(absl::StrCat( + "Shapes of a and x are inconsistent: ", + a_shape.DebugString(), " vs. ", x_shape.DebugString()))); + } + if (b_shape.dims() > 0 && x_shape.dims() > 0) { + OP_REQUIRES(ctx, b_shape == x_shape, + absl::InvalidArgumentError(absl::StrCat( + "Shapes of b and x are inconsistent: ", + b_shape.DebugString(), " vs. ", x_shape.DebugString()))); + } + + TensorShape merged_shape(a_shape); + if (b_shape.dims() > 0) merged_shape = b_shape; + if (x_shape.dims() > 0) merged_shape = x_shape; + + auto builder = ctx->builder(); + auto result = + builder->ReportErrorOrReturn([&]() -> absl::StatusOr { + TF_ASSIGN_OR_RETURN( + auto a, BroadcastTo(ctx->Input(0), merged_shape.dim_sizes())); + TF_ASSIGN_OR_RETURN( + auto b, BroadcastTo(ctx->Input(1), merged_shape.dim_sizes())); + TF_ASSIGN_OR_RETURN( + auto x, BroadcastTo(ctx->Input(2), merged_shape.dim_sizes())); + return xla::RegularizedIncompleteBeta(a, b, x); + }); + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP(Name("Betainc"), BetaincOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bias_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bias_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..4b8506dfddffb696178cdd3cbf6f80cdf52c78b6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bias_ops.cc @@ -0,0 +1,84 @@ +/* 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 + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +class BiasOp : public XlaOpKernel { + public: + explicit BiasOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + std::string data_format; + if (ctx->GetAttr("data_format", &data_format).ok()) { + OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_), + absl::InvalidArgumentError("Invalid data format")); + } else { + data_format_ = FORMAT_NHWC; + } + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + const TensorShape bias_shape = ctx->InputShape(1); + + OP_REQUIRES( + ctx, TensorShapeUtils::IsMatrixOrHigher(input_shape), + absl::InvalidArgumentError(absl::StrCat( + "Input tensor must be at least 2D: ", input_shape.DebugString()))); + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(bias_shape), + absl::InvalidArgumentError(absl::StrCat( + "Biases must be 1D: ", bias_shape.DebugString()))); + + // feature_dim is the channel (C) dimension of the data. + int feature_dim = (data_format_ == FORMAT_NHWC) + ? input_shape.dims() - 1 + : /*data_format == FORMAT_NCHW*/ 1; + OP_REQUIRES(ctx, feature_dim >= 0, + absl::InvalidArgumentError( + "Input tensor does not have enough dimensions " + "to contain the feature dimension")); + OP_REQUIRES( + ctx, bias_shape.dim_size(0) == input_shape.dim_size(feature_dim), + absl::InvalidArgumentError(absl::StrCat( + "Must provide as many biases as the last dimension " + "of the input tensor: ", + bias_shape.DebugString(), " vs. ", input_shape.DebugString()))); + + xla::XlaOp result = xla::Add(ctx->Input(0), ctx->Input(1), {feature_dim}); + ctx->SetOutput(0, result); + } + + private: + TensorFormat data_format_; +}; + +REGISTER_XLA_OP(Name("BiasAdd"), BiasOp); +REGISTER_XLA_OP(Name("BiasAddV1"), BiasOp); +REGISTER_XLA_OP(Name("BiasAddGrad"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/binary_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/binary_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..106720ce87fce9d6f2a02351037d6ebb634f23b1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/binary_ops.cc @@ -0,0 +1,357 @@ +/* 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. +==============================================================================*/ + +// Native XLA implementations of simple binary Ops + +#include +#include +#include + +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/cwise_ops.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/client/client_library.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +// A subclass of a XlaBinaryOp must build the computation that +// describes the (tensor,tensor)->tensor function to apply to each element of +// the input. +#define XLA_MAKE_BINARY(NAME, HLO) \ + class NAME##Op : public XlaBinaryOp { \ + public: \ + explicit NAME##Op(OpKernelConstruction* ctx) : XlaBinaryOp(ctx) {} \ + xla::XlaOp Computation( \ + XlaOpKernelContext* ctx, const xla::XlaOp& lhs, \ + const absl::Span& lhs_shape, const xla::XlaOp& rhs, \ + const absl::Span& rhs_shape, \ + const BCast& broadcast_helper, \ + const std::vector& extend_dimensions) override { \ + xla::XlaBuilder* b = ctx->builder(); \ + (void)b; \ + (void)lhs_shape; \ + (void)rhs_shape; \ + (void)extend_dimensions; \ + return HLO; \ + } \ + }; \ + REGISTER_XLA_OP(Name(#NAME), NAME##Op) + +XLA_MAKE_BINARY(Add, xla::Add(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(AddV2, xla::Add(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Sub, xla::Sub(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Mul, xla::Mul(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Div, xla::Div(lhs, rhs, extend_dimensions)); + +XLA_MAKE_BINARY(Atan2, xla::Atan2(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Complex, xla::Complex(lhs, rhs, extend_dimensions)); + +// Implementation of DivNoNan. Pseudo-code: +// if (y == 0) { +// return 0 +// } else { +// return x / y; +// } +static xla::XlaOp DivNoNanImpl(xla::XlaBuilder* b, DataType dtype, xla::XlaOp x, + xla::XlaOp y, const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + auto zero = XlaHelpers::Zero(b, dtype); + auto y_equals_0 = xla::Eq(y, zero); + auto zeros = xla::ZerosLike(x); + auto result = xla::Select(y_equals_0, zeros, xla::Div(x, y)); + return result; +} +XLA_MAKE_BINARY(DivNoNan, + DivNoNanImpl(b, input_type(0), lhs, rhs, broadcast_helper)); + +// Implementation of MulNoNan. Pseudo-code: +// if (y == 0) { +// return 0 +// } else { +// return x * y; +// } +static xla::XlaOp MulNoNanImpl(xla::XlaBuilder* b, DataType dtype, xla::XlaOp x, + xla::XlaOp y, const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + auto zero = XlaHelpers::Zero(b, dtype); + auto y_equals_0 = xla::Eq(y, zero); + auto zeros = xla::ZerosLike(x); + auto result = xla::Select(y_equals_0, zeros, xla::Mul(x, y)); + return result; +} +XLA_MAKE_BINARY(MulNoNan, + MulNoNanImpl(b, input_type(0), lhs, rhs, broadcast_helper)); + +// Implementation of FloorDiv. +// +// For floating-point values, simply returns floor(x / y). For integers, does: +// +// z = x / y +// if (z * y != x && (x < 0) != (y < 0)) { +// return z - 1; +// } else { +// return z; +// } +static xla::XlaOp FloorDivImpl(xla::XlaBuilder* b, DataType dtype, xla::XlaOp x, + xla::XlaOp y, const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + if (DataTypeIsFloating(dtype)) { + if (dtype == DataType::DT_BFLOAT16) { + // The result of a BF16 division may produce the Ceil of what was + // computed by F32 division, so avoid end user confusion by doing the + // intermediate divide in F32. + return xla::ConvertElementType( + xla::Floor(xla::Div(xla::ConvertElementType(x, xla::F32), + xla::ConvertElementType(y, xla::F32))), + xla::BF16); + } else { + return xla::Floor(xla::Div(x, y)); + } + } + if (DataTypeIsUnsigned(dtype)) { + return xla::Div(x, y); + } + auto zero = XlaHelpers::Zero(b, dtype); + auto one = XlaHelpers::One(b, dtype); + auto x_div_y = xla::Div(x, y); + auto round_down = xla::And(xla::Ne(xla::Mul(x_div_y, y), x), + xla::Ne(xla::Lt(x, zero), xla::Lt(y, zero))); + return xla::Select(round_down, xla::Sub(x_div_y, one), x_div_y); +} +XLA_MAKE_BINARY(FloorDiv, + FloorDivImpl(b, input_type(0), lhs, rhs, broadcast_helper)); + +xla::XlaOp XlogyImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + auto zero = xla::ZerosLike(x); + auto is_zero = xla::Eq(x, zero); + return xla::Select(is_zero, zero, xla::Mul(x, xla::Log(y))); +} +XLA_MAKE_BINARY(Xlogy, XlogyImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp Xlog1pyImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + auto non_zero = xla::Mul(x, xla::Log1p(y)); + auto zero = xla::ZerosLike(non_zero); + auto x_is_zero = xla::Eq(x, zero); + return xla::Select(x_is_zero, zero, non_zero); +} +XLA_MAKE_BINARY(Xlog1py, Xlog1pyImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp XdivyImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + auto zero = xla::ZerosLike(x); + auto is_zero = xla::Eq(x, zero); + return xla::Select(is_zero, zero, xla::Div(x, y)); +} +XLA_MAKE_BINARY(Xdivy, XdivyImpl(lhs, rhs, broadcast_helper)); + +// Implementation of FloorMod. Pseudo-code: +// T trunc_mod = std::fmod(x, y); +// return trunc_mod != 0 && (y < 0 != trunc_mod < 0) ? trunc_mod + y +// : trunc_mod; +static xla::XlaOp FloorModImpl(xla::XlaBuilder* b, DataType dtype, xla::XlaOp x, + xla::XlaOp y, const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + auto zero = XlaHelpers::Zero(b, dtype); + auto trunc_mod = xla::Rem(x, y); + auto trunc_mod_not_zero = xla::Ne(trunc_mod, zero); + auto do_plus = xla::And(xla::Ne(xla::Lt(trunc_mod, zero), xla::Lt(y, zero)), + trunc_mod_not_zero); + return xla::Select(do_plus, xla::Add(trunc_mod, y), trunc_mod); +} +XLA_MAKE_BINARY(FloorMod, + FloorModImpl(b, input_type(0), lhs, rhs, broadcast_helper)); + +XLA_MAKE_BINARY(BitwiseAnd, xla::And(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(BitwiseOr, xla::Or(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(BitwiseXor, xla::Xor(lhs, rhs, extend_dimensions)); + +XLA_MAKE_BINARY(LeftShift, xla::ShiftLeft(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(RightShift, + (DataTypeIsUnsigned(ctx->input_type(0)) + ? xla::ShiftRightLogical(lhs, rhs, extend_dimensions) + : xla::ShiftRightArithmetic(lhs, rhs, extend_dimensions))); + +XLA_MAKE_BINARY(LogicalAnd, xla::And(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(LogicalOr, xla::Or(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Mod, xla::Rem(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Maximum, xla::Max(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Minimum, xla::Min(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(RealDiv, xla::Div(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(ReciprocalGrad, xla::Neg(xla::Mul(rhs, xla::Mul(lhs, lhs)))); +XLA_MAKE_BINARY( + RsqrtGrad, + xla::Mul((lhs * lhs) * lhs, + xla::Div(rhs, XlaHelpers::IntegerLiteral(b, input_type(0), -2)), + extend_dimensions)); +XLA_MAKE_BINARY( + SqrtGrad, + xla::Div(xla::Mul(rhs, XlaHelpers::FloatLiteral(b, input_type(0), 0.5)), + lhs, extend_dimensions)); + +// Implementation of TruncateDiv. +// +// For floating-point values, returns trunc(x / y). For integers, simply +// returns x / y. +static xla::XlaOp TruncateDivImpl(xla::XlaBuilder* b, DataType dtype, + xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + if (!DataTypeIsFloating(dtype)) { + return xla::Div(x, y); + } + auto zero = XlaHelpers::Zero(b, dtype); + auto x_div_y = xla::Div(x, y); + auto round_up = xla::Lt(x_div_y, zero); + return xla::Select(round_up, xla::Ceil(x_div_y), xla::Floor(x_div_y)); +} +XLA_MAKE_BINARY(TruncateDiv, + TruncateDivImpl(b, input_type(0), lhs, rhs, broadcast_helper)); +XLA_MAKE_BINARY(TruncateMod, xla::Rem(lhs, rhs, extend_dimensions)); + +// Comparison ops +XLA_MAKE_BINARY(Equal, xla::Eq(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(NotEqual, xla::Ne(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Greater, xla::Gt(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(GreaterEqual, xla::Ge(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(Less, xla::Lt(lhs, rhs, extend_dimensions)); +XLA_MAKE_BINARY(LessEqual, xla::Le(lhs, rhs, extend_dimensions)); + +// Non-linear ops +XLA_MAKE_BINARY(SigmoidGrad, + xla::Mul(xla::Mul(rhs, lhs), + xla::Sub(XlaHelpers::One(b, input_type(0)), lhs))); + +XLA_MAKE_BINARY(SoftplusGrad, xla::Mul(lhs, xla::Logistic(rhs))); + +// softsigngrad(gradients, features) = gradients / (1 + abs(features)) ** 2 +XLA_MAKE_BINARY(SoftsignGrad, + xla::Div(lhs, + xla::Square(xla::Add(XlaHelpers::One(b, input_type(0)), + xla::Abs(rhs))))); + +XLA_MAKE_BINARY(TanhGrad, + xla::Mul(rhs, xla::Sub(XlaHelpers::One(b, input_type(0)), + xla::Mul(lhs, lhs)))); + +XLA_MAKE_BINARY(Pow, xla::Pow(lhs, rhs, extend_dimensions)); + +xla::XlaOp SquaredDifferenceImpl( + DataType dtype, xla::XlaOp x, xla::XlaOp y, + const std::vector& extend_dimensions) { + auto difference = xla::Sub(x, y, extend_dimensions); + if (DataTypeIsComplex(dtype)) { + return xla::Conj(difference) * difference; + } else { + return xla::Square(difference); + } +} +XLA_MAKE_BINARY(SquaredDifference, + SquaredDifferenceImpl(input_type(0), lhs, rhs, + extend_dimensions)); + +xla::XlaOp IgammaImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + return xla::Igamma(x, y); +} + +XLA_MAKE_BINARY(Igamma, IgammaImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp IgammaGradAImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + return xla::IgammaGradA(x, y); +} + +XLA_MAKE_BINARY(IgammaGradA, IgammaGradAImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp RandomGammaGradImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + return xla::RandomGammaGrad(x, y); +} + +XLA_MAKE_BINARY(RandomGammaGrad, + RandomGammaGradImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp IgammacImpl(xla::XlaOp x, xla::XlaOp y, + const BCast& broadcast_helper) { + std::tie(x, y) = XlaBinaryOp::Broadcast(x, y, broadcast_helper); + return xla::Igammac(x, y); +} + +XLA_MAKE_BINARY(Igammac, IgammacImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp PolygammaImpl(xla::XlaOp n, xla::XlaOp x, + const BCast& broadcast_helper) { + std::tie(n, x) = XlaBinaryOp::Broadcast(n, x, broadcast_helper); + return xla::Polygamma(n, x); +} + +XLA_MAKE_BINARY(Polygamma, PolygammaImpl(lhs, rhs, broadcast_helper)); + +xla::XlaOp ZetaImpl(xla::XlaOp x, xla::XlaOp q, const BCast& broadcast_helper) { + std::tie(x, q) = XlaBinaryOp::Broadcast(x, q, broadcast_helper); + return xla::Zeta(x, q); +} + +XLA_MAKE_BINARY(Zeta, ZetaImpl(lhs, rhs, broadcast_helper)); + +#undef XLA_MAKE_BINARY + +class ApproximateEqualOp : public XlaOpKernel { + public: + explicit ApproximateEqualOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("tolerance", &tolerance_)); + } + + // Computes the max of the scalar input x and 0. + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + auto abs = xla::Abs(xla::Sub(ctx->Input(0), ctx->Input(1))); + auto abs_shape = b->GetShape(abs); + OP_REQUIRES_OK(ctx, abs_shape.status()); + auto abs_type = abs_shape.value().element_type(); + auto result = + xla::Lt(abs, xla::ConvertElementType( + xla::ConstantR0(b, tolerance_), abs_type)); + ctx->SetOutput(0, result); + } + + private: + float tolerance_; +}; +REGISTER_XLA_OP(Name("ApproximateEqual"), ApproximateEqualOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bincount_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bincount_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..55cc455e8bda5e926823175bc65fce0292dcce70 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bincount_op.cc @@ -0,0 +1,179 @@ +/* Copyright 2022 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 +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/comparators.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" + +namespace tensorflow { +namespace { + +class DenseBincountOp : public XlaOpKernel { + public: + explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + // It is optional for Bincount and required for DenseBincount + (void)ctx->GetAttr("binary_output", &binary_output_); + } + + private: + bool binary_output_ = false; + void Compile(XlaOpKernelContext* ctx) override { + int64_t output_size; + xla::XlaOp output_size_param = ctx->Input("size"); + absl::StatusOr output_shape_or = + ctx->builder()->GetShape(output_size_param); + OP_REQUIRES_OK(ctx, output_shape_or.status()); + auto output_shape_param = output_shape_or.value(); + auto output_rank = output_shape_param.dimensions().size(); + OP_REQUIRES(ctx, output_rank == 0, + absl::InvalidArgumentError(absl::StrCat( + "Shape must be rank 0 but is rank ", output_rank))); + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("size", &output_size)); + OP_REQUIRES(ctx, output_size >= 0, + absl::InvalidArgumentError(absl::StrCat( + "size (", output_size, ") must be non-negative"))); + xla::XlaOp idx, updates, output; + xla::XlaOp input = ctx->Input(0); + auto input_xla_type = ctx->input_xla_type(0); + xla::PrimitiveType dtype = ctx->InputXlaType("weights"); + auto zero = xla::Zero(ctx->builder(), dtype); + auto one = xla::One(ctx->builder(), dtype); + absl::StatusOr input_shape_or = ctx->builder()->GetShape(input); + OP_REQUIRES_OK(ctx, input_shape_or.status()); + auto input_shape = input_shape_or.value(); + + auto rank = input_shape.dimensions().size(); + + OP_REQUIRES(ctx, rank <= 2, + absl::InvalidArgumentError(absl::StrCat( + "Shape must be at most rank 2 but is rank ", rank))); + std::vector input_values; + if (ctx->ConstantInputReshapedToIntVector(0, &input_values).ok()) { + for (int64_t value : input_values) { + OP_REQUIRES( + ctx, value >= 0, + absl::InvalidArgumentError("Input arr must be non-negative!")); + } + } + xla::XlaOp weights = ctx->Input(2); + absl::StatusOr weights_shape_or = + ctx->builder()->GetShape(weights); + + OP_REQUIRES_OK(ctx, weights_shape_or.status()); + + auto weights_shape = weights_shape_or.value(); + OP_REQUIRES(ctx, + xla::ShapeUtil::CompatibleIgnoringElementType(weights_shape, + input_shape) || + (weights_shape.dimensions().size() > 0 && + weights_shape.dimensions(0) == 0), + absl::InvalidArgumentError(absl::StrCat( + "`weights` must be the same shape as `arr` or a length-0 " + "`Tensor`, in which case it acts as all weights equal to " + "1. Received ", + weights_shape.ToString()))); + + auto size = input_shape.dimensions(0); + + if (!size) { + output = xla::Broadcast(zero, {output_size}); + ctx->SetOutput(0, output); + return; + } + + auto weights_size = weights_shape.dimensions(0); + bool has_weights = false; + if (weights_size) { + has_weights = true; + } + + xla::Shape output_shape = xla::ShapeUtil::MakeShape(dtype, {output_size}); + xla::ScatterDimensionNumbers scatter_dnums; + scatter_dnums.set_index_vector_dim(1); + scatter_dnums.add_inserted_window_dims(0); + scatter_dnums.add_scatter_dims_to_operand_dims(0); + + if (rank == 2) { + output_shape = xla::ShapeUtil::MakeShape(dtype, {size, output_size}); + scatter_dnums.add_inserted_window_dims(1); + scatter_dnums.add_scatter_dims_to_operand_dims(1); + auto i_shape = + xla::ShapeUtil::MakeShape(input_xla_type, {input_shape.dimensions()}); + auto i = xla::Iota(ctx->builder(), i_shape, 0); + i = xla::Reshape( + i, {input_shape.dimensions(0) * input_shape.dimensions(1), 1}); + auto j = xla::Reshape( + input, {input_shape.dimensions(0) * input_shape.dimensions(1), 1}); + std::vector iotas_to_concat; + iotas_to_concat.push_back(i); + iotas_to_concat.push_back(j); + idx = xla::ConcatInDim(ctx->builder(), iotas_to_concat, 1); + updates = xla::Broadcast( + one, {input_shape.dimensions(0) * input_shape.dimensions(1)}); + output = xla::Broadcast( + zero, {output_shape.dimensions(0), output_shape.dimensions(1)}); + if (has_weights && !binary_output_) { + weights = xla::Reshape( + weights, {input_shape.dimensions(0) * input_shape.dimensions(1)}); + updates = weights; + } + } else { + input = xla::Reshape(input, {size, 1}); + idx = xla::Reshape(input, {size, 1}); + updates = xla::Broadcast(one, {size}); + output = xla::Broadcast(zero, {output_size}); + if (has_weights && !binary_output_) { + updates = weights; + } + } + + xla::XlaComputation assn_computation = [&] { + std::unique_ptr subb = + ctx->builder()->CreateSubBuilder("scatter_bincount"); + xla::Shape param_shape = xla::ShapeUtil::MakeShape(dtype, {}); + auto p0 = xla::Parameter(subb.get(), 0, param_shape, "p0"); + auto p1 = xla::Parameter(subb.get(), 1, param_shape, "p1"); + if (!binary_output_) { + xla::Add(p0, p1); + } + return subb->BuildAndNoteError(); + }(); + output = xla::Scatter(output, idx, updates, assn_computation, scatter_dnums, + false, false); + ctx->SetOutput(0, output); + } +}; + +REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"), + DenseBincountOp); +REGISTER_XLA_OP(Name("Bincount").CompileTimeConstantInput("size"), + DenseBincountOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/broadcast_to_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/broadcast_to_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..6fee8aeecdf6445e1b079f9fe9322c9eaf3609b7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/broadcast_to_op.cc @@ -0,0 +1,64 @@ +/* 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 +#include + +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class BroadcastToOp : public XlaOpKernel { + public: + explicit BroadcastToOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + TensorShape output_shape; + OP_REQUIRES_OK(context, + context->ConstantInputAsShape( + 1, &output_shape, xla::ValueInferenceMode::kUpperBound)); + auto output_status_or = + BroadcastTo(context->Input(0), output_shape.dim_sizes()); + OP_REQUIRES_OK(context, output_status_or.status()); + auto output = output_status_or.value(); + std::vector dynamic_dims; + OP_REQUIRES_OK( + context, context->ResolveInputDynamismIntoPredVector(1, &dynamic_dims)); + for (int64_t dim = 0; dim < dynamic_dims.size(); ++dim) { + if (dynamic_dims[dim]) { + output = xla::SetDimensionSize( + output, + xla::Reshape(xla::Slice(context->Input(1), {dim}, {dim + 1}, {1}), + {}), + dim); + } + } + + context->SetOutput(0, output); + } +}; + +REGISTER_XLA_OP(Name("BroadcastTo").CompileTimeConstantInput("shape"), + BroadcastToOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bucketize_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bucketize_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..91486bd9cd55d69bc818daa73d7d1e07a474ac5d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/bucketize_op.cc @@ -0,0 +1,73 @@ +/* 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 +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class BucketizeOp : public XlaOpKernel { + public: + explicit BucketizeOp(OpKernelConstruction* context) : XlaOpKernel(context) { + OP_REQUIRES_OK(context, context->GetAttr("boundaries", &boundaries_)); + OP_REQUIRES(context, std::is_sorted(boundaries_.begin(), boundaries_.end()), + absl::InvalidArgumentError("Expected sorted boundaries")); + } + + void Compile(XlaOpKernelContext* context) override { + xla::XlaBuilder* builder = context->builder(); + const DataType dtype = context->input_type(0); + xla::XlaOp input = context->Input(0); + + xla::XlaOp boundaries = xla::ConstantR1(builder, boundaries_); + // TODO(phawkins): the following behavior matches the behavior of the core + // Bucketize kernel. However, comparing an int32 or int64 against float may + // lead to inaccurate bucketing due to rounding. + if (dtype == DT_DOUBLE) { + input = xla::ConvertElementType(input, xla::F64); + boundaries = xla::ConvertElementType(boundaries, xla::F64); + } else { + input = xla::ConvertElementType(input, xla::F32); + } + xla::XlaOp comparison = + xla::ConvertElementType(xla::Ge(xla::Broadcast(input, {1}), boundaries, + /*broadcast_dimensions=*/{0}), + xla::S32); + xla::XlaOp buckets = xla::Reduce( + comparison, /*init_value=*/xla::ConstantR0(builder, 0), + /*computation=*/xla::CreateScalarAddComputation(xla::S32, builder), + /*dimensions_to_reduce=*/{0}); + context->SetOutput(0, buckets); + } + + private: + std::vector boundaries_; +}; + +REGISTER_XLA_OP(Name("Bucketize"), BucketizeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/callback.proto b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/callback.proto new file mode 100644 index 0000000000000000000000000000000000000000..930fbc6e0a6e7bcdb0c90792f97437225241e1c9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/callback.proto @@ -0,0 +1,34 @@ +syntax = "proto2"; + +package tensorflow; + +import "tensorflow/core/framework/node_def.proto"; +import "tensorflow/core/framework/tensor.proto"; +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +message TfCallbackData { + message BufferDescription { + optional TensorShapeProto shape = 1; + optional DataType type = 2; + } + + message InputBufferDescription { + optional BufferDescription buffer_description = 1; + + // The input value might be already fixed at the compilation time. + // This value may or may not be present. + optional TensorProto value = 2; + } + + message OutputBufferDescription { + optional BufferDescription buffer_description = 1; + // Whether the buffer stores dynamically padded data: in that case, actual + // concrete dimensions need to be stored after the buffer. + optional bool is_dynamically_padded = 2; + } + + optional tensorflow.NodeDef op = 1; + repeated InputBufferDescription inputs = 2; + repeated OutputBufferDescription outputs = 3; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/case_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/case_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..bb77e7ec518b7a9fbd7922a5cc14604ca365cc34 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/case_op.cc @@ -0,0 +1,386 @@ +/* Copyright 2019 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/kernels/case_op.h" + +#include +#include +#include +#include +#include + +#include "absl/log/log.h" +#include "absl/log/vlog_is_on.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/if_while_utils.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +XlaCaseOp::XlaCaseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("branches", &unpruned_branches_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tin", &input_types_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tout", &output_types_)); + if (!ctx->GetAttr(kXlaTokenInputNodesAttrName, &token_input_nodes_).ok()) { + has_token_input_output_ = false; + } else { + has_token_input_output_ = !token_input_nodes_.empty(); + } + if (ctx->HasAttr(kPropagateCompileTimeConsts)) { + OP_REQUIRES_OK(ctx, ctx->GetAttr(kPropagateCompileTimeConsts, + &propagate_compile_time_consts_)); + } + if (!ctx->GetAttr(kXlaOriginalOutsideCompilationNodeName, + &original_node_name_) + .ok()) + original_node_name_ = name(); +} + +std::pair, xla::XlaOp> +XlaCaseOp::GetPrunedBranchesAndIndex(XlaOpKernelContext* ctx) { + xla::Literal branch_index_literal; + bool branch_index_is_constant = + ctx->ConstantInput(0, &branch_index_literal).ok(); + + if (!branch_index_is_constant) { + return {unpruned_branches_, ctx->Input(0)}; + } + + int32_t branch_index = branch_index_literal.Get({}); + if (branch_index < 0 || branch_index >= unpruned_branches_.size()) { + branch_index = unpruned_branches_.size() - 1; + } + + std::vector pruned_branch = {unpruned_branches_[branch_index]}; + return {pruned_branch, xla::ZerosLike(ctx->Input(0))}; +} + +// TODO(b/35949885): There is duplication here with the handling of the +// while_op/if_op. Refactor the common code out/rework. +void XlaCaseOp::Compile(XlaOpKernelContext* ctx) { + OP_REQUIRES( + ctx, !unpruned_branches_.empty(), + absl::InvalidArgumentError("Must provide at least one case branch")); + OP_REQUIRES(ctx, input_type(0) == DT_INT32, + absl::InvalidArgumentError( + "branch_index argument must be a int32 for XLA compilation")); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(ctx->InputShape(0)), + absl::InvalidArgumentError( + "branch_index argument must be scalar for XLA compilation")); + + xla::XlaBuilder* b = ctx->builder(); + + // We opportunistically prune out branches if the branch index is a + // compile-time constant. This is important in the context of the DeviceIndex + // ops (and other such ops that may come later) since we may have a Case with + // trivially unselected branches that cannot be compiled into HLO. + std::vector branches; + xla::XlaOp branch_index; + std::tie(branches, branch_index) = GetPrunedBranchesAndIndex(ctx); + + int num_branches = branches.size(); + + VLOG(1) << "Building Case: " << input_types_.size() << " inputs"; + + std::vector arguments(input_types_.size()); + int num_resource_args = 0; + for (int i = 0; i < input_types_.size(); ++i) { + XlaCompiler::Argument& arg = arguments[i]; + DataType type = ctx->input_type(i + 1); + + if (type == DT_RESOURCE) { + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(i + 1, &resource)); + XlaCompiler::PopulateArgumentFromResource(*resource, &arg); + OP_REQUIRES(ctx, arg.initialized, + absl::UnimplementedError( + absl::StrCat("Uninitialized arguments: ", arg.name))); + VLOG(2) << "Resource " << resource->name() + << " type: " << DataTypeString(arg.type) + << " shape: " << arg.HumanString() + << " initialized: " << arg.initialized; + + num_resource_args++; + } else { + arg.kind = XlaCompiler::Argument::kParameter; + arg.type = input_types_[i]; + // Use the xla::Shape for the input instead of ctx->InputShape. This is + // necessary for forwarding shapes of DT_VARIANTs, e.g. TensorLists. + auto shape_or = ctx->builder()->GetShape(ctx->Input(i + 1)); + OP_REQUIRES_OK(ctx, shape_or.status()); + arg.shape = shape_or.value(); + VLOG(2) << "Arg type: " << DataTypeString(arg.type) + << " shape: " << arg.HumanString(); + } + } + + if (propagate_compile_time_consts_) { + std::vector> case_branch_must_be_const_nodes( + num_branches); + std::vector case_bodies(num_branches); + for (int branch_idx = 0; branch_idx < num_branches; branch_idx++) { + OP_REQUIRES_OK(ctx, FindMustBeConstNodes( + ctx, branches[branch_idx], + &case_branch_must_be_const_nodes[branch_idx], + &case_bodies[branch_idx])); + } + + // Replaces `kParameter` type args in `arguments` with `kConstant` if + // the op input corresponding to that arg is a compile-time const. This + // is necessary to propagate compile time consts to ops in the branch + // functions. + auto arg_is_parameter = [&](int arg_idx) { + if (arguments[arg_idx].kind != XlaCompiler::Argument::kParameter) { + return false; + } + return true; + }; + ConvertCompileTimeConstArgumentsToConst(ctx, &arguments, + /*xla_expression_offset=*/1, + arg_is_parameter); + } + + // Compile each branch of the conditional. + XlaCompiler::CompileOptions options; + options.use_tuple_arg = true; + options.return_updated_values_for_all_resources = true; + options.is_entry_computation = false; + options.add_token_input_output = has_token_input_output_; + XlaCompiler* compiler = ctx->compiler(); + + std::vector branch_results(num_branches); + for (int j = 0; j < num_branches; ++j) { + OP_REQUIRES_OK(ctx, + compiler->CompileFunction(options, branches[j], arguments, + &branch_results[j])); + OP_REQUIRES_OK( + ctx, + ctx->xla_context()->RecordCollectiveInfoFromNestedCompilationResult( + branch_results[j])); + } + + bool has_tensor_array_gradients = false; + for (XlaCompiler::CompilationResult& result : branch_results) { + for (const XlaCompiler::ResourceUpdate& update : result.resource_updates) { + XlaResource* resource; + OP_REQUIRES_OK(ctx, + ctx->GetResourceInput(update.input_index + 1, &resource)); + XlaCompiler::Argument& arg = arguments[update.input_index]; + + // Add any TensorArray gradients touched by the then/else computation to + // the enclosing graph. + for (const std::string& grad_source : + update.tensor_array_gradients_accessed) { + VLOG(5) << "TensorArray " << resource->name() << " accessed gradient " + << grad_source; + XlaResource* gradient; + OP_REQUIRES_OK(ctx, resource->GetOrCreateTensorArrayGradient( + grad_source, b, &gradient)); + } + // Add all of the TensorArray gradients to the argument. For simplicity, + // we always pass all known gradients. + for (const auto& gradient : resource->tensor_array_gradients()) { + arg.tensor_array_gradients.insert(gradient.first); + } + if (!resource->tensor_array_gradients().empty()) { + has_tensor_array_gradients = true; + } + } + } + + // Recompile the functions to update the argument shapes for tensor arrays. + if (has_tensor_array_gradients) { + for (int j = 0; j < num_branches; ++j) { + branch_results[j] = {}; + OP_REQUIRES_OK(ctx, + compiler->CompileFunction(options, branches[j], arguments, + &branch_results[j])); + } + } + + xla::Shape branch0_input_shape; + std::vector result_computations(num_branches); + for (int j = 0; j < num_branches; ++j) { + // Check that all branches have identical input shapes. + OP_REQUIRES(ctx, branch_results[j].xla_input_shapes.size() == 1, + absl::FailedPreconditionError("Expected one input shape")); + xla::Shape branch_input_shape = branch_results[j].xla_input_shapes[0]; + if (j == 0) { + branch0_input_shape = branch_input_shape; + } + OP_REQUIRES(ctx, branch_input_shape.IsTuple(), + absl::FailedPreconditionError("Expected tuple shape")); + OP_REQUIRES( + ctx, + xla::ShapeUtil::Compatible(branch0_input_shape, branch_input_shape), + absl::InvalidArgumentError(absl::StrCat( + "Input shapes of 0 and ", j, " branches do not match: ", + xla::ShapeUtil::HumanString(branch0_input_shape), " vs. ", + xla::ShapeUtil::HumanString(branch_input_shape)))); + + if (j == 0) { + VLOG(2) << "Input shape: " + << xla::ShapeUtil::HumanString(branch0_input_shape); + VLOG(2) << "Output shape: " + << xla::ShapeUtil::HumanString( + branch_results[0].xla_output_shape); + } + + // Check that all branches have same TensorList output indices. + for (int output_index = 0; output_index < branch_results[0].outputs.size(); + output_index++) { + bool is_tensor_list_in_branch_0 = + branch_results[0].outputs[output_index].is_tensor_list; + bool is_tensor_list_in_branch_j = + branch_results[j].outputs[output_index].is_tensor_list; + OP_REQUIRES(ctx, is_tensor_list_in_branch_0 == is_tensor_list_in_branch_j, + absl::FailedPreconditionError( + absl::StrCat("Output #", output_index, " is ", + is_tensor_list_in_branch_0 ? "" : "not", + " a TensorList in branch 0, but is ", + is_tensor_list_in_branch_j ? "" : "not", + " a TensorList in branch ", j))); + } + + // We set return_updated_values_for_all_resources=true and we pass the same + // arguments to both computations, so the resource update count must match. + OP_REQUIRES(ctx, + branch_results[0].resource_updates.size() == + branch_results[j].resource_updates.size(), + absl::FailedPreconditionError(absl::StrCat( + "Different number of resources in 0 and ", j, " branch"))); + for (int i = 0; i < branch_results[0].resource_updates.size(); ++i) { + const auto& lhs = branch_results[0].resource_updates[i]; + const auto& rhs = branch_results[j].resource_updates[i]; + bool equal = lhs.input_index == rhs.input_index && + lhs.shape == rhs.shape && + lhs.tensor_array_gradients_accessed == + rhs.tensor_array_gradients_accessed; + OP_REQUIRES(ctx, equal, + absl::FailedPreconditionError( + absl::StrCat("Mismatch in resource of 0 and ", j, + " branch for resource ", i))); + } + result_computations[j] = branch_results[j].computation.get(); + } + + // Prepare the input arg Tuple. + int num_inputs = branch_results[0].input_mapping.size(); + std::vector inputs(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + int input_num = branch_results[0].input_mapping[i] + 1; + if (has_token_input_output_ && i == num_inputs - 1) { + // Set token input for this "case" op. + std::vector token_inputs; + token_inputs.reserve(token_input_nodes_.size()); + for (const std::string& node_name : token_input_nodes_) { + auto token_or = compiler->GetNodeToken(node_name); + OP_REQUIRES_OK(ctx, token_or.status()); + token_inputs.push_back(token_or.value()); + } + inputs[i] = xla::AfterAll(b, token_inputs); + } else if (ctx->input_type(input_num) == DT_RESOURCE) { + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(input_num, &resource)); + OP_REQUIRES_OK(ctx, resource->Pack(&inputs[i], b)); + } else { + inputs[i] = ctx->Input(input_num); + } + } + auto input_tuple = xla::Tuple(b, inputs); + xla::XlaOp outputs = xla::DynamicConditional( + ctx->builder(), branch_index, absl::MakeSpan(result_computations), + std::vector(num_branches, input_tuple)); + // Sets non-variable outputs. + for (int i = 0; i < output_types_.size(); ++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.value()); + } else { + LOG(INFO) << "Shape unknown for output " << i; + } + } + // We have checked that all branches have same TensorList output indices. + if (branch_results[0].outputs[i].is_tensor_list) { + ctx->SetTensorListOutput(i, output_handle); + } else { + ctx->SetOutput(i, output_handle); + } + } + if (has_token_input_output_) { + // Set token output for this "Case" op. Token output is the last output of + // XLA computation, which comes after all "normal" TF outputs and resource + // updates. For "Case" node, num of resource updates equals to number of + // resource args because we set `return_updated_values_for_all_resources` + // to true in XlaCompiler option. + xla::XlaOp token_output = + xla::GetTupleElement(outputs, output_types_.size() + num_resource_args); + auto shape_or = b->GetShape(token_output); + OP_REQUIRES_OK(ctx, shape_or.status()); + OP_REQUIRES(ctx, shape_or.value().IsToken(), + absl::FailedPreconditionError(absl::StrCat( + "Token output is not token type: ", + xla::ShapeUtil::HumanString(shape_or.value())))); + OP_REQUIRES_OK(ctx, + compiler->SetNodeToken(original_node_name_, token_output)); + } + + // Updates the values of any resource variables modified by the conditional + // bodies. + for (const XlaCompiler::CompilationResult& result : branch_results) { + for (int i = 0; i < result.resource_updates.size(); ++i) { + const XlaCompiler::ResourceUpdate& update = result.resource_updates[i]; + XlaResource* resource; + OP_REQUIRES_OK(ctx, + ctx->GetResourceInput(update.input_index + 1, &resource)); + if (update.modified) { + int pos = static_cast(result.outputs.size()) + i; + OP_REQUIRES_OK(ctx, + resource->SetFromPack( + arguments[update.input_index].tensor_array_gradients, + xla::GetTupleElement(outputs, pos), b)); + } + VLOG(2) << "Case variable: pos: " << update.input_index + << " name: " << resource->name() + << " modified: " << update.modified + << " type: " << DataTypeString(update.type) + << " shape: " << update.shape.DebugString(); + } + } + VLOG(1) << "Done building Case"; +} + +REGISTER_XLA_OP(Name("Case").AllowResourceTypes().AllowVariantTypes(), + XlaCaseOp); +REGISTER_XLA_OP(Name("StatelessCase").AllowResourceTypes().AllowVariantTypes(), + XlaCaseOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/case_op.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/case_op.h new file mode 100644 index 0000000000000000000000000000000000000000..8e8ae76f808832c4f6461f0269525fe851f39879 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/case_op.h @@ -0,0 +1,78 @@ +/* Copyright 2019 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_KERNELS_CASE_OP_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_CASE_OP_H_ + +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/types.h" + +namespace tensorflow { + +// This TensorFlow op provides a functional switch/case primitive. +// +// The outputs of the branches must agree on the number, types, and +// shapes of the Tensors carried around the two bodies. +// +// Computations in branch bodies may read from and write to resource variables. +// Resource variables may be passed as arguments to the branch function's +// bodies. The XlaCompiler converts resource variable arguments +// into parameters to the XLA computation and moves them to the end of the +// parameter list, and by using the `return_updated_values_for_all_variables` +// we ensure that all variables that appear in the input also appear at the +// end of the branch bodies output. This ensures the branch bodies output +// signatures match. +// +// It is the user's responsibility to ensure that each non-variable _Arg matches +// the corresponding _Retval. +class XlaCaseOp : public XlaOpKernel { + public: + explicit XlaCaseOp(OpKernelConstruction* ctx); + + void Compile(XlaOpKernelContext* ctx) override; + + private: + XlaCaseOp(const XlaCaseOp&) = delete; + void operator=(const XlaCaseOp&) = delete; + + // If the branch_index input is a constant: prunes out all but the branch + // corrresponding to that constant branch index, and returns that branch and + // the literal 0 (as the first and second component of the pair). + // + // If the branch_index input is not a constant: returns unpruned_branches_ and + // the branch_index input. + std::pair, xla::XlaOp> GetPrunedBranchesAndIndex( + XlaOpKernelContext* ctx); + + std::vector unpruned_branches_; + DataTypeVector input_types_; + DataTypeVector output_types_; + bool has_token_input_output_; + std::vector token_input_nodes_; + std::string original_node_name_; + // Whether to propagate compile time consts into the cond branches. + // This is not supported by default now since it may cause HBM memory + // overheads. + bool propagate_compile_time_consts_ = false; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_CASE_OP_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cast_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cast_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..583a2e4c0be3bcd00fa7a22066aee6970d362ec6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cast_op.cc @@ -0,0 +1,157 @@ +/* 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 + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/lib/util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +namespace { + +class CastOp : public XlaOpKernel { + public: + explicit CastOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("SrcT", &src_dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("DstT", &dst_dtype_)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(src_dtype_, &src_type_)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dst_dtype_, &dst_type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Truncate", &use_truncation_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* builder = ctx->builder(); + xla::XlaOp input = ctx->Input(0); + xla::XlaOp output; + + if (src_dtype_ == dst_dtype_) { + output = input; + } else if (dst_dtype_ == DT_BOOL) { + output = xla::Ne(input, XlaHelpers::Zero(builder, src_dtype_)); + } else if (xla::primitive_util::IsComplexType(src_type_) && + !xla::primitive_util::IsComplexType(dst_type_)) { + // As in cast_op.h, we replicate the numpy behavior of truncating the + // imaginary part. + output = xla::ConvertElementType(xla::Real(input), dst_type_); + } else { + if (use_truncation_) { + OP_REQUIRES(ctx, + xla::primitive_util::IsFloatingPointType(src_type_) && + xla::primitive_util::IsFloatingPointType(dst_type_), + absl::UnimplementedError( + "Truncate attribute is only " + "implemented for floating point datatypes.")); + int mantissa_difference = + xla::primitive_util::SignificandWidth(src_type_) - + xla::primitive_util::SignificandWidth(dst_type_); + OP_REQUIRES(ctx, mantissa_difference > 0, + absl::UnimplementedError( + "Truncate attribute is only implemented in cases where " + "dst datatype " + "has fewer mantissa bits than the src datatype")); + int src_bitwidth = xla::primitive_util::BitWidth(src_type_); + + // Bitcast to same-width integer, mask off the LSBs, bitcast back to the + // source datatype. + int64_t mask = ~((1L << mantissa_difference) - 1); + xla::PrimitiveType same_width_int = + xla::primitive_util::UnsignedIntegralTypeForBitWidth(src_bitwidth); + OP_REQUIRES(ctx, same_width_int != xla::PRIMITIVE_TYPE_INVALID, + absl::UnimplementedError("Unexpected type bitwidth")); + input = xla::BitcastConvertType( + xla::And( + xla::BitcastConvertType(input, same_width_int), + ::tensorflow::IntegerLiteral(builder, same_width_int, mask)), + src_type_); + } + output = xla::ConvertElementType(input, dst_type_); + } + + ctx->SetOutput(0, output); + } + + protected: + DataType src_dtype_, dst_dtype_; + xla::PrimitiveType src_type_, dst_type_; + bool use_truncation_; + + CastOp(const CastOp&) = delete; + void operator=(const CastOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Cast"), CastOp); + +class BitcastOp : public XlaOpKernel { + public: + explicit BitcastOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &src_dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("type", &dst_dtype_)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(src_dtype_, &src_type_)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dst_dtype_, &dst_type_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + xla::XlaOp output; + + if (src_dtype_ == dst_dtype_) { + output = input; + ctx->SetOutput(0, output); + return; + } + // Error out if the bitcast has a complex source or destination type and + // the bitcast is not trivial. + OP_REQUIRES(ctx, + !xla::primitive_util::IsComplexType(src_type_) && + !xla::primitive_util::IsComplexType(dst_type_), + absl::UnimplementedError("Complex types not supported.")); + auto input_bit_width = xla::primitive_util::BitWidth(src_type_); + auto output_bit_width = xla::primitive_util::BitWidth(dst_type_); + + OP_REQUIRES(ctx, + output_bit_width % input_bit_width == 0 || + input_bit_width % output_bit_width == 0, + absl::InvalidArgumentError( + "Neither bit width is a multiple of the other.")); + output = xla::BitcastConvertType(input, dst_type_); + ctx->SetOutput(0, output); + } + + protected: + DataType src_dtype_, dst_dtype_; + xla::PrimitiveType src_type_, dst_type_; + + BitcastOp(const BitcastOp&) = delete; + void operator=(const BitcastOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Bitcast"), BitcastOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/categorical_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/categorical_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef55157ef5d2c62aaff98897bc0943becc798d47 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/categorical_op.cc @@ -0,0 +1,206 @@ +/* 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. +==============================================================================*/ + +// XLA implementations of Categorical op. + +#include +#include +#include + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/random_ops_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/prng.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class CategoricalOp : public XlaOpKernel { + public: + explicit CategoricalOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // Get the logits + const xla::XlaOp& logits = ctx->Input(0); + TensorShape logits_shape = ctx->InputShape(0); + int64_t num_samples; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntScalar( + 1, &num_samples, xla::ValueInferenceMode::kUpperBound)); + OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(logits_shape), + absl::InvalidArgumentError( + absl::StrCat("logits should be a matrix, got shape ", + logits_shape.DebugString()))); + OP_REQUIRES(ctx, num_samples >= 0, + absl::InvalidArgumentError(absl::StrCat( + "num_samples should be nonnegative, got ", num_samples))); + + for (int i = 0; i < 2; i++) { + const int64_t dim = logits_shape.dim_size(i); + OP_REQUIRES(ctx, static_cast(dim) == dim, + absl::InvalidArgumentError(absl::StrCat( + "logits.shape = ", logits_shape.DebugString(), + " too large for int"))); + } + + const int64_t batch_size = logits_shape.dim_size(0); + const int64_t num_classes = logits_shape.dim_size(1); + + xla::Shape uniform_shape; + int class_dimension; + bool num_samples_is_dynamic = false; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPred(1, &num_samples_is_dynamic)); + if (num_samples != 1 || num_samples_is_dynamic) { + std::array uniform_shape_array = { + {batch_size, num_samples, num_classes}}; + xla::PrimitiveType uniform_xla_type; + OP_REQUIRES_OK(ctx, + DataTypeToPrimitiveType(input_type(0), &uniform_xla_type)); + uniform_shape = + xla::ShapeUtil::MakeShape(uniform_xla_type, uniform_shape_array); + class_dimension = 2; + } else { + // Have a special case for when we only need one sample, because + // dimensions may be padded on architectures with tiled memory layouts, so + // if the num_classes or batch size is large then this can lead to + // expensive wasted memory. + std::array uniform_shape_array = {{batch_size, num_classes}}; + xla::PrimitiveType uniform_xla_type; + OP_REQUIRES_OK(ctx, + DataTypeToPrimitiveType(input_type(0), &uniform_xla_type)); + uniform_shape = + xla::ShapeUtil::MakeShape(uniform_xla_type, uniform_shape_array); + class_dimension = 1; + } + xla::PrimitiveType type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(input_type(0), &type)); + xla::XlaOp log_uniforms = GetLogUniforms(uniform_shape, type, ctx); + + if (num_samples_is_dynamic) { + // num_samples is dimension 1 in uniform_shape_array. + log_uniforms = xla::SetDimensionSize(log_uniforms, ctx->Input(1), 1); + } + + // Use Gumbel softmax trick to generate categorical samples. + // See: + // https://hips.seas.harvard.edu/blog/2013/04/06/the-gumbel-max-trick-for-discrete-distributions/ + // TODO(b/68769470): Switch to using a cumulative sum approach. + auto softmax_entries = + xla::Sub(logits, log_uniforms, + /*broadcast_dimensions=*/{0, class_dimension}); + + xla::PrimitiveType xla_output_type; + OP_REQUIRES_OK(ctx, + DataTypeToPrimitiveType(output_type(0), &xla_output_type)); + xla::XlaOp argmax = xla::ArgMax(softmax_entries, xla_output_type, + /*axis=*/class_dimension); + + if (num_samples == 1 && !num_samples_is_dynamic) { + argmax = xla::Reshape(argmax, {batch_size, 1}); + } + + ctx->SetOutput(0, argmax); + } + + virtual xla::XlaOp GetLogUniforms(xla::Shape uniform_shape, + xla::PrimitiveType type, + XlaOpKernelContext* ctx) { + xla::XlaBuilder* builder = ctx->builder(); + LOG_FIRST_N(WARNING, 1) << "Warning: Using tf.random.categorical with XLA" + " compilation will ignore seeds."; + // We want a number in (0, 1) rather than [0, 1) or (0, 1]: + // * log(-log(0)) is ∞. + // * log(-log(1)) is -∞. + auto uniforms = xla::RngUniform( + xla::MinPositiveNormalValue(builder, type), + xla::One(builder, uniform_shape.element_type()), uniform_shape); + return xla::Log(-xla::Log(uniforms)); + } + + private: + CategoricalOp(const CategoricalOp&) = delete; + void operator=(const CategoricalOp&) = delete; +}; + +// TODO(b/68769717): Rename this sampler to Categorical. +REGISTER_XLA_OP(Name("Multinomial").CompileTimeConstantInput("num_samples"), + CategoricalOp); + +class StatelessCategoricalOp : public CategoricalOp { + public: + explicit StatelessCategoricalOp(OpKernelConstruction* ctx) + : CategoricalOp(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + xla::XlaOp GetLogUniforms(xla::Shape uniform_shape, xla::PrimitiveType type, + XlaOpKernelContext* ctx) override { + xla::XlaOp seed = ctx->Input(2); + + xla::XlaBuilder* builder = ctx->builder(); + if (uniform_shape.element_type() == xla::BF16) { + uniform_shape.set_element_type(xla::F32); + } + // We want a number in (0, 1) rather than [0, 1) or (0, 1]: + // * log(-log(0)) is ∞. + // * log(-log(1)) is -∞. + xla::XlaOp uniforms = StatelessRngUniform( + device_type_string_, seed, uniform_shape, + xla::MinPositiveNormalValue(builder, uniform_shape.element_type()), + xla::One(builder, uniform_shape.element_type())); + return xla::ConvertElementType(xla::Log(-xla::Log(uniforms)), type); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape seed_shape = ctx->InputShape(2); + OP_REQUIRES( + ctx, seed_shape.dims() == 1 && seed_shape.dim_size(0) == 2, + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + CategoricalOp::Compile(ctx); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessCategoricalOp(const StatelessCategoricalOp&) = delete; + void operator=(const StatelessCategoricalOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessMultinomial") + .CompileTimeConstantInput("num_samples") + .TypeConstraint("T", {DT_DOUBLE, DT_FLOAT, DT_BFLOAT16}) + .TypeConstraint("Tseed", DT_INT32), + StatelessCategoricalOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/check_numerics_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/check_numerics_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..24f074f463574365a246ea8287b1a3063e799488 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/check_numerics_op.cc @@ -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. +==============================================================================*/ + +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("CheckNumerics"), MlirXlaOpKernel); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cholesky_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cholesky_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..10aaf07b4f828651c5a02aefafad25ef823940bc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cholesky_op.cc @@ -0,0 +1,38 @@ +/* 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/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" + +namespace tensorflow { +namespace { + +class CholeskyOp : public XlaOpKernel { + public: + explicit CholeskyOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + ctx->SetOutput(0, + xla::Triangle(xla::Cholesky(ctx->Input(0), /*lower=*/true), + /*lower=*/true)); + } +}; + +REGISTER_XLA_OP(Name("Cholesky").TypeConstraint("T", kFloatAndComplexTypes), + CholeskyOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/clip_by_value_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/clip_by_value_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..9deba8db0df130c1f7a0c7ce81478c9955a0a22a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/clip_by_value_op.cc @@ -0,0 +1,63 @@ +/* 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 "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace tensorflow { +namespace { + +class ClipByValueOp : public XlaOpKernel { + public: + explicit ClipByValueOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape shape = ctx->InputShape(0); + const TensorShape min_shape = ctx->InputShape(1); + const TensorShape max_shape = ctx->InputShape(2); + + auto input = ctx->Input(0); + auto min = ctx->Input(1); + auto max = ctx->Input(2); + + auto shape_error = [&]() -> absl::Status { + return absl::InvalidArgumentError( + absl::StrCat("clip_value_min and clip_value_max must be either of " + "the same shape as input, or a scalar. ", + "Input shape: ", shape.DebugString(), + " clip_value_min shape: ", min_shape.DebugString(), + " clip_value_max shape: ", max_shape.DebugString())); + }; + + if (shape != min_shape) { + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(min_shape), shape_error()); + min = xla::Broadcast(min, shape.dim_sizes()); + } + if (shape != max_shape) { + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(max_shape), shape_error()); + max = xla::Broadcast(max, shape.dim_sizes()); + } + ctx->SetOutput(0, xla::Clamp(min, input, max)); + } +}; + +REGISTER_XLA_OP(Name("ClipByValue"), ClipByValueOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/concat_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/concat_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..fcd152d6085d52ee1857100eb3c678b83966bb18 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/concat_op.cc @@ -0,0 +1,229 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Concat Ops. + +#include +#include + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/kernels/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// -------------------------------------------------------------------------- +class ConcatBaseOp : public XlaOpKernel { + public: + ConcatBaseOp(OpKernelConstruction* c, int64_t axis_index) + : XlaOpKernel(c), axis_index_(axis_index) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape concat_dim_tensor_shape = ctx->InputShape(axis_index_); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(concat_dim_tensor_shape), + absl::InvalidArgumentError(absl::StrCat( + "Concat dim tensor should be a scalar, but got shape ", + concat_dim_tensor_shape.DebugString()))); + int64_t concat_dim; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntScalar(axis_index_, &concat_dim)); + + std::vector values; + std::vector shapes; + OP_REQUIRES_OK(ctx, ctx->InputList("values", &values, &shapes)); + const int N = values.size(); + const int input_dims = shapes[0].dims(); + const TensorShape& input_shape = shapes[0]; + + int64_t axis = concat_dim < 0 ? concat_dim + input_dims : concat_dim; + OP_REQUIRES(ctx, 0 <= axis && axis < input_dims, + absl::InvalidArgumentError(absl::StrCat( + "ConcatOp : Expected concatenating dimensions in the range " + "[", + -input_dims, ", ", input_dims, "), but got ", concat_dim))); + + // Make a vector holding the XlaOp for each of the inputs that has non-zero + // elements. + std::vector input_data; + int output_concat_dim = 0; + for (int i = 0; i < N; ++i) { + xla::XlaOp handle = values[i]; + const TensorShape& in_shape = shapes[i]; + OP_REQUIRES( + ctx, in_shape.dims() == input_dims, + absl::InvalidArgumentError(absl::StrCat( + "ConcatOp : Ranks of all input tensors should match: shape[0] = ", + input_shape.DebugString(), " vs. shape[", i, + "] = ", in_shape.DebugString()))); + if (in_shape.dims() == 0) { + // Inputs that come in as scalars must be reshaped to 1-vectors. + input_data.push_back(xla::Reshape(handle, {1})); + } else { + input_data.push_back(handle); + } + output_concat_dim += in_shape.dims() > 0 ? in_shape.dim_size(axis) : 1; + } + + VLOG(1) << "Concat dim " << concat_dim << " equivalent to " << axis; + ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), input_data, axis)); + } + + private: + int axis_index_; +}; + +class ConcatOp : public ConcatBaseOp { + public: + explicit ConcatOp(OpKernelConstruction* c) + : ConcatBaseOp(c, /* axis_index */ 0) {} +}; + +// ConcatV2 operation is the same as Concat except 'concat_dim' +// is the last input instead of the first and renamed to 'axis'. +class ConcatV2Op : public ConcatBaseOp { + public: + explicit ConcatV2Op(OpKernelConstruction* c) + : ConcatBaseOp(c, /* axis_index */ c->num_inputs() - 1) {} +}; + +REGISTER_XLA_OP(Name("Concat").CompileTimeConstantInput("concat_dim"), + ConcatOp); +REGISTER_XLA_OP(Name("ConcatV2") + .TypeConstraint("Tidx", {DT_INT32, DT_INT64}) + .CompileTimeConstantInput("axis"), + ConcatV2Op); + +class ConcatOffsetOp : public XlaOpKernel { + public: + explicit ConcatOffsetOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("shape_type", &shape_type_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape concat_dim_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(concat_dim_shape), + absl::InvalidArgumentError(absl::StrCat( + "Concat dim tensor should be a scalar, but got shape ", + concat_dim_shape.DebugString()))); + for (int i = 1; i < ctx->num_inputs(); ++i) { + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ctx->InputShape(i)), + absl::InvalidArgumentError(absl::StrCat( + "input ", i, " should be a vector, but got shape ", + ctx->InputShape(i).DebugString()))); + } + // Suppose a Concat() op needs to Concatenate N tensors, each of + // which has the same number of dimensions. Their shapes match + // except the concat dimension. + // + // E.g., say, we want to concatenate 3 tensors in the 2nd + // dimension, and their shapes are: + // + // [2, 2, 5, 7] + // [2, 3, 5, 7] + // [2, 4, 5, 7] + // + // Here, N=3, cdim=1, dims=4. The concatenated tensor has shape + // [2,9,5,7]. We will compute the cumulative sum along the 2nd + // dimension to figure out each input's offset in the concatenated + // output: + // [0, 0, 0, 0] + // [0, 2, 0, 0] + // [0, 5, 0, 0] + const int32_t N = ctx->num_inputs() - 1; + const TensorShape inp0_shape = ctx->InputShape(1); + std::vector inp0_dims; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntVector( + 1, &inp0_dims, xla::ValueInferenceMode::kUpperBound)); + const int64_t inp0_rank = inp0_shape.num_elements(); + + int64_t cdim; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(0, &cdim)); + + VLOG(1) << "ConcatOffset " << cdim << "," << inp0_rank; + int32_t axis = cdim < 0 ? cdim + inp0_rank : cdim; + OP_REQUIRES(ctx, FastBoundsCheck(axis, inp0_rank), + absl::InvalidArgumentError(absl::StrCat( + "Concat dim is out of range: ", axis, " vs. ", inp0_rank))); + int64_t offset = 0; + for (int i = 0; i < N; ++i) { + const TensorShape inp_shape = ctx->InputShape(1 + i); + OP_REQUIRES(ctx, inp0_rank == inp_shape.num_elements(), + absl::InvalidArgumentError(absl::StrCat( + "input ", i, " should contain ", inp0_rank, + " elements, but got ", inp_shape.num_elements()))); + std::vector inp_dims; + OP_REQUIRES_OK( + ctx, ctx->ConstantInputAsIntVector( + 1 + i, &inp_dims, xla::ValueInferenceMode::kUpperBound)); + + std::vector output_dims(inp0_rank); + for (int64_t j = 0; j < inp0_rank; ++j) { + if (j == axis) { + output_dims[j] = offset; + offset += inp_dims[j]; + } else { + const int64_t inp0_element = inp0_dims[j]; + const int64_t inp_element = inp_dims[j]; + OP_REQUIRES(ctx, inp0_element == inp_element, + absl::InvalidArgumentError(absl::StrCat( + "All dimensions except ", axis, " must match. Input ", + i, " has shape [", absl::StrJoin(inp_dims, " "), + "] and doesn't match input 0 with shape [", + absl::StrJoin(inp0_dims, " "), "]."))); + output_dims[j] = 0; + } + } + TensorShape out_shape; + OP_REQUIRES_OK(ctx, + TensorShape::BuildTensorShape(output_dims, &out_shape)); + Tensor out_constant(shape_type_, TensorShape({inp0_rank})); + OP_REQUIRES_OK(ctx, TensorShapeToConstant(out_shape, &out_constant)); + + ctx->SetConstantOutput(i, out_constant); + } + } + + private: + DataType shape_type_; +}; + +REGISTER_XLA_OP(Name("ConcatOffset") + .TypeConstraint("shape_type", {DT_INT32, DT_INT64}) + .CompileTimeConstantInput("concat_dim") + .CompileTimeConstantInput("shape"), + ConcatOffsetOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/const_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/const_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..0a8fcd9a634110d94e2289f4b6f53abe2048afb4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/const_op.cc @@ -0,0 +1,151 @@ +/* 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 +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/tensor.pb.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +template +DstT CastTo(SrcT src) { + return static_cast(src); +} + +template ::value || + std::is_same::value>::type* = + nullptr> +DstT CastTo(int32_t src) { + return absl::bit_cast(static_cast(src)); +} + +// Returns scalar constant with the value in the tensor, if the given proto has +// exactly one value but more than one elements. This encoding is used to +// efficiently serialize tensors that have one value repeated for all the +// indices. +xla::XlaOp GetScalarConst(const TensorProto& proto, xla::XlaBuilder* b) { + if (!proto.tensor_content().empty()) return xla::XlaOp(); + TensorShape shape(proto.tensor_shape()); + if (shape.num_elements() > 1) { + switch (proto.dtype()) { +#define HANDLE_SPLAT(DTYPE, field_name, xla_type) \ + case DTYPE: \ + if (proto.field_name##_val_size() == 0) { \ + return xla::ConstantR0(b, CastTo(0)); \ + } else if (proto.field_name##_val_size() == 1) { \ + return xla::ConstantR0(b, CastTo(proto.field_name##_val(0))); \ + } \ + break; + + HANDLE_SPLAT(DT_BOOL, bool, bool); + + HANDLE_SPLAT(DT_INT8, int, int8_t); + HANDLE_SPLAT(DT_INT16, int, int16_t); + HANDLE_SPLAT(DT_INT32, int, int32_t); + HANDLE_SPLAT(DT_INT64, int64, int64_t); + + HANDLE_SPLAT(DT_UINT8, int, uint8_t); + HANDLE_SPLAT(DT_UINT16, int, uint16_t); + HANDLE_SPLAT(DT_UINT32, uint32, uint32_t); + HANDLE_SPLAT(DT_UINT64, uint64, uint64_t); + + HANDLE_SPLAT(DT_FLOAT, float, float); + HANDLE_SPLAT(DT_DOUBLE, double, double); + + HANDLE_SPLAT(DT_BFLOAT16, half, bfloat16); + HANDLE_SPLAT(DT_HALF, half, Eigen::half); + +#undef HANDLE_SPLAT + +#define HANDLE_COMPLEX_SPLAT(DTYPE, field_name, xla_type) \ + case DTYPE: \ + if (proto.field_name##_val_size() == 2) { \ + return xla::ConstantR0( \ + b, xla_type(proto.field_name##_val(0), proto.field_name##_val(1))); \ + } \ + break; + + HANDLE_COMPLEX_SPLAT(DT_COMPLEX64, scomplex, xla::complex64); + HANDLE_COMPLEX_SPLAT(DT_COMPLEX128, dcomplex, xla::complex128); + +#undef HANDLE_COMPLEXSPLAT + + default: + break; + } + } + + return xla::XlaOp(); +} + +class ConstOp : public XlaOpKernel { + public: + explicit ConstOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + const TensorProto* proto = nullptr; + OP_REQUIRES_OK(ctx, ctx->GetAttr("value", &proto)); + proto_ = *proto; + OP_REQUIRES( + ctx, ctx->output_type(0) == proto_.dtype(), + absl::InvalidArgumentError(absl::StrCat( + "Type mismatch between value (", DataTypeString(proto_.dtype()), + ") and dtype (", DataTypeString(ctx->output_type(0)), ")"))); + OP_REQUIRES_OK(ctx, TensorShape::IsValidShape(proto_.tensor_shape())); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + // To avoid blowups for large constants filled with the same value, + // recognize that case and emit a scalar broadcast instead. + TensorShape shape(proto_.tensor_shape()); + if (shape.num_elements() > 1) { + xla::XlaOp value = GetScalarConst(proto_, b); + if (value.valid()) { + ctx->SetOutput(0, xla::Broadcast(value, shape.dim_sizes())); + return; + } + } + + Tensor tensor(proto_.dtype()); + OP_REQUIRES(ctx, tensor.FromProto(cpu_allocator(), proto_), + absl::InvalidArgumentError(absl::StrCat( + "Cannot parse tensor from proto: ", proto_.DebugString()))); + ctx->SetConstantOutput(0, tensor); + } + + private: + TensorProto proto_; + ConstOp(const ConstOp&) = delete; + void operator=(const ConstOp&) = delete; +}; + +// XLA_* devices also register a "real" Const operator so we suppress the +// dummy operator using CompilationOnly(). +REGISTER_XLA_OP(Name("Const").CompilationOnly(), ConstOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c45cdd17a39713e5e682ff559fccf728bfa9820 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.cc @@ -0,0 +1,615 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Ops for 2D convolution. + +#include "tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h" + +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/kernel_shape_util.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/numeric_op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/kernels/conv_grad_shape_utils.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" +#include "tsl/platform/tensor_float_32_utils.h" + +namespace tensorflow { +namespace { + +xla::PrecisionConfig GetPrecisionConfig() { + xla::PrecisionConfig::Precision precision = + tsl::tensor_float_32_execution_enabled() ? xla::PrecisionConfig::DEFAULT + : xla::PrecisionConfig::HIGHEST; + xla::PrecisionConfig config; + const int num_inputs = 2; + config.mutable_operand_precision()->Reserve(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + config.add_operand_precision(precision); + } + return config; +} + +// Returns the expanded size of a filter used for depthwise convolution. +// If `shape` is [H, W, ..., M, N] returns [H, W, ..., 1, M*N]. +xla::Shape GroupedFilterShapeForDepthwiseConvolution( + const xla::Shape& filter_shape) { + int64_t input_feature_dim = filter_shape.dimensions().size() - 2; + int64_t output_feature_dim = filter_shape.dimensions().size() - 1; + int64_t depthwise_multiplier = filter_shape.dimensions(output_feature_dim); + int64_t input_feature = filter_shape.dimensions(input_feature_dim); + + // Create a [H, W, ..., 1, M*N] reshape of the filter. + xla::Shape grouped_filter_shape = filter_shape; + grouped_filter_shape.set_dimensions(input_feature_dim, 1); + grouped_filter_shape.set_dimensions(output_feature_dim, + depthwise_multiplier * input_feature); + return grouped_filter_shape; +} + +// Returns the transposed filter for use in BackpropInput of group convolution. +xla::XlaOp TransposeFilterForGroupConvolutionBackpropInput( + xla::XlaOp filter, const xla::Shape& filter_shape, int64_t num_groups, + int num_spatial_dims) { + // 1. Reshape from [H, W, ..., filter_in_depth, out_depth] to [H, W, ..., + // filter_in_depth, G, out_depth / G] + int num_dims = filter_shape.dimensions().size(); + CHECK_GE(num_dims, 2); // Crash OK + xla::Shape new_shape = filter_shape; + new_shape.set_dimensions(num_dims - 1, num_groups); + new_shape.add_dimensions(filter_shape.dimensions(num_dims - 1) / num_groups); + xla::XlaOp result = xla::Reshape(filter, new_shape.dimensions()); + + // 2. Transpose to [H, W, ..., G, filter_in_depth, out_depth / G] + std::vector transpose_dims(num_dims + 1); + std::iota(transpose_dims.begin(), transpose_dims.end(), 0); + std::swap(transpose_dims[num_spatial_dims], + transpose_dims[num_spatial_dims + 1]); + result = xla::Transpose(result, transpose_dims); + + // 3. Reshape to [H, W, ..., in_depth, out_depth / G] + result = xla::Collapse(result, {num_spatial_dims, num_spatial_dims + 1}); + return result; +} + +// 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 xla::Shape& filter_shape, + xla::XlaOp filter) { + return xla::Reshape( + filter, + GroupedFilterShapeForDepthwiseConvolution(filter_shape).dimensions()); +} + +// Performs some basic checks on ConvOpAttrs that are true for all kinds of XLA +// convolutions (as currently implemented). +absl::Status CheckConvAttrs(const ConvOpAttrs& attrs) { + const int num_dims = attrs.num_spatial_dims + 2; + const int attrs_strides_size = attrs.strides.size(); + if (attrs_strides_size != num_dims) { + return absl::InvalidArgumentError(absl::StrCat( + "Sliding window strides field must specify ", num_dims, " dimensions")); + } + int batch_dim = GetTensorBatchDimIndex(num_dims, attrs.data_format); + int feature_dim = GetTensorFeatureDimIndex(num_dims, attrs.data_format); + if (attrs.strides[batch_dim] != 1 || attrs.strides[feature_dim] != 1) { + return absl::UnimplementedError( + "Current implementation does not yet support strides in the batch and " + "depth dimensions."); + } + const int attrs_dilations_size = attrs.dilations.size(); + if (attrs_dilations_size != num_dims) { + return absl::InvalidArgumentError( + absl::StrCat("Dilations field must specify ", num_dims, " dimensions")); + } + if (attrs.dilations[batch_dim] != 1 || attrs.dilations[feature_dim] != 1) { + return absl::UnimplementedError( + "Current implementation does not support dilations in the batch and " + "depth dimensions."); + } + for (int i = 0; i < attrs.num_spatial_dims; ++i) { + int input_dim = GetTensorSpatialDimIndex(num_dims, attrs.data_format, i); + if (attrs.dilations[input_dim] < 1) { + return absl::UnimplementedError(absl::StrCat( + "Dilation values must be positive; ", i, + "th spatial dimension had dilation ", attrs.dilations[input_dim])); + } + } + return absl::OkStatus(); +} + +// Wrapper around ConvBackpropComputeDimensions that converts from XLA shapes +// to TensorShapes. +absl::Status ConvBackpropComputeDimensionsV2XlaShapes( + absl::string_view label, int num_spatial_dims, + const xla::Shape& input_shape, const xla::Shape& filter_shape, + const xla::Shape& out_backprop_shape, absl::Span dilations, + const std::vector& strides, Padding padding, + TensorFormat data_format, ConvBackpropDimensions* dims, + absl::Span explicit_paddings) { + TensorShape input_tensor_shape, filter_tensor_shape, + out_backprop_tensor_shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(input_shape, &input_tensor_shape)); + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(filter_shape, &filter_tensor_shape)); + TF_RETURN_IF_ERROR( + XLAShapeToTensorShape(out_backprop_shape, &out_backprop_tensor_shape)); + return ConvBackpropComputeDimensionsV2( + label, num_spatial_dims, input_tensor_shape, filter_tensor_shape, + out_backprop_tensor_shape, dilations, strides, padding, explicit_paddings, + data_format, dims); +} + +} // anonymous namespace + +std::vector GetXlaConvTypesForNonGpu() { + return {DT_FLOAT, DT_BFLOAT16, DT_HALF, DT_DOUBLE, DT_INT32}; +} + +std::vector GetXlaConvTypesForGpu() { + return {DT_FLOAT, DT_BFLOAT16, DT_HALF, DT_DOUBLE}; +} + +absl::StatusOr ConvOpAttrs::Create(int num_spatial_dims, + bool depthwise, + OpKernelConstruction* ctx) { + ConvOpAttrs attrs; + attrs.num_spatial_dims = num_spatial_dims; + attrs.depthwise = depthwise; + TF_RETURN_IF_ERROR(ctx->GetAttr("dilations", &attrs.dilations)); + TF_RETURN_IF_ERROR(ctx->GetAttr("strides", &attrs.strides)); + TF_RETURN_IF_ERROR(ctx->GetAttr("padding", &attrs.padding)); + if (attrs.padding == EXPLICIT) { + TF_RETURN_IF_ERROR( + ctx->GetAttr("explicit_paddings", &attrs.explicit_paddings)); + } + + std::string data_format; + TF_RETURN_IF_ERROR(ctx->GetAttr("data_format", &data_format)); + if (!FormatFromString(data_format, &attrs.data_format)) { + return absl::InvalidArgumentError( + absl::StrCat("Invalid data format: ", data_format)); + } + + TF_RETURN_IF_ERROR(CheckValidPadding(attrs.padding, attrs.explicit_paddings, + /*num_dims=*/num_spatial_dims + 2, + attrs.data_format)); + + return attrs; +} + +absl::StatusOr ConvNDOpAttrs::Create(OpKernelConstruction* ctx) { + ConvNDOpAttrs attrs; + TF_RETURN_IF_ERROR(ctx->GetAttr("groups", &attrs.groups)); + TF_RETURN_IF_ERROR(ctx->GetAttr("batch_dims", &attrs.batch_dims)); + if (attrs.batch_dims < 1) { + return absl::InvalidArgumentError("batch_dims must be non-negative."); + } + TF_RETURN_IF_ERROR(ctx->GetAttr("dilations", &attrs.dilations)); + TF_RETURN_IF_ERROR(ctx->GetAttr("strides", &attrs.strides)); + TF_RETURN_IF_ERROR(ctx->GetAttr("padding", &attrs.padding)); + if (attrs.padding == EXPLICIT) { + TF_RETURN_IF_ERROR( + ctx->GetAttr("explicit_paddings", &attrs.explicit_paddings)); + } + + std::string data_format_str; + TF_RETURN_IF_ERROR(ctx->GetAttr("data_format", &data_format_str)); + if (!(data_format_str == "CHANNELS_LAST" || + data_format_str == "CHANNELS_FIRST")) { + return absl::InvalidArgumentError( + absl::StrCat("Unknown data format: ", data_format_str)); + } + attrs.data_format = + data_format_str == "CHANNELS_LAST" ? FORMAT_NHWC : FORMAT_NCHW; + + return attrs; +} + +absl::StatusOr MakeXlaForwardConvOp( + absl::string_view /*type_string*/, xla::XlaOp conv_input, xla::XlaOp filter, + const ConvOpAttrs& attrs) { + TF_RETURN_IF_ERROR(CheckConvAttrs(attrs)); + + auto* builder = conv_input.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape input_shape, builder->GetShape(conv_input)); + // Filter has the form [filter_rows, filter_cols, ..., in_depth, out_depth] + TF_ASSIGN_OR_RETURN(xla::Shape filter_shape, builder->GetShape(filter)); + + // For 2D convolution, there should be 4 dimensions. + int num_dims = attrs.num_spatial_dims + 2; + if (input_shape.dimensions().size() != num_dims) { + return absl::InvalidArgumentError(absl::StrCat( + "input must be ", num_dims, "-dimensional", input_shape.ToString())); + } + if (filter_shape.dimensions().size() != num_dims) { + return absl::InvalidArgumentError( + absl::StrCat("filter must be ", num_dims, + "-dimensional: ", filter_shape.ToString())); + } + + // The last two dimensions of the filter are the input and output shapes. + int batch_dim = GetTensorBatchDimIndex(num_dims, attrs.data_format); + int feature_dim = GetTensorFeatureDimIndex(num_dims, attrs.data_format); + + int64_t filter_in_depth = filter_shape.dimensions(attrs.num_spatial_dims), + out_depth = filter_shape.dimensions(attrs.num_spatial_dims + 1), + in_depth = input_shape.dimensions(feature_dim); + // The 'C' dimension for input is in_depth. + // It must be a multiple of the filter's in_depth. + if (in_depth % filter_in_depth != 0) { + return absl::InvalidArgumentError(absl::StrCat( + "Depth of input must be a multiple of depth of filter: ", in_depth, + " vs ", filter_in_depth)); + } + int64_t feature_group_count = in_depth / filter_in_depth; + if (out_depth % feature_group_count != 0) { + return absl::InvalidArgumentError(absl::StrCat( + "Depth of output must be a multiple of the number of groups: ", + out_depth, " vs ", feature_group_count)); + } + + if (attrs.depthwise) { + filter = ReshapeFilterForDepthwiseConvolution(filter_shape, filter); + } + + xla::ConvolutionDimensionNumbers dims; + std::vector window_strides(attrs.num_spatial_dims); + std::vector lhs_dilation(attrs.num_spatial_dims, 1); + std::vector rhs_dilation(attrs.num_spatial_dims); + std::vector> padding(attrs.num_spatial_dims); + + dims.set_input_batch_dimension(batch_dim); + dims.set_output_batch_dimension(batch_dim); + dims.set_input_feature_dimension(feature_dim); + dims.set_output_feature_dimension(feature_dim); + dims.set_kernel_input_feature_dimension(attrs.num_spatial_dims); + dims.set_kernel_output_feature_dimension(attrs.num_spatial_dims + 1); + xla::PaddingType padding_type = xla::PaddingType::PADDING_INVALID; + for (int i = 0; i < attrs.num_spatial_dims; ++i) { + const int64_t dim = + GetTensorSpatialDimIndex(num_dims, attrs.data_format, i); + if (input_shape.is_dynamic_dimension(dim)) { + TF_RET_CHECK(attrs.padding == VALID || attrs.padding == SAME) + << "Dynamic convolution only supports valid and same padding"; + if (attrs.padding == VALID) { + padding_type = xla::PaddingType::PADDING_VALID; + } + if (attrs.padding == SAME) { + padding_type = xla::PaddingType::PADDING_SAME; + } + } + dims.add_input_spatial_dimensions(dim); + dims.add_kernel_spatial_dimensions(i); + dims.add_output_spatial_dimensions(dim); + window_strides[i] = attrs.strides.at(dim); + rhs_dilation[i] = attrs.dilations.at(dim); + + if (attrs.padding == EXPLICIT) { + padding[i] = {attrs.explicit_paddings.at(dim * 2), + attrs.explicit_paddings.at(dim * 2 + 1)}; + } + + int64_t unused_output_size; + TF_RETURN_IF_ERROR(GetWindowedOutputSizeVerbose( + input_shape.dimensions(dim), filter_shape.dimensions(i), + rhs_dilation[i], window_strides[i], attrs.padding, &unused_output_size, + &padding[i].first, &padding[i].second)); + } + xla::PrecisionConfig precision_config = GetPrecisionConfig(); + + if (padding_type != xla::PaddingType::PADDING_INVALID) { + return xla::DynamicConvForward( + conv_input, filter, window_strides, padding, lhs_dilation, rhs_dilation, + dims, + /*feature_group_count=*/attrs.depthwise ? in_depth + : feature_group_count, + /*batch_group_count=*/1, &precision_config, padding_type); + } + + return xla::ConvGeneralDilated( + conv_input, filter, window_strides, padding, lhs_dilation, rhs_dilation, + dims, + /*feature_group_count=*/attrs.depthwise ? in_depth : feature_group_count, + /*batch_group_count=*/1, &precision_config); +} + +absl::StatusOr MakeXlaBackpropInputConvOp( + absl::string_view type_string, const xla::Shape& input_shape, + xla::XlaOp filter, xla::XlaOp out_backprop, const ConvOpAttrs& attrs, + xla::XlaOp* input_sizes) { + TF_RETURN_IF_ERROR(CheckConvAttrs(attrs)); + + int num_dims = attrs.num_spatial_dims + 2; + int batch_dim = GetTensorBatchDimIndex(num_dims, attrs.data_format); + int feature_dim = GetTensorFeatureDimIndex(num_dims, attrs.data_format); + + auto* builder = filter.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape filter_shape, builder->GetShape(filter)); + TF_ASSIGN_OR_RETURN(xla::Shape out_backprop_shape, + builder->GetShape(out_backprop)); + + int64_t in_depth = input_shape.dimensions(feature_dim), + filter_in_depth = filter_shape.dimensions(attrs.num_spatial_dims), + feature_group_count = + attrs.depthwise ? filter_in_depth : in_depth / filter_in_depth; + + xla::Shape grouped_filter_shape = + attrs.depthwise ? GroupedFilterShapeForDepthwiseConvolution(filter_shape) + : filter_shape; + // Reuse dimension computation logic from conv_grad_shape_utils.cc. + ConvBackpropDimensions dims; + TF_RETURN_IF_ERROR(ConvBackpropComputeDimensionsV2XlaShapes( + type_string, attrs.num_spatial_dims, input_shape, grouped_filter_shape, + out_backprop_shape, attrs.dilations, attrs.strides, attrs.padding, + attrs.data_format, &dims, attrs.explicit_paddings)); + + // The input gradients are computed by a convolution of the output + // gradients and the filter, with some appropriate padding. See the + // comment at the top of conv_grad_shape_utils.h for details. + + xla::ConvolutionDimensionNumbers dnums; + dnums.set_input_batch_dimension(batch_dim); + dnums.set_output_batch_dimension(batch_dim); + dnums.set_input_feature_dimension(feature_dim); + dnums.set_output_feature_dimension(feature_dim); + + // TF filter shape is [ H, W, ..., inC, outC ] + // Transpose the input and output features for computing the gradient. + dnums.set_kernel_input_feature_dimension(attrs.num_spatial_dims + 1); + dnums.set_kernel_output_feature_dimension(attrs.num_spatial_dims); + + std::vector kernel_spatial_dims(attrs.num_spatial_dims); + std::vector> padding(attrs.num_spatial_dims); + std::vector lhs_dilation(attrs.num_spatial_dims); + std::vector rhs_dilation(attrs.num_spatial_dims); + std::vector ones(attrs.num_spatial_dims, 1); + xla::PaddingType padding_type = xla::PaddingType::PADDING_INVALID; + for (int i = 0; i < attrs.num_spatial_dims; ++i) { + int64_t dim = GetTensorSpatialDimIndex(num_dims, attrs.data_format, i); + if (out_backprop_shape.is_dynamic_dimension(dim)) { + TF_RET_CHECK(attrs.padding == VALID || attrs.padding == SAME) + << "Dynamic convolution only supports valid and same padding"; + if (attrs.padding == VALID) { + padding_type = xla::PaddingType::PADDING_VALID; + } + if (attrs.padding == SAME) { + padding_type = xla::PaddingType::PADDING_SAME; + } + } + dnums.add_input_spatial_dimensions(dim); + dnums.add_kernel_spatial_dimensions(i); + dnums.add_output_spatial_dimensions(dim); + + kernel_spatial_dims[i] = i; + padding[i] = {dims.spatial_dims[i].pad_before, + dims.spatial_dims[i].pad_after}; + lhs_dilation[i] = dims.spatial_dims[i].stride; + rhs_dilation[i] = attrs.dilations[dim]; + } + xla::PrecisionConfig precision_config = GetPrecisionConfig(); + + if (feature_group_count != 1 && !attrs.depthwise) { + filter = TransposeFilterForGroupConvolutionBackpropInput( + filter, filter_shape, feature_group_count, attrs.num_spatial_dims); + } + // Mirror the filter in the spatial dimensions. + filter = xla::Rev(filter, kernel_spatial_dims); + if (padding_type != xla::PaddingType::PADDING_INVALID) { + TF_RET_CHECK(input_sizes != nullptr); + return xla::DynamicConvInputGrad( + *input_sizes, out_backprop, filter, /*window_strides=*/ones, padding, + lhs_dilation, rhs_dilation, dnums, + /*feature_group_count=*/ + feature_group_count, + /*batch_group_count=*/1, &precision_config, padding_type); + } + // activation gradients + // = gradients (with padding and dilation) mirrored_weights + return xla::ConvGeneralDilated(out_backprop, filter, /*window_strides=*/ones, + padding, lhs_dilation, rhs_dilation, dnums, + /*feature_group_count=*/ + feature_group_count, + /*batch_group_count=*/1, &precision_config); +} + +absl::StatusOr MakeXlaBackpropFilterConvOp( + absl::string_view type_string, xla::XlaOp activations, + const xla::Shape& filter_shape, xla::XlaOp gradients, + const ConvOpAttrs& attrs) { + TF_RETURN_IF_ERROR(CheckConvAttrs(attrs)); + + auto* builder = activations.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape activations_shape, + builder->GetShape(activations)); + TF_ASSIGN_OR_RETURN(xla::Shape out_backprop_shape, + builder->GetShape(gradients)); + xla::XlaOp filter_backprop; + + xla::Shape input_shape = activations_shape; + xla::Shape output_shape = out_backprop_shape; + + TensorShape input_tensor_shape, filter_tensor_shape, output_tensor_shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(filter_shape, &filter_tensor_shape)); + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(input_shape, &input_tensor_shape)); + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(output_shape, &output_tensor_shape)); + + const xla::Shape grouped_filter_shape = + attrs.depthwise ? GroupedFilterShapeForDepthwiseConvolution(filter_shape) + : filter_shape; + // Reuse dimension computation logic from conv_grad_shape_utils.cc. + ConvBackpropDimensions dims; + // The filter gradients are computed by a convolution of the input + // activations and the output gradients, with some appropriate padding. + // See the comment at the top of conv_grad_shape_utils.h for details. + xla::ConvolutionDimensionNumbers dnums; + + TF_RETURN_IF_ERROR(ConvBackpropComputeDimensionsV2XlaShapes( + type_string, attrs.num_spatial_dims, activations_shape, + grouped_filter_shape, out_backprop_shape, attrs.dilations, attrs.strides, + attrs.padding, attrs.data_format, &dims, attrs.explicit_paddings)); + + // Obtain some useful dimensions: + // The last two dimensions of the filter are the input and output shapes. + int num_dims = attrs.num_spatial_dims + 2; + int n_dim = GetTensorBatchDimIndex(num_dims, attrs.data_format); + int c_dim = GetTensorFeatureDimIndex(num_dims, attrs.data_format); + int64_t in_depth = input_shape.dimensions(c_dim), + filter_in_depth = filter_shape.dimensions(attrs.num_spatial_dims), + batch_group_count = + attrs.depthwise ? filter_in_depth : in_depth / filter_in_depth; + + std::vector> padding(attrs.num_spatial_dims); + std::vector rhs_dilation(attrs.num_spatial_dims); + std::vector window_strides(attrs.num_spatial_dims); + std::vector ones(attrs.num_spatial_dims, 1); + + // Swap n_dim and c_dim in the activations. + dnums.set_input_batch_dimension(c_dim); + dnums.set_input_feature_dimension(n_dim); + + // The gradients become the RHS of the convolution. + // The gradients have shape [batch, out_rows, out_cols, ..., out_depth] + // where the batch becomes the input feature for the convolution. + dnums.set_kernel_input_feature_dimension(n_dim); + dnums.set_kernel_output_feature_dimension(c_dim); + + dnums.set_output_batch_dimension(attrs.num_spatial_dims); + dnums.set_output_feature_dimension(attrs.num_spatial_dims + 1); + + // Tensorflow filter shape is [ H, W, ..., inC, outC ]. + for (int i = 0; i < attrs.num_spatial_dims; ++i) { + dnums.add_output_spatial_dimensions(i); + } + xla::PaddingType padding_type = xla::PaddingType::PADDING_INVALID; + for (int64_t i = 0; i < attrs.num_spatial_dims; ++i) { + int64_t dim = GetTensorSpatialDimIndex(num_dims, attrs.data_format, i); + if (activations_shape.is_dynamic_dimension(dim)) { + TF_RET_CHECK(attrs.padding == VALID || attrs.padding == SAME) + << "Dynamic convolution only supports valid and same padding"; + if (attrs.padding == VALID) { + padding_type = xla::PaddingType::PADDING_VALID; + } + if (attrs.padding == SAME) { + padding_type = xla::PaddingType::PADDING_SAME; + } + } + dnums.add_input_spatial_dimensions(dim); + dnums.add_kernel_spatial_dimensions(dim); + rhs_dilation[i] = dims.spatial_dims[i].stride; + window_strides[i] = attrs.dilations[dim]; + + // We will also need to pad the input with zeros such that after the + // convolution, we get the right size for the filter. + // The padded_in_rows should be such that when we convolve this with the + // expanded_out_rows as a filter, we should get filter_rows back. + + const int64_t padded_in_size = + dims.spatial_dims[i].expanded_output_size + + (dims.spatial_dims[i].filter_size - 1) * attrs.dilations[dim]; + + // However it can be smaller than input_rows: in this + // case it means some of the inputs are not used. + // + // An example is to have input_cols = 3, filter_cols = 2 and stride = 2: + // + // INPUT = [ A B C ] + // + // FILTER = [ x y ] + // + // and the output will only have one column: a = A * x + B * y + // + // and input "C" is not used at all. + // + // We apply negative padding in this case. + const int64_t pad_total = padded_in_size - dims.spatial_dims[i].input_size; + + // + For the EXPLICIT padding, we pad the top/left side with the explicit + // padding and pad the bottom/right side with the remaining space. + // + For the VALID padding, we don't pad anything on the top/left side + // and pad the bottom/right side with the remaining space. + // + For the SAME padding, we pad top/left side the same as bottom/right + // side. + // + // In addition, if the padded input size is smaller than the input size, + // we need to ignore some training elements of the input. We do this by + // applying negative padding on the right/bottom. + const int64_t pad_before = + attrs.padding == Padding::EXPLICIT ? attrs.explicit_paddings[2 * dim] + : attrs.padding == Padding::SAME ? std::max(pad_total / 2, 0) + : 0; + padding[i] = {pad_before, pad_total - pad_before}; + } + xla::PrecisionConfig precision_config = GetPrecisionConfig(); + + // Besides padding the input, we will also expand output_rows to + // expanded_out_rows = (output_rows - 1) * stride + 1 + // with zeros in between: + // + // a . . . b . . . c . . . d . . . e + // + // This is done by specifying the window dilation factors in the + // convolution HLO below. + if (padding_type != xla::PaddingType::PADDING_INVALID) { + filter_backprop = xla::DynamicConvKernelGrad( + activations, gradients, window_strides, padding, /*lhs_dilation=*/ones, + rhs_dilation, dnums, + /*feature_group_count=*/1, + /*batch_group_count=*/batch_group_count, &precision_config, + padding_type); + } else { + filter_backprop = xla::ConvGeneralDilated( + activations, gradients, window_strides, padding, /*lhs_dilation=*/ones, + rhs_dilation, dnums, + /*feature_group_count=*/1, + /*batch_group_count=*/batch_group_count, &precision_config); + } + + if (attrs.depthwise) { + filter_backprop = xla::Reshape(filter_backprop, filter_shape.dimensions()); + } + + return filter_backprop; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..d58c909dc703af3a8add4cdc47e2aef7ae759d8a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h @@ -0,0 +1,95 @@ +/* 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_TF2XLA_KERNELS_CONV_OP_HELPERS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_CONV_OP_HELPERS_H_ + +#include +#include + +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/statusor.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +// This header exposes utilities for translating TensorFlow convolution ops into +// XLA ops. +// +// conv_ops.cc contains lowerings for many of these TF convolution ops (e.g. +// Conv2D, Conv3DBackpropFilterV2), but you might want to use the utilities in +// this header to implement a new and exciting convolution op, for example a +// fused TensorFlow op that contains a convolution and other things. + +namespace tensorflow { + +// We don't support integers for convolutions for GPU, so we list the supported +// types for non-gpu and gpu here. +std::vector GetXlaConvTypesForNonGpu(); +std::vector GetXlaConvTypesForGpu(); + +// ConvOpAttrs contains all of the metadata necessary to specify a TF or XLA +// convolution. +struct ConvOpAttrs { + // Constructs a ConvOpAttrs, reading most of the attributes from `ctx`. + static absl::StatusOr Create(int num_spatial_dims, + bool depthwise, + OpKernelConstruction* ctx); + + bool depthwise; + int num_spatial_dims; + std::vector dilations; + std::vector strides; + Padding padding; + std::vector explicit_paddings; + TensorFormat data_format; +}; + +// Helper for the general Conv Op. +struct ConvNDOpAttrs { + // Constructs a ConvOpAttrs, reading most of the attributes from `ctx`. + static absl::StatusOr Create(OpKernelConstruction* ctx); + + int groups; + int batch_dims; + std::vector dilations; + std::vector strides; + Padding padding; + std::vector explicit_paddings; + TensorFormat data_format; +}; + +// Creates a new XLA forward or backward convolution with the given inputs and +// attributes. +absl::StatusOr MakeXlaForwardConvOp(absl::string_view type_string, + xla::XlaOp conv_input, + xla::XlaOp filter, + const ConvOpAttrs& attrs); +absl::StatusOr MakeXlaBackpropInputConvOp( + absl::string_view type_string, const xla::Shape& input_shape, + xla::XlaOp filter, xla::XlaOp out_backprop, const ConvOpAttrs& attrs, + xla::XlaOp* input_sizes = nullptr); +absl::StatusOr MakeXlaBackpropFilterConvOp( + absl::string_view type_string, xla::XlaOp activations, + const xla::Shape& filter_shape, xla::XlaOp gradients, + const ConvOpAttrs& attrs); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_CONV_OP_HELPERS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..d5ae04ee330c8ee4c06febff2982fecc5571224d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/conv_ops.cc @@ -0,0 +1,308 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Ops for 2D convolution. + +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/numeric_op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/ops_util.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +class ConvOp : public XlaOpKernel { + public: + explicit ConvOp(OpKernelConstruction* ctx, int num_spatial_dims, + bool depthwise) + : XlaOpKernel(ctx) { + absl::StatusOr attrs = + ConvOpAttrs::Create(num_spatial_dims, depthwise, ctx); + OP_REQUIRES_OK(ctx, attrs.status()); + attrs_ = attrs.value(); + } + + void Compile(XlaOpKernelContext* ctx) override { + absl::StatusOr conv = MakeXlaForwardConvOp( + ctx->op_kernel().type_string(), ctx->Input(0), ctx->Input(1), attrs_); + OP_REQUIRES_OK(ctx, conv.status()); + ctx->SetOutput(0, conv.value()); + } + + protected: + ConvOpAttrs attrs_; + + private: + ConvOp(const ConvOp&) = delete; + void operator=(const ConvOp&) = delete; +}; + +class ConvNDOp : public XlaOpKernel { + public: + explicit ConvNDOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + absl::StatusOr attrs = ConvNDOpAttrs::Create(ctx); + OP_REQUIRES_OK(ctx, attrs.status()); + attrs_ = attrs.value(); + } + + void Compile(XlaOpKernelContext* ctx) override { + // Need to know input rank ahead of time to determine type of convolution. + OP_REQUIRES_VALUE(xla::Shape input_shape, ctx, ctx->InputXlaShape(0)); + int num_spatial_dims = + input_shape.dimensions().size() - 1 - attrs_.batch_dims; + OP_REQUIRES_OK(ctx, + CheckValidPadding(attrs_.padding, attrs_.explicit_paddings, + /*num_dims=*/num_spatial_dims + 2, + attrs_.data_format)); + + ConvOpAttrs forward_attrs; + forward_attrs.depthwise = false; + forward_attrs.num_spatial_dims = num_spatial_dims; + forward_attrs.dilations = + attrs_.dilations.empty() ? std::vector(num_spatial_dims + 2, 1) + : attrs_.dilations; + forward_attrs.strides = attrs_.strides; + forward_attrs.padding = attrs_.padding; + forward_attrs.explicit_paddings = attrs_.explicit_paddings; + forward_attrs.data_format = attrs_.data_format; + + xla::XlaOp input = ctx->Input(0); + xla::XlaOp filter = ctx->Input(1); + + if (attrs_.batch_dims == 0) { + // Expand dummy batch dimension. + xla::Shape expanded_input_shape(input_shape); + for (int i = 0; i < expanded_input_shape.dimensions().size() - 1; ++i) { + expanded_input_shape.set_dimensions(i + 1, input_shape.dimensions(i)); + } + expanded_input_shape.set_dimensions(0, 1); + input = xla::Reshape(input, expanded_input_shape.dimensions()); + } else if (attrs_.batch_dims > 1) { + // Flatten batch_dims. + std::vector to_collapse(attrs_.batch_dims); + for (int i = 0; i < attrs_.batch_dims; ++i) { + to_collapse[i] = i; + } + input = xla::Collapse(input, to_collapse); + } + + absl::StatusOr forward = MakeXlaForwardConvOp( + ctx->op_kernel().type_string(), input, filter, forward_attrs); + OP_REQUIRES_OK(ctx, forward.status()); + + xla::XlaOp out = forward.value(); + auto* builder = out.builder(); + OP_REQUIRES_VALUE(xla::Shape out_shape, ctx, builder->GetShape(out)); + // Reshape output. + if (attrs_.batch_dims == 0) { + xla::Shape no_batch_shape(out_shape); + no_batch_shape.DeleteDimension(0); + out = xla::Reshape(out, no_batch_shape.dimensions()); + } else if (attrs_.batch_dims > 1) { + xla::Shape expanded_out_shape(input_shape); + for (int i = attrs_.batch_dims; i < input_shape.dimensions().size(); + ++i) { + expanded_out_shape.set_dimensions( + i, out_shape.dimensions(i - (attrs_.batch_dims - 1))); + } + out = xla::Reshape(out, expanded_out_shape.dimensions()); + } + ctx->SetOutput(0, out); + } + + protected: + ConvNDOpAttrs attrs_; +}; +REGISTER_XLA_CONV_OP(Name("Conv"), ConvNDOp); + +class Conv2DOp : public ConvOp { + public: + explicit Conv2DOp(OpKernelConstruction* ctx) + : ConvOp(ctx, /*num_spatial_dims=*/2, /*depthwise=*/false) {} +}; +REGISTER_XLA_CONV_OP(Name("Conv2D"), Conv2DOp); + +class Conv3DOp : public ConvOp { + public: + explicit Conv3DOp(OpKernelConstruction* ctx) + : ConvOp(ctx, /*num_spatial_dims=*/3, /*depthwise=*/false) {} +}; +REGISTER_XLA_CONV_OP(Name("Conv3D"), Conv3DOp); + +class DepthwiseConv2DOp : public ConvOp { + public: + explicit DepthwiseConv2DOp(OpKernelConstruction* ctx) + : ConvOp(ctx, /*num_spatial_dims=*/2, /*depthwise=*/true) {} +}; +REGISTER_XLA_CONV_OP(Name("DepthwiseConv2dNative"), DepthwiseConv2DOp); + +// Backprop for input. +class ConvBackpropInputOp : public XlaOpKernel { + public: + explicit ConvBackpropInputOp(OpKernelConstruction* ctx, int num_spatial_dims, + bool depthwise) + : XlaOpKernel(ctx) { + absl::StatusOr attrs = + ConvOpAttrs::Create(num_spatial_dims, depthwise, ctx); + OP_REQUIRES_OK(ctx, attrs.status()); + attrs_ = attrs.value(); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape input_tensor_shape; + OP_REQUIRES_OK( + ctx, ctx->ConstantInputAsShape(0, &input_tensor_shape, + xla::ValueInferenceMode::kUpperBound)); + xla::Shape input_shape = + TensorShapeToXLAShape(ctx->input_xla_type(1), input_tensor_shape); + OP_REQUIRES(ctx, + input_shape.dimensions().size() == attrs_.num_spatial_dims + 2, + absl::InvalidArgumentError(absl::StrCat( + "The rank of the specified input shape must be " + "num_spatial_dims + 2. Expected ", + attrs_.num_spatial_dims + 2, " got ", + input_shape.dimensions().size()))); + xla::XlaOp input_sizes = ctx->Input(0); + absl::StatusOr in_backprop = MakeXlaBackpropInputConvOp( + ctx->op_kernel().type_string(), input_shape, ctx->Input(1), + ctx->Input(2), attrs_, &input_sizes); + OP_REQUIRES_OK(ctx, in_backprop.status()); + ctx->SetOutput(0, in_backprop.value()); + } + + protected: + ConvOpAttrs attrs_; + + private: + ConvBackpropInputOp(const ConvBackpropInputOp&) = delete; + void operator=(const ConvBackpropInputOp&) = delete; +}; + +class Conv2DBackpropInputOp : public ConvBackpropInputOp { + public: + explicit Conv2DBackpropInputOp(OpKernelConstruction* ctx) + : ConvBackpropInputOp(ctx, /*num_spatial_dims=*/2, /*depthwise=*/false) {} +}; +REGISTER_XLA_CONV_OP( + Name("Conv2DBackpropInput").CompileTimeConstantInput("input_sizes"), + Conv2DBackpropInputOp); + +class Conv3DBackpropInputOp : public ConvBackpropInputOp { + public: + explicit Conv3DBackpropInputOp(OpKernelConstruction* ctx) + : ConvBackpropInputOp(ctx, /*num_spatial_dims=*/3, /*depthwise=*/false) {} +}; +REGISTER_XLA_CONV_OP( + Name("Conv3DBackpropInputV2").CompileTimeConstantInput("input_sizes"), + Conv3DBackpropInputOp); + +class DepthwiseConv2DBackpropInputOp : public ConvBackpropInputOp { + public: + explicit DepthwiseConv2DBackpropInputOp(OpKernelConstruction* ctx) + : ConvBackpropInputOp(ctx, /*num_spatial_dims=*/2, /*depthwise=*/true) {} +}; +REGISTER_XLA_CONV_OP(Name("DepthwiseConv2dNativeBackpropInput") + .CompileTimeConstantInput("input_sizes"), + DepthwiseConv2DBackpropInputOp); + +class ConvBackpropFilterOp : public XlaOpKernel { + public: + explicit ConvBackpropFilterOp(OpKernelConstruction* ctx, int num_spatial_dims, + bool depthwise) + : XlaOpKernel(ctx) { + absl::StatusOr attrs = + ConvOpAttrs::Create(num_spatial_dims, depthwise, ctx); + OP_REQUIRES_OK(ctx, attrs.status()); + attrs_ = attrs.value(); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape filter_tensor_shape; + OP_REQUIRES_OK( + ctx, ctx->ConstantInputAsShape(1, &filter_tensor_shape, + xla::ValueInferenceMode::kUpperBound)); + xla::Shape filter_shape = + TensorShapeToXLAShape(ctx->input_xla_type(0), filter_tensor_shape); + + absl::StatusOr filter_backprop = MakeXlaBackpropFilterConvOp( + ctx->op_kernel().type_string(), ctx->Input(0), filter_shape, + ctx->Input(2), attrs_); + OP_REQUIRES_OK(ctx, filter_backprop.status()); + ctx->SetOutput(0, filter_backprop.value()); + } + + protected: + ConvOpAttrs attrs_; + + private: + ConvBackpropFilterOp(const ConvBackpropFilterOp&) = delete; + void operator=(const ConvBackpropFilterOp&) = delete; +}; + +class Conv2DBackpropFilterOp : public ConvBackpropFilterOp { + public: + explicit Conv2DBackpropFilterOp(OpKernelConstruction* ctx) + : ConvBackpropFilterOp(ctx, /*num_spatial_dims=*/2, /*depthwise=*/false) { + } +}; +REGISTER_XLA_CONV_OP( + Name("Conv2DBackpropFilter").CompileTimeConstantInput("filter_sizes"), + Conv2DBackpropFilterOp); + +class Conv3DBackpropFilterOp : public ConvBackpropFilterOp { + public: + explicit Conv3DBackpropFilterOp(OpKernelConstruction* ctx) + : ConvBackpropFilterOp(ctx, /*num_spatial_dims=*/3, /*depthwise=*/false) { + } +}; +REGISTER_XLA_CONV_OP( + Name("Conv3DBackpropFilterV2").CompileTimeConstantInput("filter_sizes"), + Conv3DBackpropFilterOp); + +class DepthwiseConv2DBackpropFilterOp : public ConvBackpropFilterOp { + public: + explicit DepthwiseConv2DBackpropFilterOp(OpKernelConstruction* ctx) + : ConvBackpropFilterOp(ctx, /*num_spatial_dims=*/2, /*depthwise=*/true) {} +}; +REGISTER_XLA_CONV_OP(Name("DepthwiseConv2dNativeBackpropFilter") + .CompileTimeConstantInput("filter_sizes"), + DepthwiseConv2DBackpropFilterOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cross_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cross_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..980ebfa15ac3737da8fffa7ee2d16ee1594ce339 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cross_op.cc @@ -0,0 +1,97 @@ +/* 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 +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" + +namespace tensorflow { +namespace { + +class CrossOp : public XlaOpKernel { + public: + explicit CrossOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape in0_shape = ctx->InputShape(0); + TensorShape in1_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, in0_shape == in1_shape, + absl::InvalidArgumentError(absl::StrCat( + "Both inputs must be of same shape: ", in0_shape.DebugString(), + " vs. ", in1_shape.DebugString()))); + OP_REQUIRES(ctx, in0_shape.dims() >= 1, + absl::InvalidArgumentError(absl::StrCat( + "Input must be at least 1D", in0_shape.DebugString()))); + + auto inner_dim = in0_shape.dim_size(in0_shape.dims() - 1); + OP_REQUIRES(ctx, inner_dim == 3, + absl::FailedPreconditionError( + "Cross-products are only defined for 3-element vectors.")); + + // in0 is a [...,X,Y,Z,3] + // in1 is the same shape as in0 + // So slice 0 is: in0[...,:,:,:,0:1] + // So slice 1 is: in0[...,:,:,:,1:2] + // So slice 2 is: in0[...,:,:,:,2:3] + + std::vector starts(in0_shape.dims(), 0); + std::vector limits; + const auto& dim_sizes = in0_shape.dim_sizes(); + limits.reserve(dim_sizes.size()); + for (auto dim_size : in0_shape.dim_sizes()) { + limits.push_back(dim_size); + } + std::vector strides(in0_shape.dims(), 1); + + xla::XlaBuilder* b = ctx->builder(); + auto in0 = ctx->Input(0); + auto in1 = ctx->Input(1); + starts.back() = 0; + limits.back() = 1; + auto u1 = xla::Slice(in0, starts, limits, strides); + auto v1 = xla::Slice(in1, starts, limits, strides); + starts.back() = 1; + limits.back() = 2; + auto u2 = xla::Slice(in0, starts, limits, strides); + auto v2 = xla::Slice(in1, starts, limits, strides); + starts.back() = 2; + limits.back() = 3; + auto u3 = xla::Slice(in0, starts, limits, strides); + auto v3 = xla::Slice(in1, starts, limits, strides); + + auto s1 = xla::Sub(xla::Mul(u2, v3), xla::Mul(u3, v2)); + auto s2 = xla::Sub(xla::Mul(u3, v1), xla::Mul(u1, v3)); + auto s3 = xla::Sub(xla::Mul(u1, v2), xla::Mul(u2, v1)); + auto output = xla::ConcatInDim(b, {s1, s2, s3}, in0_shape.dims() - 1); + + ctx->SetOutput(0, output); + } + + private: + CrossOp(const CrossOp&) = delete; + void operator=(const CrossOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Cross"), CrossOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cwise_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cwise_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..6d51e260bd48e7479070f46ffdd195956b5f4996 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cwise_ops.cc @@ -0,0 +1,213 @@ +/* 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. +==============================================================================*/ + +// XLA-specific base classes for Unary and Binary Ops. + +#include "tensorflow/compiler/tf2xla/kernels/cwise_ops.h" + +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/util/bcast.h" + +namespace tensorflow { + +void XlaBinaryOp::Compile(XlaOpKernelContext* ctx) { + TensorShape lhs_shape = ctx->InputShape(0); + TensorShape rhs_shape = ctx->InputShape(1); + xla::Shape lhs_xla_shape = ctx->InputXlaShape(0).value(); + xla::Shape rhs_xla_shape = ctx->InputXlaShape(1).value(); + // Fetch the expressions containing the input tensors. + auto lhs_handle = ctx->Input(0); + auto rhs_handle = ctx->Input(1); + if (lhs_shape.dims() == rhs_shape.dims()) { + auto reconcile_tensor_mismatched_dims = [ctx]( + xla::XlaOp lhs, xla::XlaOp rhs, + const xla::Shape& lhs_xla_shape, + const xla::Shape& rhs_xla_shape, + TensorShape* lhs_tensor_shape) { + // Find out mismatched dimensions that are non-broadcastable. + // Reconcile the + // difference by slicing the bigger dimension. + for (int64_t i = 0; i < lhs_xla_shape.dimensions().size(); ++i) { + if (lhs_xla_shape.is_dynamic_dimension(i)) { + if (!rhs_xla_shape.is_dynamic_dimension(i) && + lhs_xla_shape.dimensions(i) > rhs_xla_shape.dimensions(i) && + rhs_xla_shape.dimensions(i) != 1) { + // e.g., : + // lhs = [..., <=N, ...] + // rhs = [..., 2 , ...] + // Slice N into 2. + // Size 1 dim doesn't need slice as the other side is + // broadcastable. + auto size = xla::GetDimensionSize(lhs, i); + lhs = xla::SliceInDim(lhs, 0, rhs_xla_shape.dimensions(i), 1, + /*dimno=*/i); + lhs_tensor_shape->set_dim(i, rhs_xla_shape.dimensions(i)); + // Propagate dynamic dimension. + lhs = xla::SetDimensionSize(lhs, size, i); + } + if (rhs_xla_shape.is_dynamic_dimension(i) && + lhs_xla_shape.dimensions(i) < rhs_xla_shape.dimensions(i) && + rhs_xla_shape.dimensions(i) != 1 && + lhs_xla_shape.dimensions(i) != 1) { + // e.g., : + // lhs = [..., <=M, ...] + // rhs = [..., <=N , ...] + // where M < N + // + // In this case we pad M into N to make the bounds the same. + // Note that we can't slice N into M because M could be a + // dynamic size 1 dim that's meant to be broadcasted to N. + auto size = xla::GetDimensionSize(lhs, i); + int64_t diff = + rhs_xla_shape.dimensions(i) - lhs_xla_shape.dimensions(i); + lhs = xla::PadInDim( + lhs, xla::Zero(ctx->builder(), lhs_xla_shape.element_type()), i, + 0, diff); + lhs_tensor_shape->set_dim(i, rhs_xla_shape.dimensions(i)); + // Propagate dynamic dimension. + lhs = xla::SetDimensionSize(lhs, size, i); + } + if (lhs_xla_shape.dimensions(i) == 1 && + rhs_xla_shape.dimensions(i) != 1) { + // lhs = [..., <=1, ...] + // rhs = [..., N, ...] or [..., <=N, ...] + // where N != 1. + // + // In this case we will need to broadcast this dimension to N. + // If the dynamic size is 0, the result size is zero. + // If the dynamic size is 1, the result size is N. + // + // However, XLA only does degenerate broadcasts for non-dynamic + // dimensions of size 1. + + // Get the original size. + auto size = xla::GetDimensionSize(lhs, i); + + // Remove the dynamic dimension. + lhs = xla::RemoveDynamicDimension(lhs, i); + + // Broadcast the dimension to N. + std::vector dimensions(lhs_xla_shape.dimensions().begin(), + lhs_xla_shape.dimensions().end()); + dimensions[i] = rhs_xla_shape.dimensions(i); + std::vector broadcast_dimensions( + lhs_xla_shape.dimensions().size()); + absl::c_iota(broadcast_dimensions, 0); + lhs = xla::BroadcastInDim(lhs, dimensions, broadcast_dimensions); + + xla::XlaOp rhs_size; + if (rhs_xla_shape.is_dynamic_dimension(i)) { + rhs_size = xla::GetDimensionSize(rhs, i); + } else { + rhs_size = xla::ConstantR0(lhs.builder(), + rhs_xla_shape.dimensions(i)); + } + + // The original size is 0 or 1, so we can multiply it by the RHS + // size to get the size of the resulting broadcast. + size = xla::Mul(size, rhs_size); + + // Set the resulting dimension size. + lhs = xla::SetDimensionSize(lhs, size, i); + + lhs_tensor_shape->set_dim(i, rhs_xla_shape.dimensions(i)); + } + } + } + return lhs; + }; + lhs_handle = reconcile_tensor_mismatched_dims( + lhs_handle, rhs_handle, lhs_xla_shape, rhs_xla_shape, &lhs_shape); + rhs_handle = reconcile_tensor_mismatched_dims( + rhs_handle, lhs_handle, rhs_xla_shape, lhs_xla_shape, &rhs_shape); + } + // By TensorFlow conventions the inputs may not have the same + // shapes, in which case they will be automatically broadcast if + // possible before mapping. Use the standard TensorFlow helper to + // compute valid broadcast shapes, but rely below on XLA to + // automatically perform the broadcast assuming its valid shapes are + // a superset of TensorFlow's valid shapes. + BCast bcast(BCast::FromShape(lhs_shape), BCast::FromShape(rhs_shape), + /*fewer_dims_optimization=*/false); + if (!bcast.IsValid()) { + ctx->SetStatus(absl::InvalidArgumentError( + absl::StrCat("Incompatible shapes: ", lhs_shape.DebugString(), " vs. ", + rhs_shape.DebugString()))); + return; + } + + // If the ranks of the inputs don't match, TensorFlow automatically + // reshapes the smaller by padding with dimensions of size 1 as a + // prefix. In other words to pad a 5-vector to a 3-dimensional + // tensor it is reshaped to have shape [1,1,5]. XLA's automatic + // broadcast code is able to broadcast from lower to higher rank, + // but doesn't assume you want to pad as a prefix of the dimensions, + // and instead needs to be told which dimensions of the higher rank + // tensor to match to the lower rank tensor. In this example it + // would be dimensions [2]. If we were matching a matrix against a + // 4-D tensor the dimensions to match would be [2,3], + // etc. extend_dimension encodes the general case. + std::vector extend_dimension; + int max_rank = std::max(lhs_shape.dims(), rhs_shape.dims()); + int min_rank = std::min(lhs_shape.dims(), rhs_shape.dims()); + if (min_rank != max_rank) { + for (int i = 0; i < min_rank; ++i) { + // Match the lower rank tensor along the larger-numbered + // dimensions of the higher rank tensor. + extend_dimension.push_back(max_rank - min_rank + i); + } + } + + // Call virtual method to emit the computation. + xla::XlaOp output = + Computation(ctx, lhs_handle, lhs_shape.dim_sizes(), rhs_handle, + rhs_shape.dim_sizes(), bcast, extend_dimension); + + // The TensorFlow helper computed the post-broadcast shape in + // output_shape: we rely on subclassed Computations to implement the + // same broadcast semantics. + ctx->SetOutput(0, output); +} + +/* static */ std::pair XlaBinaryOp::Broadcast( + xla::XlaOp lhs, xla::XlaOp rhs, const BCast& broadcast_helper) { + auto lhs_output = BroadcastTo(lhs, broadcast_helper.output_shape()); + if (!lhs_output.ok()) { + xla::XlaOp error = lhs.builder()->ReportError(lhs_output.status()); + return {error, error}; + } + auto rhs_output = BroadcastTo(rhs, broadcast_helper.output_shape()); + if (!rhs_output.ok()) { + xla::XlaOp error = rhs.builder()->ReportError(rhs_output.status()); + return {error, error}; + } + return {lhs_output.value(), rhs_output.value()}; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cwise_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cwise_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..cdf17644eab0751b3232564f8e1d31f2dd56a245 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/cwise_ops.h @@ -0,0 +1,83 @@ +/* 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. +==============================================================================*/ + +// XLA-specific base classes for Unary and Binary Ops. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_KERNELS_CWISE_OPS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_CWISE_OPS_H_ + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/client/client_library.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/util/bcast.h" + +namespace tensorflow { + +// Coefficient-wise binary operations. Each binary Op expects two +// inputs that can be broadcast to the same shape. The base class +// contains pure virtual methods to override: description is a textual +// description of the operation; and Computation adds the +// implementation of the operation to a xla::XlaBuilder. For most +// arithmetic Ops XLA handles the broadcasting automatically given the input +// tensors. +class XlaBinaryOp : public XlaOpKernel { + public: + explicit XlaBinaryOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + const DataType lhs = BaseType(input_type(0)); + const DataType rhs = BaseType(input_type(1)); + OP_REQUIRES( + ctx, lhs == rhs, + absl::InvalidArgumentError("Input types of binary op must match")); + } + ~XlaBinaryOp() override = default; + + // Implement the (tensor,tensor)->tensor lambda that should be + // applied to the inputs. The desired computation should be added to + // 'tc->builder()' and '(lhs,rhs)' are the function's inputs and + // (lhs_shape,rhs_shape) are their respective + // shapes. 'broadcast_helper' contains metadata about the shapes of + // the inputs and the dimensions that need to be broadcast, which + // may be useful for Ops that can't use standard XLA automatic + // broadcasting. 'extend_dimension' is non-empty if lhs and rhs have + // different ranks, and indicates which dimensions of the + // higher-rank input should be matched when broadcasting the + // lower-rank input. See comment below and the documentation on broadcasting + // in the XLA documentation. + virtual xla::XlaOp Computation( + XlaOpKernelContext* ctx, const xla::XlaOp& lhs, + const absl::Span& lhs_shape, const xla::XlaOp& rhs, + const absl::Span& rhs_shape, const BCast& broadcast_helper, + const std::vector& extend_dimensions) = 0; + + void Compile(XlaOpKernelContext* ctx) override; + + // Helper function that performs the broadcasting described by + // 'broadcast_helper', yielding arguments 'lhs' and 'rhs' that have the same + // shape. + static std::pair Broadcast( + xla::XlaOp lhs, xla::XlaOp rhs, const BCast& broadcast_helper); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_CWISE_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/data_format_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/data_format_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..ae4fc6fea1c8c52c89f35370594467e89a4b25f8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/data_format_ops.cc @@ -0,0 +1,201 @@ +/* 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 +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/slicing.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +class DataFormatDimMapOp : public XlaOpKernel { + public: + explicit DataFormatDimMapOp(OpKernelConstruction* context) + : XlaOpKernel(context) { + std::string src_format; + OP_REQUIRES_OK(context, context->GetAttr("src_format", &src_format)); + std::string dst_format; + OP_REQUIRES_OK(context, context->GetAttr("dst_format", &dst_format)); + OP_REQUIRES(context, src_format.size() == 4 || src_format.size() == 5, + absl::InvalidArgumentError( + absl::StrCat("Source format must of length 4 or 5, " + "received src_format = ", + src_format))); + OP_REQUIRES( + context, dst_format.size() == 4 || dst_format.size() == 5, + absl::InvalidArgumentError(absl::StrCat( + "Destination format must of length 4 or 5, received dst_format = ", + dst_format))); + for (int i = 0; i < src_format.size(); ++i) { + dst_idx_.push_back(-1); + } + for (int i = 0; i < src_format.size(); ++i) { + for (int j = 0; j < dst_format.size(); ++j) { + if (dst_format[j] == src_format[i]) { + dst_idx_[i] = j; + break; + } + } + OP_REQUIRES(context, dst_idx_[i] != -1, + absl::InvalidArgumentError(absl::StrCat( + src_format, " is not a permutation of ", dst_format))); + } + } + + void Compile(XlaOpKernelContext* context) override { + auto builder = context->builder(); + xla::XlaOp dst_indices = + xla::ConstantR1(builder, absl::Span(dst_idx_)); + const int dims = dst_idx_.size(); + xla::XlaOp rank = xla::ConstantR0(builder, dims); + xla::XlaOp src_indices = + (xla::ConvertElementType(context->Input(0), xla::S32) + rank) % rank; + xla::XlaOp output = + xla::TorchIndexSelect(dst_indices, src_indices, /*dim=*/0); + context->SetOutput( + 0, xla::ConvertElementType(output, context->input_xla_type(0))); + } + + private: + std::vector dst_idx_; + + DataFormatDimMapOp(const DataFormatDimMapOp&) = delete; + void operator=(const DataFormatDimMapOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("DataFormatDimMap").TypeConstraint("T", {DT_INT32, DT_INT64}), + DataFormatDimMapOp); + +class DataFormatVecPermuteOp : public XlaOpKernel { + public: + explicit DataFormatVecPermuteOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("src_format", &src_format_)); + OP_REQUIRES(ctx, src_format_.size() == 4 || src_format_.size() == 5, + absl::InvalidArgumentError( + "Data format should have 4 or 5 characters")); + TensorFormat data_format; + OP_REQUIRES(ctx, FormatFromString(src_format_, &data_format), + absl::InvalidArgumentError("Invalid data format")); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dst_format", &dst_format_)); + OP_REQUIRES(ctx, dst_format_.size() == 4 || dst_format_.size() == 5, + absl::InvalidArgumentError( + "Data format should have 4 or 5 characters")); + OP_REQUIRES(ctx, FormatFromString(dst_format_, &data_format), + absl::InvalidArgumentError("Invalid data format")); + } + void Compile(XlaOpKernelContext* ctx) override { + auto builder = ctx->builder(); + const TensorShape input_tensor_shape = ctx->InputShape(0); + int input_rank = input_tensor_shape.dims(); + OP_REQUIRES(ctx, input_rank == 1 || input_rank == 2, + absl::InvalidArgumentError(absl::StrCat( + "Input must be a vector or matrix, but got shape ", + input_tensor_shape.DebugString()))); + const int dim0 = input_tensor_shape.dim_size(0); + + const int full_dim_count = src_format_.size(); + const int spatial_dim_count = full_dim_count - 2; + + if (input_rank == 1) { + OP_REQUIRES(ctx, + input_tensor_shape.num_elements() == spatial_dim_count || + input_tensor_shape.num_elements() == full_dim_count, + absl::InvalidArgumentError(absl::StrCat( + "1D input must be of size ", spatial_dim_count, " or ", + full_dim_count, ", but got shape ", + input_tensor_shape.DebugString()))); + } else if (input_rank == 2) { + OP_REQUIRES(ctx, + input_tensor_shape.dim_size(0) == spatial_dim_count || + input_tensor_shape.dim_size(0) == full_dim_count, + absl::InvalidArgumentError(absl::StrCat( + "First dimension of 2D input must be " + "of size ", + spatial_dim_count, " or ", full_dim_count, + ", but got shape ", input_tensor_shape.DebugString()))); + OP_REQUIRES( + ctx, input_tensor_shape.dim_size(1) == 2, + absl::InvalidArgumentError(absl::StrCat( + "Second dimension of 2D input must be of size 2, but got shape ", + input_tensor_shape.DebugString()))); + } + + std::string src_format_str = src_format_; + std::string dst_format_str = dst_format_; + if (input_tensor_shape.dim_size(0) == spatial_dim_count) { + // If the input is a vector of size spatial_dim_count, treat the elements + // as spatial dimensions. + auto keep_only_spatial_dimensions = + [spatial_dim_count](std::string* format_str) -> void { + auto new_end = + std::remove_if(format_str->begin(), format_str->end(), + [spatial_dim_count](const char dim) { + return dim != 'H' && dim != 'W' && + (spatial_dim_count == 2 || dim != 'D'); + }); + format_str->erase(new_end, format_str->end()); + }; + keep_only_spatial_dimensions(&src_format_str); + keep_only_spatial_dimensions(&dst_format_str); + } + std::vector dst_indices(dim0); + for (int i = 0; i < dim0; ++i) { + for (int j = 0; j < dim0; ++j) { + if (src_format_str[i] == dst_format_str[j]) { + dst_indices[j] = i; + break; + } + } + } + xla::XlaOp indices = + xla::ConstantR1(builder, absl::Span(dst_indices)); + xla::XlaOp output = xla::TorchIndexSelect(ctx->Input(0), indices, 0); + ctx->SetOutput(0, output); + } + + private: + std::string src_format_; + std::string dst_format_; + + DataFormatVecPermuteOp(const DataFormatVecPermuteOp&) = delete; + void operator=(const DataFormatVecPermuteOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("DataFormatVecPermute").TypeConstraint("T", {DT_INT32, DT_INT64}), + DataFormatVecPermuteOp); +REGISTER_XLA_OP(Name("DataFormatVecPermute") + .Label("host") + .TypeConstraint("T", {DT_INT32, DT_INT64}), + DataFormatVecPermuteOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/depthtospace_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/depthtospace_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f2d11094b9d3c2405346710483fc79a777ad6331 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/depthtospace_op.cc @@ -0,0 +1,196 @@ +/* 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 +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/lib/data_format.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +class DepthToSpaceOp : public XlaOpKernel { + public: + explicit DepthToSpaceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + std::string data_format_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); + OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_), + absl::InvalidArgumentError("Invalid data format")); + + OP_REQUIRES_OK(ctx, ctx->GetAttr("block_size", &block_size_)); + OP_REQUIRES(ctx, block_size_ > 1, + absl::InvalidArgumentError( + absl::StrCat("Block size should be > 1: ", block_size_))); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + + TensorFormat data_format = data_format_; + // If the data is in a vectorized format, reformat it into a non-vectorized + // version first. We'll undo the transformation later. + if (data_format == FORMAT_NCHW_VECT_C) { + data_format = FORMAT_NCHW; + auto input_reshaped = NCHW_VECT_CToNCHW(input); + OP_REQUIRES_OK(ctx, input_reshaped.status()); + input = input_reshaped.value(); + } + + OP_REQUIRES(ctx, data_format == FORMAT_NCHW || data_format == FORMAT_NHWC, + absl::InvalidArgumentError(absl::StrCat( + "Unsupported data format ", ToString(data_format_)))); + + xla::XlaBuilder* builder = input.builder(); + auto input_xla_shape = builder->GetShape(input); + OP_REQUIRES_OK(ctx, input_xla_shape.status()); + absl::Span input_shape = + input_xla_shape.value().dimensions(); + int input_rank = input_shape.size(); + + static const int kRequiredDims = 4; + OP_REQUIRES( + ctx, kRequiredDims == input_rank, + absl::InvalidArgumentError(absl::StrCat( + "Input rank should be ", kRequiredDims, "; got: ", input_rank))); + + int feature_dim = GetTensorFeatureDimIndex(input_rank, data_format); + int num_spatial_dims = GetTensorSpatialDims(input_rank, data_format); + + std::vector reshaped_shape; + std::vector transpose_order; + std::vector output_shape; + reshaped_shape.reserve(input_rank); + transpose_order.reserve(input_rank); + output_shape.reserve(input_rank); + if (data_format == FORMAT_NHWC) { + reshaped_shape.push_back(input_shape[0]); + for (int i = 0; i < num_spatial_dims; ++i) { + reshaped_shape.push_back(input_shape[1 + i]); + } + int64_t block_elems = 1; + for (int i = 0; i < num_spatial_dims; ++i) { + reshaped_shape.push_back(block_size_); + block_elems *= block_size_; + } + reshaped_shape.push_back(input_shape[feature_dim] / block_elems); + + transpose_order.push_back(0); + for (int i = 0; i < num_spatial_dims; ++i) { + transpose_order.push_back(i + 1); + transpose_order.push_back(i + 1 + num_spatial_dims); + } + transpose_order.push_back(feature_dim + num_spatial_dims); + + output_shape.push_back(input_shape[0]); + for (int i = 0; i < num_spatial_dims; ++i) { + output_shape.push_back(input_shape[1 + i] * block_size_); + } + output_shape.push_back(input_shape[feature_dim] / block_elems); + } else { + // NCHW format. + reshaped_shape.push_back(input_shape[0]); + int64_t block_elems = 1; + for (int i = 0; i < num_spatial_dims; ++i) { + reshaped_shape.push_back(block_size_); + block_elems *= block_size_; + } + reshaped_shape.push_back(input_shape[feature_dim] / block_elems); + for (int i = 0; i < num_spatial_dims; ++i) { + reshaped_shape.push_back(input_shape[2 + i]); + } + + transpose_order.push_back(0); + transpose_order.push_back(1 + num_spatial_dims); + for (int i = 0; i < num_spatial_dims; ++i) { + transpose_order.push_back(2 + num_spatial_dims + i); + transpose_order.push_back(1 + i); + } + + output_shape.push_back(input_shape[0]); + output_shape.push_back(input_shape[feature_dim] / block_elems); + for (int i = 0; i < num_spatial_dims; ++i) { + output_shape.push_back(input_shape[2 + i] * block_size_); + } + } + + // Note: comments are given in NHWC format; NCHW is similar with a different + // dimension order. + // 1. Reshape `input` to `reshaped` of shape: + // + // [batch, + // input_shape[1], + // input_shape[2], + // block_size_, + // block_size_, + // depth / (block_size_ * block_size_)] + OP_REQUIRES(ctx, + input_shape[feature_dim] % (block_size_ * block_size_) == 0, + absl::InvalidArgumentError(absl::StrCat( + "Input depth dimension (", input_shape[3], + ") is not divisible by square of the block size (", + block_size_, ")"))); + + xla::XlaOp reshaped = xla::Reshape(input, reshaped_shape); + + // 2. Permute dimensions of `reshaped` to produce + // `permuted_reshaped` of shape: + // + // [batch, + // input_shape[1], + // block_size_, + // input_shape[2], + // block_size_, + // depth / (block_size_ * block_size_)] + xla::XlaOp permuted_reshaped = xla::Transpose(reshaped, transpose_order); + + // 3. Reshape `permuted_reshaped` to flatten `block_shape` into the + // batch dimension, producing an output tensor of shape: + // + // [batch, + // input_shape[1] * block_size_, + // input_shape[2] * block_size_, + // depth / (block_size_ * block_size_)] + // + xla::XlaOp output = xla::Reshape(permuted_reshaped, output_shape); + + // If this used to be a vectorized format turn it back now. + if (data_format != data_format_) { + DCHECK(data_format == FORMAT_NCHW && data_format_ == FORMAT_NCHW_VECT_C); + auto output_reshaped = NCHWToNCHW_VECT_C(output); + OP_REQUIRES_OK(ctx, output_reshaped.status()); + output = output_reshaped.value(); + } + + ctx->SetOutput(0, output); + } + + private: + TensorFormat data_format_; + int block_size_; +}; +REGISTER_XLA_OP(Name("DepthToSpace"), DepthToSpaceOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dequantize_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dequantize_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..385562774a08f1526fe8c77197c9dd4727d7ffef --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dequantize_op.cc @@ -0,0 +1,108 @@ +/* Copyright 2019 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 +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/numeric_types.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +// TODO(mingyao|ylc): Support 16bits and 32 bits. +constexpr std::array kQuantizedType = {{DT_QINT8, DT_QUINT8}}; + +template +float get_fullrange() { + return static_cast(std::numeric_limits::max()) - + std::numeric_limits::min(); +} + +class DequantizeOp : public XlaOpKernel { + public: + explicit DequantizeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + std::string mode_string; + int axis; + bool narrow_range; + + OP_REQUIRES_OK(ctx, ctx->GetAttr("mode", &mode_string)); + OP_REQUIRES( + ctx, (mode_string == "MIN_COMBINED"), + absl::InvalidArgumentError("Mode string must be 'MIN_COMBINED' is " + + mode_string + "'")); + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range)); + OP_REQUIRES(ctx, narrow_range == false, + absl::InvalidArgumentError("narrow_range must be false")); + OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis)); + OP_REQUIRES( + ctx, axis == -1, + absl::InvalidArgumentError(absl::StrCat("axis must be -1' is ", axis))); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + ~DequantizeOp() override = default; + + void Compile(XlaOpKernelContext* ctx) override { + DataType input_type = ctx->input_type(0); + + xla::XlaOp input = ctx->Input(0); + xla::XlaOp output = xla::ConvertElementType(input, xla::F32); + xla::XlaOp min_range = xla::ConvertElementType(ctx->Input(1), xla::F32); + xla::XlaOp max_range = xla::ConvertElementType(ctx->Input(2), xla::F32); + xla::XlaOp full_range; + xla::XlaOp half_range; + if (input_type == DT_QINT8) { + full_range = ScalarLike(output, get_fullrange()); + half_range = + (full_range + ScalarLike(output, 1.0f)) / ScalarLike(output, 2.0f); + } else { + OP_REQUIRES(ctx, input_type == DT_QUINT8, + absl::InvalidArgumentError(absl::StrCat( + "Only support DT_QINT8 or DT_QUINT8, got ", input_type))); + full_range = ScalarLike(output, get_fullrange()); + half_range = ScalarLike(output, 0.0f); + } + + xla::XlaOp scale = (max_range - min_range) / full_range; + + output = xla::Add(xla::Mul(xla::Add(output, half_range), scale), min_range); + + if (dtype_ == DT_BFLOAT16) { + output = xla::ConvertElementType(output, xla::BF16); + } + ctx->SetOutput(0, output); + } + + private: + DataType dtype_; +}; + +REGISTER_XLA_OP(Name("Dequantize").TypeConstraint("T", kQuantizedType), + DequantizeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/device_index_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/device_index_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..6e5099f8f94bd7d7d4e3037f7165437a41be63d4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/device_index_op.cc @@ -0,0 +1,54 @@ +/* Copyright 2020 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 +#include +#include + +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/client/client_library.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/kernel_def_builder.h" + +namespace tensorflow { +namespace { + +class DeviceIndexOp : public XlaOpKernel { + public: + explicit DeviceIndexOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("device_names", &device_names_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + // When compiling we are not executing on any physical device, so we return + // a sentinel value (size of the list of devices). + ctx->SetOutput( + 0, xla::ConstantR0(ctx->builder(), device_names_.size())); + } + + private: + std::vector device_names_; +}; + +REGISTER_XLA_OP(Name("DeviceIndex"), DeviceIndexOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/diag_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/diag_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f0ae6be64692e7cecfdb0384af297d099acda8bc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/diag_op.cc @@ -0,0 +1,129 @@ +/* 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 +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/lib/util.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/lib/pooling.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { +namespace { + +// Create a diagonal / batch diagonal matrix with 'input' on the diagonal. +xla::XlaOp CreateDiagonal(xla::XlaOp input, int64_t last_dim_size, + absl::Span other_dims) { + xla::XlaBuilder* builder = input.builder(); + // Create two matrices that have the following forms, and compare them: + // + // [[0, 0, 0, 0] [[0, 1, 2, 3] + // [1, 1, 1, 1] [0, 1, 2, 3] + // [2, 2, 2, 2] [0, 1, 2, 3] + // [3, 3, 3, 3]] [0, 1, 2, 3]] + // + // This produces a predicate matrix of the right size, with "true" on the + // diagonal. + xla::XlaOp iota = xla::Iota(builder, xla::S32, last_dim_size); + xla::XlaOp iota_broadcast = xla::Broadcast(iota, {last_dim_size}); + xla::XlaOp mask = xla::Eq(iota_broadcast, iota, {0}); + + // If this is a batched diagonal, broadcast the mask across the other + // dimensions. + if (!other_dims.empty()) { + mask = xla::Broadcast(mask, other_dims); + } + + // Broadcast the input, and then use the mask computed above to select the + // diagonal: + // e.g, in 2D: + // [[t, f, f] [[1, 1, 1] [[0, 0, 0] [[1, 0, 0] + // select( [f, t, f] , [4, 4, 4] , [0, 0, 0] ) = [0, 4, 0] + // [f, f, t]] [9, 9, 9]] [0, 0, 0]] [0, 0, 9]] + // + std::vector out_dim_sizes(other_dims.begin(), other_dims.end()); + out_dim_sizes.push_back(last_dim_size); + out_dim_sizes.push_back(last_dim_size); + + // Broadcast into the second to last dimension. + std::vector broadcast_dimensions(other_dims.size() + 1); + absl::c_iota(broadcast_dimensions, 0); + ++broadcast_dimensions.back(); + xla::XlaOp input_broadcast = + xla::BroadcastInDim(input, out_dim_sizes, broadcast_dimensions); + return xla::Select(mask, input_broadcast, xla::ZerosLike(input_broadcast)); +} + +class DiagOp : public XlaOpKernel { + public: + explicit DiagOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES(ctx, ctx->num_inputs() >= 1, + absl::InvalidArgumentError("Diag op must have at an input")); + const TensorShape input_shape = ctx->InputShape(0); + + auto dims = input_shape.dim_sizes(); + OP_REQUIRES( + ctx, !dims.empty(), + absl::InvalidArgumentError(absl::StrCat( + "Expected 1 <= dims, got shape ", input_shape.DebugString()))); + + xla::XlaOp input = ctx->Input(0); + + // Picture: + // tf.diag([1, 2, 3, 4]) ==> [[1, 0, 0, 0] + // [0, 2, 0, 0] + // [0, 0, 3, 0] + // [0, 0, 0, 4]] + + // Flattens the input to 1D. + int64_t size = input_shape.num_elements(); + input = xla::Reshape(input, {size}); + + // Create an R2 with the R1 diagonal. + xla::XlaOp diag = CreateDiagonal(input, size, /*other_dims=*/{}); + + // Reshapes to the final shape. + std::vector new_dims(dims.size() * 2); + std::copy(dims.begin(), dims.end(), new_dims.begin()); + std::copy(dims.begin(), dims.end(), new_dims.begin() + dims.size()); + diag = xla::Reshape(diag, new_dims); + + ctx->SetOutput(0, diag); + } +}; + +REGISTER_XLA_OP(Name("Diag"), DiagOp); + +REGISTER_XLA_OP(Name("DiagPart"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_partition_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_partition_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..df04ca54eb29edec28ab5c272a630f146e1ef1e9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_partition_op.cc @@ -0,0 +1,199 @@ +/* Copyright 2021 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 +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/comparison_util.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/comparators.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/ops_util.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/tpu/tpu_defs.h" + +namespace tensorflow { +namespace { + +class DynamicPartitionOp : public XlaOpKernel { + public: + explicit DynamicPartitionOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_partitions", &num_partitions_)); + } + + // Returns a S32 tensor representing how many items in `input` are equal to + // `target` + xla::XlaOp CountS32(XlaOpKernelContext* ctx, xla::XlaOp input, + int64_t target) { + xla::XlaOp equal_dim = + xla::Compare(input, xla::ConstantR0(ctx->builder(), target), + {}, xla::ComparisonDirection::kEq); + xla::XlaOp casted = xla::ConvertElementType(equal_dim, xla::S32); + return xla::ReduceAll( + casted, xla::Zero(ctx->builder(), xla::S32), + xla::CreateScalarAddComputation(xla::S32, ctx->builder())); + } + + std::pair, std::vector> + DynamicPartition1D(XlaOpKernelContext* ctx, xla::XlaOp data_1d, + xla::XlaOp partitions_1d, const xla::Shape& data_1d_shape, + const xla::Shape& partition_1d_shape) { + int64_t input_count = data_1d_shape.dimensions(0); + std::vector to_sort = {partitions_1d, data_1d}; + std::vector types_to_sort = { + partition_1d_shape.element_type(), data_1d_shape.element_type()}; + xla::XlaOp sorted = xla::Sort( + to_sort, xla::CreateScalarLtComputation(types_to_sort, ctx->builder()), + /*dimension=*/0, + /*is_stable=*/true); + xla::XlaOp sorted_partitions = xla::GetTupleElement(sorted, 0); + xla::XlaOp sorted_data = xla::GetTupleElement(sorted, 1); + + // `partition_length[i]` is length of partition_i + std::vector partition_length(num_partitions_); + // `partition_start[i]` is sum(partition_start[0:i]) + std::vector partition_start(num_partitions_); + xla::XlaOp count_so_far = xla::Zero(ctx->builder(), xla::S32); + for (int64_t i = 0; i < num_partitions_; ++i) { + xla::XlaOp count = CountS32(ctx, sorted_partitions, /*target=*/i); + partition_length[i] = count; + partition_start[i] = count_so_far; + count_so_far = xla::Add(count_so_far, count); + } + + // Pad input with `input_count` to avoid OOB -- dynamic slice with + // OOB slice produces undefined result. + xla::PaddingConfig padding_config; + auto* dims = padding_config.add_dimensions(); + dims->set_edge_padding_low(0); + dims->set_edge_padding_high(input_count); + dims->set_interior_padding(0); + auto padded_data = + xla::Pad(sorted_data, xla::Zero(ctx->builder(), ctx->input_xla_type(0)), + padding_config); + std::vector output(num_partitions_); + for (int64_t i = 0; i < num_partitions_; ++i) { + // Dynamic size will be set later after this function. + padded_data = xla::RemoveDynamicDimension(padded_data, 0); + // Slice full size out of the input starting from the offsets. + auto sliced = + xla::DynamicSlice(padded_data, {partition_start[i]}, {input_count}); + output[i] = sliced; + } + return {output, partition_length}; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::Shape data_shape = ctx->InputXlaShape(0).value(); + xla::Shape partition_shape = ctx->InputXlaShape(1).value(); + xla::XlaOp data = ctx->Input(0); + xla::XlaOp partitions = ctx->Input(1); + std::vector partitions_static; + bool partitions_are_static = + ctx->ConstantInputReshapedToIntVector(1, &partitions_static).ok(); + // We know how to solve DynamicPartition on 1D inputs using + // DynamicPartition1D. For other input, we do two things: + // + // 1. If partition_shape has lower rank than data_shape, we broadcast + // partition_shape so it's the same as data_shape. This makes + // partition_shape the same as data_shape. + // + // 2. If the data_shape has rank higher than 1, we reshape both data and + // partition to R1. This reduces the problem to 1D, which we've already + // solved using DynamicPartition1D. + // + // 3. We reshape the result of DynamicPartition1D back from 1D to output + // shape. + if (data_shape.dimensions().size() > partition_shape.dimensions().size()) { + // Broadcast parititon_shape so that it can be the same as data_shape. + std::vector broadcasted_dims; + auto rank = partition_shape.dimensions().size(); + broadcasted_dims.reserve(rank); + for (int64_t i = 0; i < rank; ++i) { + broadcasted_dims.push_back(i); + } + partitions = xla::BroadcastInDim(partitions, data_shape.dimensions(), + broadcasted_dims); + } + + // Output shape bounded is calculated by + // [count(partitions)] + data.shape[partitions.ndim:] + // See also the output shape calculation at + // https://www.tensorflow.org/api_docs/python/tf/dynamic_partition + std::vector output_shape_bound_dims; + output_shape_bound_dims.push_back( + xla::ShapeUtil::ElementsIn(partition_shape)); + int64_t count_diff = 1; + for (int64_t i = partition_shape.dimensions().size(); + i < data_shape.dimensions().size(); ++i) { + output_shape_bound_dims.push_back(data_shape.dimensions(i)); + count_diff *= data_shape.dimensions(i); + } + + int64_t input_count = xla::ShapeUtil::ElementsIn(data_shape); + auto data_1d = xla::Reshape(data, {input_count}); + auto partitions_1d = xla::Reshape(partitions, {input_count}); + xla::Shape data_1d_shape = + xla::ShapeUtil::MakeShape(data_shape.element_type(), {input_count}); + + xla::Shape partitions_1d_shape = xla::ShapeUtil::MakeShape( + partition_shape.element_type(), {input_count}); + + std::vector output, partition_length; + std::tie(output, partition_length) = DynamicPartition1D( + ctx, data_1d, partitions_1d, data_1d_shape, partitions_1d_shape); + for (int64_t i = 0; i < num_partitions_; ++i) { + auto reshape = xla::Reshape(output[i], output_shape_bound_dims); + if (partitions_are_static) { + int64_t size = absl::c_count(partitions_static, i); + ctx->SetOutput(i, xla::SliceInDim(reshape, 0, size, 1, 0)); + } else { + xla::XlaOp length; + if (count_diff != 0) { + length = + xla::Div(partition_length[i], + xla::ConstantR0(ctx->builder(), count_diff)); + } else { + length = CountS32(ctx, ctx->Input(1), /*target=*/i); + } + ctx->SetOutput(i, xla::SetDimensionSize(reshape, length, 0)); + } + } + } + + private: + int64_t num_partitions_; +}; + +REGISTER_XLA_OP(Name("DynamicPartition"), DynamicPartitionOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_slice_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_slice_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..2144ccfe2cb3f84d168995bf870e052199b49eea --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_slice_ops.cc @@ -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. +==============================================================================*/ + +#include + +#include "absl/container/inlined_vector.h" +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +absl::InlinedVector SliceVector(xla::XlaOp input, int64_t rank) { + absl::InlinedVector scalar_indices; + scalar_indices.reserve(rank); + for (int i = 0; i < rank; i++) + scalar_indices.push_back( + xla::Reshape(xla::Slice(input, {i}, {i + 1}, {1}), {})); + return scalar_indices; +} + +class DynamicUpdateSliceOp : public XlaOpKernel { + public: + explicit DynamicUpdateSliceOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* ctx) override { + DataType index_type = ctx->InputType("indices"); + CHECK(index_type == DT_INT32 || index_type == DT_INT64); + + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape update_shape = ctx->InputShape("update"); + const TensorShape index_shape = ctx->InputShape("indices"); + + int64_t rank = input_shape.dims(); + OP_REQUIRES(ctx, + TensorShapeUtils::IsVector(index_shape) && + index_shape.num_elements() == rank, + absl::InvalidArgumentError( + "index must be a vector with length equal to " + "the number of input dimensions")); + OP_REQUIRES(ctx, rank == update_shape.dims(), + absl::InvalidArgumentError(absl::StrCat( + "input and update must have the same rank," + " input shape is ", + input_shape.DebugString(), "; update shape is ", + update_shape.DebugString()))); + + xla::XlaOp indices = ctx->Input("indices"); + xla::XlaOp result = xla::DynamicUpdateSlice( + ctx->Input("input"), ctx->Input("update"), SliceVector(indices, rank)); + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP(Name("XlaDynamicUpdateSlice"), DynamicUpdateSliceOp); + +REGISTER_XLA_OP( + Name("XlaDynamicSlice").CompileTimeConstantInput("size_indices"), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_stitch_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_stitch_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..0adde08844e147f8cc61a9abcf159db0170cc3a4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/dynamic_stitch_op.cc @@ -0,0 +1,240 @@ +/* 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. +==============================================================================*/ + +// XLA-specific dynamic stitch Op. + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class DynamicStitchOp : public XlaOpKernel { + public: + explicit DynamicStitchOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES( + ctx, ctx->num_inputs() > 0, + absl::InvalidArgumentError("DynamicStitchOp: Must have some inputs")); + OP_REQUIRES(ctx, ctx->num_inputs() % 2 == 0, + absl::InvalidArgumentError( + "DynamicStitchOp: Must have even number of arguments")); + // Compute expected input signature + const int n = ctx->num_inputs() / 2; + const DataType dt = ctx->input_type(n); + DataTypeVector expected; + for (int i = 0; i < n; i++) { + expected.push_back(DT_INT32); + } + for (int i = 0; i < n; i++) { + expected.push_back(dt); + } + OP_REQUIRES_OK(ctx, ctx->MatchSignature(expected, {dt})); + } + + void Compile(XlaOpKernelContext* ctx) override { + // Validate that data_shape[i] = indices[i].shape() + constant + std::vector indices_input; + OP_REQUIRES_OK(ctx, ctx->ConstantInputList("indices", &indices_input)); + + std::vector data; + std::vector data_shapes; + OP_REQUIRES_OK(ctx, ctx->InputList("data", &data, &data_shapes)); + + std::vector indices(indices_input.size()); + + const TensorShape& data0_shape = data_shapes[0]; + TensorShape indices0_shape; + OP_REQUIRES_OK( + ctx, XLAShapeToTensorShape(indices_input[0].shape(), &indices0_shape)); + for (int input_num = 0; input_num < indices_input.size(); input_num++) { + TensorShape indices_shape; + OP_REQUIRES_OK(ctx, + XLAShapeToTensorShape(indices_input[input_num].shape(), + &indices_shape)); + TensorShape& data_shape = data_shapes[input_num]; + if (!TensorShapeUtils::StartsWith(data_shape, indices_shape)) { + // This happens when data shape is a dynamic shape with bound with + // indices_shape is a concrete shape. We use slice to reconcile the + // mismatch. + for (int64_t i = 0; i < indices_shape.dims(); ++i) { + data_shape.set_dim(i, indices_shape.dim_size(i)); + data[input_num] = xla::SliceInDim(data[input_num], 0, + indices_shape.dim_size(i), 1, i); + } + } + OP_REQUIRES(ctx, TensorShapeUtils::StartsWith(data_shape, indices_shape), + absl::InvalidArgumentError(absl::StrCat( + "data[", input_num, "].shape = ", + data_shape.DebugString(), " does not start with indices[", + input_num, "].shape = ", indices_shape.DebugString()))); + OP_REQUIRES( + ctx, + input_num == 0 || SameExtraShape(data0_shape, indices0_shape, + data_shape, indices_shape), + errors::InvalidArgument( + "Need data[0].shape[", indices0_shape.dims(), ":] = data[", + input_num, "].shape[", indices_shape.dims(), + ":], got data[0].shape = ", data0_shape.DebugString(), ", data[", + input_num, "].shape = ", data_shape.DebugString(), + ", indices[0].shape = ", indices0_shape.DebugString(), + ", indices[", input_num, + "].shape = ", indices_shape.DebugString())); + + OP_REQUIRES_OK(ctx, + XlaHelpers::ReshapeLiteral(indices_input[input_num], + {indices_shape.num_elements()}, + &indices[input_num])); + } + + // Find which slice will be used for each index. If the same index + // appears in multiple inputs, the last one is used. The logic + // here is different from that in third_party/tensorflow because + // it is important for XLA that there be a well-formed Concat + // operation at the end. The existing CPU/GPU code copies multiple + // source slices to the same destination slice if there are + // repeated indices, whereas the XLA code works out which + // source slice will 'win' and only uses that in the Concat. + int max_index = -1; + for (int input_num = 0; input_num < indices.size(); input_num++) { + for (int i = 0; i < indices[input_num].shape().dimensions(0); ++i) { + max_index = std::max(max_index, indices[input_num].Get({i})); + } + } + int number_of_indices = max_index + 1; + int64_t result_rank = 1 + data0_shape.dims() - indices0_shape.dims(); + if (number_of_indices == 0) { + std::vector result_shape(result_rank); + for (int d = indices0_shape.dims(); d < data0_shape.dims(); d++) { + result_shape[d - indices0_shape.dims() + 1] = data0_shape.dim_size(d); + } + xla::PrimitiveType element_type = + ctx->input_xla_type(ctx->num_inputs() - 1); + xla::Literal empty_literal = xla::Literal::CreateFromShape( + xla::ShapeUtil::MakeShape(element_type, result_shape)); + ctx->SetOutput(0, xla::ConstantLiteral(ctx->builder(), empty_literal)); + return; + } + + // Construct the reverse mapping, for each index, of which slice of which + // input it comes from. + std::vector src_input_vector(number_of_indices); + std::vector src_slice_vector(number_of_indices); + std::vector src_index_used(number_of_indices); + int index_used_count = 0; + for (int input_num = 0; input_num < indices.size(); input_num++) { + for (int i = 0; i < indices[input_num].shape().dimensions(0); ++i) { + int index = indices[input_num].Get({i}); + OP_REQUIRES(ctx, index >= 0, + absl::InvalidArgumentError( + absl::StrCat("indices[", index, "] is out of range"))); + + src_input_vector[index] = input_num; + src_slice_vector[index] = i; + if (!src_index_used[index]) { + src_index_used[index] = true; + ++index_used_count; + } + } + } + OP_REQUIRES(ctx, index_used_count == number_of_indices, + absl::InvalidArgumentError("not all indices are used")); + + // Look up all the children expressions that represent the data + // inputs. + std::vector input(indices.size()); + for (int input_num = 0; input_num < indices.size(); input_num++) { + TensorShape new_shape; + // first reshaped dimension is the number of indices for this input. + new_shape.AddDim(indices[input_num].shape().dimensions(0)); + // Then the rest are the common extra shape. + for (int d = indices0_shape.dims(); d < data0_shape.dims(); d++) { + new_shape.AddDim(data0_shape.dim_size(d)); + } + // Get the data, shaped appropriately. + auto handle = data[input_num]; + if (new_shape == data_shapes[input_num]) { + input[input_num] = handle; + } else { + input[input_num] = xla::Reshape(handle, new_shape.dim_sizes()); + } + } + + // Set up the vectors for slicing: the first dimension will vary + // slice by slice, and the rest take the full common extra shape. + std::vector slice_start(result_rank); + std::vector slice_limit(result_rank); + std::vector stride(result_rank, 1); + for (int d = indices0_shape.dims(); d < data0_shape.dims(); d++) { + slice_limit[1 + d - indices0_shape.dims()] = data0_shape.dim_size(d); + } + std::vector to_concat(number_of_indices); + for (int index_num = 0; index_num < number_of_indices; index_num++) { + const auto& expression = input[src_input_vector[index_num]]; + // Take the appropriate slice of data. + slice_start[0] = src_slice_vector[index_num]; + slice_limit[0] = src_slice_vector[index_num] + 1; + // And place it in the concat list in the place indicated by + // the index. + to_concat[index_num] = + xla::Slice(expression, slice_start, slice_limit, stride); + } + + ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), to_concat, 0)); + } + + private: + // Check if data0_shape[indices0.dims():] == data1_shape[indices1.dims():] + static bool SameExtraShape(const TensorShape& data0_shape, + const TensorShape& indices0, + const TensorShape& data1_shape, + const TensorShape& indices1) { + const int extra0 = data0_shape.dims() - indices0.dims(); + const int extra1 = data1_shape.dims() - indices1.dims(); + if (extra0 != extra1) return false; + for (int i = 0; i < extra0; i++) { + if (data0_shape.dim_size(indices0.dims() + i) != + data1_shape.dim_size(indices1.dims() + i)) { + return false; + } + } + return true; + } +}; + +REGISTER_XLA_OP(Name("DynamicStitch").CompileTimeConstantInput("indices"), + DynamicStitchOp); +REGISTER_XLA_OP( + Name("ParallelDynamicStitch").CompileTimeConstantInput("indices"), + DynamicStitchOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/einsum_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/einsum_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..8209b4bc8874398fb3f56f3c6d9819611af269c4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/einsum_op.cc @@ -0,0 +1,40 @@ +/* Copyright 2019 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 + +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +constexpr std::array kEinsumTypes = { + {DT_INT32, DT_INT64, DT_UINT64, DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE, + DT_COMPLEX64, DT_COMPLEX128}}; + +REGISTER_XLA_OP(Name("XlaEinsum").TypeConstraint("T", kEinsumTypes), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Einsum").TypeConstraint("T", kEinsumTypes), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/elu_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/elu_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..a551ad0f1248d80ee78fd702fcf9898639d9142d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/elu_op.cc @@ -0,0 +1,111 @@ +/* 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. +==============================================================================*/ + +// Native XLA implementations of XLA Elu Ops + +#include "tensorflow/compiler/tf2xla/kernels/elu_op.h" + +#include "tensorflow/compiler/tf2xla/kernels/cwise_ops.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/literal.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/types.h" + +namespace xla { +XlaOp Elu(XlaOp x) { + const auto zero = ScalarLike(x, 0); + const auto pred = Gt(x, zero); + const auto expm1 = Expm1(x); + return Select(pred, x, expm1); +} + +XlaOp Selu(XlaOp x) { + const auto zero = ScalarLike(x, 0); + const auto scale = ScalarLike(x, 1.0507009873554804934193349852946); + const auto scale_alpha = ScalarLike(x, 1.7580993408473768599402175208123); + const auto pred = Gt(x, zero); + const auto expm1 = Expm1(x); + return Select(pred, Mul(scale, x), Mul(scale_alpha, expm1)); +} +} // namespace xla + +namespace tensorflow { +namespace { + +class EluOp : public XlaOpKernel { + public: + explicit EluOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + // Computes the max of the scalar input x and 0. + void Compile(XlaOpKernelContext* ctx) override { + ctx->SetOutput(0, xla::Elu(ctx->Input(0))); + } +}; + +class EluGradOp : public XlaOpKernel { + public: + explicit EluGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + // Return the lhs (incoming gradient) if the rhs (input feature) > 0, + // otherwise return lhs * (1 + rhs). + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + const auto zero = XlaHelpers::Zero(b, input_type(0)); + const auto one = XlaHelpers::One(b, input_type(0)); + const auto grad = ctx->Input(0); + const auto activation = ctx->Input(1); + const auto exp_grad = xla::Mul(grad, xla::Add(activation, one)); + const auto pred = xla::Gt(activation, zero); + ctx->SetOutput(0, xla::Select(pred, grad, exp_grad)); + } +}; + +REGISTER_XLA_OP(Name("Elu"), EluOp); +REGISTER_XLA_OP(Name("EluGrad"), EluGradOp); + +class SeluOp : public XlaOpKernel { + public: + explicit SeluOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + // Computes the max of the scalar input x and 0. + void Compile(XlaOpKernelContext* ctx) override { + ctx->SetOutput(0, xla::Selu(ctx->Input(0))); + } +}; + +class SeluGradOp : public XlaOpKernel { + public: + explicit SeluGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + // Return the lhs (incoming gradient) if the rhs (input feature) > 0, + // otherwise return lhs * (1 + rhs). + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + const auto zero = XlaHelpers::Zero(b, input_type(0)); + const auto scale = XlaHelpers::FloatLiteral(b, input_type(0), + 1.0507009873554804934193349852946); + const auto scale_alpha = XlaHelpers::FloatLiteral(b, input_type(0), + 1.7580993408473768599402175208123); + const auto grad = ctx->Input(0); + const auto activation = ctx->Input(1); + const auto lin_grad = xla::Mul(grad, scale); + const auto exp_grad = xla::Mul(grad, xla::Add(activation, scale_alpha)); + const auto pred = xla::Gt(activation, zero); + ctx->SetOutput(0, xla::Select(pred, lin_grad, exp_grad)); + } +}; + +REGISTER_XLA_OP(Name("Selu"), SeluOp); +REGISTER_XLA_OP(Name("SeluGrad"), SeluGradOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/elu_op.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/elu_op.h new file mode 100644 index 0000000000000000000000000000000000000000..0087a731ebaa3906afc5d0eaa2af59810355d7bb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/elu_op.h @@ -0,0 +1,26 @@ +/* Copyright 2019 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_KERNELS_ELU_OP_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_ELU_OP_H_ + +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" + +namespace xla { +XlaOp Elu(XlaOp x); +XlaOp Selu(XlaOp x); +} // namespace xla + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_ELU_OP_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/empty_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/empty_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f9aa4989444347f2d153e0a03906de107fc28e27 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/empty_op.cc @@ -0,0 +1,73 @@ +/* Copyright 2019 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. +==============================================================================*/ + +// XLA-specific Empty Op. + +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class EmptyOp : public XlaOpKernel { + public: + explicit EmptyOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype_, &type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("init", &init_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + // The output of this Op is a tensor of shape 'shape' with each + // element set to the default value of 'dtype'. If 'init' is false then + // the result values may be left undefined, though we don't do that here. + const TensorShape shape_shape = ctx->InputShape("shape"); + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(shape_shape), + absl::InvalidArgumentError( + absl::StrCat("shape must be a vector of int32, got shape ", + shape_shape.DebugString()))); + + std::vector shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector("shape", &shape)); + + auto default_value = xla::Zero(ctx->builder(), type_); + auto result = xla::Broadcast(default_value, shape); + ctx->SetOutput(0, result); + } + + private: + DataType dtype_; + xla::PrimitiveType type_; + bool init_; +}; + +REGISTER_XLA_OP(Name("Empty").CompileTimeConstantInput("shape"), EmptyOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/ensure_shape_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/ensure_shape_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..1bedb3336d6c42d64e151c21a3c45abc97ff4e19 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/ensure_shape_op.cc @@ -0,0 +1,76 @@ +/* Copyright 2020 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. +==============================================================================*/ + +// XLA-specific ensure_shape Op. + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { +namespace { + +class EnsureShapeOp : public XlaOpKernel { + public: + explicit EnsureShapeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &expected_shape_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape shape = ctx->InputShape(0); + + // valiate shape + OP_REQUIRES( + ctx, expected_shape_.IsCompatibleWith(shape), + absl::InvalidArgumentError(absl::StrCat( + "Shape of tensor ", this->def().input(0), " ", shape.DebugString(), + " is not compatible with expected shape ", + expected_shape_.DebugString(), "."))); + + // If the shape dimension in `expected_shape_` is already static, we would + // remove the dynamic dimensions in XLA dynamic padder. Here we don't check + // whether the original input has dynamic shapes, because + // `ctx->ResolveInputDynamismIntoPredVector` runs a DFS underneath which is + // more expensive. + xla::XlaOp tensor = ctx->Input(0); + for (int i = 0; i < expected_shape_.dims(); ++i) { + if (expected_shape_.dim_size(i) > 0) { + VLOG(1) << "RemoveDynamicDimension: " << i << " of shape " + << shape.DebugString(); + tensor = xla::RemoveDynamicDimension(tensor, i); + } + } + + // If shape matches, outputs the tensor. + ctx->SetOutput(0, tensor); + } + + private: + PartialTensorShape expected_shape_; +}; + +REGISTER_XLA_OP(Name("EnsureShape"), EnsureShapeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/extract_image_patches_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/extract_image_patches_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..42303fdc0bbdee9b410223e526d4759410739b12 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/extract_image_patches_op.cc @@ -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. +==============================================================================*/ + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/kernel_shape_util.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { + +namespace { + +class ExtractImagePatchesOp : public XlaOpKernel { + public: + explicit ExtractImagePatchesOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("ksizes", &ksizes_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &strides_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("rates", &dilations_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorFormat data_format = FORMAT_NHWC; + const int num_dims = ksizes_.size(); + + OP_REQUIRES(ctx, num_dims >= 3, + absl::InvalidArgumentError( + "Kernel size must have at least 3 dimensions")); + const int num_spatial_dims = num_dims - 2; + + OP_REQUIRES(ctx, strides_.size() == num_dims, + absl::InvalidArgumentError( + absl::StrCat("Sliding window strides field must " + "specify ", + num_dims, " dimensions"))); + OP_REQUIRES( + ctx, dilations_.size() == num_dims, + absl::InvalidArgumentError(absl::StrCat("Dilations field must " + "specify ", + num_dims, " dimensions"))); + + int batch_dim = GetTensorBatchDimIndex(num_dims, data_format); + int feature_dim = GetTensorFeatureDimIndex(num_dims, data_format); + OP_REQUIRES( + ctx, ksizes_[batch_dim] == 1 && ksizes_[feature_dim] == 1, + absl::UnimplementedError("Current implementation does not yet support " + "kernel sizes > 1 in the batch and depth " + "dimensions.")); + OP_REQUIRES( + ctx, strides_[batch_dim] == 1 && strides_[feature_dim] == 1, + absl::UnimplementedError("Current implementation does not yet support " + "strides in the batch and depth dimensions.")); + OP_REQUIRES(ctx, dilations_[batch_dim] == 1 && dilations_[feature_dim] == 1, + absl::UnimplementedError( + "Current implementation does not support " + "dilations in the batch and depth dimensions.")); + + for (int i = 0; i < num_spatial_dims; ++i) { + int input_dim = GetTensorSpatialDimIndex(num_dims, data_format, i); + OP_REQUIRES( + ctx, ksizes_[input_dim] >= 1, + absl::OutOfRangeError(absl::StrCat( + "Kernel size values must be positive; ", i, + "th spatial dimension had kernel size ", ksizes_[input_dim]))); + OP_REQUIRES( + ctx, strides_[input_dim] >= 1, + absl::UnimplementedError(absl::StrCat( + "Stride values must be positive; ", i, + "th spatial dimension had dilation ", dilations_[input_dim]))); + OP_REQUIRES( + ctx, dilations_[input_dim] >= 1, + absl::UnimplementedError(absl::StrCat( + "Dilation values must be positive; ", i, + "th spatial dimension had dilation ", dilations_[input_dim]))); + } + + xla::PrimitiveType type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(ctx->input_type(0), &type)); + + const TensorShape input_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, input_shape.dims() == num_dims, + absl::InvalidArgumentError( + absl::StrCat("input must be ", num_dims, "-dimensional", + input_shape.DebugString()))); + const int64_t depth = input_shape.dim_size(feature_dim); + + xla::XlaBuilder* builder = ctx->builder(); + + // The following code is equivalent to: + // eye = np.eye(kH * kW * D).reshape([kH, kW, D, kH * kW * kD]) + int64_t kernel_size = 1; + std::vector kernel_shape(num_dims, 1); + for (int i = 0; i < num_spatial_dims; ++i) { + int input_dim = GetTensorSpatialDimIndex(num_dims, data_format, i); + kernel_shape[i] = ksizes_[input_dim]; + kernel_size *= ksizes_[input_dim]; + } + kernel_shape[num_spatial_dims] = 1; + kernel_shape[num_spatial_dims + 1] = kernel_size * depth; + xla::Shape iota_kernel_shape = + xla::ShapeUtil::MakeShape(xla::S32, {kernel_size, depth, kernel_size}); + xla::XlaOp pred_intermediate = xla::Eq(xla::Iota(builder, iota_kernel_shape, + /* iota_dimension= */ 0), + xla::Iota(builder, iota_kernel_shape, + /* iota_dimension= */ 2)); + // In some cases TPU implementations give different results than CPU and GPU + // when doing the conversion directly from pred to the final type. Add an + // extra conversion to S32 here solves this. + xla::XlaOp int_intermediate = + xla::ConvertElementType(pred_intermediate, xla::S32); + xla::XlaOp filter = xla::Reshape( + xla::ConvertElementType(int_intermediate, type), kernel_shape); + + xla::ConvolutionDimensionNumbers dims; + std::vector window_strides(num_spatial_dims); + std::vector lhs_dilation(num_spatial_dims, 1); + std::vector rhs_dilation(num_spatial_dims); + std::vector> padding(num_spatial_dims); + + dims.set_input_batch_dimension(batch_dim); + dims.set_output_batch_dimension(batch_dim); + dims.set_input_feature_dimension(feature_dim); + dims.set_output_feature_dimension(feature_dim); + dims.set_kernel_input_feature_dimension(num_spatial_dims); + dims.set_kernel_output_feature_dimension(num_spatial_dims + 1); + + for (int i = 0; i < num_spatial_dims; ++i) { + const int64_t dim = GetTensorSpatialDimIndex(num_dims, data_format, i); + dims.add_input_spatial_dimensions(dim); + dims.add_kernel_spatial_dimensions(i); + dims.add_output_spatial_dimensions(dim); + window_strides[i] = strides_.at(dim); + rhs_dilation[i] = dilations_.at(dim); + + int64_t unused_output_size; + OP_REQUIRES_OK( + ctx, GetWindowedOutputSizeVerbose( + input_shape.dim_size(dim), ksizes_[dim], 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, depth); + // Feature group convolution, will end up with the kernel_size change more + // rapidly than the depth. Reshape, transpose and reshape to reorder them. + std::vector conv_dims = + xla::SpanToVector(builder->GetShape(conv).value().dimensions()); + conv_dims.back() = depth; + conv_dims.push_back(kernel_size); + conv = xla::TransposeInMinorDims(xla::Reshape(conv, conv_dims)); + conv_dims.pop_back(); + conv_dims.back() *= kernel_size; + conv = xla::Reshape(conv, conv_dims); + ctx->SetOutput(0, conv); + } + + protected: + std::vector ksizes_; + std::vector dilations_; + std::vector strides_; + Padding padding_; + + private: + ExtractImagePatchesOp(const ExtractImagePatchesOp&) = delete; + void operator=(const ExtractImagePatchesOp&) = delete; +}; + +// We don't support integers for the convolution for GPU used in the +// implementation of this op, so we limit the supported types. +REGISTER_XLA_CONV_OP(Name("ExtractImagePatches"), ExtractImagePatchesOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fake_param_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fake_param_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..725fd116938ee80ae4872831c69d02d73609f52e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fake_param_op.cc @@ -0,0 +1,55 @@ +/* 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/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { + +// This OpKernel implements the FakeParam Op for XLA JIT devices. Create zeros +// with the appropriate shape for FakeParam op. +class XlaFakeParamOp : public XlaOpKernel { + public: + explicit XlaFakeParamOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + DataType dtype; + // Tensor shape can be unknown. + PartialTensorShape tensor_shape; + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &tensor_shape)); + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype, tensor_shape, &shape_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + ctx->SetOutput(0, xla::Zeros(b, shape_)); + } + + private: + xla::Shape shape_; + + XlaFakeParamOp(const XlaFakeParamOp&) = delete; + void operator=(const XlaFakeParamOp&) = delete; +}; + +REGISTER_XLA_OP(Name("FakeParam"), XlaFakeParamOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fake_quantize_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fake_quantize_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..502775f612c3ba5f5e3451cc415c832ae923d601 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fake_quantize_ops.cc @@ -0,0 +1,386 @@ +/* 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 +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { +namespace { + +// Gymnastics with nudged zero point is to ensure that the real zero maps to +// an integer, which is required for e.g. zero-padding in convolutional layers. +void CpuNudge(const float min, const float max, const float quant_min, + const float quant_max, float* nudged_min, float* nudged_max, + float* scale) { + *scale = (max - min) / (quant_max - quant_min); + + const float zero_point_from_min = quant_min - min / *scale; + float nudged_zero_point; + if (zero_point_from_min <= quant_min) { + nudged_zero_point = quant_min; + } else if (zero_point_from_min >= quant_max) { + nudged_zero_point = quant_max; + } else { + nudged_zero_point = std::round(zero_point_from_min); + } + + *nudged_min = (quant_min - nudged_zero_point) * (*scale); + *nudged_max = (quant_max - nudged_zero_point) * (*scale); +} + +// An XLA version of CpuNudge(). +void XlaNudge(xla::XlaBuilder* b, const DataType data_type, + const xla::XlaOp min, const xla::XlaOp max, + const float quant_min_value, const float quant_max_value, + xla::XlaOp* nudged_min, xla::XlaOp* nudged_max, + xla::XlaOp* scale) { + *scale = xla::Div(xla::Sub(max, min), + XlaHelpers::FloatLiteral( + b, data_type, quant_max_value - quant_min_value)); + xla::XlaOp quant_min = + XlaHelpers::FloatLiteral(b, data_type, quant_min_value); + xla::XlaOp zero_point_from_min = xla::Sub(quant_min, xla::Div(min, *scale)); + xla::XlaOp quant_max = + XlaHelpers::FloatLiteral(b, data_type, quant_max_value); + xla::XlaOp half = XlaHelpers::FloatLiteral(b, data_type, 0.5f); + xla::XlaOp nudged_zero_point = xla::Select( + xla::Le(zero_point_from_min, quant_min), quant_min, + xla::Select(xla::Ge(zero_point_from_min, quant_max), quant_max, + xla::Floor(xla::Add(zero_point_from_min, half)))); + *nudged_min = xla::Mul(xla::Sub(quant_min, nudged_zero_point), *scale); + *nudged_max = xla::Mul(xla::Sub(quant_max, nudged_zero_point), *scale); +} + +xla::XlaOp Quantize(xla::XlaBuilder* b, const xla::XlaOp input, + const DataType data_type, const xla::XlaOp nudged_input_min, + const xla::XlaOp nudged_input_max, + const xla::XlaOp input_scale) { + xla::XlaOp one = XlaHelpers::FloatLiteral(b, data_type, 1.0f); + xla::XlaOp inv_scale = xla::Div(one, input_scale); + xla::XlaOp half = XlaHelpers::FloatLiteral(b, data_type, 0.5f); + + xla::XlaOp clamped = xla::Clamp(nudged_input_min, input, nudged_input_max); + xla::XlaOp clamped_shifted = xla::Sub(clamped, nudged_input_min); + xla::XlaOp rounded = + xla::Floor(xla::Add(xla::Mul(clamped_shifted, inv_scale), half)); + return xla::Add(xla::Mul(rounded, input_scale), nudged_input_min); +} + +REGISTER_XLA_OP(Name("FakeQuantWithMinMaxArgs"), MlirXlaOpKernel); + +class FakeQuantWithMinMaxArgsGradOp : public XlaOpKernel { + public: + explicit FakeQuantWithMinMaxArgsGradOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + int num_bits; + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits)); + OP_REQUIRES(ctx, num_bits >= 2 && num_bits <= 16, + absl::InvalidArgumentError( + absl::StrCat("num_bits is out of range, expected " + "between 2 and 16, was: ", + num_bits))); + bool narrow_range; + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range)); + const float quant_min = narrow_range ? 1 : 0; + const float quant_max = (1 << num_bits) - 1; + + float input_min, input_max, scale; + OP_REQUIRES_OK(ctx, ctx->GetAttr("min", &input_min)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("max", &input_max)); + CpuNudge(input_min, input_max, quant_min, quant_max, &nudged_input_min_, + &nudged_input_max_, &scale); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp gradient = ctx->Input(0); + const TensorShape gradient_shape = ctx->InputShape(0); + xla::XlaOp input = ctx->Input(1); + const DataType data_type = ctx->input_type(1); + + xla::XlaBuilder* b = ctx->builder(); + xla::XlaOp nudged_input_min = + XlaHelpers::FloatLiteral(b, data_type, nudged_input_min_); + xla::XlaOp nudged_input_max = + XlaHelpers::FloatLiteral(b, data_type, nudged_input_max_); + + xla::XlaOp between_nudged_min_max = xla::And( + xla::Le(nudged_input_min, input), xla::Le(input, nudged_input_max)); + xla::XlaOp zeroes = xla::Broadcast(XlaHelpers::Zero(b, data_type), + gradient_shape.dim_sizes()); + xla::XlaOp output = xla::Select(between_nudged_min_max, gradient, zeroes); + ctx->SetOutput(0, output); + } + + private: + float nudged_input_min_; + float nudged_input_max_; +}; + +REGISTER_XLA_OP(Name("FakeQuantWithMinMaxArgsGradient"), + FakeQuantWithMinMaxArgsGradOp); + +class FakeQuantWithMinMaxVarsOp : public XlaOpKernel { + public: + explicit FakeQuantWithMinMaxVarsOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); + OP_REQUIRES(ctx, num_bits_ >= 2 && num_bits_ <= 16, + absl::InvalidArgumentError( + absl::StrCat("num_bits is out of range, expected " + "between 2 and 16, was: ", + num_bits_))); + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range_)); + quant_min_ = narrow_range_ ? 1 : 0; + quant_max_ = (1 << num_bits_) - 1; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + xla::XlaOp input = ctx->Input(0); + const DataType data_type = ctx->input_type(0); + xla::XlaOp input_min = ctx->Input(1); + xla::XlaOp input_max = ctx->Input(2); + + xla::XlaOp nudged_input_min, nudged_input_max, input_scale; + XlaNudge(b, data_type, input_min, input_max, quant_min_, quant_max_, + &nudged_input_min, &nudged_input_max, &input_scale); + + xla::XlaOp output = Quantize(b, input, data_type, nudged_input_min, + nudged_input_max, input_scale); + ctx->SetOutput(0, output); + } + + private: + int num_bits_; + bool narrow_range_; + float quant_min_; + float quant_max_; +}; + +REGISTER_XLA_OP(Name("FakeQuantWithMinMaxVars"), FakeQuantWithMinMaxVarsOp); + +class FakeQuantWithMinMaxVarsGradOp : public XlaOpKernel { + public: + explicit FakeQuantWithMinMaxVarsGradOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + int num_bits; + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits)); + OP_REQUIRES(ctx, num_bits >= 2 && num_bits <= 16, + absl::InvalidArgumentError( + absl::StrCat("num_bits is out of range, expected " + "between 2 and 16, was: ", + num_bits))); + bool narrow_range; + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range)); + quant_min_ = narrow_range ? 1 : 0; + quant_max_ = (1 << num_bits) - 1; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp gradient = ctx->Input(0); + const TensorShape gradient_shape = ctx->InputShape(0); + xla::XlaOp input = ctx->Input(1); + const DataType data_type = ctx->input_type(1); + const DataType accumulation_type = + XlaHelpers::SumAccumulationType(data_type); + xla::XlaOp input_min = ctx->Input(2); + xla::XlaOp input_max = ctx->Input(3); + + xla::XlaBuilder* b = ctx->builder(); + xla::XlaOp nudged_input_min, nudged_input_max, input_scale; + XlaNudge(b, data_type, input_min, input_max, quant_min_, quant_max_, + &nudged_input_min, &nudged_input_max, &input_scale); + + xla::XlaOp between_nudged_min_max = xla::And( + xla::Le(nudged_input_min, input), xla::Le(input, nudged_input_max)); + xla::XlaOp zero = XlaHelpers::Zero(b, data_type); + xla::XlaOp zeroes = xla::Broadcast(zero, gradient_shape.dim_sizes()); + xla::XlaOp output0 = xla::Select(between_nudged_min_max, gradient, zeroes); + ctx->SetOutput(0, output0); + + xla::XlaOp below_min = xla::Lt(input, nudged_input_min); + xla::XlaOp select1 = xla::Select(below_min, gradient, zeroes); + xla::XlaOp reduce1 = xla::ReduceAll( + XlaHelpers::ConvertElementType(select1, accumulation_type), + XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type)); + xla::XlaOp output1 = XlaHelpers::ConvertElementType(reduce1, data_type); + ctx->SetOutput(1, output1); + + xla::XlaOp above_max = xla::Gt(input, nudged_input_max); + xla::XlaOp select2 = xla::Select(above_max, gradient, zeroes); + xla::XlaOp reduce2 = xla::ReduceAll( + XlaHelpers::ConvertElementType(select2, accumulation_type), + XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type)); + xla::XlaOp output2 = XlaHelpers::ConvertElementType(reduce2, data_type); + ctx->SetOutput(2, output2); + } + + private: + float quant_min_; + float quant_max_; +}; + +REGISTER_XLA_OP(Name("FakeQuantWithMinMaxVarsGradient"), + FakeQuantWithMinMaxVarsGradOp); + +class FakeQuantWithMinMaxVarsPerChannelOp : public XlaOpKernel { + public: + explicit FakeQuantWithMinMaxVarsPerChannelOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); + OP_REQUIRES(ctx, num_bits_ >= 2 && num_bits_ <= 16, + absl::InvalidArgumentError( + absl::StrCat("num_bits is out of range, expected " + "between 2 and 16, was: ", + num_bits_))); + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range_)); + quant_min_ = narrow_range_ ? 1 : 0; + quant_max_ = (1 << num_bits_) - 1; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + xla::XlaOp input = ctx->Input(0); + + const DataType data_type = ctx->input_type(0); + xla::XlaOp input_min = ctx->Input(1); + xla::XlaOp input_max = ctx->Input(2); + + xla::Shape input_shape = b->GetShape(input).value(); + absl::Span input_dimensions = input_shape.dimensions(); + auto convert_to_input_shape = [&](const xla::XlaOp op) { + return xla::BroadcastInDim(op, input_dimensions, + {input_shape.dimensions_size() - 1}); + }; + input_min = convert_to_input_shape(input_min); + input_max = convert_to_input_shape(input_max); + + xla::XlaOp nudged_input_min, nudged_input_max, input_scale; + XlaNudge(b, data_type, input_min, input_max, quant_min_, quant_max_, + &nudged_input_min, &nudged_input_max, &input_scale); + + xla::XlaOp output = Quantize(b, input, data_type, nudged_input_min, + nudged_input_max, input_scale); + ctx->SetOutput(0, output); + } + + private: + int num_bits_; + bool narrow_range_; + float quant_min_; + float quant_max_; +}; + +REGISTER_XLA_OP(Name("FakeQuantWithMinMaxVarsPerChannel"), + FakeQuantWithMinMaxVarsPerChannelOp); + +class FakeQuantWithMinMaxVarsPerChannelGradOp : public XlaOpKernel { + public: + explicit FakeQuantWithMinMaxVarsPerChannelGradOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + int num_bits; + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits)); + OP_REQUIRES(ctx, num_bits >= 2 && num_bits <= 16, + absl::InvalidArgumentError( + absl::StrCat("num_bits is out of range, expected " + "between 2 and 16, was: ", + num_bits))); + bool narrow_range; + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range)); + quant_min_ = narrow_range ? 1 : 0; + quant_max_ = (1 << num_bits) - 1; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp gradient = ctx->Input(0); + const TensorShape gradient_shape = ctx->InputShape(0); + xla::XlaOp input = ctx->Input(1); + const DataType data_type = ctx->input_type(1); + const DataType accumulation_type = + XlaHelpers::SumAccumulationType(data_type); + xla::XlaOp input_min = ctx->Input(2); + xla::XlaOp input_max = ctx->Input(3); + + xla::XlaBuilder* b = ctx->builder(); + xla::Shape input_shape = b->GetShape(input).value(); + absl::Span input_dimensions = input_shape.dimensions(); + + std::vector reduce_axes; + for (int64_t i = 0; i + 1 < input_shape.dimensions().size(); ++i) { + reduce_axes.push_back(i); + } + + auto convert_to_input_shape = [&](const xla::XlaOp op) { + return xla::BroadcastInDim(op, input_dimensions, + {input_shape.dimensions_size() - 1}); + }; + input_min = convert_to_input_shape(input_min); + input_max = convert_to_input_shape(input_max); + + xla::XlaOp nudged_input_min, nudged_input_max, input_scale; + XlaNudge(b, data_type, input_min, input_max, quant_min_, quant_max_, + &nudged_input_min, &nudged_input_max, &input_scale); + + xla::XlaOp between_nudged_min_max = xla::And( + xla::Le(nudged_input_min, input), xla::Le(input, nudged_input_max)); + xla::XlaOp zero = XlaHelpers::Zero(b, data_type); + xla::XlaOp zeroes = xla::Broadcast(zero, gradient_shape.dim_sizes()); + xla::XlaOp output0 = xla::Select(between_nudged_min_max, gradient, zeroes); + ctx->SetOutput(0, output0); + + xla::XlaOp below_min = xla::Lt(input, nudged_input_min); + xla::XlaOp select1 = xla::Select(below_min, gradient, zeroes); + xla::XlaOp reduce1 = + xla::Reduce(XlaHelpers::ConvertElementType(select1, accumulation_type), + XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), reduce_axes); + xla::XlaOp output1 = XlaHelpers::ConvertElementType(reduce1, data_type); + ctx->SetOutput(1, output1); + + xla::XlaOp above_max = xla::Gt(input, nudged_input_max); + xla::XlaOp select2 = xla::Select(above_max, gradient, zeroes); + xla::XlaOp reduce2 = + xla::Reduce(XlaHelpers::ConvertElementType(select2, accumulation_type), + XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), reduce_axes); + xla::XlaOp output2 = XlaHelpers::ConvertElementType(reduce2, data_type); + ctx->SetOutput(2, output2); + } + + private: + float quant_min_; + float quant_max_; +}; + +REGISTER_XLA_OP(Name("FakeQuantWithMinMaxVarsPerChannelGradient"), + FakeQuantWithMinMaxVarsPerChannelGradOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fft_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fft_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..e2ae91ebcd8a95e0b57cc93736ce6bdd5d6ca1f9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fft_ops.cc @@ -0,0 +1,199 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Ops for FFT. + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/numeric_op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/ops_util.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_slice.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { + +namespace { + +using xla::FftType; + +class GenericFftOp : public XlaOpKernel { + public: + explicit GenericFftOp(OpKernelConstruction* ctx, FftType fft_type, + int fft_rank) + : XlaOpKernel(ctx), fft_type_(fft_type), fft_rank_(fft_rank) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + OP_REQUIRES( + ctx, TensorShapeUtils::IsVectorOrHigher(input_shape), + absl::InvalidArgumentError("input must be at least 1 dimensional")); + + std::vector fft_length; + xla::XlaOp input = ctx->Input(0); + if (fft_type_ == FftType::RFFT || fft_type_ == FftType::IRFFT) { + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &fft_length)); + OP_REQUIRES(ctx, fft_length.size() == fft_rank_, + absl::InvalidArgumentError(absl::StrCat( + "fft_length must be length ", fft_rank_, " vector"))); + + // Zero pad or truncate the axes we're doing FFT on. + absl::InlinedVector slice_sizes = input_shape.dim_sizes(); + std::vector> padding_sizes( + slice_sizes.size()); + std::vector expected_sizes = fft_length; + // IRFFT wants the innermost axis to be n / 2 + 1. + if (fft_type_ == FftType::IRFFT) { + expected_sizes[fft_rank_ - 1] = fft_length[fft_rank_ - 1] / 2 + 1; + } + for (int i = 0; i < fft_rank_; i++) { + int index = input_shape.dims() - fft_rank_ + i; + OP_REQUIRES( + ctx, + input_shape.dim_size(index) == 0 || + input_shape.dim_size(index) >= expected_sizes[i], + absl::InvalidArgumentError(absl::StrCat( + "Input dimension ", index, " must have length of at least ", + expected_sizes[i], " but got: ", input_shape.dim_size(index)))); + if (input_shape.dim_size(index) > expected_sizes[i]) { + slice_sizes[index] = expected_sizes[i]; + } else { + padding_sizes[index].second = + expected_sizes[i] - input_shape.dim_size(index); + } + } + + std::vector start_indices(input_shape.dims(), 0); + std::vector strides(input_shape.dims(), 1); + input = xla::Pad(xla::Slice(input, start_indices, slice_sizes, strides), + XlaHelpers::Zero(ctx->builder(), ctx->input_type(0)), + xla::MakeEdgePaddingConfig(padding_sizes)); + } else { + // Innermost axis provides the FFT length. + for (int i = 0; i < fft_rank_; i++) { + fft_length.push_back( + input_shape.dim_size(input_shape.dims() - fft_rank_ + i)); + } + } + + xla::XlaOp fft = xla::Fft(input, fft_type_, fft_length); + ctx->SetOutput(0, fft); + } + + protected: + const FftType fft_type_; + const int fft_rank_; + + private: + GenericFftOp(const GenericFftOp&) = delete; + void operator=(const GenericFftOp&) = delete; +}; + +template +class FFTOp : public GenericFftOp { + public: + explicit FFTOp(OpKernelConstruction* ctx) + : GenericFftOp(ctx, /*fft_type=*/FftType::FFT, /*fft_rank=*/FFTRank) {} +}; +REGISTER_XLA_OP(Name("FFT").TypeConstraint("Tcomplex", + {DT_COMPLEX64, DT_COMPLEX128}), + FFTOp<1>); +REGISTER_XLA_OP(Name("FFT2D").TypeConstraint("Tcomplex", + {DT_COMPLEX64, DT_COMPLEX128}), + FFTOp<2>); +REGISTER_XLA_OP(Name("FFT3D").TypeConstraint("Tcomplex", + {DT_COMPLEX64, DT_COMPLEX128}), + FFTOp<3>); + +template +class IFFTOp : public GenericFftOp { + public: + explicit IFFTOp(OpKernelConstruction* ctx) + : GenericFftOp(ctx, /*fft_type=*/FftType::IFFT, /*fft_rank=*/FFTRank) {} +}; +REGISTER_XLA_OP(Name("IFFT").TypeConstraint("Tcomplex", + {DT_COMPLEX64, DT_COMPLEX128}), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("IFFT2D").TypeConstraint("Tcomplex", + {DT_COMPLEX64, DT_COMPLEX128}), + IFFTOp<2>); +REGISTER_XLA_OP(Name("IFFT3D").TypeConstraint("Tcomplex", + {DT_COMPLEX64, DT_COMPLEX128}), + IFFTOp<3>); + +template +class RFFTOp : public GenericFftOp { + public: + explicit RFFTOp(OpKernelConstruction* ctx) + : GenericFftOp(ctx, /*fft_type=*/FftType::RFFT, /*fft_rank=*/FFTRank) {} +}; +REGISTER_XLA_OP(Name("RFFT") + .TypeConstraint("Treal", {DT_FLOAT, DT_DOUBLE}) + .TypeConstraint("Tcomplex", {DT_COMPLEX64, DT_COMPLEX128}) + .CompileTimeConstantInput("fft_length"), + RFFTOp<1>); +REGISTER_XLA_OP(Name("RFFT2D") + .TypeConstraint("Treal", {DT_FLOAT, DT_DOUBLE}) + .TypeConstraint("Tcomplex", {DT_COMPLEX64, DT_COMPLEX128}) + .CompileTimeConstantInput("fft_length"), + RFFTOp<2>); +REGISTER_XLA_OP(Name("RFFT3D") + .TypeConstraint("Treal", {DT_FLOAT, DT_DOUBLE}) + .TypeConstraint("Tcomplex", {DT_COMPLEX64, DT_COMPLEX128}) + .CompileTimeConstantInput("fft_length"), + RFFTOp<3>); + +template +class IRFFTOp : public GenericFftOp { + public: + explicit IRFFTOp(OpKernelConstruction* ctx) + : GenericFftOp(ctx, /*fft_type=*/FftType::IRFFT, /*fft_rank=*/FFTRank) {} +}; +REGISTER_XLA_OP(Name("IRFFT") + .TypeConstraint("Treal", {DT_FLOAT, DT_DOUBLE}) + .TypeConstraint("Tcomplex", {DT_COMPLEX64, DT_COMPLEX128}) + .CompileTimeConstantInput("fft_length"), + IRFFTOp<1>); +REGISTER_XLA_OP(Name("IRFFT2D") + .TypeConstraint("Treal", {DT_FLOAT, DT_DOUBLE}) + .TypeConstraint("Tcomplex", {DT_COMPLEX64, DT_COMPLEX128}) + .CompileTimeConstantInput("fft_length"), + IRFFTOp<2>); +REGISTER_XLA_OP(Name("IRFFT3D") + .TypeConstraint("Treal", {DT_FLOAT, DT_DOUBLE}) + .TypeConstraint("Tcomplex", {DT_COMPLEX64, DT_COMPLEX128}) + .CompileTimeConstantInput("fft_length"), + IRFFTOp<3>); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fill_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fill_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f9f40dffad1cfc9719e537793a049ca278e4806b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fill_op.cc @@ -0,0 +1,80 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Fill Op. + +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/register_types.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace tensorflow { +namespace { + +class FillOp : public XlaOpKernel { + public: + explicit FillOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // The output of this Op is a tensor of shape 'dims_shape' with each + // element set to the scalar 'dims_literal'. + const TensorShape dims_shape = ctx->InputShape("dims"); + const TensorShape value_shape = ctx->InputShape("value"); + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(dims_shape), + absl::InvalidArgumentError( + absl::StrCat("dims must be a vector of int32, got shape ", + dims_shape.DebugString()))); + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(value_shape), + absl::InvalidArgumentError(absl::StrCat( + "value must be a scalar, got shape ", value_shape.DebugString()))); + + std::vector dims; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntVector( + "dims", &dims, xla::ValueInferenceMode::kUpperBound)); + std::vector dynamic_dims; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPredVector("dims", &dynamic_dims)); + + auto output = xla::Broadcast(ctx->Input("value"), dims); + for (int64_t i = 0; i < dims.size(); ++i) { + // If a dimension is dynamic, call set-dimension-size on the output. + if (dynamic_dims[i]) { + auto dynamic_dim_size = xla::Slice(ctx->Input(0), {i}, {i + 1}, {1}); + dynamic_dim_size = xla::Reshape(dynamic_dim_size, {}); + dynamic_dim_size = xla::ConvertElementType(dynamic_dim_size, xla::S32); + output = xla::SetDimensionSize(output, dynamic_dim_size, i); + } + } + ctx->SetOutput(0, output); + } +}; + +REGISTER_XLA_OP(Name("Fill").CompileTimeConstantInput("dims"), FillOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/function_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/function_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..63b31faaa1fcca86e984736ab9fd08b0540891ae --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/function_ops.cc @@ -0,0 +1,88 @@ +/* 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 "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/node_def.pb.h" + +namespace tensorflow { +namespace { + +const char* const kGradientOp = "SymbolicGradient"; + +// Implementations of _ListToArray and _ArrayToList for functions. +class PassOn : public XlaOpKernel { + public: + explicit PassOn(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES(ctx, ctx->num_inputs() == ctx->num_outputs(), + absl::InternalError( + absl::StrCat("#inputs != #outputs : ", ctx->num_inputs(), + " vs. ", ctx->num_outputs()))); + for (int i = 0; i < ctx->num_inputs(); ++i) { + OP_REQUIRES(ctx, input_type(i) == output_type(i), + absl::InternalError(absl::StrCat( + "Input and output types for position ", i, + " do not match: ", DataTypeString(input_type(i)), " vs. ", + DataTypeString(output_type(i))))); + } + } + + void Compile(XlaOpKernelContext* ctx) override { + for (int i = 0; i < ctx->num_inputs(); ++i) { + ctx->SetOutput(i, ctx->Input(i)); + } + } +}; + +REGISTER_XLA_OP(Name("_ListToArray"), PassOn); +REGISTER_XLA_OP(Name("_ArrayToList"), PassOn); + +class AlwaysFailOp : public OpKernel { + public: + explicit AlwaysFailOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} + + ~AlwaysFailOp() override = default; + + void Compute(OpKernelContext* ctx) override { + ctx->CtxFailure(absl::FailedPreconditionError(absl::StrCat( + "Unexpected attempt to compile ", name(), " which is a ", type_string(), + ". These nodes should always be handled by the graph compiler"))); + } +}; + +// These operations are handled specially in the TF/XLA bridge so their +// OpKernel's should never be called. We still register a dummy kernel so that +// they show up as "supported" when we are deciding whether a graph containing +// them is compilable with XLA. + +REGISTER_XLA_OP(Name(kGradientOp), AlwaysFailOp); +REGISTER_XLA_OP(Name("PartitionedCall") + .AllowResourceTypes() + .AllowVariantTypes() + .AllowStringType(), + AlwaysFailOp); +REGISTER_XLA_OP(Name("StatefulPartitionedCall") + .AllowResourceTypes() + .AllowVariantTypes() + .AllowStringType(), + AlwaysFailOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fused_conv_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fused_conv_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..5760f95c38a788eb21f857bdcba9a750da00ee53 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/fused_conv_ops.cc @@ -0,0 +1,305 @@ +/* Copyright 2022 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 +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/conv_op_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +using xla::ShapeUtil; +using xla::XlaOp; + +// XLA lowering for _FusedConv2D op for int8 and QInt8 +// Computes: +// +// activation( +// conv_scale * conv(conv_input, filter) + +// side_input * side_input_scale + broadcast(bias) +// ) +// +// where +// +// - conv_scale and side_input_scale are scalars. +// - side-input is either the size of conv() or a zero-length tensor (in +// which case it's ignored). +// - bias is a 1D tensor with size matching output depth. +// - activation is either the identity function or relu. +// +// conv_scale is called "conv_input_scale" in the TF op, and TF envisions the +// semantics as conv(conv_input_scale * conv_input). Because conv is a linear +// operation, this is mathematically the same. But in the int8 case it matters +// whether the multiply goes inside or outside the conv, because there are these +// extra type conversions. +// +// This class is only for int8 convolution, the types are: +// +// convert(clamp_to_s8(activation( +// conv_scale * +// convert(conv(convert(conv_input), +// convert(filter))) +// convert(side_input) * side_input_scale + +// broadcast(bias) +// ))) +// +// See cudnn semantics at +// +// https://docs.nvidia.com/deeplearning/cudnn/api/index.html#cudnnConvolutionBiasActivationForward +// https://docs.nvidia.com/deeplearning/cudnn/developer-guide/index.html#scaling-parameters +// +// On GPU we lower these calls to a custom-call which translates directly to +// cudnnConvolutionBiasActivationForward(). On other platforms we expand these +// calls out into a series of pure XLA ops. +// +// (As an alternative implementation strategy, we could always lower to a series +// of pure XLA ops and then pattern-match to the cudnn op. This is challenging +// and fragile because the pattern is rather complicated.) +class FusedConv2DInt8Op : public XlaOpKernel { + public: + enum class ActivationMode { kNone, kRelu }; + + explicit FusedConv2DInt8Op(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + is_gpu_(ctx->device_type().type_string() == "XLA_GPU_JIT") { + OP_REQUIRES( + ctx, ctx->num_inputs() == 6, + absl::InvalidArgumentError(absl::StrCat( + "_FusedConv2D must have 6 inputs but has ", ctx->num_inputs()))); + absl::StatusOr conv_attrs = + ConvOpAttrs::Create(/*num_spatial_dims=*/2, /*depthwise=*/false, ctx); + OP_REQUIRES_OK(ctx, conv_attrs.status()); + conv_attrs_ = conv_attrs.value(); + + std::string filter_format; + OP_REQUIRES_OK(ctx, ctx->GetAttr("filter_format", &filter_format)); + OP_REQUIRES(ctx, FilterFormatFromString(filter_format, &filter_format_), + absl::InvalidArgumentError( + absl::StrCat("Invalid filter format: ", filter_format))); + + std::vector fused_ops; + OP_REQUIRES_OK(ctx, ctx->GetAttr("fused_ops", &fused_ops)); + OP_REQUIRES(ctx, !fused_ops.empty(), + absl::InvalidArgumentError( + "FusedConv2DInt8Op must have at least one fused op.")); + std::string activation_mode = "None"; + if (fused_ops.size() > 1) { + activation_mode = fused_ops[1]; + } + OP_REQUIRES(ctx, activation_mode == "None" || activation_mode == "Relu", + absl::InvalidArgumentError(absl::StrCat( + "Unknown activation_mode, must be 'None' or 'Relu': ", + activation_mode))); + activation_mode_ = activation_mode == "None" ? ActivationMode::kNone + : ActivationMode::kRelu; + } + + absl::Status DoCompile(XlaOpKernelContext* ctx) { + XlaOp conv_input = ctx->Input(0); + XlaOp filter = ctx->Input(1); + XlaOp bias = ctx->Input(2); + XlaOp side_input = ctx->Input(3); + XlaOp conv_scale = ctx->Input(4); + XlaOp side_input_scale = ctx->Input(5); + + auto* builder = ctx->builder(); + TF_ASSIGN_OR_RETURN(auto conv_input_shape, builder->GetShape(conv_input)); + TF_ASSIGN_OR_RETURN(auto filter_shape, builder->GetShape(filter)); + TF_ASSIGN_OR_RETURN(auto side_input_shape, builder->GetShape(side_input)); + TF_ASSIGN_OR_RETURN(auto conv_scale_shape, builder->GetShape(conv_scale)); + TF_ASSIGN_OR_RETURN(auto side_input_scale_shape, + builder->GetShape(side_input_scale)); + + if (conv_input_shape.element_type() != xla::S8) { + return absl::InvalidArgumentError( + absl::StrCat("_FusedConv2D is implemented only for int8: but ", + conv_input_shape.element_type(), " is passed")); + } + + if (!ShapeUtil::IsScalar(conv_scale_shape)) { + return absl::InvalidArgumentError( + absl::StrCat("conv input scale must be a scalar, but was ", + ShapeUtil::HumanString(conv_scale_shape))); + } + if (!ShapeUtil::IsScalar(side_input_scale_shape)) { + return absl::InvalidArgumentError( + absl::StrCat("side input scale must be a scalar, but was ", + ShapeUtil::HumanString(side_input_scale_shape))); + } + + // Un-vectorize NCHW_VECT_C to NCHW. + TensorFormat orig_data_format = conv_attrs_.data_format; + int64_t vect_width = -1; + switch (conv_attrs_.data_format) { + case FORMAT_NCHW_VECT_C: + vect_width = conv_input_shape.dimensions(4); + conv_input = + xla::Collapse(xla::Transpose(conv_input, {0, 1, 4, 2, 3}), {1, 2}); + if (!ShapeUtil::IsZeroElementArray(side_input_shape)) { + side_input = xla::Collapse( + xla::Transpose(side_input, {0, 1, 4, 2, 3}), {1, 2}); + } + break; + case FORMAT_NHWC_VECT_W: + return absl::UnimplementedError("NHWC_VECT_W layout is unsupported."); + default: + break; + } + + // Conv2D expects the filter to be in HWIO format. If the filter is IOHW, + // transpose it. We expect XLA to make this reshape a nop anyway. + switch (filter_format_) { + case FORMAT_HWIO: + break; + case FORMAT_OHWI: + filter = xla::Transpose(filter, {1, 2, 3, 0}); + break; + case FORMAT_OIHW: { + filter = xla::Transpose(filter, {2, 3, 1, 0}); + break; + } + case FORMAT_OIHW_VECT_I: { + TF_ASSIGN_OR_RETURN(auto filter_shape, builder->GetShape(filter)); + // Shape should be of the form [O, I, H, W, {4 or 32}]. Transpose to + // [H, W, I, {4 or 32}, O] and then collapse to [H, W, I, O]. + filter = xla::Collapse(xla::Transpose(filter, {2, 3, 1, 4, 0}), {2, 3}); + TF_ASSIGN_OR_RETURN(auto new_filter_shape, builder->GetShape(filter)); + break; + } + } + + // On XLA:GPU, spell the conv as using S32, which matches cudnn's + // semantics. On other platforms, spell it as an F32 conv, because S32 + // convs are very slow (CPU) or unsupported (TPU). + auto conv_ty = is_gpu_ ? xla::S32 : xla::F32; + conv_input = xla::ConvertElementType(conv_input, conv_ty); + filter = xla::ConvertElementType(filter, conv_ty); + + auto conv_attrs = conv_attrs_; + switch (conv_attrs_.data_format) { + case FORMAT_NCHW_VECT_C: + conv_attrs.data_format = FORMAT_NCHW; + break; + case FORMAT_NHWC_VECT_W: + conv_attrs.data_format = FORMAT_NHWC; + break; + default: + break; + } + TF_ASSIGN_OR_RETURN( + XlaOp conv, + MakeXlaForwardConvOp(type_string(), conv_input, filter, conv_attrs)); + + conv = xla::ConvertElementType(conv, xla::F32); + + conv = conv * conv_scale; + + // Add bias. For int8 convs, bias must be fp32. + bias = xla::ConvertElementType(bias, xla::F32); + XlaOp result = xla::Add( + conv, bias, /*broadcast_dimensions=*/ + {GetTensorFeatureDimIndex(/*num_dims=*/4, conv_attrs.data_format)}); + + // Add in the side input if it's present. Do this before the NCHW -> + // NCHW_VECT_C reshape because that's easier for XLA to pattern-match. + // + // Canonically, if side input is not present, then side_input_scale should + // be 0. But XLA doesn't have the capability of asserting this, and + // asserting it outside of XLA would be expensive, requiring a host-device + // sync. + TF_ASSIGN_OR_RETURN(auto result_shape, builder->GetShape(result)); + if (!ShapeUtil::IsZeroElementArray(side_input_shape)) { + // In the case of an int8 conv, side_input can be s8 or f32. If it's s8, + // just convert it. + side_input = xla::ConvertElementType(side_input, xla::F32); + TF_ASSIGN_OR_RETURN(side_input_shape, builder->GetShape(side_input)); + if (!ShapeUtil::Compatible(side_input_shape, result_shape)) { + return absl::InvalidArgumentError(absl::StrCat( + "Side-input shape ", ShapeUtil::HumanString(side_input_shape), + " must be equal to convolution output shape ", + ShapeUtil::HumanString(result_shape))); + } + result = result + side_input * side_input_scale; + } + + if (activation_mode_ == ActivationMode::kRelu) { + result = xla::Max(result, xla::ZerosLike(result)); + } + + result = xla::Clamp(xla::ConstantR0(builder, -128.0f), result, + xla::ConstantR0(builder, 127.0f)); + + // Hack: Omit RoundToEven in GPU mode to make the HLO easier to + // pattern-match to a cudnn fused convolution. Even without the + // RoundToEven, this is by far the most complex and fragile pattern-match + // we have in XLA. Also, cudnn doesn't give us numerical guarantees + // *anyway*. + if (!is_gpu_) { + result = xla::RoundToEven(result); + } + + result = xla::ConvertElementType(result, xla::S8); + + // Un-convert NCHW -> NCHW_VECT_C. Do this at the very end so that we can + // pattern-match everything above into a cudnn fused conv. + if (orig_data_format == FORMAT_NCHW_VECT_C) { + int n = result_shape.dimensions(0); + int c = result_shape.dimensions(1); + int h = result_shape.dimensions(2); + int w = result_shape.dimensions(3); + CHECK_NE(vect_width, -1); // Crash OK + CHECK_EQ(c % vect_width, 0); // Crash OK + result = xla::Transpose( + xla::Reshape(result, {n, c / vect_width, vect_width, h, w}), + {0, 1, 3, 4, 2}); + } + + ctx->SetOutput(0, result); + return absl::OkStatus(); + } + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES_OK(ctx, DoCompile(ctx)); + } + + private: + bool is_gpu_; + ConvOpAttrs conv_attrs_; + ActivationMode activation_mode_; + FilterTensorFormat filter_format_; +}; + +REGISTER_XLA_OP(Name("_FusedConv2D") + .CompileTimeConstantInput("host_args") + .TypeConstraint("T", {DT_INT8, DT_QINT8}), + FusedConv2DInt8Op); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..d71ffbff602de6fe6a89836bf04ac111d0d22ebe --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_op.cc @@ -0,0 +1,381 @@ +/* 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 +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/slicing.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/status_macros.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/kernel_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +absl::Status XlaGather(const xla::XlaOp& input, const TensorShape& input_shape, + const xla::XlaOp& indices, + const TensorShape& indices_shape, int64_t axis, + bool indices_are_nd, DataType dtype, DataType index_type, + xla::XlaBuilder* builder, xla::XlaOp* gather_output) { + // There is no deep reason why we need this precondition, but this is the only + // combination that is used and tested today. + CHECK(!indices_are_nd || axis == 0); + + // num_index_dims is the number of components in each index in the indices + // tensor. + // + // num_indices is the total number of (n dimensional or scalar) indices in the + // indices tensor. + // + // If the indices are N-dimensional, then the minor dimension of indices + // should be of size N and correspond to the N indices. + int64_t num_index_dims; + int64_t num_indices = 1; + if (indices_are_nd) { + CHECK_GE(indices_shape.dims(), 1); + num_index_dims = indices_shape.dim_size(indices_shape.dims() - 1); + for (int64_t i = 0, e = indices_shape.dims() - 1; i < e; i++) { + num_indices *= indices_shape.dim_size(i); + } + } else { + num_index_dims = 1; + for (int64_t i = 0, e = indices_shape.dims(); i < e; i++) { + num_indices *= indices_shape.dim_size(i); + } + } + + // Degenerate case: empty indices. + if (num_indices == 0) { + TensorShape input_shape_pre_axis{input_shape}; + input_shape_pre_axis.RemoveDimRange(axis, input_shape.dims()); + TensorShape input_shape_post_axis{input_shape}; + input_shape_post_axis.RemoveDimRange(0, axis + num_index_dims); + + TensorShape indices_shape_no_index_vectors{indices_shape}; + if (indices_are_nd) { + indices_shape_no_index_vectors.RemoveLastDims(1); + } + + TensorShape out_shape; + out_shape.AppendShape(input_shape_pre_axis); + out_shape.AppendShape(indices_shape_no_index_vectors); + out_shape.AppendShape(input_shape_post_axis); + + *gather_output = + xla::Broadcast(XlaHelpers::Zero(builder, dtype), out_shape.dim_sizes()); + return absl::OkStatus(); + } + + for (int64_t i = 0; i < num_index_dims; ++i) { + if (input_shape.dim_size(axis + i) == 0) { + // Gather dimension of size zero in tensor results in constant 0. + // This is done to match the legacy behavior of the MLIR legalization and + // avoid breaking existing models. + auto slice_sizes = input_shape.dim_sizes(); + slice_sizes.erase(slice_sizes.begin() + axis); + *gather_output = + xla::Broadcast(XlaHelpers::Zero(builder, dtype), slice_sizes); + return absl::OkStatus(); + } + } + + // Example of a 1-D gather with axis=1, pulling two [3,1] tensors out of a + // tensor of shape [3,3]. + // + // operand = s32[3,3] parameter(0) + // indices = s32[2] parameter(1) + // gather = s32[3,2] gather(operand, indices), + // offset_dims={0}, + // collapsed_slice_dims={1}, + // start_index_map={1}, + // index_vector_dim=1, + // slice_sizes={3, 1} + // + // + // Example of an N-D gather pulling out slices of shape [1,1,2] out of a + // tensor of shape [3,3,2]. + // + // operand = s32[3,3,2] parameter(0) + // indices = s32[2,2] parameter(1) + // gather = s32[2,2] gather(operand, indices), + // offset_dims={1}, + // collapsed_slice_dims={0,1}, + // start_index_map={0,1}, + // index_vector_dim=0, + // slice_sizes={1,1,2} + + xla::GatherDimensionNumbers dim_numbers; + std::vector slice_sizes; + slice_sizes.reserve(input_shape.dims()); + for (int64_t i = 0; i < input_shape.dims(); i++) { + int64_t window_bound; + if (axis <= i && i < (axis + num_index_dims)) { + dim_numbers.add_collapsed_slice_dims(i); + window_bound = 1; + } else { + window_bound = input_shape.dim_size(i); + } + + slice_sizes.push_back(window_bound); + + if (i < axis) { + dim_numbers.add_offset_dims(i); + } else if (i >= (axis + num_index_dims)) { + int64_t indices_rank = + indices_are_nd ? (indices_shape.dims() - 1) : indices_shape.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_t i = axis; i < axis + num_index_dims; i++) { + dim_numbers.add_start_index_map(i); + } + + *gather_output = xla::Gather(input, indices, dim_numbers, slice_sizes); + return absl::OkStatus(); +} + +absl::Status XlaGatherWithBatchDimsOpImpl(XlaOpKernelContext* context, + const xla::XlaOp input, + const TensorShape& input_shape, + int batch_dims, + xla::XlaOp* gather_output) { + auto indices = context->Input(1); + auto indices_shape = context->InputShape(1); + + std::optional axis; + if (context->num_inputs() == 3) { + const TensorShape axis_shape = context->InputShape(2); + if (!TensorShapeUtils::IsScalar(axis_shape)) { + return absl::InvalidArgumentError("axis must be scalar"); + } + DataType axis_type = context->input_type(2); + if (axis_type != DT_INT32 && axis_type != DT_INT64) { + return absl::InvalidArgumentError("axis must be int32 or int64"); + } + + int64_t axis_input; + TF_RETURN_IF_ERROR(context->ConstantInputAsIntScalar(2, &axis_input)); + + const auto params_dims = input_shape.dims(); + if (-params_dims > axis_input || axis_input >= params_dims) { + // Check that params has rank of at least axis + 1. + const auto min_params_rank = + axis_input < 0 ? -axis_input : axis_input + 1; + return absl::InvalidArgumentError( + absl::StrCat("Shape must be at least rank ", min_params_rank, + " but is rank ", params_dims)); + } + if (axis_input < 0) { + axis_input += params_dims; + } + axis = axis_input; + } + + if (batch_dims != 0) { + if (batch_dims < 0) { + batch_dims = indices_shape.dims() + batch_dims; + } + + axis = axis.value_or(batch_dims); + + if (batch_dims < -indices_shape.dims() || + batch_dims > indices_shape.dims()) { + return absl::InvalidArgumentError(absl::StrCat( + "Expected batch_dims in the range [", -indices_shape.dims(), ", ", + indices_shape.dims(), "], but got ", batch_dims)); + } + + if (batch_dims >= input_shape.dims()) { + return absl::InvalidArgumentError(absl::StrCat( + "batch_dims (", batch_dims, ") must be less than rank(input) (", + input_shape.dims(), ").")); + } + + if (*axis < batch_dims) { + return absl::InvalidArgumentError(absl::StrCat( + "batch_dims (", batch_dims, ") must be less than or equal to ", + "axis (", *axis, ").")); + } + } + + axis = axis.value_or(0); + DataType index_type = context->input_type(1); + if (index_type != DT_INT16 && index_type != DT_INT32 && + index_type != DT_INT64) { + return absl::InvalidArgumentError("indices must be int16, int32, or int64"); + } + + xla::XlaOp gather; + if (batch_dims > 0) { + *gather_output = xla::TorchIndexSelect(input, indices, *axis, batch_dims); + } else { + // XlaGather() manages degenerate cases, like empty-indices, which are + // error conditions and caught above if batch_dims is not 0. + TF_RETURN_IF_ERROR( + XlaGather(input, input_shape, indices, indices_shape, *axis, + /*indices_are_nd=*/false, context->expected_output_dtype(0), + index_type, context->builder(), gather_output)); + } + return absl::OkStatus(); +} +class GatherOp : public XlaOpKernel { + public: + explicit GatherOp(OpKernelConstruction* context) : XlaOpKernel(context) { + // Set batch_dims_ to 0 if the attribute does not exist. + if (context->HasAttr("batch_dims")) { + OP_REQUIRES_OK(context, context->GetAttr("batch_dims", &batch_dims_)); + } else { + batch_dims_ = 0; + } + } + + void Compile(XlaOpKernelContext* context) override { + auto input = context->Input(0); + auto input_shape = context->InputShape(0); + + xla::XlaOp gather; + OP_REQUIRES_OK(context, + XlaGatherWithBatchDimsOpImpl(context, input, input_shape, + batch_dims_, &gather)); + context->SetOutput(0, gather); + } + + private: + GatherOp(const GatherOp&) = delete; + void operator=(const GatherOp&) = delete; + + // The number of batch dimensions, as passed in the batch_dims attribute. + // It must be less than or equal to rank(indices). + int32_t batch_dims_ = 0; +}; + +REGISTER_XLA_OP(Name("Gather"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("GatherV2").CompileTimeConstantInput("axis"), GatherOp); + +class GatherNdOp : public XlaOpKernel { + public: + explicit GatherNdOp(OpKernelConstruction* context) : XlaOpKernel(context) { + if (context->HasAttr("bad_indices_policy")) { + OP_REQUIRES_OK(context, context->GetAttr("bad_indices_policy", + &bad_indices_policy_)); + } + } + + void Compile(XlaOpKernelContext* context) override { + DataType params_type = context->input_type(0); + DataType indices_type = context->input_type(1); + + TensorShape params_shape = context->InputShape(0); + TensorShape indices_shape = context->InputShape(1); + OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(params_shape), + absl::InvalidArgumentError("params must be at least a vector")); + OP_REQUIRES( + context, TensorShapeUtils::IsVectorOrHigher(indices_shape), + absl::InvalidArgumentError("indices must be at least a vector")); + const int64_t num_index_dims = + indices_shape.dim_size(indices_shape.dims() - 1); + OP_REQUIRES( + context, num_index_dims <= params_shape.dims(), + absl::InvalidArgumentError(absl::StrCat( + "index innermost dimension length must be <= params rank; saw: ", + indices_shape.dim_size(indices_shape.dims() - 1), " vs. ", + params_shape.dims()))); + + xla::XlaBuilder* builder = context->builder(); + auto params = context->Input(0); + auto indices = context->Input(1); + xla::XlaOp gather; + OP_REQUIRES_OK(context, XlaGather(params, params_shape, indices, + indices_shape, /*axis=*/0, + /*indices_are_nd=*/true, params_type, + indices_type, builder, &gather)); + // By default, XLA clips OOB indices, while "IGNORE" policy demands to fill + // 0s to the output. The following code implements the "IGNORE" policy by + // masking the gather result with the valid indices mask. + if (bad_indices_policy_ == "IGNORE") { + xla::XlaOp valid_mask; + for (int i = 0; i < num_index_dims; ++i) { + xla::XlaOp i_limit = XlaHelpers::IntegerLiteral( + builder, indices_type, params_shape.dim_size(i)); + xla::XlaOp i_zero = XlaHelpers::Zero(builder, indices_type); + xla::XlaOp indices_i = + xla::SliceInDim(indices, i, i + 1, 1, indices_shape.dims() - 1); + + xla::XlaOp indices_i_good = + xla::And(xla::Ge(indices_i, i_zero), xla::Lt(indices_i, i_limit)); + if (i == 0) { + valid_mask = indices_i_good; + } else { + valid_mask = xla::And(valid_mask, indices_i_good); + } + } + auto gather_shape_status = builder->GetShape(gather); + OP_REQUIRES_OK(context, gather_shape_status.status()); + auto gather_shape = gather_shape_status.value(); + + // The last dim of indices tensor is the index vector dimension, which is + // omitted from the gather tensor. + auto valid_mask_dims = indices_shape.dim_sizes(); + valid_mask_dims.pop_back(); + valid_mask = xla::Reshape(valid_mask, valid_mask_dims); + if (indices_shape.dims() != gather_shape.dimensions().size()) { + OP_REQUIRES( + context, + gather_shape.dimensions().size() == indices_shape.dims() - 1, + absl::InvalidArgumentError( + "Indices rank must be equal to output rank (with channel " + "dimension) or 1 less (w/o channel dimension)")); + } else { + std::vector broadcast_dims(valid_mask_dims.size(), 1); + for (int i = 0; i < broadcast_dims.size(); ++i) { + broadcast_dims[i] = i; + } + valid_mask = xla::BroadcastInDim(valid_mask, gather_shape.dimensions(), + broadcast_dims); + } + + gather = + xla::Select(valid_mask, gather, + xla::Broadcast(XlaHelpers::Zero(builder, params_type), + gather_shape.dimensions())); + } + context->SetOutput(0, gather); + } + + std::string bad_indices_policy_; +}; + +REGISTER_XLA_OP(Name("GatherNd"), GatherNdOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..d7f516a52c8afadb993dce088bf8341c65419b44 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h @@ -0,0 +1,52 @@ +/* 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. +==============================================================================*/ + +// Helper methods for XLA Gather Ops. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_KERNELS_GATHER_OP_HELPERS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_GATHER_OP_HELPERS_H_ + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/client/client_library.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/util/bcast.h" + +namespace tensorflow { + +// Adds to builder an XLA computation that performs a gather on input (of +// shape input_shape) keyed on indices (of shape indices_shape). +// +// index_type must be must be DT_INT32 or DT_INT64. +// If `indices_are_nd` is true, the last dimension of `indices` are treated as +// a multidimensional index values. Otherwise, `indices` is treated as a tensor +// of scalar indices. +absl::Status XlaGather(const xla::XlaOp& input, const TensorShape& input_shape, + const xla::XlaOp& indices, + const TensorShape& indices_shape, int64_t axis, + bool indices_are_nd, DataType dtype, DataType index_type, + xla::XlaBuilder* builder, xla::XlaOp* gather_output); + +// The implementation of Gather and ResourceGather through XLA. Uses `input` as +// the input instead of context->input(0) in order to allow ResourceGather to +// handle obtaining the data from the ResourceVariable. +absl::Status XlaGatherWithBatchDimsOpImpl(XlaOpKernelContext* context, + xla::XlaOp input, + const TensorShape& input_shape, + int batch_dims, + xla::XlaOp* gather_output); +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_GATHER_OP_HELPERS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_scatter_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_scatter_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..a7ac1cc97832b58cf6aafbcf13d47f89da50b2a1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/gather_scatter_ops.cc @@ -0,0 +1,108 @@ +/* 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 +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { +namespace { + +class GatherOp : public XlaOpKernel { + public: + explicit GatherOp(OpKernelConstruction* context) : XlaOpKernel(context) { + std::string dnums_attr; + OP_REQUIRES_OK(context, context->GetAttr("dimension_numbers", &dnums_attr)); + OP_REQUIRES( + context, dnums_.ParsePartialFromString(dnums_attr), + absl::InvalidArgumentError("Error parsing gather dimension numbers")); + OP_REQUIRES_OK( + context, context->GetAttr("indices_are_sorted", &indices_are_sorted_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + std::vector slice_sizes; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntVector("slice_sizes", &slice_sizes)); + xla::XlaOp result = + xla::Gather(ctx->Input("operand"), ctx->Input("start_indices"), dnums_, + slice_sizes, indices_are_sorted_); + ctx->SetOutput(0, result); + } + + private: + xla::GatherDimensionNumbers dnums_; + bool indices_are_sorted_; +}; + +REGISTER_XLA_OP(Name("XlaGather").CompileTimeConstantInput("slice_sizes"), + GatherOp); + +class ScatterOp : public XlaOpKernel { + public: + explicit ScatterOp(OpKernelConstruction* context) : XlaOpKernel(context) { + OP_REQUIRES_OK( + context, context->GetAttr("update_computation", &update_computation_)); + std::string dnums_attr; + OP_REQUIRES_OK(context, context->GetAttr("dimension_numbers", &dnums_attr)); + OP_REQUIRES( + context, dnums_.ParsePartialFromString(dnums_attr), + absl::InvalidArgumentError("Error parsing scatter dimension numbers")); + OP_REQUIRES_OK( + context, context->GetAttr("indices_are_sorted", &indices_are_sorted_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const DataType dtype = ctx->input_type(0); + + XlaCompiler::Argument update_computation_arg; + update_computation_arg.kind = XlaCompiler::Argument::kParameter; + update_computation_arg.type = dtype; + update_computation_arg.shape = TensorShape(); + + XlaCompiler::CompileOptions compile_options; + compile_options.use_tuple_arg = false; + compile_options.always_return_tuple = false; + compile_options.is_entry_computation = false; + XlaCompiler::CompilationResult update_computation; + OP_REQUIRES_OK(ctx, ctx->compiler()->CompileFunction( + compile_options, *update_computation_, + {update_computation_arg, update_computation_arg}, + &update_computation)); + + xla::XlaOp result = + xla::Scatter(ctx->Input("operand"), ctx->Input("scatter_indices"), + ctx->Input("updates"), *update_computation.computation, + dnums_, indices_are_sorted_); + ctx->SetOutput(0, result); + } + + private: + const NameAttrList* update_computation_; + xla::ScatterDimensionNumbers dnums_; + bool indices_are_sorted_; +}; + +REGISTER_XLA_OP(Name("XlaScatter"), ScatterOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/identity_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/identity_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..a7174f6357de75c5381eb9faed5f7724f676f3e8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/identity_op.cc @@ -0,0 +1,67 @@ +/* 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 "absl/log/check.h" +#include "tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class IdentityOp : public XlaOpKernel { + public: + explicit IdentityOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* ctx) override { + for (int i = 0; i < ctx->num_inputs(); ++i) { + if (IsTensorListInput(ctx, i)) { + ctx->SetTensorListOutput(i, ctx->Input(i)); + } else { + DCHECK(ctx->input_type(i) != DT_VARIANT); + // 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)); + } + } + } + + private: + IdentityOp(const IdentityOp&) = delete; + void operator=(const IdentityOp&) = delete; +}; + +// XLA_* devices also register a "real" Identity operator so we suppress the +// dummy operator using CompilationOnly(). +REGISTER_XLA_OP( + Name("Identity").AllowResourceTypes().AllowVariantTypes().CompilationOnly(), + IdentityOp); +REGISTER_XLA_OP(Name("IdentityN") + .AllowResourceTypes() + .AllowVariantTypes() + .CompilationOnly(), + IdentityOp); +REGISTER_XLA_OP(Name("PlaceholderWithDefault"), IdentityOp); +REGISTER_XLA_OP(Name("PreventGradient"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("StopGradient").AllowVariantTypes(), IdentityOp); +REGISTER_XLA_OP(Name("Snapshot"), IdentityOp); +REGISTER_XLA_OP(Name("_EagerConst"), IdentityOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..0267732336942ba7cef757624f7bcd8825b41633 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_op.cc @@ -0,0 +1,411 @@ +/* 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/tf2xla/kernels/if_op.h" + +#include +#include + +#include "absl/log/log.h" +#include "absl/log/vlog_is_on.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/if_while_utils.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +XlaIfOp::XlaIfOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + const NameAttrList* name_attr; + OP_REQUIRES_OK(ctx, ctx->GetAttr("then_branch", &name_attr)); + then_branch_ = *name_attr; + OP_REQUIRES_OK(ctx, ctx->GetAttr("else_branch", &name_attr)); + else_branch_ = *name_attr; + + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tcond", &cond_type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tin", &input_types_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tout", &output_types_)); + if (!ctx->GetAttr(kXlaTokenInputNodesAttrName, &token_input_nodes_).ok()) { + has_token_input_output_ = false; + } else { + has_token_input_output_ = !token_input_nodes_.empty(); + if (!ctx->GetAttr(kXlaOriginalOutsideCompilationNodeName, + &original_node_name_) + .ok()) + original_node_name_ = name(); + } + OP_REQUIRES_OK(ctx, ctx->GetAttr("output_shapes", &output_shapes_)); +} + +// Populates tensor array gradients for compiled branches, returns whether the +// set of found tensor array gradients is non-empty. +static absl::StatusOr PopulateTensorArrayGradients( + XlaOpKernelContext* ctx, xla::XlaBuilder* b, + absl::Span arguments, + XlaCompiler::CompilationResult* then_result, + XlaCompiler::CompilationResult* else_result) { + bool has_tensor_array_gradients = false; + for (XlaCompiler::CompilationResult* result : {then_result, else_result}) { + for (const XlaCompiler::ResourceUpdate& update : result->resource_updates) { + XlaResource* resource; + TF_RETURN_IF_ERROR( + ctx->GetResourceInput(update.input_index + 1, &resource)); + XlaCompiler::Argument& arg = arguments[update.input_index]; + + // Add any TensorArray gradients touched by the then/else computation to + // the enclosing graph. + for (const std::string& grad_source : + update.tensor_array_gradients_accessed) { + VLOG(5) << "TensorArray " << resource->name() << " accessed gradient " + << grad_source; + XlaResource* gradient; + TF_RETURN_IF_ERROR(resource->GetOrCreateTensorArrayGradient( + grad_source, b, &gradient)); + } + // Add all of the TensorArray gradients to the argument. For simplicity, + // we always pass all known gradients. + for (const auto& gradient : resource->tensor_array_gradients()) { + arg.tensor_array_gradients.insert(gradient.first); + } + if (!resource->tensor_array_gradients().empty()) + has_tensor_array_gradients = true; + } + } + return has_tensor_array_gradients; +} + +// Checks that shapes matches on both sides of the conditional. +static absl::Status ValidateShapes( + XlaOpKernelContext* ctx, const XlaCompiler::CompilationResult& then_result, + const XlaCompiler::CompilationResult& else_result, + std::vector& output_shapes) { + // Check that both branches have identical input shapes. + if (then_result.xla_input_shapes.size() != 1) { + return absl::FailedPreconditionError("Expected one input shape"); + } + + xla::Shape then_input_shape = then_result.xla_input_shapes[0]; + if (!then_input_shape.IsTuple()) { + return absl::FailedPreconditionError("Expected tuple shape"); + } + + if (else_result.xla_input_shapes.size() != 1) { + return absl::FailedPreconditionError("Expected one input shape"); + } + xla::Shape else_input_shape = else_result.xla_input_shapes[0]; + if (!else_input_shape.IsTuple()) { + return absl::FailedPreconditionError("Expected tuple shape"); + } + if (!xla::ShapeUtil::Compatible(then_input_shape, else_input_shape)) { + return absl::InvalidArgumentError( + absl::StrCat("Input shapes of then and else branches do not match: ", + xla::ShapeUtil::HumanString(then_input_shape), " vs. ", + xla::ShapeUtil::HumanString(else_input_shape))); + } + + // Check that both branches have identical output shapes. + if (!xla::ShapeUtil::DynamicShapeIsCompatible(then_result.xla_output_shape, + else_result.xla_output_shape) && + !xla::ShapeUtil::DynamicShapeIsCompatible(else_result.xla_output_shape, + then_result.xla_output_shape)) { + // Check if it is a currently unsupported case to report a different error + // message. + for (const PartialTensorShape& shape : output_shapes) { + if (!shape.IsFullyDefined()) { + return absl::InvalidArgumentError(absl::StrCat( + "Output shapes of then and else branches do not match: ", + xla::ShapeUtil::HumanString(then_result.xla_output_shape), " vs. ", + xla::ShapeUtil::HumanString(else_result.xla_output_shape), + "; this TF operation has dynamic output dimensions and TF and HLO " + "have different requirements wrt shape constraints. This cannot be " + "handled currently.")); + } + } + return absl::InvalidArgumentError(absl::StrCat( + "Output shapes of then and else branches do not match: ", + xla::ShapeUtil::HumanString(then_result.xla_output_shape), " vs. ", + xla::ShapeUtil::HumanString(else_result.xla_output_shape))); + } + + // Check that both branches have same TensorList output indices. + for (int output_index = 0; output_index < then_result.outputs.size(); + output_index++) { + bool is_tensor_list_in_then_branch = + then_result.outputs[output_index].is_tensor_list; + bool is_tensor_list_in_else_branch = + else_result.outputs[output_index].is_tensor_list; + if (is_tensor_list_in_then_branch != is_tensor_list_in_else_branch) { + return absl::FailedPreconditionError( + absl::StrCat("Output #", output_index, " is ", + is_tensor_list_in_then_branch ? "" : "not", + " a TensorList in then branch, but is ", + is_tensor_list_in_else_branch ? "" : "not", + " a TensorList in else branch")); + } + } + + VLOG(2) << "Input shape: " << xla::ShapeUtil::HumanString(then_input_shape); + VLOG(2) << "Output shape: " + << xla::ShapeUtil::HumanString(then_result.xla_output_shape); + + // We set return_updated_values_for_all_resources=true and we pass the same + // arguments to both computations, so the resource update count must match. + if (then_result.resource_updates.size() != + else_result.resource_updates.size()) { + return absl::FailedPreconditionError( + "Different number of resources in then and else branch"); + } + + for (int i = 0; i < then_result.resource_updates.size(); ++i) { + const auto& lhs = then_result.resource_updates[i]; + const auto& rhs = else_result.resource_updates[i]; + bool equal = lhs.input_index == rhs.input_index && lhs.shape == rhs.shape && + lhs.tensor_array_gradients_accessed == + rhs.tensor_array_gradients_accessed; + if (!equal) { + return absl::FailedPreconditionError(absl::StrCat( + "Mismatch in resource of then and else branch for resource ", i)); + } + } + return absl::OkStatus(); +} + +// TODO(b/35949885): There is duplication here with the handling of the +// while_op. Refactor the common code out/rework. +void XlaIfOp::Compile(XlaOpKernelContext* ctx) { + xla::XlaBuilder* b = ctx->builder(); + + OP_REQUIRES(ctx, cond_type_ == DT_BOOL, + absl::InvalidArgumentError( + "Condition argument must be a boolean for XLA compilation")); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(ctx->InputShape(0)), + absl::InvalidArgumentError( + "Condition argument must be a scalar for XLA compilation")); + + VLOG(1) << "Building If: " << input_types_.size() << " inputs"; + + std::vector arguments(input_types_.size()); + int num_resource_args = 0; + for (int i = 0; i < input_types_.size(); ++i) { + XlaCompiler::Argument& arg = arguments[i]; + DataType type = ctx->input_type(i + 1); + + if (type == DT_RESOURCE) { + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(i + 1, &resource)); + + XlaCompiler::PopulateArgumentFromResource(*resource, &arg); + OP_REQUIRES(ctx, arg.initialized, + absl::UnimplementedError( + absl::StrCat("Uninitialized arguments: ", arg.name))); + VLOG(2) << "Resource " << resource->name() + << " type: " << DataTypeString(arg.type) + << " shape: " << arg.HumanString() + << " initialized: " << arg.initialized; + num_resource_args++; + } else { + arg.kind = XlaCompiler::Argument::kParameter; + arg.type = input_types_[i]; + // Use the xla::Shape for the input instead of ctx->InputShape. This is + // necessary for forwarding shapes of DT_VARIANTs, e.g. TensorLists. + auto shape_or = ctx->builder()->GetShape(ctx->Input(i + 1)); + OP_REQUIRES_OK(ctx, shape_or.status()); + arg.shape = shape_or.value(); + VLOG(2) << "Arg type: " << DataTypeString(arg.type) + << " shape: " << arg.HumanString(); + } + } + + std::vector then_branch_must_be_const_nodes; + const FunctionBody* then_body; + std::vector else_branch_must_be_const_nodes; + const FunctionBody* else_body; + OP_REQUIRES_OK( + ctx, FindMustBeConstNodes(ctx, then_branch_, + &then_branch_must_be_const_nodes, &then_body)); + OP_REQUIRES_OK( + ctx, FindMustBeConstNodes(ctx, else_branch_, + &else_branch_must_be_const_nodes, &else_body)); + + auto should_resolve_const = [&](int arg_idx) { + XlaCompiler::Argument& arg = arguments[arg_idx]; + return arg.kind == XlaCompiler::Argument::kParameter && + (then_branch_must_be_const_nodes[then_body->arg_nodes[arg_idx] + ->id()] || + else_branch_must_be_const_nodes[else_body->arg_nodes[arg_idx] + ->id()]); + }; + + // Replaces `kParameter` type args in `arguments` with `kConstant` if + // the op input corresponding to that arg is a compile-time const. This + // is necessary to propagate compile time consts to ops in the branch + // functions. + ConvertCompileTimeConstArgumentsToConst(ctx, &arguments, + /*xla_expression_offset=*/1, + should_resolve_const); + + // Compile both branches of the conditional. + XlaCompiler::CompileOptions options; + options.use_tuple_arg = true; + options.return_updated_values_for_all_resources = true; + options.is_entry_computation = false; + options.add_token_input_output = has_token_input_output_; + XlaCompiler* compiler = ctx->compiler(); + + XlaCompiler::CompilationResult then_result; + OP_REQUIRES_OK(ctx, compiler->CompileFunction(options, then_branch_, + arguments, &then_result)); + OP_REQUIRES_OK( + ctx, ctx->xla_context()->RecordCollectiveInfoFromNestedCompilationResult( + then_result)); + XlaCompiler::CompilationResult else_result; + OP_REQUIRES_OK(ctx, compiler->CompileFunction(options, else_branch_, + arguments, &else_result)); + OP_REQUIRES_OK( + ctx, ctx->xla_context()->RecordCollectiveInfoFromNestedCompilationResult( + else_result)); + + absl::StatusOr has_tensor_array_gradients = + PopulateTensorArrayGradients(ctx, b, absl::MakeSpan(arguments), + &then_result, &else_result); + OP_REQUIRES_OK(ctx, has_tensor_array_gradients.status()); + + // Recompile the functions to update the argument shapes for tensor arrays. + if (*has_tensor_array_gradients) { + then_result = {}; + OP_REQUIRES_OK(ctx, compiler->CompileFunction(options, then_branch_, + arguments, &then_result)); + else_result = {}; + OP_REQUIRES_OK(ctx, compiler->CompileFunction(options, else_branch_, + arguments, &else_result)); + } + + OP_REQUIRES_OK(ctx, + ValidateShapes(ctx, then_result, else_result, output_shapes_)); + + int num_inputs = then_result.input_mapping.size(); + std::vector inputs(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + int input_num = then_result.input_mapping[i] + 1; + if (has_token_input_output_ && i == num_inputs - 1) { + // Set token input for this "if" op. + std::vector token_inputs; + for (const std::string& node_name : token_input_nodes_) { + auto token_or = compiler->GetNodeToken(node_name); + OP_REQUIRES_OK(ctx, token_or.status()); + token_inputs.push_back(token_or.value()); + } + inputs[i] = xla::AfterAll(b, token_inputs); + } else if (ctx->input_type(input_num) == DT_RESOURCE) { + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(input_num, &resource)); + OP_REQUIRES_OK(ctx, resource->Pack(&inputs[i], b)); + } else { + inputs[i] = ctx->Input(input_num); + } + } + + xla::XlaOp input_tuple = xla::Tuple(b, inputs); + xla::XlaOp outputs = xla::DynamicConditional( + ctx->builder(), 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) { + xla::XlaOp output_handle = xla::GetTupleElement(outputs, i); + if (VLOG_IS_ON(2)) { + absl::StatusOr shape = b->GetShape(output_handle); + VLOG(2) << "Setting output " << i << " with shape " + << (shape.ok() ? shape->ToString() : ""); + } + // We have checked that both branches have same TensorList output indices. + if (then_result.outputs[i].is_tensor_list) { + ctx->SetTensorListOutput(i, output_handle); + } else { + ctx->SetOutput(i, output_handle); + } + } + + if (has_token_input_output_) { + // Set token output for this "If" op. Token output is the last output of + // XLA computation, which comes after all "normal" TF outputs and resource + // updates. For "If" node, num of resource updates equals to number of + // resource args because we set `return_updated_values_for_all_resources` + // to true in XlaCompiler option. + xla::XlaOp token_output = + xla::GetTupleElement(outputs, output_types_.size() + num_resource_args); + auto shape_or = b->GetShape(token_output); + OP_REQUIRES_OK(ctx, shape_or.status()); + OP_REQUIRES(ctx, shape_or.value().IsToken(), + absl::FailedPreconditionError(absl::StrCat( + "Token output is not token type: ", + xla::ShapeUtil::HumanString(shape_or.value())))); + OP_REQUIRES_OK(ctx, + compiler->SetNodeToken(original_node_name_, token_output)); + } + + // Updates the values of any resource variables modified by the conditional + // bodies. + for (XlaCompiler::CompilationResult* result : {&then_result, &else_result}) { + for (int i = 0; i < result->resource_updates.size(); ++i) { + const XlaCompiler::ResourceUpdate& update = result->resource_updates[i]; + XlaResource* resource; + OP_REQUIRES_OK(ctx, + ctx->GetResourceInput(update.input_index + 1, &resource)); + if (update.modified) { + int pos = result->outputs.size() + i; + OP_REQUIRES_OK(ctx, + resource->SetFromPack( + arguments[update.input_index].tensor_array_gradients, + xla::GetTupleElement(outputs, pos), b)); + } + VLOG(2) << "If variable: pos: " << update.input_index + << " name: " << resource->name() + << " modified: " << update.modified + << " type: " << DataTypeString(update.type) + << " shape: " << update.shape.DebugString(); + } + } + VLOG(1) << "Done building If"; +} + +REGISTER_XLA_OP(Name("If").AllowResourceTypes().AllowVariantTypes(), XlaIfOp); +REGISTER_XLA_OP(Name("StatelessIf").AllowResourceTypes().AllowVariantTypes(), + XlaIfOp); +REGISTER_XLA_OP(Name("XlaIf").AllowResourceTypes().AllowVariantTypes(), + XlaIfOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_op.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_op.h new file mode 100644 index 0000000000000000000000000000000000000000..180dd3941177960a2597ac34119f11187d35f76d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_op.h @@ -0,0 +1,70 @@ +/* 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_TF2XLA_KERNELS_IF_OP_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_IF_OP_H_ + +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// This TensorFlow op provides a functional conditional primitive. +// +// The outputs of the then/else branches must agree on the number, types, and +// shapes of the Tensors carried around the two bodies. +// +// Computations in then/else bodies may read from and write to resource +// variables. +// Resource variables may be passed as arguments to the then/else function's +// bodies. The XlaCompiler converts resource variable arguments +// into parameters to the XLA computation and moves them to the end of the +// parameter list, and by using the `return_updated_values_for_all_variables` +// we ensure that all variables that appear in the input also appear at the +// end of the then/else bodies output. This ensures the then/else bodies output +// signatures match. +// +// It is the user's responsibility to ensure that each non-variable _Arg matches +// the corresponding _Retval. +class XlaIfOp : public XlaOpKernel { + public: + explicit XlaIfOp(OpKernelConstruction* ctx); + + void Compile(XlaOpKernelContext* ctx) override; + + private: + XlaIfOp(const XlaIfOp&) = delete; + void operator=(const XlaIfOp&) = delete; + + NameAttrList then_branch_; + NameAttrList else_branch_; + DataType cond_type_; + DataTypeVector input_types_; + DataTypeVector output_types_; + std::vector output_shapes_; + bool has_token_input_output_; + std::vector token_input_nodes_; + std::string original_node_name_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_IF_OP_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_while_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_while_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..ddbefc23bb8fc6180474c4a780318ce40e74ce6f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_while_utils.cc @@ -0,0 +1,105 @@ +/* Copyright 2019 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/kernels/if_while_utils.h" + +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/log/log.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/const_analysis.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/literal.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +const char kPropagateCompileTimeConsts[] = "_xla_propagate_compile_time_consts"; + +absl::InlinedVector ConvertCompileTimeConstArgumentsToConst( + XlaOpKernelContext* ctx, std::vector* args, + int xla_expression_offset, + std::function should_resolve_constant) { + absl::InlinedVector resolved_constant_idxs; + for (int i = 0; i < args->size(); i++) { + XlaCompiler::Argument* arg = &(*args)[i]; + const XlaExpression& expression = + ctx->InputExpression(i + xla_expression_offset); + // If the input tensor is a compile time constant build a kConstant type + // argument. + if (should_resolve_constant(i)) { + VLOG(1) << "Trying to resolve constant " << i; + // NOTE: We can not simply check that this is Kind::kConstant because + // this could be the output of a MetadataOnly op e.g. Size. + + // If we can infer the constant values of an inner computation's argument, + // replace them with constants. If that fails, we fallback to infer the + // bounds of the argument. + absl::StatusOr> maybe_constant = + expression.ResolveConstant(ctx->compiler()->client()); + absl::StatusOr> bounds = + expression.ResolveConstant(ctx->compiler()->client(), false, + xla::ValueInferenceMode::kUpperBound); + if ((maybe_constant.ok() && maybe_constant->has_value()) || + (bounds.ok() && bounds->has_value())) { + absl::StatusOr values_are_dynamic = + expression.ResolveDynamism(); + bool all_values_are_static = false; + if (values_are_dynamic.ok()) { + xla::Literal literal = + HostTensorToLiteral(values_are_dynamic.value()).value(); + all_values_are_static = literal.IsAll(0); + } + + if (all_values_are_static) { + arg->kind = XlaCompiler::Argument::kConstant; + arg->type = expression.dtype(); + arg->constant_value = std::move(maybe_constant.value().value()); + arg->shape = expression.GetShape().value(); + resolved_constant_idxs.push_back(i); + } else { + arg->value_bound.emplace(std::move(bounds.value().value())); + arg->value_dynamism.emplace(std::move(values_are_dynamic.value())); + } + } + } + } + return resolved_constant_idxs; +} + +absl::Status FindMustBeConstNodes(XlaOpKernelContext* ctx, + const NameAttrList& func_name, + std::vector* must_be_const_nodes, + const FunctionBody** body) { + TF_RETURN_IF_ERROR(ctx->compiler()->FindFunctionBody(func_name, body)); + must_be_const_nodes->resize((*body)->graph->num_node_ids(), false); + return BackwardsConstAnalysis(*((*body)->graph), + /*compile_time_const_arg_indices=*/nullptr, + must_be_const_nodes, ctx->function_library()); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_while_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_while_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..bd86707441ed2cc715c3d8952766244c239d8732 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/if_while_utils.h @@ -0,0 +1,54 @@ +/* Copyright 2019 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_KERNELS_IF_WHILE_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_IF_WHILE_UTILS_H_ + +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +extern const char kPropagateCompileTimeConsts[]; + +// Convert arguments in `args` to constants provided they are compile-time +// constants and they satisfy the condition in `should_resolve_constant`. The +// argument `xla_expression_offset` determines what offset is needed to get the +// input expression from context given the argument index in `args`. +// +// Returns a list of indices which were converted to constants. +absl::InlinedVector ConvertCompileTimeConstArgumentsToConst( + XlaOpKernelContext* ctx, std::vector* args, + int xla_expression_offset, + std::function should_resolve_constant); + +// Find and populate `must_be_const_nodes` and `body` of the function +// corresponding to the kernel with context `ctx` with name `func_name`. +absl::Status FindMustBeConstNodes(XlaOpKernelContext* ctx, + const NameAttrList& func_name, + std::vector* must_be_const_nodes, + const FunctionBody** body); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_IF_WHILE_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..9edf6ae3dc054094ac6baebeeec8391bf906124e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_ops.cc @@ -0,0 +1,674 @@ +/* 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 +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/comparators.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/lib/loops.h" +#include "xla/hlo/builder/lib/sorting.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// Converts 'input' from RGB format to HSV format. +// 'shape' is the shape of the red/green/blue tensors. +std::array RGBToHSV(XlaOpKernelContext* ctx, xla::XlaBuilder* b, + const std::array& rgb, + DataType dtype, const TensorShape& shape) { + auto zero = XlaHelpers::Zero(b, dtype); + auto one = XlaHelpers::One(b, dtype); + + auto red = rgb[0]; + auto green = rgb[1]; + auto blue = rgb[2]; + auto value = xla::Max(xla::Max(red, green), blue); + auto minimum = xla::Min(xla::Min(red, green), blue); + auto range = xla::Sub(value, minimum); + + auto zeros = xla::Broadcast(zero, shape.dim_sizes()); + auto saturation = + xla::Select(xla::Gt(value, zero), xla::Div(range, value), zeros); + + auto norm = xla::Div(XlaHelpers::FloatLiteral(b, dtype, 1.0 / 6.0), range); + + auto hue = + xla::Select(xla::Eq(green, value), + xla::Add(xla::Mul(norm, xla::Sub(blue, red)), + XlaHelpers::FloatLiteral(b, dtype, 2.0 / 6.0)), + xla::Add(xla::Mul(norm, xla::Sub(red, green)), + XlaHelpers::FloatLiteral(b, dtype, 4.0 / 6.0))); + hue = xla::Select(xla::Eq(red, value), xla::Mul(norm, xla::Sub(green, blue)), + hue); + hue = xla::Select(xla::Gt(range, zero), hue, zeros); + hue = xla::Select(xla::Lt(hue, zero), xla::Add(hue, one), hue); + return {hue, saturation, value}; +} + +// Converts 'input' from HSV format to RGB format. +std::array HSVToRGB(xla::XlaBuilder* b, + const std::array& hsv, + DataType dtype) { + xla::XlaOp hue = hsv[0]; + xla::XlaOp saturation = hsv[1]; + xla::XlaOp value = hsv[2]; + auto zero = XlaHelpers::Zero(b, dtype); + auto one = XlaHelpers::FloatLiteral(b, dtype, 1.0); + auto two = XlaHelpers::FloatLiteral(b, dtype, 2.0); + auto three = XlaHelpers::FloatLiteral(b, dtype, 3.0); + auto four = XlaHelpers::FloatLiteral(b, dtype, 4.0); + auto six = XlaHelpers::FloatLiteral(b, dtype, 6.0); + + auto dh = xla::Mul(hue, six); + auto dr = xla::Clamp(zero, xla::Sub(xla::Abs(xla::Sub(dh, three)), one), one); + auto dg = xla::Clamp(zero, xla::Sub(two, xla::Abs(xla::Sub(dh, two))), one); + auto db = xla::Clamp(zero, xla::Sub(two, xla::Abs(xla::Sub(dh, four))), one); + auto one_minus_s = xla::Sub(one, saturation); + + auto red = xla::Mul(xla::Add(one_minus_s, xla::Mul(saturation, dr)), value); + auto green = xla::Mul(xla::Add(one_minus_s, xla::Mul(saturation, dg)), value); + auto blue = xla::Mul(xla::Add(one_minus_s, xla::Mul(saturation, db)), value); + return {red, green, blue}; +} + +class RGBToHSVOp : public XlaOpKernel { + public: + explicit RGBToHSVOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + const TensorShape input_shape = context->InputShape(0); + OP_REQUIRES(context, input_shape.dims() >= 1, + absl::InvalidArgumentError(absl::StrCat( + "input must be at least 1D", input_shape.DebugString()))); + int channel_dim = input_shape.dims() - 1; + int64_t channels = input_shape.dim_size(channel_dim); + OP_REQUIRES(context, channels == 3, + absl::FailedPreconditionError( + absl::StrCat("input must have 3 channels but input has ", + channels, " channels."))); + + xla::XlaBuilder* b = context->builder(); + xla::XlaOp input = context->Input(0); + + xla::XlaOp red = xla::SliceInDim(input, /*start_index=*/0, + /*limit_index=*/1, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp green = xla::SliceInDim(input, /*start_index=*/1, + /*limit_index=*/2, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp blue = xla::SliceInDim(input, /*start_index=*/2, + /*limit_index=*/3, /*stride=*/1, + /*dimno=*/channel_dim); + TensorShape channel_shape = input_shape; + channel_shape.set_dim(channel_dim, 1); + auto hsv = RGBToHSV(context, b, {red, green, blue}, context->input_type(0), + channel_shape); + + context->SetOutput(0, xla::ConcatInDim(b, hsv, channel_dim)); + } +}; +REGISTER_XLA_OP(Name("RGBToHSV"), RGBToHSVOp); + +class HSVToRGBOp : public XlaOpKernel { + public: + explicit HSVToRGBOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + const TensorShape input_shape = context->InputShape(0); + OP_REQUIRES(context, input_shape.dims() >= 1, + absl::InvalidArgumentError(absl::StrCat( + "input must be at least 1D", input_shape.DebugString()))); + int channel_dim = input_shape.dims() - 1; + int64_t channels = input_shape.dim_size(channel_dim); + OP_REQUIRES(context, channels == 3, + absl::FailedPreconditionError( + absl::StrCat("input must have 3 channels but input has ", + channels, " channels."))); + + xla::XlaBuilder* b = context->builder(); + xla::XlaOp input = context->Input(0); + xla::XlaOp hue = xla::SliceInDim(input, /*start_index=*/0, + /*limit_index=*/1, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp saturation = xla::SliceInDim(input, /*start_index=*/1, + /*limit_index=*/2, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp value = xla::SliceInDim(input, /*start_index=*/2, + /*limit_index=*/3, /*stride=*/1, + /*dimno=*/channel_dim); + + auto rgb = HSVToRGB(context->builder(), {hue, saturation, value}, + context->input_type(0)); + + context->SetOutput(0, xla::ConcatInDim(b, rgb, channel_dim)); + } +}; +REGISTER_XLA_OP(Name("HSVToRGB"), HSVToRGBOp); + +class AdjustContrastOpV2 : public XlaOpKernel { + public: + explicit AdjustContrastOpV2(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + const TensorShape& input_shape = context->InputShape(0); + const TensorShape& factor_shape = context->InputShape(1); + OP_REQUIRES(context, input_shape.dims() >= 3, + absl::InvalidArgumentError( + absl::StrCat("input must be at least 3-D, got shape", + input_shape.DebugString()))); + int height_dim = input_shape.dims() - 3; + int width_dim = input_shape.dims() - 2; + int channel_dim = input_shape.dims() - 1; + const int64_t height = input_shape.dim_size(height_dim); + const int64_t width = input_shape.dim_size(width_dim); + + OP_REQUIRES( + context, TensorShapeUtils::IsScalar(factor_shape), + absl::InvalidArgumentError(absl::StrCat( + "contrast_factor must be scalar: ", factor_shape.DebugString()))); + + xla::XlaBuilder* b = context->builder(); + DataType type = context->input_type(0); + + xla::XlaOp input = context->Input(0); + xla::XlaOp factor = XlaHelpers::ConvertElementType(context->Input(1), type); + + const DataType accumulation_type = XlaHelpers::SumAccumulationType(type); + auto converted = XlaHelpers::ConvertElementType(input, accumulation_type); + auto reduce = xla::Reduce(converted, XlaHelpers::Zero(b, accumulation_type), + *context->GetOrCreateAdd(accumulation_type), + {height_dim, width_dim}); + + auto output = xla::Div( + reduce, XlaHelpers::FloatLiteral(b, accumulation_type, height * width)); + output = XlaHelpers::ConvertElementType(output, type); + + std::vector broadcast_dims(input_shape.dims() - 2); + std::iota(broadcast_dims.begin(), broadcast_dims.end(), 0); + broadcast_dims.back() = channel_dim; + output = + xla::Add(xla::Mul(input, factor), + xla::Mul(output, xla::Sub(XlaHelpers::One(b, type), factor)), + broadcast_dims); + context->SetOutput(0, output); + } +}; +REGISTER_XLA_OP(Name("AdjustContrastv2"), AdjustContrastOpV2); + +class AdjustSaturationOp : public XlaOpKernel { + public: + explicit AdjustSaturationOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + const TensorShape& input_shape = context->InputShape(0); + const TensorShape& scale_shape = context->InputShape(1); + OP_REQUIRES(context, input_shape.dims() >= 3, + absl::InvalidArgumentError( + absl::StrCat("input must be at least 3-D, got shape", + input_shape.DebugString()))); + OP_REQUIRES(context, TensorShapeUtils::IsScalar(scale_shape), + absl::InvalidArgumentError(absl::StrCat( + "scale must be scalar: ", scale_shape.DebugString()))); + const int channel_dim = input_shape.dims() - 1; + const int64_t channels = input_shape.dim_size(channel_dim); + OP_REQUIRES(context, channels == 3, + absl::InvalidArgumentError( + absl::StrCat("input must have 3 channels but instead has ", + channels, " channels."))); + + xla::XlaBuilder* b = context->builder(); + xla::XlaOp input = + XlaHelpers::ConvertElementType(context->Input(0), DT_FLOAT); + xla::XlaOp scale = + XlaHelpers::ConvertElementType(context->Input(1), DT_FLOAT); + + DataType type = context->input_type(0); + + xla::XlaOp red = xla::SliceInDim(input, /*start_index=*/0, + /*limit_index=*/1, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp green = xla::SliceInDim(input, /*start_index=*/1, + /*limit_index=*/2, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp blue = xla::SliceInDim(input, /*start_index=*/2, + /*limit_index=*/3, /*stride=*/1, + /*dimno=*/channel_dim); + TensorShape channel_shape = input_shape; + channel_shape.set_dim(channel_dim, 1); + auto hsv = + RGBToHSV(context, b, {red, green, blue}, DT_FLOAT, channel_shape); + + hsv[1] = xla::Clamp(XlaHelpers::Zero(b, DT_FLOAT), xla::Mul(hsv[1], scale), + XlaHelpers::One(b, DT_FLOAT)); + + auto rgb = HSVToRGB(context->builder(), hsv, DT_FLOAT); + + auto output = XlaHelpers::ConvertElementType( + xla::ConcatInDim(b, rgb, channel_dim), type); + context->SetOutput(0, output); + } +}; +REGISTER_XLA_OP(Name("AdjustSaturation"), AdjustSaturationOp); + +class AdjustHueOp : public XlaOpKernel { + public: + explicit AdjustHueOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + const TensorShape& input_shape = context->InputShape(0); + const TensorShape& delta_shape = context->InputShape(1); + OP_REQUIRES(context, input_shape.dims() >= 3, + absl::InvalidArgumentError( + absl::StrCat("input must be at least 3-D, got shape", + input_shape.DebugString()))); + OP_REQUIRES(context, TensorShapeUtils::IsScalar(delta_shape), + absl::InvalidArgumentError(absl::StrCat( + "delta must be scalar: ", delta_shape.DebugString()))); + const int channel_dim = input_shape.dims() - 1; + const int64_t channels = input_shape.dim_size(channel_dim); + OP_REQUIRES(context, channels == 3, + absl::InvalidArgumentError( + absl::StrCat("input must have 3 channels but instead has ", + channels, " channels."))); + + xla::XlaBuilder* b = context->builder(); + xla::XlaOp input = + XlaHelpers::ConvertElementType(context->Input(0), DT_FLOAT); + xla::XlaOp delta = + XlaHelpers::ConvertElementType(context->Input(1), DT_FLOAT); + + DataType type = context->input_type(0); + + xla::XlaOp red = xla::SliceInDim(input, /*start_index=*/0, + /*limit_index=*/1, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp green = xla::SliceInDim(input, /*start_index=*/1, + /*limit_index=*/2, /*stride=*/1, + /*dimno=*/channel_dim); + xla::XlaOp blue = xla::SliceInDim(input, /*start_index=*/2, + /*limit_index=*/3, /*stride=*/1, + /*dimno=*/channel_dim); + TensorShape channel_shape = input_shape; + channel_shape.set_dim(channel_dim, 1); + auto hsv = + RGBToHSV(context, b, {red, green, blue}, DT_FLOAT, channel_shape); + + auto zero = XlaHelpers::Zero(b, DT_FLOAT); + auto one = XlaHelpers::One(b, DT_FLOAT); + + auto& hue = hsv[0]; + hue = xla::Rem(xla::Add(hsv[0], delta), one); + hue = + xla::Select(xla::Lt(hue, zero), xla::Rem(xla::Add(one, hue), one), hue); + + auto rgb = HSVToRGB(context->builder(), hsv, DT_FLOAT); + + auto output = XlaHelpers::ConvertElementType( + xla::ConcatInDim(b, rgb, channel_dim), type); + context->SetOutput(0, output); + } +}; +REGISTER_XLA_OP(Name("AdjustHue"), AdjustHueOp); + +struct WhileCondFn { + const int64_t num_boxes; + const int64_t output_size; + + explicit WhileCondFn(int64_t num_boxes, int64_t output_size) + : num_boxes(num_boxes), output_size(output_size) {} + + absl::StatusOr operator()(absl::Span values, + xla::XlaBuilder* cond_builder) const { + xla::XlaOp row_idx = values[0]; + xla::XlaOp row_in_bounds = + xla::Lt(row_idx, xla::ConstantR0(cond_builder, num_boxes)); + xla::XlaOp num_outputs_so_far = values[1]; + xla::XlaOp results_not_full = + xla::Lt(num_outputs_so_far, + xla::ConstantR0(cond_builder, output_size)); + return xla::And(row_in_bounds, results_not_full); + } +}; + +// Process the boxes one-by-one using the iou matrix mask. +// This implementation uses a correct, but greedy, sequential algorithm +// to ensure that suppressed boxes cannot themselves suppress other +// boxes. +struct SuppressBodyFn { + const int64_t num_boxes; + + explicit SuppressBodyFn(int64_t num_boxes) : num_boxes(num_boxes) {} + + absl::StatusOr> operator()( + absl::Span values, xla::XlaBuilder* builder) const { + auto row_idx = values[0]; + auto num_outputs_so_far = values[1]; + auto iou_mask = values[2]; + auto included_iou = values[3]; + auto zero = xla::ConstantR0(builder, 0); + // Determine if current elem is active using a slice. + // TODO(b/118437727): The only reason we need an explicit vector is because + // some old GCCs can't deduce the right type for MakeConstSpan, and + // providing a single-value initializer list directly uses the wrong + // overload. Delete this once the deprecated overload is gone. + std::vector row_idx_vector = {row_idx}; + auto active_elem = xla::DynamicSlice(included_iou, row_idx_vector, {1}); + active_elem = xla::Reshape(active_elem, {}); + // Increment output count iff current elem is not suppressed. + num_outputs_so_far = xla::Select( + active_elem, num_outputs_so_far + xla::ConstantR0(builder, 1), + num_outputs_so_far); + // Slice out the row_idx. + auto row_iou = xla::DynamicSlice(iou_mask, {row_idx, zero}, {1, num_boxes}); + + TF_ASSIGN_OR_RETURN(auto iou_shape, builder->GetShape(iou_mask)); + auto boxes_runtime_size = xla::GetDimensionSize(row_iou, 1); + if (iou_shape.is_dynamic_dimension(1)) { + row_iou = xla::SetDimensionSize(row_iou, boxes_runtime_size, 1); + } + + // Remove the diagonal from consideration. An elem cannot suppress + // itself. + row_iou = xla::DynamicUpdateSlice( + row_iou, xla::ConstantR2FromArray2D(builder, {{false}}), + {zero, row_idx}); + // Create a suppression by inverting polarity. + row_iou = xla::Reshape(row_iou, {num_boxes}); + auto supp_mask = xla::Not(row_iou); + // Update mask iff current elem is not suppressed. + auto cond = xla::Broadcast(active_elem, {num_boxes}); + if (iou_shape.is_dynamic_dimension(1)) { + cond = xla::SetDimensionSize(cond, boxes_runtime_size, 0); + } + included_iou = + xla::Select(cond, xla::And(included_iou, supp_mask), included_iou); + row_idx = row_idx + xla::ConstantR0(builder, 1); + return std::vector{row_idx, num_outputs_so_far, iou_mask, + included_iou}; + } +}; + +class NonMaxSuppressionOp : public XlaOpKernel { + public: + explicit NonMaxSuppressionOp(OpKernelConstruction* context) + : XlaOpKernel(context) { + OP_REQUIRES_OK(context, context->GetAttr("pad_to_max_output_size", + &pad_to_max_output_size_)); + } + + void Compile(XlaOpKernelContext* context) override { + // TODO(b/111646731): Improve scalability of this op, using blocking. + OP_REQUIRES(context, pad_to_max_output_size_, + absl::UnimplementedError( + "XLA compilation requires pad_to_max_output_size == True")); + + xla::XlaOp selected_indices, num_valid; + ComputeResult(context, pad_to_max_output_size_); + } + static void ComputeResult(XlaOpKernelContext* context, + bool pad_to_max_output_size = false) { + const TensorShape& boxes_shape = context->InputShape("boxes"); + OP_REQUIRES(context, TensorShapeUtils::IsMatrix(boxes_shape), + absl::InvalidArgumentError(absl::StrCat( + "boxes must be 2-D, currently: [", + std::to_string(boxes_shape.dim_size(0)), ",", + std::to_string(boxes_shape.dim_size(1)), "]"))); + const int64_t num_boxes = boxes_shape.dim_size(0); + OP_REQUIRES(context, boxes_shape.dim_size(1) == 4, + absl::InvalidArgumentError( + absl::StrCat("boxes must have 4 columns, currently: ", + std::to_string(boxes_shape.dim_size(1))))); + const TensorShape& scores_shape = context->InputShape("scores"); + OP_REQUIRES( + context, TensorShapeUtils::IsVector(scores_shape), + absl::InvalidArgumentError(absl::StrCat( + "scores must be 1-D, currently: ", scores_shape.DebugString()))); + OP_REQUIRES( + context, scores_shape.dim_size(0) == num_boxes, + absl::InvalidArgumentError(absl::StrCat( + "scores size ", std::to_string(scores_shape.dim_size(0)), + " must equal number of boxes ", std::to_string(num_boxes)))); + OP_REQUIRES(context, num_boxes <= std::numeric_limits::max(), + absl::InvalidArgumentError( + absl::StrCat("XLA compilation requires number of " + "boxes to be <= kint32max, got ", + num_boxes))); + xla::PrimitiveType boxes_xla_type = context->InputXlaType("boxes"); + xla::PrimitiveType scores_xla_type = context->InputXlaType("scores"); + const xla::XlaOp boxes_input = context->Input("boxes"); + const xla::XlaOp scores_input = context->Input("scores"); + int64_t output_size; + OP_REQUIRES( + context, + TensorShapeUtils::IsScalar(context->InputShape("max_output_size")), + absl::InvalidArgumentError("Max Output Size isn't a scalar")); + OP_REQUIRES( + context, + TensorShapeUtils::IsScalar(context->InputShape("iou_threshold")), + absl::InvalidArgumentError("IOU Threshold isn't a scalar")); + OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar(2, &output_size)); + OP_REQUIRES(context, output_size >= 0, + absl::InvalidArgumentError( + absl::StrCat("Need output_size >= 0, got ", output_size))); + OP_REQUIRES(context, output_size <= std::numeric_limits::max(), + absl::InvalidArgumentError(absl::StrCat( + "Need output_size <= kint32Max, got ", output_size))); + const xla::XlaOp score_thresh = context->Input("score_threshold"); + const xla::XlaOp iou_thresh = context->Input("iou_threshold"); + xla::XlaBuilder* const builder = context->builder(); + + // Choose a more convenient layout. + const xla::XlaOp boxes = xla::Transpose(boxes_input, {1, 0}); + const xla::XlaOp boxes_sorted = xla::GetTupleElement( + xla::Sort({xla::Broadcast(scores_input, {4}), boxes}, + xla::CreateScalarGtComputation( + {scores_xla_type, boxes_xla_type}, builder), + /*dimension=*/1), + 1); + // Track the mapping of indices into sorted domain. + const xla::XlaOp iota_indices = xla::Iota(builder, xla::S32, num_boxes); + const xla::XlaOp indices_sort = xla::Sort( + {scores_input, iota_indices}, + xla::CreateScalarGtComputation({scores_xla_type, xla::S32}, builder)); + const xla::XlaOp indices_sorted = xla::GetTupleElement(indices_sort, 1); + const xla::XlaOp scores = xla::GetTupleElement(indices_sort, 0); + + // Shapes are henceforth [1, <=num_boxes]. 'c_y0' denotes 'coordinate' y0. + const xla::XlaOp c_y0 = xla::Reshape(xla::SliceInDim(boxes_sorted, + /*start_index=*/0, + /*limit_index=*/1, + /*stride=*/1, + /*dimno=*/0), + {num_boxes}); + const xla::XlaOp c_x0 = xla::Reshape(xla::SliceInDim(boxes_sorted, + /*start_index=*/1, + /*limit_index=*/2, + /*stride=*/1, + /*dimno=*/0), + {num_boxes}); + const xla::XlaOp c_y1 = xla::Reshape(xla::SliceInDim(boxes_sorted, + /*start_index=*/2, + /*limit_index=*/3, + /*stride=*/1, + /*dimno=*/0), + {num_boxes}); + const xla::XlaOp c_x1 = xla::Reshape(xla::SliceInDim(boxes_sorted, + /*start_index=*/3, + /*limit_index=*/4, + /*stride=*/1, + /*dimno=*/0), + {num_boxes}); + + xla::XlaOp y1 = xla::Select(xla::Le(c_y0, c_y1), c_y0, c_y1); + xla::XlaOp y2 = xla::Select(xla::Le(c_y0, c_y1), c_y1, c_y0); + xla::XlaOp x1 = xla::Select(xla::Le(c_x0, c_x1), c_x0, c_x1); + xla::XlaOp x2 = xla::Select(xla::Le(c_x0, c_x1), c_x1, c_x0); + xla::XlaOp area = (y2 - y1) * (x2 - x1); + + // Shapes are henceforth [1, <=num_boxes]. + y1 = xla::Broadcast(y1, {1}); + y2 = xla::Broadcast(y2, {1}); + x1 = xla::Broadcast(x1, {1}); + x2 = xla::Broadcast(x2, {1}); + area = xla::Broadcast(area, {1}); + + // Shapes are henceforth [<=num_boxes, <=num_boxes]. + xla::XlaOp i_xmin = xla::Max(x1, xla::Transpose(x1, {1, 0})); + xla::XlaOp i_ymin = xla::Max(y1, xla::Transpose(y1, {1, 0})); + xla::XlaOp i_xmax = xla::Min(x2, xla::Transpose(x2, {1, 0})); + xla::XlaOp i_ymax = xla::Min(y2, xla::Transpose(y2, {1, 0})); + auto square_zero = xla::ZerosLike(i_xmin); + + xla::XlaOp i_area = xla::Max(i_xmax - i_xmin, square_zero) * + xla::Max(i_ymax - i_ymin, square_zero); + xla::XlaOp u_area = area + xla::Transpose(area, {1, 0}) - i_area; + xla::XlaOp iou = i_area / u_area; + + xla::XlaOp iou_thresh_mask = xla::Gt(iou, iou_thresh + square_zero); + xla::XlaOp included_iou = + xla::Broadcast(xla::ConstantR0(builder, true), {num_boxes}); + + auto iou_shape_or = builder->GetShape(iou_thresh_mask); + OP_REQUIRES_OK(context, iou_shape_or.status()); + auto boxes_runtime_size = xla::GetDimensionSize(iou_thresh_mask, 1); + if (iou_shape_or.value().is_dynamic_dimension(1)) { + included_iou = xla::SetDimensionSize(included_iou, boxes_runtime_size, 0); + } + + std::vector init_values; + init_values.reserve(4); + init_values.push_back(xla::ConstantR0(builder, 0)); // col_idx + init_values.push_back(xla::ConstantR0(builder, 0)); // num_outputs + init_values.push_back(iou_thresh_mask); + init_values.push_back(included_iou); + + auto suppress_loop_result = + xla::WhileLoopHelper(WhileCondFn(num_boxes, output_size), + SuppressBodyFn(num_boxes), init_values, + "suppress_loop", builder) + .value(); + + xla::XlaOp included_score = + xla::Gt(scores, xla::Broadcast(score_thresh, {num_boxes})); + xla::XlaOp included = xla::And(included_score, suppress_loop_result[3]); + + // Only consider boxes over which we have iterated. This allows for accurate + // counting. DynamicSlice would require knowledge of the size of the output. + auto valid_elem = xla::Lt( + iota_indices, xla::Broadcast(suppress_loop_result[0], {num_boxes})); + included = xla::And(included, valid_elem); + + xla::XlaOp neg_inf = + xla::Broadcast(xla::MinValue(builder, boxes_xla_type), {num_boxes}); + xla::XlaOp scores_included = xla::Select(included, scores, neg_inf); + xla::XlaOp output_tuple = TopK(scores_included, output_size); + xla::XlaOp selected_indices_sorted = xla::GetTupleElement(output_tuple, 1); + // Calculate num_valid. + // Note: num_valid cannot be taken from the loop outputs, because outputs + // can be suppressed by score threshold. + xla::XlaOp ones_included = xla::Select( + included, + xla::Broadcast(xla::ConstantR0(builder, 1), {num_boxes}), + xla::Broadcast(xla::ConstantR0(builder, 0), {num_boxes})); + // num_valid is scalar. Value should be bound by output_size. + + xla::XlaOp num_valid_total = xla::Reduce( + ones_included, + /*init_value=*/xla::ConstantR0(builder, 0), + /*computation=*/CreateScalarAddComputation(xla::S32, builder), + /*dimensions_to_reduce=*/{0}); + xla::XlaOp num_valid = xla::Min( + num_valid_total, xla::ConstantR0(builder, output_size)); + + // Re-index into the original scores input tensor, using a Gather. + // Boxes were suppressed in the sorted domain. + xla::XlaOp selected_indices; + DataType gather_type = context->expected_output_dtype(0); + OP_REQUIRES_OK( + context, + XlaGather(indices_sorted, scores_shape, selected_indices_sorted, + TensorShape({output_size}), + /*axis=*/0, + /*indices_are_nd=*/false, + /*dtype=*/gather_type, DT_INT32, builder, &selected_indices)); + + if (!pad_to_max_output_size) { + absl::StatusOr rebounded_result = + xla::SetDimensionSizeWithRebound(&context->value_inference(), + selected_indices, num_valid, 0); + if (rebounded_result.ok()) { + selected_indices = *rebounded_result; + } else { + // TODO(b/207187072): Remove special handling once dynamic reshape + // can also be handled. + selected_indices = + xla::SetDimensionSize(selected_indices, num_valid, 0); + } + } + context->SetOutput(0, selected_indices); + if (pad_to_max_output_size) context->SetOutput(1, num_valid); + } + + private: + bool pad_to_max_output_size_; +}; + +REGISTER_XLA_OP( + Name("NonMaxSuppressionV4").CompileTimeConstantInput("max_output_size"), + NonMaxSuppressionOp); + +class NonMaxSuppressionV3Op : public XlaOpKernel { + public: + explicit NonMaxSuppressionV3Op(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + xla::XlaOp selected_indices, num_valid; + NonMaxSuppressionOp::ComputeResult(context); + } +}; + +REGISTER_XLA_OP( + Name("NonMaxSuppressionV3").CompileTimeConstantInput("max_output_size"), + NonMaxSuppressionV3Op); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_resize_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_resize_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..7b705ce8cf2c9d7424de4fd38e6ce4467620c29a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_resize_ops.cc @@ -0,0 +1,811 @@ +/* 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/kernels/image_resize_ops.h" + +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/jit/xla_activity.pb.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/math/math_util.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// We implement bilinear interpolation by upsampling followed by convolution. +// The basic idea is as follows. To scale from NxN to RxR: +// +// 1. S := (N - 1) / gcd(N-1, R-1) +// 2. k := (R - 1) / gcd(N-1, R-1) +// 3. Convolution((2k-1)x(2k-1), stride=S, lhs_dilation=k, padding=k-1) +// +// For example, to Scale from 7x7 -> 15x15: +// +// 1. S := (7-1) / gcd(7-1, 15-1) = 6 / gcd(6, 14) = 6 / 2 = 3 +// 2. k := (15 - 1) / gcd(7-1, 15-1) = 14 / gcd(6, 14) = 14 / 2 = 7 +// 3. Convolution(15x15, stride=3, lhs_dilation=7, padding=2) +// +// +// The 7x7 -> 15x15 case is much too large to write out in full as an +// example. The smallest interesting example is 3x3 -> 4x4. +// +// S := 2 +// k := 3 +// +// 00 03 06 00 00 00 00 00 00 00 00 00 00 00 00 02 04 06 +// 09 12 15 -> 00 00 00 00 00 00 00 00 00 00 00 -> 06 08 10 12 +// 18 21 24 00 00 00 00 00 03 00 00 06 00 00 12 14 16 18 +// 00 00 00 00 00 00 00 00 00 00 00 18 20 22 24 +// 00 00 00 00 00 00 00 00 00 00 00 +// 00 00 09 00 00 12 00 00 15 00 00 +// 00 00 00 00 00 00 00 00 00 00 00 +// 00 00 00 00 00 00 00 00 00 00 00 +// 00 00 18 00 00 21 00 00 24 00 00 +// 00 00 00 00 00 00 00 00 00 00 00 +// 00 00 00 00 00 00 00 00 00 00 00 +// +// with the following convolutional kernel, with stride [2, 2]: +// 1 2 3 2 1 +// 2 4 6 4 2 +// 1/9 * 3 6 9 6 3 +// 2 4 6 4 2 +// 1 2 3 2 1 +// Note that the convolution kernel matrix is separable and thus we can instead +// use 2 consecutive 1D kernel of the dimension 2k-1, along each axis. + +// Computes the size of the convolutional kernel and stride to use when resizing +// from in_size to out_size. +struct ResizeConvolutionDims { + // Size of the kernel to use. + std::vector kernel_size; // k + + // Stride of the convolution to use. + std::vector stride; // S +}; +ResizeConvolutionDims ComputeResizeConvolutionParameters( + absl::Span in_size, absl::Span out_size, + bool align_corners) { + CHECK_EQ(in_size.size(), out_size.size()); + int num_spatial_dims = in_size.size(); + ResizeConvolutionDims dims; + dims.kernel_size.resize(num_spatial_dims); + dims.stride.resize(num_spatial_dims); + for (int i = 0; i < num_spatial_dims; ++i) { + if (in_size[i] == 1) { + // We must handle input size 1 specially because XLA convolution does + // not allow stride 0. + dims.stride[i] = dims.kernel_size[i] = 1; + } else if (out_size[i] == 1) { + // If in_size[i] > 1 but out_size[i] == 1, then we slice out the first + // entry before resizing. + dims.stride[i] = dims.kernel_size[i] = 1; + } else { + // The scaling factor changes depending on the alignment of corners. + const int64_t in_size_factor = + align_corners ? in_size[i] - 1 : in_size[i]; + const int64_t out_size_factor = + align_corners ? out_size[i] - 1 : out_size[i]; + + int64_t gcd = MathUtil::GCD(static_cast(in_size_factor), + static_cast(out_size_factor)); + dims.stride[i] = in_size_factor / gcd; + dims.kernel_size[i] = out_size_factor / gcd; + } + } + return dims; +} + +// The upper padding of the input needed by ConvGeneralDilated calls is +// determined by solving two related relationships (assuming rhs_dilation == 0): +// 1. dilated_input_dim = lower_padding + upper_padding +// + lhs_dilation * (in_size - 1) + 1 +// 2. dilated_input_dim = (2 * dims.kernel-size - 1) +// + dims.stride * (out_size - 1) +int64_t CalculateUpperPadding(int64_t in_size, int64_t out_size, + int64_t kernel_size, int64_t stride) { + int64_t padding = (2 * kernel_size - 1) + (out_size - 1) * stride - + (kernel_size - 1) - 1 - (kernel_size * (in_size - 1)); + + return padding; +} + +// Form a 2D convolution kernel like: +// 1 2 3 2 1 +// 2 4 6 4 2 +// 1/9 * 3 6 9 6 3 +// 2 4 6 4 2 +// 1 2 3 2 1 +// by multiplying two 1D kernels of the form: +// 1/3 * [1 2 3 2 1] +// If the 2D kernel would be very large, the 1D kernel can be applied once in +// each dimension due to the symmetry of the kernel along all axis to reduce the +// computational intensity. +xla::XlaOp MakeBilinear1DKernel(xla::XlaBuilder* builder, + xla::PrimitiveType type, int64_t n) { + std::vector kernel(n * 2 - 1); + for (int64_t i = 0; i < n; ++i) { + float v = (i + 1.0f) / n; + kernel[i] = v; + kernel[n * 2 - 2 - i] = v; + } + return xla::ConvertElementType(xla::ConstantR1(builder, kernel), type); +} + +// Unlike the bilinear kernel, which is triangular, the nearest neighbor +// kernel is a square. For example, a 1D kernel with n=3 would look like +// [0 1 1 1 0] +// and n=4 would look like +// [0 0 1 1 1 1 0]. +// Note that in the second case, the kernel is not symmetric and we default +// to the right (because an existing non TPU kernel +// for nearest neighbor resize already chose to default to the right, +// so we want to be consistent). +xla::XlaOp MakeNearestNeighbor1DKernel(xla::XlaBuilder* builder, + xla::PrimitiveType type, int64_t n) { + std::vector kernel(n * 2 - 1, 0.0f); + std::fill(&kernel[n / 2], &kernel[(3 * n) / 2], 1.0f); + + return xla::ConvertElementType(xla::ConstantR1(builder, kernel), type); +} + +// Kernels with more than 16 spatial elements are considered intense and the +// kernel should be applied to each dimension independently. +const int64_t kMax2DKernelSize = 16; + +xla::XlaOp MakeGeneralResizeKernel(xla::XlaBuilder* builder, + xla::PrimitiveType type, + absl::Span kernel_size, + int64_t channels, bool is_kernel_bilinear) { + auto make_kernel_func = + is_kernel_bilinear ? MakeBilinear1DKernel : MakeNearestNeighbor1DKernel; + + std::vector depthwise_kernel_sizes = { + (2 * kernel_size[0] - 1), (2 * kernel_size[1] - 1), channels, 1}; + auto depthwise_kernel = + xla::BroadcastInDim(make_kernel_func(builder, type, kernel_size[1]), + depthwise_kernel_sizes, /*broadcast_dimensions=*/{1}); + + return xla::Mul(depthwise_kernel, + make_kernel_func(builder, type, kernel_size[0]), + /*broadcast_dimensions=*/{0}); +} + +xla::XlaOp MakeGeneralResizeKernelInDim(xla::XlaBuilder* builder, + xla::PrimitiveType type, + absl::Span kernel_size, + int64_t channels, int64_t dim, + bool is_kernel_bilinear) { + auto make_kernel_func = + is_kernel_bilinear ? MakeBilinear1DKernel : MakeNearestNeighbor1DKernel; + + std::vector depthwise_kernel_sizes = { + dim == 0 ? (2 * kernel_size[0] - 1) : 1, + dim == 1 ? (2 * kernel_size[1] - 1) : 1, channels, 1}; + return xla::BroadcastInDim(make_kernel_func(builder, type, kernel_size[dim]), + depthwise_kernel_sizes, + /*broadcast_dimensions=*/{dim}); +} + +xla::XlaOp BroadcastSpatialDimensions(xla::XlaBuilder* builder, + const xla::XlaOp input, + int32_t spatial_dimensions_offset, + absl::Span in_size, + absl::Span out_size) { + // Add broadcasts to handle expanding from a size == 1 dimension to a + // size > 1 dimension. + auto broadcast_shape_or_status = builder->GetShape(input); + if (!broadcast_shape_or_status.ok()) { + return builder->ReportError(broadcast_shape_or_status.status()); + } + xla::Shape broadcast_shape = broadcast_shape_or_status.value(); + for (int32_t i = 0; i < in_size.size(); ++i) { + if (in_size[i] == 1 && out_size[i] > 1) { + broadcast_shape.set_dimensions(spatial_dimensions_offset + i, + out_size[i]); + } + } + return xla::BroadcastInDim(input, broadcast_shape.dimensions(), + /*broadcast_dimensions=*/{0, 1, 2, 3}); +} + +xla::XlaOp ResizeUsingDilationAndConvolutionGradOp( + xla::XlaBuilder* builder, const xla::XlaOp grad, xla::PrimitiveType type, + const int num_spatial_dims, absl::Span in_size, + absl::Span grad_size, const int64_t channels, + const bool align_corners, bool is_kernel_bilinear) { + ResizeConvolutionDims dims = + ComputeResizeConvolutionParameters(in_size, grad_size, align_corners); + + // To form the backward convolution, we keep the kernel unchanged (it is + // already symmetric) and swap the roles of strides and LHS dilation. + xla::ConvolutionDimensionNumbers dimension_numbers; + dimension_numbers.set_input_batch_dimension(0); + dimension_numbers.set_output_batch_dimension(0); + dimension_numbers.set_input_feature_dimension(num_spatial_dims + 1); + dimension_numbers.set_output_feature_dimension(num_spatial_dims + 1); + for (int i = 0; i < num_spatial_dims; ++i) { + dimension_numbers.add_input_spatial_dimensions(i + 1); + dimension_numbers.add_output_spatial_dimensions(i + 1); + dimension_numbers.add_kernel_spatial_dimensions(i); + } + dimension_numbers.set_kernel_input_feature_dimension(num_spatial_dims + 1); + dimension_numbers.set_kernel_output_feature_dimension(num_spatial_dims); + xla::XlaOp output; + if (dims.kernel_size[0] * dims.kernel_size[1] < kMax2DKernelSize) { + xla::XlaOp kernel = MakeGeneralResizeKernel(builder, type, dims.kernel_size, + channels, is_kernel_bilinear); + + // Broadcast the input kernel where the forward op expanded from a size == 1 + // dimension to a size > 1 dimension. This has the effect of summing the + // gradient contributions in that dimension. + kernel = BroadcastSpatialDimensions( + builder, kernel, /*spatial_dimensions_offset=*/0, in_size, grad_size); + + output = xla::ConvGeneralDilated( + grad, kernel, /*window_strides=*/dims.kernel_size, + /*padding=*/ + {{dims.kernel_size[0] - 1, dims.kernel_size[0] - 1}, + {dims.kernel_size[1] - 1, dims.kernel_size[1] - 1}}, + /*lhs_dilation=*/dims.stride, + /*rhs_dilation=*/{1, 1}, dimension_numbers, + /*feature_group_count=*/channels); + } else { + xla::XlaOp kernel0 = MakeGeneralResizeKernelInDim( + builder, type, dims.kernel_size, channels, 0, is_kernel_bilinear); + xla::XlaOp kernel1 = MakeGeneralResizeKernelInDim( + builder, type, dims.kernel_size, channels, 1, is_kernel_bilinear); + + // Broadcast the input kernel where the forward op expanded from a + // size == 1 dimension to a size > 1 dimension. This has the effect of + // summing the gradient contributions in that dimension. + if (in_size[0] == 1 && grad_size[0] > 1) { + kernel0 = BroadcastSpatialDimensions(builder, kernel0, + /*spatial_dimensions_offset=*/0, {1}, + {grad_size[0]}); + } + if (in_size[1] == 1 && grad_size[1] > 1) { + kernel1 = BroadcastSpatialDimensions(builder, kernel0, + /*spatial_dimensions_offset=*/0, + in_size, grad_size); + } + + output = xla::ConvGeneralDilated( + grad, kernel0, /*window_strides=*/{dims.kernel_size[0], 1}, + /*padding=*/ + {{dims.kernel_size[0] - 1, dims.kernel_size[0] - 1}, {0, 0}}, + /*lhs_dilation=*/{dims.stride[0], 1}, + /*rhs_dilation=*/{1, 1}, dimension_numbers, + /*feature_group_count=*/channels); + + output = xla::ConvGeneralDilated( + output, kernel1, /*window_strides=*/{1, dims.kernel_size[1]}, + /*padding=*/ + {{0, 0}, {dims.kernel_size[1] - 1, dims.kernel_size[1] - 1}}, + /*lhs_dilation=*/{1, dims.stride[1]}, + /*rhs_dilation=*/{1, 1}, dimension_numbers, + /*feature_group_count=*/channels); + } + + // If in_size[i] > 1 and grad_size[i] == 1, pad the output in dimension i. + // Opposite of the slice performed by the forward op. + xla::PaddingConfig padding = xla::MakeNoPaddingConfig(4); + bool pad_output = false; + for (int i = 0; i < num_spatial_dims; ++i) { + if (in_size[i] > 1 && grad_size[i] == 1) { + pad_output = true; + padding.mutable_dimensions(1 + i)->set_edge_padding_high(in_size[i] - 1); + } + } + if (pad_output) { + output = xla::Pad(output, xla::Zero(builder, type), padding); + } + return output; +} + +void MakeAddCombiner(xla::PrimitiveType type, + xla::XlaComputation& combiner_computation) { + xla::XlaBuilder cb("image-resize-grad-combiner"); + auto xla_scalar_shape = xla::ShapeUtil::MakeShape(type, {}); + auto p0 = xla::Parameter(&cb, 0, xla_scalar_shape, "p0"); + auto p1 = xla::Parameter(&cb, 1, xla_scalar_shape, "p1"); + xla::Add(p0, p1); + combiner_computation = cb.Build().value(); +} + +// Create the constant weight tensors for `GeneralCompile`/`GeneralCompileGrad`. +// `GeneralCompileGrad` is the reverse of `GeneralCompile` so they can share the +// same constant weights for their substeps. `concatted` is the weight used by +// Gather/Scatter. `dot_weights` is the weight used by DotGeneral. +void GeneralCompileWeights(XlaOpKernelContext* ctx, bool align_corners, + bool half_pixel_centers, bool is_kernel_bilinear, + xla::PrimitiveType input_type, DataType output_dtype, + const int64_t batch, std::vector in_size, + const int64_t channels, + std::vector out_size, int64_t& h_span_size, + int64_t& w_span_size, xla::XlaOp& concatted, + xla::XlaOp& dot_weights) { + xla::XlaBuilder* b = ctx->builder(); + + xla::XlaOp scalar_one_op = + xla::ConvertElementType(xla::ConstantR0(b, 1), input_type); + xla::XlaOp scalar_half_op = + xla::ConvertElementType(xla::ConstantR0(b, 0.5), input_type); + xla::XlaOp scalar_zero_op = + xla::ConvertElementType(xla::ConstantR0(b, 0), input_type); + float h_scale; + if (align_corners && out_size[0] > 1) { + h_scale = (in_size[0] - 1) / static_cast(out_size[0] - 1); + } else { + h_scale = in_size[0] / static_cast(out_size[0]); + } + xla::XlaOp h_span_start = + xla::Iota(b, xla::ShapeUtil::MakeShape(input_type, {out_size[0]}), 0); + if (half_pixel_centers) { + h_span_start = xla::Add(h_span_start, scalar_half_op); + } + xla::XlaOp h_scale_op = + xla::ConvertElementType(xla::ConstantR0(b, h_scale), input_type); + xla::XlaOp h_sample_f = xla::Mul(h_span_start, h_scale_op); + + if (is_kernel_bilinear) { + h_span_start = xla::Sub(h_sample_f, scalar_one_op); + if (half_pixel_centers) { + h_span_start = xla::Sub(h_span_start, scalar_half_op); + } + h_span_start = xla::Ceil(h_span_start); + } else { + h_span_start = + align_corners ? xla::Round(h_sample_f) : xla::Floor(h_sample_f); + } + h_span_size = + is_kernel_bilinear ? std::min(static_cast(3), in_size[0]) : 1; + xla::XlaOp h_upper_bound = xla::ConvertElementType( + xla::ConstantR0(b, in_size[0] - h_span_size), input_type); + if (!is_kernel_bilinear && !half_pixel_centers) { + h_span_start = xla::Min(h_span_start, h_upper_bound); + } else { + h_span_start = xla::Clamp(scalar_zero_op, h_span_start, h_upper_bound); + } + xla::XlaOp broadcasted_h_span_start = + xla::BroadcastInDim(h_span_start, {out_size[0], out_size[1], 1}, {0}); + + float w_scale; + if (align_corners && out_size[1] > 1) { + w_scale = (in_size[1] - 1) / static_cast(out_size[1] - 1); + } else { + w_scale = in_size[1] / static_cast(out_size[1]); + } + xla::XlaOp w_span_start = + xla::Iota(b, xla::ShapeUtil::MakeShape(input_type, {out_size[1]}), 0); + if (half_pixel_centers) { + w_span_start = xla::Add(w_span_start, scalar_half_op); + } + xla::XlaOp w_scale_op = + xla::ConvertElementType(xla::ConstantR0(b, w_scale), input_type); + xla::XlaOp w_sample_f = xla::Mul(w_span_start, w_scale_op); + if (is_kernel_bilinear) { + w_span_start = xla::Sub(w_sample_f, scalar_one_op); + if (half_pixel_centers) { + w_span_start = xla::Sub(w_span_start, scalar_half_op); + } + w_span_start = xla::Ceil(w_span_start); + } else { + w_span_start = + align_corners ? xla::Round(w_sample_f) : xla::Floor(w_sample_f); + } + w_span_size = + is_kernel_bilinear ? std::min(static_cast(3), in_size[1]) : 1; + xla::XlaOp w_upper_bound = xla::ConvertElementType( + xla::ConstantR0(b, in_size[1] - w_span_size), input_type); + if (!is_kernel_bilinear && !half_pixel_centers) { + w_span_start = xla::Min(w_span_start, w_upper_bound); + } else { + w_span_start = xla::Clamp(scalar_zero_op, w_span_start, w_upper_bound); + } + xla::XlaOp broadcasted_w_span_start = + xla::BroadcastInDim(w_span_start, {out_size[0], out_size[1], 1}, {1}); + + concatted = xla::ConvertElementType( + xla::ConcatInDim(b, {broadcasted_h_span_start, broadcasted_w_span_start}, + 2), + xla::S32); + + xla::XlaOp w_weight; + if (is_kernel_bilinear) { + xla::XlaOp w_sub = xla::Sub(w_span_start, w_sample_f); + w_sub = xla::BroadcastInDim(w_sub, {out_size[1], w_span_size}, {0}); + xla::XlaOp w_offset = + xla::Iota(b, xla::ShapeUtil::MakeShape(input_type, {w_span_size}), 0); + xla::XlaOp w_kernel_pos = xla::Add(w_sub, w_offset, {1}); + if (half_pixel_centers) { + w_kernel_pos = xla::Add(w_kernel_pos, scalar_half_op); + } + w_weight = xla::Max(scalar_zero_op, + xla::Sub(scalar_one_op, xla::Abs(w_kernel_pos))); + } else { + w_weight = xla::Broadcast(scalar_one_op, {out_size[1], w_span_size}); + } + xla::XlaOp w_weight_sum = xla::Reduce( + w_weight, scalar_zero_op, *ctx->GetOrCreateAdd(output_dtype), {1}); + w_weight = xla::Div(w_weight, w_weight_sum, {0}); + + xla::XlaOp h_weight; + if (is_kernel_bilinear) { + xla::XlaOp h_sub = xla::Sub(h_span_start, h_sample_f); + h_sub = xla::BroadcastInDim(h_sub, {out_size[0], h_span_size}, {0}); + xla::XlaOp h_offset = + xla::Iota(b, xla::ShapeUtil::MakeShape(input_type, {h_span_size}), 0); + xla::XlaOp h_kernel_pos = xla::Add(h_sub, h_offset, {1}); + if (half_pixel_centers) { + h_kernel_pos = xla::Add(h_kernel_pos, scalar_half_op); + } + h_weight = xla::Max(scalar_zero_op, + xla::Sub(scalar_one_op, xla::Abs(h_kernel_pos))); + } else { + h_weight = xla::Broadcast(scalar_one_op, {out_size[0], h_span_size}); + } + xla::XlaOp h_weight_sum = xla::Reduce( + h_weight, scalar_zero_op, *ctx->GetOrCreateAdd(output_dtype), {1}); + h_weight = xla::Div(h_weight, h_weight_sum, {0}); + + dot_weights = xla::DotGeneral(w_weight, h_weight, xla::DotDimensionNumbers()); +} + +void GeneralCompile(XlaOpKernelContext* ctx, bool align_corners, + bool half_pixel_centers, bool is_kernel_bilinear) { + // We implement bilinear interpolation and nearest neighbor with a Gather op. + // For each output pixel, we gather the necessary slices of the input. + // We then construct the weights that are necessary to calculate the weighted + // sum for each output pixel. We do this with a DotGeneral op. + + TensorShape input_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, input_shape.dims() == 4, + absl::InvalidArgumentError(absl::StrCat( + "input must be 4-dimensional", input_shape.DebugString()))); + // First dimension always assumed to be batch + const int64_t batch = input_shape.dim_size(0); + std::vector in_size = {input_shape.dim_size(1), + input_shape.dim_size(2)}; + // Last/4th dimension always assumed to be num channels + const int64_t channels = input_shape.dim_size(3); + OP_REQUIRES(ctx, in_size[0] > 0 && in_size[1] > 0, + absl::InvalidArgumentError( + absl::StrCat("input size must be positive, got [", in_size[0], + ",", in_size[1], "]"))); + + std::vector out_size; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &out_size)); + OP_REQUIRES(ctx, out_size.size() == 2, + absl::InvalidArgumentError(absl::StrCat( + "output size must be length 2, got ", out_size.size()))); + OP_REQUIRES(ctx, out_size[0] > 0 && out_size[1] > 0, + absl::InvalidArgumentError( + absl::StrCat("output size must be positive, got [", + out_size[0], ",", out_size[1], "]"))); + + xla::XlaOp input = ctx->Input(0); + xla::PrimitiveType input_type = ctx->input_xla_type(0); + xla::PrimitiveType original_input_type = input_type; + if (is_kernel_bilinear || xla::primitive_util::IsIntegralType(input_type)) { + input = xla::ConvertElementType(input, xla::F32); + input_type = xla::F32; + } + DataType output_dtype = EncodePrimitiveTypeAsDataType(input_type).value(); + + int64_t h_span_size, w_span_size; + xla::XlaOp concatted; + xla::XlaOp dot_weights; + GeneralCompileWeights(ctx, align_corners, half_pixel_centers, + is_kernel_bilinear, input_type, output_dtype, batch, + in_size, channels, out_size, h_span_size, w_span_size, + concatted, dot_weights); + + xla::GatherDimensionNumbers dimension_numbers; + dimension_numbers.add_offset_dims(0); + dimension_numbers.add_offset_dims(1); + dimension_numbers.add_offset_dims(2); + dimension_numbers.add_offset_dims(3); + dimension_numbers.add_start_index_map(1); + dimension_numbers.add_start_index_map(2); + dimension_numbers.set_index_vector_dim(2); + absl::InlinedVector slice_sizes = {batch, h_span_size, + w_span_size, channels}; + input = xla::Gather(input, concatted, dimension_numbers, slice_sizes, false); + + xla::DotDimensionNumbers dot_dnum; + dot_dnum.add_lhs_contracting_dimensions(3); + dot_dnum.add_lhs_contracting_dimensions(1); + dot_dnum.add_rhs_contracting_dimensions(1); + dot_dnum.add_rhs_contracting_dimensions(2); + dot_dnum.add_lhs_batch_dimensions(2); + dot_dnum.add_lhs_batch_dimensions(0); + dot_dnum.add_rhs_batch_dimensions(4); + dot_dnum.add_rhs_batch_dimensions(5); + input = xla::DotGeneral(dot_weights, input, dot_dnum); + + absl::InlinedVector perm = {2, 0, 1, 3}; + input = xla::Transpose(input, perm); + + if (!is_kernel_bilinear && original_input_type != input_type) { + input = xla::ConvertElementType(input, original_input_type); + } + ctx->SetOutput(0, input); +} + +// `GeneralCompileGrad` reverses `GeneralCompile`. It does `DotGeneral` then +// `Scatter` to reverse `Gather` then `DotGeneral`. +void GeneralCompileGrad(XlaOpKernelContext* ctx, bool align_corners, + bool half_pixel_centers, bool is_kernel_bilinear, + const int64_t batch, const std::vector in_size, + const int64_t channels, + const std::vector out_size) { + xla::XlaBuilder* b = ctx->builder(); + + xla::XlaOp grad = ctx->Input(0); + xla::PrimitiveType grad_type = ctx->input_xla_type(0); + xla::PrimitiveType original_grad_type = grad_type; + if (is_kernel_bilinear || xla::primitive_util::IsIntegralType(grad_type)) { + grad = xla::ConvertElementType(grad, xla::F32); + grad_type = xla::F32; + } + DataType output_dtype = EncodePrimitiveTypeAsDataType(grad_type).value(); + + int64_t h_span_size, w_span_size; + xla::XlaOp concatted; + xla::XlaOp dot_weights; + GeneralCompileWeights(ctx, align_corners, half_pixel_centers, + is_kernel_bilinear, grad_type, output_dtype, batch, + in_size, channels, out_size, h_span_size, w_span_size, + concatted, dot_weights); + + // Reverse the forward direction's DotGeneral. + // `dot_weights` has dimensions + // {out_size[1], kernel_width, out_size[0], kernel_height} + // Before this step `grad` has dimensions + // {batch, out_size[0], out_size[1], channel} + // After this step `grad` has dimensions + // {out_size[0], out_size[1], kernel_width, kernel_height, batch, channel} + xla::DotDimensionNumbers dot_dnum; + dot_dnum.add_lhs_batch_dimensions(2); + dot_dnum.add_lhs_batch_dimensions(0); + dot_dnum.add_rhs_batch_dimensions(1); + dot_dnum.add_rhs_batch_dimensions(2); + grad = xla::DotGeneral(dot_weights, grad, dot_dnum); + int dot_out_size_height_index = 0; + int dot_out_size_width_index = 1; + int dot_kernel_width_index = 2; + int dot_kernel_height_index = 3; + int dot_batch_index = 4; + int dot_channel_index = 5; + + // Transpose DotGeneral result's dimensions to be the same order as the + // forward direction's input to DotGeneral. This is needed because the + // backward's Scatter's input has the same order as the forward's Gather + // output. + // After this step `grad` has dimensions + // {batch, kernel_height, kernel_width, channel, out_size[0], out_size[1]} + absl::InlinedVector perm = { + dot_batch_index, dot_kernel_height_index, dot_kernel_width_index, + dot_channel_index, dot_out_size_height_index, dot_out_size_width_index}; + grad = xla::Transpose(grad, perm); + + // A Scatter reverses the forward op's Gather. Gather can be thought of as a + // matrix-vector multiply where each row has one 1 and the rest 0. The + // reversing Scatter does the transposed matrix-vector multiply. + // `scatter_dest_zeros` has dimensions + // {batch, in_size[0], in_size[1], channel} + // `concatted` has dimensions {out_size[0], out_size[1], image_indices} + // `update_window_dims` are {batch, kernel_height, kernel_width, channel} + // `scatter_dims_to_operand_dims` are {kernel_height, kernel_width} + // `index_vector_dim` is the index of image_indices in `concatted`. + // After this step `grad` has dimensions + // {batch, in_size[0], out_size[0], channel} + absl::InlinedVector slice_sizes = {batch, in_size[0], in_size[1], + channels}; + xla::ScatterDimensionNumbers dimension_numbers; + dimension_numbers.add_update_window_dims(0); + dimension_numbers.add_update_window_dims(1); + dimension_numbers.add_update_window_dims(2); + dimension_numbers.add_update_window_dims(3); + dimension_numbers.add_scatter_dims_to_operand_dims(1); + dimension_numbers.add_scatter_dims_to_operand_dims(2); + dimension_numbers.set_index_vector_dim(2); + xla::XlaOp scatter_dest_zeros = xla::Broadcast( + xla::ConvertElementType(xla::ConstantR0(b, 0), grad_type), slice_sizes); + // A matrix-vector multiply's combining function is Add. + xla::XlaComputation combiner_computation; + MakeAddCombiner(grad_type, combiner_computation); + grad = xla::Scatter(scatter_dest_zeros, /*scatter_indices=*/concatted, grad, + combiner_computation, dimension_numbers, + /*indices_are_sorted=*/false, /*unique_indices=*/false); + + if (!is_kernel_bilinear && original_grad_type != grad_type) { + grad = xla::ConvertElementType(grad, original_grad_type); + } + ctx->SetOutput(0, grad); +} + +// Compile ResizeBilinearGrad via reduction to convolution with dilation. +void DilationAndConvolutionCompileGrad(XlaOpKernelContext* ctx, + bool align_corners, + xla::PrimitiveType output_type, + std::vector in_size, + const int64_t channels, + const std::vector grad_size) { + xla::XlaBuilder* b = ctx->builder(); + + const int num_spatial_dims = 2; + + xla::XlaOp grad = ctx->Input(0); + + xla::XlaOp output = grad; + while (in_size != grad_size) { + if (in_size[0] != 1 && in_size[1] != 1) { + std::vector k = { + (static_cast(grad_size[0]) - 1) / ((in_size[0] - 1) * 2), + (static_cast(grad_size[1]) - 1) / ((in_size[1] - 1) * 2)}; + if ((k[0] == std::floor(k[0])) && (k[1] == std::floor(k[1])) && + k[0] > 1 && k[1] > 1) { + std::vector next_grad_size = {(in_size[0] - 1) * 2 + 1, + (in_size[1] - 1) * 2 + 1}; + // TODO(b/288101036): Fix bug that mixes up the iteration order of + // `next_grad_size`, `in_size`, and `grad`. The easiest way to fix + // this is to use `GeneralCompileGrad` instead. Note that the trace of + // `in_size` over iterations does not reverse the forward ops order. + output = ResizeUsingDilationAndConvolutionGradOp( + b, grad, xla::F32, num_spatial_dims, in_size, next_grad_size, + channels, align_corners, true); + grad = output; + in_size = next_grad_size; + } else { + output = ResizeUsingDilationAndConvolutionGradOp( + b, grad, xla::F32, num_spatial_dims, in_size, grad_size, channels, + align_corners, true); + in_size = grad_size; + } + } else { + output = ResizeUsingDilationAndConvolutionGradOp( + b, grad, xla::F32, num_spatial_dims, in_size, grad_size, channels, + align_corners, true); + in_size = grad_size; + } + } + + output = xla::ConvertElementType(output, output_type); + ctx->SetOutput(0, output); +} + +} // namespace + +ResizeNearestNeighborOp::ResizeNearestNeighborOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("align_corners", &align_corners_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("half_pixel_centers", &half_pixel_centers_)); + OP_REQUIRES(ctx, !half_pixel_centers_ || !align_corners_, + absl::UnimplementedError("If half_pixel_centers is True, " + "align_corners must be False.")); +} + +void ResizeNearestNeighborOp::Compile(XlaOpKernelContext* ctx) { + GeneralCompile(ctx, align_corners_, half_pixel_centers_, is_kernel_bilinear_); +} + +REGISTER_XLA_OP(Name("ResizeNearestNeighbor").CompileTimeConstantInput("size"), + ResizeNearestNeighborOp); + +ResizeBilinearOp::ResizeBilinearOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("align_corners", &align_corners_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("half_pixel_centers", &half_pixel_centers_)); + OP_REQUIRES(ctx, !half_pixel_centers_ || !align_corners_, + absl::UnimplementedError("If half_pixel_centers is True, " + "align_corners must be False.")); +} + +void ResizeBilinearOp::Compile(XlaOpKernelContext* ctx) { + GeneralCompile(ctx, align_corners_, half_pixel_centers_, is_kernel_bilinear_); +} + +REGISTER_XLA_OP(Name("ResizeBilinear").CompileTimeConstantInput("size"), + ResizeBilinearOp); + +ResizeBilinearGradOp::ResizeBilinearGradOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("align_corners", &align_corners_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("half_pixel_centers", &half_pixel_centers_)); + OP_REQUIRES(ctx, !half_pixel_centers_ || !align_corners_, + absl::UnimplementedError("If half_pixel_centers is True, " + "align_corners must be False.")); + DataType output_dtype; + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &output_dtype)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(output_dtype, &output_type_)); +} + +void ResizeBilinearGradOp::Compile(XlaOpKernelContext* ctx) { + TensorShape input_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, input_shape.dims() == 4, + absl::InvalidArgumentError(absl::StrCat( + "input must be 4-dimensional", input_shape.DebugString()))); + const int64_t batch = input_shape.dim_size(0); + std::vector in_size = {input_shape.dim_size(1), + input_shape.dim_size(2)}; + const int64_t channels = input_shape.dim_size(3); + OP_REQUIRES(ctx, in_size[0] > 0 && in_size[1] > 0, + absl::InvalidArgumentError( + absl::StrCat("input size must be positive, got [", in_size[0], + ",", in_size[1], "]"))); + + TensorShape grad_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, grad_shape.dims() == 4, + absl::InvalidArgumentError(absl::StrCat( + "gradient must be 4-dimensional", grad_shape.DebugString()))); + const int64_t grad_batch = grad_shape.dim_size(0); + const std::vector grad_size = {grad_shape.dim_size(1), + grad_shape.dim_size(2)}; + const int64_t grad_channels = grad_shape.dim_size(3); + OP_REQUIRES(ctx, batch == grad_batch, + absl::InvalidArgumentError(absl::StrCat( + "activations and gradients must have the same batch size (", + batch, " vs. ", grad_batch, ")"))); + OP_REQUIRES(ctx, grad_size[0] > 0 && grad_size[1] > 0, + absl::InvalidArgumentError( + absl::StrCat("gradient size must be positive, got [", + grad_size[0], ",", grad_size[1], "]"))); + OP_REQUIRES( + ctx, channels == grad_channels, + absl::InvalidArgumentError(absl::StrCat( + "activations and gradients must have the same number of channels (", + channels, " vs. ", grad_channels, ")"))); + + if (half_pixel_centers_ || !align_corners_) { + // TODO(b/288101036): This case also works for half_pixel_centers_=false so + // delete the DilationAndConvolutionCompileGrad case given good performance + // results. + GeneralCompileGrad(ctx, align_corners_, half_pixel_centers_, + /*is_kernel_bilinear=*/true, batch, in_size, channels, + grad_size); + } else { + DilationAndConvolutionCompileGrad(ctx, align_corners_, output_type_, + in_size, channels, grad_size); + } +} + +REGISTER_XLA_OP(Name("ResizeBilinearGrad"), ResizeBilinearGradOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_resize_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_resize_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..3d2fbfde376d08d5547d42df2ea8b24444d96dc0 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/image_resize_ops.h @@ -0,0 +1,62 @@ +/* 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_KERNELS_IMAGE_RESIZE_OPS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_IMAGE_RESIZE_OPS_H_ + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/primitive_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { + +class ResizeNearestNeighborOp : public XlaOpKernel { + public: + explicit ResizeNearestNeighborOp(OpKernelConstruction* ctx); + void Compile(XlaOpKernelContext* ctx) override; + + protected: + bool align_corners_ = true; + bool half_pixel_centers_ = true; + bool is_kernel_bilinear_ = false; +}; + +class ResizeBilinearOp : public XlaOpKernel { + public: + explicit ResizeBilinearOp(OpKernelConstruction* ctx); + + void Compile(XlaOpKernelContext* ctx) override; + + protected: + bool align_corners_ = true; + bool half_pixel_centers_ = true; + bool is_kernel_bilinear_ = true; +}; + +class ResizeBilinearGradOp : public XlaOpKernel { + public: + explicit ResizeBilinearGradOp(OpKernelConstruction* ctx); + + void Compile(XlaOpKernelContext* ctx) override; + + protected: + bool align_corners_; + bool half_pixel_centers_ = true; + xla::PrimitiveType output_type_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_IMAGE_RESIZE_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/in_topk_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/in_topk_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..ad5c923dc76a87ed4329d9a8490f422d7c899f35 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/in_topk_op.cc @@ -0,0 +1,123 @@ +/* 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 + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class InTopKOp : public XlaOpKernel { + public: + explicit InTopKOp(OpKernelConstruction* context) : XlaOpKernel(context) { + OP_REQUIRES_OK(context, context->GetAttr("T", &targets_dtype_)); + OP_REQUIRES_OK(context, + DataTypeToPrimitiveType(targets_dtype_, &targets_type_)); + } + + void Compile(XlaOpKernelContext* context) override { + int64_t k; + OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar(2, &k)); + OP_REQUIRES( + context, k >= 0, + absl::InvalidArgumentError(absl::StrCat("Need k >= 0, got ", k))); + const TensorShape predictions_shape = context->InputShape(0); + OP_REQUIRES(context, predictions_shape.dims() == 2, + absl::InvalidArgumentError( + absl::StrCat("predictions must be == 2-D, got shape ", + predictions_shape.DebugString()))); + const TensorShape targets_shape = context->InputShape(1); + OP_REQUIRES(context, targets_shape.dims() == 1, + absl::InvalidArgumentError( + absl::StrCat("targets must be == 1-D, got shape ", + targets_shape.DebugString()))); + + int64_t batch_size = predictions_shape.dim_size(0); + OP_REQUIRES(context, batch_size == targets_shape.dim_size(0), + absl::InvalidArgumentError(absl::StrCat( + "targets must have same elements as predictions rows. Had ", + targets_shape.dim_size(0), ", needed ", batch_size))); + + // Given `predictions` with shape batch_size*num_classes and `target` with + // shape num_classes, we generate `targets_values_r1` with shape num_classes + // which the elements are the corresponding values of `targets` in + // `predictions` for each example. This step can be done using xla::Gather + // as well. + xla::XlaOp predictions_r2 = context->Input(0); + xla::XlaOp targets_r1 = context->Input(1); + + xla::XlaBuilder* xla_builder = context->builder(); + xla::XlaOp iota_r1 = + xla::Iota(xla_builder, targets_type_, predictions_shape.dim_size(1)); + xla::XlaOp iota_r2 = xla::Broadcast(iota_r1, {batch_size}); + + xla::XlaOp eq_r2 = xla::Eq(targets_r1, iota_r2, {0}); + xla::XlaOp zero_r0_f32 = xla::Zero(xla_builder, xla::F32); + xla::XlaOp zero_r2_f32 = xla::ZerosLike(predictions_r2); + xla::XlaOp select_r2 = xla::Select(eq_r2, predictions_r2, zero_r2_f32); + xla::XlaOp targets_values_r1 = xla::Reduce( + select_r2, zero_r0_f32, + xla::CreateScalarAddComputation(xla::F32, xla_builder), {1}); + + // Calculate in each row of `predictions`, how many values are larger than + // the value of target class. Then return the result whether the count < k, + // which indicates the target is in topk. + xla::XlaOp gt_r2 = xla::Gt(predictions_r2, targets_values_r1, {0}); + xla::XlaOp zero_r0 = xla::Zero(xla_builder, xla::S32); + xla::XlaOp zero_r2 = xla::Broadcast(zero_r0, predictions_shape.dim_sizes()); + xla::XlaOp one_r0 = xla::One(xla_builder, xla::S32); + xla::XlaOp one_r2 = xla::Broadcast(one_r0, predictions_shape.dim_sizes()); + xla::XlaOp one_hot_r2 = xla::Select(gt_r2, one_r2, zero_r2); + xla::XlaOp num_gt_r1 = xla::Reduce( + one_hot_r2, zero_r0, + xla::CreateScalarAddComputation(xla::S32, xla_builder), {1}); + + xla::XlaOp result = + xla::And(xla::Lt(num_gt_r1, xla::ConstantR0(xla_builder, k)), + xla::IsFinite(targets_values_r1)); + + context->SetOutput(0, result); + } + + protected: + DataType targets_dtype_; + xla::PrimitiveType targets_type_; + + InTopKOp(const InTopKOp&) = delete; + void operator=(const InTopKOp&) = delete; +}; + +REGISTER_XLA_OP(Name("InTopKV2") + .CompileTimeConstantInput("k") + .TypeConstraint("T", {DT_INT32, DT_INT64}), + InTopKOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/index_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/index_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..4bcfcd2649dfc67aceeccf9d2f4686b453a70a11 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/index_ops.cc @@ -0,0 +1,93 @@ +/* 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. +==============================================================================*/ + +// Native XLA implementations of indexing ops. + +#include "tensorflow/compiler/tf2xla/kernels/index_ops.h" + +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +XlaArgMinMaxOp::XlaArgMinMaxOp(OpKernelConstruction* ctx, bool is_min) + : XlaOpKernel(ctx), is_min_(is_min) {} + +void XlaArgMinMaxOp::Compile(XlaOpKernelContext* ctx) { + const TensorShape input_shape = ctx->InputShape(0); + const TensorShape dimension_shape = ctx->InputShape(1); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(dimension_shape), + absl::InvalidArgumentError(absl::StrCat( + "dim must be a scalar, but received tensor of shape: ", + dimension_shape.DebugString()))); + + int64_t dim; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &dim)); + + const int input_dims = input_shape.dims(); + const int axis = dim < 0 ? dim + input_dims : dim; + + OP_REQUIRES(ctx, axis >= 0 && axis < input_dims, + absl::InvalidArgumentError( + absl::StrCat("Expected dimension in the range [", -input_dims, + ", ", input_dims, "), but got ", dim))); + const int64_t axis_size = input_shape.dim_size(axis); + OP_REQUIRES(ctx, axis_size > 0, + absl::InvalidArgumentError( + absl::StrCat("Reduction axis ", dim, " is empty in shape ", + input_shape.DebugString()))); + + DataType index_type = output_type(0); + xla::PrimitiveType index_xla_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(index_type, &index_xla_type)); + + xla::XlaOp input = ctx->Input(0); + xla::XlaOp output = + xla::ArgMinMax(input, index_xla_type, axis, /*is_min=*/is_min_); + + ctx->SetOutput(0, output); +} + +XlaArgMaxOp::XlaArgMaxOp(OpKernelConstruction* ctx) + : XlaArgMinMaxOp(ctx, /*is_min=*/false) {} +REGISTER_XLA_OP(Name("ArgMax").CompileTimeConstantInput("dimension"), + XlaArgMaxOp); + +namespace { + +class XlaArgMinOp : public XlaArgMinMaxOp { + public: + explicit XlaArgMinOp(OpKernelConstruction* ctx); +}; +XlaArgMinOp::XlaArgMinOp(OpKernelConstruction* ctx) + : XlaArgMinMaxOp(ctx, /*is_min=*/true) {} +REGISTER_XLA_OP(Name("ArgMin").CompileTimeConstantInput("dimension"), + XlaArgMinOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/index_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/index_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..6e50acb4982842ee0aa8edd470da22208a90d0a4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/index_ops.h @@ -0,0 +1,42 @@ +/* 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. +==============================================================================*/ + +// Declarations of the ArgMax/ArgMin ops using a pure XLA implementation. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_KERNELS_INDEX_OPS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_INDEX_OPS_H_ + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { + +class XlaArgMinMaxOp : public XlaOpKernel { + public: + explicit XlaArgMinMaxOp(OpKernelConstruction* ctx, bool is_min); + void Compile(XlaOpKernelContext* ctx) override; + + private: + const bool is_min_; // Are we computing ArgMin (true) or ArgMax (false)? +}; + +class XlaArgMaxOp : public XlaArgMinMaxOp { + public: + explicit XlaArgMaxOp(OpKernelConstruction* ctx); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_INDEX_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/l2loss_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/l2loss_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..5e4689f72b15e932caeb4c9a82330d340ba7302f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/l2loss_op.cc @@ -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. +==============================================================================*/ + +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class L2LossOp : public XlaOpKernel { + public: + explicit L2LossOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + std::vector dims(ctx->InputShape(0).dims()); + std::iota(dims.begin(), dims.end(), 0); + + DataType dtype = ctx->input_type(0); + xla::XlaBuilder* const b = ctx->builder(); + + // output = sum(t ** 2) / 2 + const DataType accumulation_type = XlaHelpers::SumAccumulationType(dtype); + auto t = XlaHelpers::ConvertElementType(ctx->Input(0), accumulation_type); + auto square = xla::Mul(t, t); + auto reduce = xla::Reduce(square, XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), dims); + auto deconverted = XlaHelpers::ConvertElementType(reduce, dtype); + auto two = XlaHelpers::IntegerLiteral(b, dtype, 2); + ctx->SetOutput(0, xla::Div(deconverted, two)); + } +}; + +REGISTER_XLA_OP(Name("L2Loss"), L2LossOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.cc new file mode 100644 index 0000000000000000000000000000000000000000..370e2a98322889e18fd1426e4af73bf82c02961d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.cc @@ -0,0 +1,739 @@ +/* Copyright 2022 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/kernels/light_outside_compilation.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/base/const_init.h" // NOLINT incorrectly flagged as unused +#include "absl/base/thread_annotations.h" +#include "absl/cleanup/cleanup.h" +#include "absl/container/flat_hash_map.h" +#include "absl/container/inlined_vector.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/memory/memory.h" +#include "absl/status/status.h" +#include "absl/strings/escaping.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_format.h" +#include "absl/strings/str_join.h" +#include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/callback.pb.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/layout_util.h" +#include "xla/service/custom_call_status.h" +#include "xla/service/custom_call_target_registry.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform_manager.h" +#include "xla/stream_executor/stream.h" +#include "xla/stream_executor/stream_finder.h" +#include "xla/tsl/lib/strings/proto_serialization.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "tensorflow/core/common_runtime/gpu/gpu_process_state.h" +#include "tensorflow/core/common_runtime/process_state.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_def_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/platform/fingerprint.h" + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM +#include "tensorflow/core/common_runtime/gpu/gpu_device.h" +#endif + +namespace tensorflow { + +namespace { + +const char* const kTfCallbackCustomCall = "GenericTfCallbackGPU"; + +// Each unique TfCallbackData in a call to Compile() generates a new +// KernelInstantiation. We cache these in a global hashtable, because creating +// OpKernels is expensive. +// +// The KernelInstantiation contains a list of OpKernel+DeviceBase objects. +// These are all equivalent to each other. When we want to run the kernel, we +// "check out" an element from the list, removing it. When we're done, we add +// it back. If there are no available elements in the list, we create one. +struct KernelInstantiation { + static absl::StatusOr> Create( + TfCallbackData callback_data) { + auto instantiation = std::make_unique(); + instantiation->input_shapes.reserve(callback_data.inputs_size()); + for (const auto& input : callback_data.inputs()) { + TensorShape shape; + TF_RETURN_IF_ERROR(TensorShape::BuildTensorShape( + input.buffer_description().shape(), &shape)); + instantiation->input_shapes.push_back(std::move(shape)); + } + instantiation->callback_data = std::move(callback_data); + return instantiation; + } + + // Cache of + // TensorShape::BuildTensorShape( + // callback_data.inputs(i).buffer_description().shape()), + // because calling this for every invocation of the op is expensive. + std::vector input_shapes; + + TfCallbackData callback_data; + + // In order to run an Instantiation, we need a TF OpKernel object. Creating + // one is expensive, so we cache them. When we run an op, we "check out" an + // element from this vector, and then we return it when we're done. + absl::Mutex mu; + std::vector, std::unique_ptr>> + devices_and_kernels ABSL_GUARDED_BY(mu); +}; + +absl::StatusOr MakeOpaque(TfCallbackData callback_data) { + // Clear the `name` field in the callback_data, because this contains the full + // TF op name scope. We want ops with different names to map to the same + // Instantiation (so that if the same op with the same shape appears 10 times + // in a model, they all have the same logical TfCallbackData.) + callback_data.mutable_op()->clear_name(); + + std::string serialized_data; + if (!tsl::SerializeToStringDeterministic(callback_data, &serialized_data)) { + return absl::InternalError( + "Failed in serializing TfCallbackData to string"); + } + auto fingerprint = tsl::Fingerprint128(serialized_data); + return absl::StrFormat( + "fingerprint128=%s serialized=%s (%s)", + absl::Base64Escape(absl::string_view( + reinterpret_cast(&fingerprint), sizeof(fingerprint))), + absl::Base64Escape(serialized_data), callback_data.op().op()); +} + +absl::StatusOr GetInstantiation( + absl::string_view opaque) { + constexpr absl::string_view kFingerprintPrefix = "fingerprint128="; + if (!absl::StartsWith(opaque, kFingerprintPrefix)) { + return xla::Internal("Invalid opaque; must start with '%s', but was '%s'", + kFingerprintPrefix, opaque); + } + opaque.remove_prefix(kFingerprintPrefix.length()); + + // We use a 128-bit fingerprint, encoded as base64. It's 24 chars long + // including padding. + constexpr int kFingerprintLen = 24; + absl::string_view fingerprint_str = opaque.substr(0, kFingerprintLen); + opaque.remove_prefix(kFingerprintLen); + if (fingerprint_str.length() != kFingerprintLen) { + return xla::Internal("Invalid opaque; fingerprint is wrong length: '%s'", + fingerprint_str); + } + + static absl::Mutex mu{absl::kConstInit}; + static auto& instantiations ABSL_GUARDED_BY(mu) = + *new absl::flat_hash_map>(); + + absl::MutexLock lock(mu); + std::unique_ptr& instantiation = + instantiations[fingerprint_str]; + if (instantiation == nullptr) { + // Cache miss; create the instantiation. To do this, we need to parse out + // the serialized TfCallbackData from the opaque. + constexpr absl::string_view kSerializedPrefix = " serialized="; + if (!absl::StartsWith(opaque, kSerializedPrefix)) { + return xla::Internal("Invalid opaque; must start with '%s', but was '%s'", + kSerializedPrefix, opaque); + } + opaque.remove_prefix(kSerializedPrefix.length()); + + // Find the end of the base64-encoded serialized proto. + opaque = opaque.substr(0, opaque.find_first_of(' ')); + + // Unescape the base64 string, then parse the proto. + std::string unescaped_opaque; + if (!absl::Base64Unescape(opaque, &unescaped_opaque)) { + return xla::Internal("Failed to base64 decode opaque %s", opaque); + } + TfCallbackData callback_data; + if (!callback_data.ParseFromString(unescaped_opaque)) { + return xla::Internal("Failed to parse TfCallbackData from opaque %s", + opaque); + } + TF_ASSIGN_OR_RETURN(instantiation, + KernelInstantiation::Create(std::move(callback_data))); + + // Log a warning every power of 2 if `instantiations` gets large. + if (size_t n = instantiations.size(); + n >= (1 << 12) && (n & (n - 1)) == 0) { + LOG(WARNING) // + << "Light outside compilation has compiled " << n + << " unique op+shape combinations. Each of these permanently " + "leaks CPU memory. Exactly how much depends on the op, but " + "expect ~1kb per op. This is probably happening because you're " + "recompiling an XLA model many times with different shapes. " + "This message will be logged again at the next power of 2."; + } + } + return instantiation.get(); +} + +} // namespace + +static absl::StatusOr TensorFromProto(const TensorProto& proto) { + Tensor out; + if (!out.FromProto(proto)) { + return absl::InternalError("Failed deserializing a TensorProto"); + } + return out; +} + +absl::Status LightOutsideCompilationOp::CompileToCustomCallCallingTfKernel( + int graph_def_version, const NodeDef& node_def, XlaOpKernelContext* ctx) { + const OpRegistrationData* data = OpRegistry::Global()->LookUp(node_def.op()); + int num_inputs = ctx->num_inputs(); + int num_outputs = ctx->num_outputs(); + + std::vector tensor_storage(num_inputs); + std::vector input_tensors(num_inputs); + std::vector input_shapes; + + shape_inference::InferenceContext ic( + graph_def_version, node_def, data->op_def, + std::vector(num_inputs), {}, {}, {}); + TF_RETURN_IF_ERROR(ic.construction_status()); + + TfCallbackData callback_data; + *callback_data.mutable_op() = node_def; + + TF_ASSIGN_OR_RETURN( + std::vector constant_inputs, + XlaOpRegistry::CompileTimeConstantInputs(node_def, data->op_def)); + VLOG(1) << "Constant inputs we got: " << absl::StrJoin(constant_inputs, ", "); + + std::vector operand_shapes_with_layout; + std::vector operands; + for (int i = 0; i < num_inputs; ++i) { + TF_ASSIGN_OR_RETURN(xla::Shape xla_shape, ctx->InputXlaShape(i)); + if (absl::c_any_of(xla_shape.dynamic_dimensions(), + [](const bool is_dynamic) { return is_dynamic; })) { + // TODO(cheshire): Support input dynamic dimensions. + return absl::InternalError( + "Input dynamic dimensions are not supported for light outside " + "compilation"); + } + // TODO(cheshire): Use InputXlaShape. + TensorShape shape = ctx->InputShape(i); + TfCallbackData::InputBufferDescription input_description; + + *input_description.mutable_buffer_description()->mutable_shape() = + shape.AsProto(); + input_description.mutable_buffer_description()->set_type( + ctx->input_type(i)); + + if (absl::c_linear_search(constant_inputs, i)) { + // Assuming kernels want to read INT32 datatypes. + TF_ASSIGN_OR_RETURN(Tensor input_tensor, ctx->ConstantInputTensor(i)); + tensor_storage[i] = input_tensor; + input_tensors[i] = &tensor_storage.at(i); + input_tensor.AsProtoTensorContent(input_description.mutable_value()); + } else { + input_tensors[i] = nullptr; + operands.push_back(ctx->Input(i)); + operand_shapes_with_layout.push_back(xla_shape); + xla::LayoutUtil::SetToDefaultLayout(&operand_shapes_with_layout.back()); + } + + *callback_data.add_inputs() = input_description; + + TF_ASSIGN_OR_RETURN(shape_inference::ShapeHandle handle, + ic.MakeShapeFromShapeTensor(shape)); + ic.SetInput(i, handle); + } + + ic.set_input_tensors(input_tensors); + + TF_RETURN_IF_ERROR(data->shape_inference_fn(&ic)); + TF_ASSIGN_OR_RETURN(OutputDimensionBoundsMap output_dimension_bounds, + DynamicOutputDimensions(node_def, ctx)); + + std::vector output_xla_shapes; + for (int i = 0; i < num_outputs; ++i) { + const DimensionBoundsMap& dimension_bounds = output_dimension_bounds[i]; + TfCallbackData::OutputBufferDescription output_description; + output_description.mutable_buffer_description()->set_type( + ctx->expected_output_dtype(i)); + + TensorShapeProto output_tensor_shape_proto = + ic.ShapeHandleToProto(ic.output(i)); + if (output_tensor_shape_proto.unknown_rank()) { + return absl::InternalError( + absl::StrCat("Output ", i, " has unknown rank")); + } + + int rank = output_tensor_shape_proto.dim_size(); + std::vector dynamic_dimensions(rank, false); + + // Modify output tensor shape proto to replace dynamic dimensions with upper + // bounds: that is the information we will be storing in the callback. + for (int d = 0; d < output_tensor_shape_proto.dim_size(); ++d) { + auto* dim = output_tensor_shape_proto.mutable_dim(d); + auto it = dimension_bounds.find(d); + + if (dim->size() < 0) { + if (it == dimension_bounds.end()) { + return absl::InternalError(absl::StrCat( + "Bound for unknown dimension not found for dimension ", d)); + } + dim->set_size(it->second); + dynamic_dimensions[d] = true; + output_description.set_is_dynamically_padded(true); + } else { + if (it == dimension_bounds.end()) { + continue; + } + if (it->second < dim->size()) { + dim->set_size(it->second); + } + } + } + + *output_description.mutable_buffer_description()->mutable_shape() = + output_tensor_shape_proto; + *callback_data.add_outputs() = output_description; + + TF_ASSIGN_OR_RETURN( + TensorShape output_tensor_shape, + TensorShape::BuildTensorShape(output_tensor_shape_proto)); + + TF_ASSIGN_OR_RETURN(xla::Shape output_shape, + TensorShapeToXLAShape(ctx->expected_output_dtype(i), + output_tensor_shape)); + + // Set corresponding dynamic bounds on the output xla::Shape. + for (int64_t d = 0; d < dynamic_dimensions.size(); ++d) { + output_shape.set_dynamic_dimension(d, dynamic_dimensions[d]); + } + output_xla_shapes.push_back(output_shape); + } + + TF_ASSIGN_OR_RETURN( + auto output_shape, + xla::ShapeUtil::MakeValidatedMaybeTupleShape(output_xla_shapes)); + VLOG(1) << "Created output shape: " << output_shape.ToString(); + + TF_ASSIGN_OR_RETURN(std::string opaque, MakeOpaque(std::move(callback_data))); + xla::XlaOp out = xla::CustomCallWithLayout( + ctx->builder(), kTfCallbackCustomCall, operands, output_shape, + operand_shapes_with_layout, opaque, + /*has_side_effect=*/false, + /*output_operand_aliasing=*/{}, /*literal=*/nullptr, + xla::CustomCallSchedule::SCHEDULE_NONE, + xla::CustomCallApiVersion::API_VERSION_STATUS_RETURNING); + + for (int i = 0; i < num_outputs; ++i) { + ctx->SetOutput(i, + output_shape.IsTuple() ? xla::GetTupleElement(out, i) : out); + } + + return absl::OkStatus(); +} + +namespace { + +class WriteIntoXlaBufferAllocator : public Allocator { + public: + WriteIntoXlaBufferAllocator(void* xla_buffer, size_t buffer_size, + absl::string_view description) + : xla_buffer_(xla_buffer), + buffer_size_(buffer_size), + description_(description) {} + + std::string Name() override { + return absl::StrCat("allocator-xla-", description_); + } + + void* AllocateRaw(size_t alignment, size_t num_bytes) override { + VLOG(1) << "Faking allocation of " << num_bytes << " bytes into xla buffer " + << description_; + + if (num_bytes > buffer_size_) { + LOG(ERROR) << "Failed allocation: requested larger size than the " + "underlying buffer"; + return nullptr; + } + return xla_buffer_; + } + + // Do not perform our own memory management. + void DeallocateRaw(void* ptr) override { + VLOG(1) << "Not deallocating pointer " << ptr << " for " << description_; + } + + private: + void* xla_buffer_; + size_t buffer_size_; + std::string description_; +}; + +int GetNumConstants(const TfCallbackData& callback_data) { + return absl::c_count_if(callback_data.inputs(), + [&](const auto& input) { return input.has_value(); }); +} + +int GetOutputBufferId(int output_num, const TfCallbackData& callback_data) { + return (callback_data.inputs_size() - GetNumConstants(callback_data)) + + output_num; +} + +int64_t BufferSize(const TfCallbackData::BufferDescription& descr) { + // Do this without calling TensorShape::BuildTensorShape, because that's + // nontrivially expensive. + int64_t num_elems = 1; + for (const auto& d : descr.shape().dim()) { + num_elems *= d.size(); + } + return num_elems * DataTypeSize(descr.type()); +} + +class TfCallbackDevice : public DeviceBase { + public: + TfCallbackDevice() + : DeviceBase(Env::Default()), + cpu_allocator_( + ProcessState::singleton()->GetCPUAllocator(/*numa_node=*/0)) {} + + void SetUpForCall(se::Stream* stream, void** buffers, + const TfCallbackData& callback_data) { + stream_ = stream; + +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + gpu_allocator_ = GPUProcessState::singleton()->GetGPUAllocator( + *BaseGPUDevice::FindTfDeviceId(stream)); +#endif + + allocators_.clear(); + for (int i = 0; i < callback_data.outputs_size(); ++i) { + int buffer_num = GetOutputBufferId(i, callback_data); + VLOG(1) << "Binding output " << i << " to buffer " << buffers[buffer_num]; + int64_t buffer_size = + BufferSize(callback_data.outputs(i).buffer_description()); + allocators_.emplace_back(buffers[buffer_num], buffer_size, + absl::StrCat("xla-output-", i)); + } + + accelerator_device_info_.stream = stream; + set_tensorflow_accelerator_device_info(&accelerator_device_info_); + } + + const std::string& name() const override { return name_; } + + PerOpGpuDevice* MakeGpuDevice() override { +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + return new ConcretePerOpGpuDevice(); +#else + LOG(FATAL) << "CUDA-enabled build is required"; // Crash OK +#endif + } + + absl::Status ReinitializeGpuDevice(OpKernelContext* context, + PerOpGpuDevice* device, DeviceContext* dc, + Allocator* allocator) override { +#if GOOGLE_CUDA || TENSORFLOW_USE_ROCM + auto concrete_device = static_cast(device); + concrete_device->Reinitialize( + context, stream_->platform_specific_handle().stream, + /*platform_device_id=*/ + tsl::PlatformDeviceId(stream_->parent()->device_ordinal()), allocator, + // TODO(cheshire): Pass meaningful scratch buffer. + /*scratch=*/nullptr); + return absl::OkStatus(); +#else + LOG(FATAL) << "CUDA-enabled build is required"; // Crash OK +#endif + } + + Allocator* GetScopedAllocator(AllocatorAttributes attrs, + int64_t step_id) override { + return &allocators_[attrs.scope_id - 1]; + } + + Allocator* GetAllocator(AllocatorAttributes attr) override { + if (attr.on_host()) { + if (attr.gpu_compatible()) { + GPUProcessState* ps = GPUProcessState::singleton(); + // TODO(jlebar): The very first call to GetGpuHostAllocator sets its + // memory limits. So passing {} for the options here means that if + // nobody gets this allocator before us, we will not respect any limits + // the user might have set on host memory allocation. Our call to + // GetGPUAllocator in the constructor has the same problem. + return ps->GetGpuHostAllocator(/*options=*/{}, 0); + } else { + return cpu_allocator_; + } + } else { + return gpu_allocator_; + } + } + + private: + std::vector allocators_; + se::Stream* stream_ = nullptr; // NOLINT (used under GOOGLE_CUDA) + Allocator* gpu_allocator_ = nullptr; + Allocator* cpu_allocator_ = nullptr; + AcceleratorDeviceInfo accelerator_device_info_; + std::string name_ = "tf_callback_device"; +}; + +// Populate the output with actual dimensions of the allocated shapes. +// +// Populates the vector on the host and then copies it over to the GPU. +absl::Status PopulateMetadataBufferIfNeeded(OpKernelContext& ctx, + const TfCallbackData& callback_data, + void** buffers, + se::Stream* stream) { + for (int i = 0; i < ctx.num_outputs(); i++) { + if (callback_data.outputs(i).is_dynamically_padded()) { + Tensor* allocated = ctx.mutable_output(i); + TensorShape allocated_shape = allocated->shape(); + int num_dimensions = allocated_shape.dims(); + std::vector shape_info(num_dimensions); + for (int d = 0; d < allocated_shape.dims(); d++) { + int dim_size = allocated_shape.dim_size(d); + shape_info[d] = dim_size; + } + + TF_ASSIGN_OR_RETURN( + xla::Shape xla_shape, + tensorflow::TensorShapeToXLAShape( + callback_data.outputs(i).buffer_description().type(), + callback_data.outputs(i).buffer_description().shape())); + void* location = static_cast(allocated->data()) + + xla::ShapeUtil::ByteSizeOf(xla_shape); + stream_executor::DeviceAddressBase m{location, + num_dimensions * sizeof(int32_t)}; + TF_RETURN_IF_ERROR(stream->Memcpy(&m, shape_info.data(), + num_dimensions * sizeof(int32_t))); + } + } + return absl::OkStatus(); +} + +class FakeDeviceContext : public DeviceContext { + public: + explicit FakeDeviceContext(se::Stream* stream) { stream_ = stream; } + se::Stream* stream() const override { return stream_; } + + private: + se::Stream* stream_; +}; + +absl::Status CallTfKernel(void* stream_handle, void** buffers, + const char* opaque, int opaque_len) { + // Look up the platform only once, for a small performance gain. + static absl::Status* platform_status = nullptr; + static se::Platform* platform = [&]() -> se::Platform* { + absl::StatusOr p = + se::PlatformManager::PlatformWithName("CUDA"); + if (!p.ok()) { + platform_status = new absl::Status(p.status()); + return nullptr; + } + return *p; + }(); + if (platform_status != nullptr) return *platform_status; + + TF_ASSIGN_OR_RETURN(se::Stream * stream, + stream_executor::FindStream(platform, stream_handle)); + if (!stream) { + return xla::Internal("Stream not found for %p", stream_handle); + } + + TF_ASSIGN_OR_RETURN(KernelInstantiation * instantiation, + GetInstantiation(absl::string_view(opaque, opaque_len))); + const TfCallbackData& callback_data = instantiation->callback_data; + + // Get an existing TfCallbackDevice + OpKernel pair from the instantiation, or + // create a new set. + std::unique_ptr device; + std::unique_ptr kernel; + { + absl::MutexLock lock(instantiation->mu); + + if (instantiation->devices_and_kernels.empty()) { + auto device = std::make_unique(); + + absl::Status nested_status; + auto kernel = + CreateOpKernel(DeviceType(DEVICE_GPU), + /*device=*/device.get(), + // NB: real allocator is passed with device, the one + // here is only called during the kernel construction. + // TODO(cheshire): Pass scratch allocator. + /*allocator=*/nullptr, callback_data.op(), + /*graph_def_version=*/1, &nested_status); + TF_RETURN_IF_ERROR(nested_status); + + instantiation->devices_and_kernels.push_back( + {std::move(device), std::move(kernel)}); + } + + // Grab the last element of devices_and_kernels. + auto& dk = instantiation->devices_and_kernels.back(); + device = + absl::WrapUnique(static_cast(dk.first.release())); + kernel = std::move(dk.second); + instantiation->devices_and_kernels.pop_back(); + } + + // Put callback_device and kernel back in `devices_and_kernels` when we're + // done with them. + auto cleanup = absl::MakeCleanup([&] { + absl::MutexLock lock(instantiation->mu); + instantiation->devices_and_kernels.push_back( + std::make_pair(std::move(device), std::move(kernel))); + }); + + // Point this fake device at our stream and buffers. + device->SetUpForCall(stream, buffers, callback_data); + + std::vector allocator_attributes; + for (int output_idx = 0; output_idx < callback_data.outputs_size(); + ++output_idx) { + AllocatorAttributes attr; + // Repurpose `scope_id` to communicate which output is it. + // Shift by one to make it greater than zero. + attr.scope_id = output_idx + 1; + allocator_attributes.push_back(attr); + } + + auto device_context = + core::RefCountPtr(new FakeDeviceContext(stream)); + + OpKernelContext::Params params; + params.output_attr_array = allocator_attributes.data(); + params.op_kernel = kernel.get(); + params.device = device.get(); + params.ensure_eigen_gpu_device(); + params.op_device_context = device_context.get(); + + absl::InlinedVector inputs; + + // Deque usage is important to avoid moving objects. + std::deque input_allocators; + std::deque input_tensors; + + int constant_offset = 0; + + TF_RET_CHECK(callback_data.inputs_size() == + instantiation->input_shapes.size()); + + for (int i = 0; i < callback_data.inputs_size(); ++i) { + DataType dt = callback_data.inputs(i).buffer_description().type(); + const TensorShape& shape = instantiation->input_shapes[i]; + + VLOG(2) << "Input shape: " << shape.DebugString(); + int64_t input_size = shape.num_elements() * DataTypeSize(dt); + + if (callback_data.inputs(i).has_value()) { + // Value provided at compile time: reconstruct the tensor. + TF_ASSIGN_OR_RETURN(Tensor input, + TensorFromProto(callback_data.inputs(i).value())); + + VLOG(1) << "Input " << i << " is a tensor: " << input.DebugString(); + input_tensors.push_back(std::move(input)); + constant_offset++; + } else { + VLOG(1) << "Reading into the buffer for the input " << i; + + // We only get backing input buffer for those inputs which are *not* + // forced to be constant at compile time. + input_allocators.emplace_back(buffers[i - constant_offset], input_size, + absl::StrCat("input-", i)); + input_tensors.emplace_back(&input_allocators[i], dt, shape); + } + inputs.emplace_back(&input_tensors.back()); + } + + params.inputs = absl::MakeSpan(inputs); + OpKernelContext ctx(¶ms, callback_data.outputs_size()); + kernel->Compute(&ctx); + + bool has_dynamic_outputs = absl::c_any_of( + callback_data.outputs(), + [](const auto& out) { return out.is_dynamically_padded(); }); + + if (has_dynamic_outputs) { + TF_RETURN_IF_ERROR( + PopulateMetadataBufferIfNeeded(ctx, callback_data, buffers, stream)); + } + + TF_RETURN_IF_ERROR(ctx.status()); + return absl::OkStatus(); +} + +void GenericTfCallback(void* stream_handle, void** buffers, const char* opaque, + int opaque_len, XlaCustomCallStatus* status) { + absl::Status s = CallTfKernel(stream_handle, buffers, opaque, opaque_len); + if (!s.ok()) { + auto msg = s.message(); + XlaCustomCallStatusSetFailure(status, msg.data(), msg.size()); + } +} + +XLA_REGISTER_CUSTOM_CALL_TARGET_WITH_SYM(kTfCallbackCustomCall, + GenericTfCallback, "CUDA"); + +} // namespace + +LightOutsideCompilationOp::LightOutsideCompilationOp( + OpKernelConstruction* context) + : XlaOpKernel(context), + def_(context->def()), + graph_def_version_(context->graph_def_version()) {} + +void LightOutsideCompilationOp::Compile(XlaOpKernelContext* ctx) { + OP_REQUIRES_OK( + ctx, CompileToCustomCallCallingTfKernel(graph_def_version_, def_, ctx)); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.h new file mode 100644 index 0000000000000000000000000000000000000000..f733f91f092dc42e14f1671834c7171008112457 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/light_outside_compilation.h @@ -0,0 +1,71 @@ +/* Copyright 2022 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_KERNELS_LIGHT_OUTSIDE_COMPILATION_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_LIGHT_OUTSIDE_COMPILATION_H_ + +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/kernels/callback.pb.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +// Using std::map as the maps are presumed to be tiny, and we want a +// deterministic iteration order. +// +// Dimension -> bound. +using DimensionBoundsMap = std::map; + +// Output -> dimension -> bound. +using OutputDimensionBoundsMap = std::map; + +// Generic kernel for registering TF2XLA kernels which call back into the TF +// runtime to run a given kernel defined by the wrapped node. +// +// Cf. example usages in light_outside_compilation_kernels_for_test.cc. +// +// Currently does not support dynamic shape or resource variables. Currently +// works only on GPU. +class LightOutsideCompilationOp : public XlaOpKernel { + public: + explicit LightOutsideCompilationOp(OpKernelConstruction* context); + void Compile(XlaOpKernelContext* ctx) override; + + // Override to provide statically known bounds on output in case of dynamic + // shapes. + virtual absl::StatusOr DynamicOutputDimensions( + const NodeDef& ndef, XlaOpKernelContext* ctx) const { + return OutputDimensionBoundsMap{}; + } + + private: + absl::Status CompileToCustomCallCallingTfKernel(int graph_def_version, + const NodeDef& node_def, + XlaOpKernelContext* ctx); + static absl::Status CallTfKernel(void* stream_handle, void** buffers, + const char* opaque, int opaque_len); + + NodeDef def_; + int graph_def_version_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_LIGHT_OUTSIDE_COMPILATION_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/listdiff_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/listdiff_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..213deeca4d8b1be9e06d15011952b69999b5fa61 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/listdiff_op.cc @@ -0,0 +1,135 @@ +/* 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. +==============================================================================*/ + +// XLA-specific ListDiff Op. This only supports constant DT_INT32 and DT_INT64 +// input. + +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +constexpr std::array kListDiffTypes = {DT_INT32, DT_INT64}; + +// ListDiffOp is an XLA kernel that supports constant-only x and y input. +class ListDiffOp : public XlaOpKernel { + public: + explicit ListDiffOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + OP_REQUIRES(context, TensorShapeUtils::IsVector(context->InputShape(0)), + absl::InvalidArgumentError( + absl::StrCat("ListDiff expects x as a vector, not ", + context->InputShape(0).DebugString()))); + + OP_REQUIRES(context, TensorShapeUtils::IsVector(context->InputShape(1)), + absl::InvalidArgumentError( + absl::StrCat("ListDiff expects y as a vector, not ", + context->InputShape(1).DebugString()))); + + DataType val_type = context->expected_output_dtype(0); + DataType idx_type = context->expected_output_dtype(1); + + absl::Status status; + switch (val_type) { + case DT_INT32: + status = ListDiffWithIndexType(context, idx_type); + break; + case DT_INT64: + status = ListDiffWithIndexType(context, idx_type); + break; + default: + // This should never happen since we restrict this kernel to only match + // inputs with supported Tensor datatype. + status = absl::InvalidArgumentError( + absl::StrCat("ListDiff expects x and y as either ", + "int32 or int64, not ", DataTypeString(val_type))); + } + OP_REQUIRES_OK(context, status); + } + + private: + template + absl::Status ListDiff(XlaOpKernelContext* context) { + std::vector x_input, y_input; + TF_RETURN_IF_ERROR(context->ConstantInputAsIntVector(0, &x_input)); + TF_RETURN_IF_ERROR(context->ConstantInputAsIntVector(1, &y_input)); + + absl::flat_hash_set y_input_set; + y_input_set.reserve(y_input.size()); + for (auto y : y_input) { + y_input_set.insert(y); + } + + std::vector val_output; + std::vector idx_output; + auto x_size = x_input.size(); + for (Tidx i = 0; i < x_size; ++i) { + if (y_input_set.count(x_input[i]) > 0) { + continue; + } + val_output.push_back(x_input[i]); + idx_output.push_back(i); + } + + context->SetOutput(0, + xla::ConstantR1(context->builder(), val_output)); + context->SetOutput(1, + xla::ConstantR1(context->builder(), idx_output)); + return absl::OkStatus(); + } + + template + absl::Status ListDiffWithIndexType(XlaOpKernelContext* context, + DataType idx_type) { + switch (idx_type) { + case DT_INT32: + return ListDiff(context); + case DT_INT64: + return ListDiff(context); + default: + return absl::InvalidArgumentError(absl::StrCat( + "ListDiff expects idx_out as either int32 or int64, not ", + DataTypeString(idx_type))); + } + } +}; + +REGISTER_XLA_OP(Name("ListDiff") + .TypeConstraint("T", kListDiffTypes) + .CompileTimeConstantInput("x") + .CompileTimeConstantInput("y"), + ListDiffOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/lower_upper_bound_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/lower_upper_bound_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ff31f4b5affb889194a884d634c8be063206949 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/lower_upper_bound_ops.cc @@ -0,0 +1,126 @@ +/* Copyright 2020 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 "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/comparison_util.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +// Builds a LowerBound or UpperBound op, the distinction lying in +// comparison_direction: GT => LowerBoundOp, GE => UpperBoundOp. +// Note that this is an O(MN) algorithm: all entries in each sorted_inputs row +// are considered, and their sorted nature is not fully exploited. +void BuildLowerUpperBoundOp(XlaOpKernelContext* ctx, DataType out_dtype, + xla::ComparisonDirection comparison_direction, + bool nan_values_compare_greater = false) { + const TensorShape sorted_inputs_shape = ctx->InputShape("sorted_inputs"); + const TensorShape values_shape = ctx->InputShape("values"); + const xla::XlaOp sorted_inputs = ctx->Input("sorted_inputs"); + const xla::XlaOp values = ctx->Input("values"); + + // We are assuming both inputs are 2D, which they will be given the current + // implementation of tf.searchsorted. + OP_REQUIRES(ctx, sorted_inputs_shape.dims() == 2, + absl::FailedPreconditionError("sorted_inputs must be 2D")); + OP_REQUIRES(ctx, values_shape.dims() == 2, + absl::FailedPreconditionError("values must be 2D")); + + // Add a new inner dimension to values, to allow broadcasting along the inner + // dimension of sorted_sequence. + auto new_values_shape = values_shape; + new_values_shape.InsertDim(/* d */ 2, /* size */ 1); + auto values_reshaped = xla::Reshape(values, new_values_shape.dim_sizes()); + + // Add a new penultimate dimension to sorted_inputs, to allow broadcasting of + // sorted_sequence entries for each value. + auto new_sorted_inputs_shape = sorted_inputs_shape; + new_sorted_inputs_shape.InsertDim(/* d */ 1, /* size */ 1); + auto sorted_inputs_reshaped = + xla::Reshape(sorted_inputs, new_sorted_inputs_shape.dim_sizes()); + + // We are relying on broadcasting to compare each value against each entry in + // the associated sorted_inputs row. + // The reshapes above leave the tensors with equal rank of 3, so broadcast + // dimensions are not explicitly specified. + auto comparison = xla::Compare(values_reshaped, sorted_inputs_reshaped, {}, + comparison_direction); + if (nan_values_compare_greater) { + // Match eager searchsorted side='right' behavior for NaN search values. + // A NaN search value is placed after all entries in the sorted input row. + auto value_is_nan = xla::Compare(values_reshaped, values_reshaped, {}, + xla::ComparisonDirection::kNe); + comparison = xla::Or(comparison, value_is_nan); + } + const DataType accumulation_type = XlaHelpers::SumAccumulationType(out_dtype); + + // Convert boolean comparison results to integers so we can sum them. + auto comparison_int = + XlaHelpers::ConvertElementType(comparison, accumulation_type); + + // Sum the comparison results over the inner dimension to find the index for + // each value. + xla::XlaBuilder* builder = ctx->builder(); + auto reduced = + xla::Reduce(comparison_int, XlaHelpers::Zero(builder, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), {2}); + + ctx->SetOutput(0, reduced); +} + +class LowerBoundOp : public XlaOpKernel { + public: + explicit LowerBoundOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + BuildLowerUpperBoundOp(ctx, out_dtype_, xla::ComparisonDirection::kGt); + } + + private: + DataType out_dtype_; +}; + +REGISTER_XLA_OP(Name("LowerBound"), LowerBoundOp); + +class UpperBoundOp : public XlaOpKernel { + public: + explicit UpperBoundOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + BuildLowerUpperBoundOp(ctx, out_dtype_, xla::ComparisonDirection::kGe, + /*nan_values_compare_greater=*/true); + } + + private: + DataType out_dtype_; +}; + +REGISTER_XLA_OP(Name("UpperBound"), UpperBoundOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/lrn_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/lrn_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ef4a37eb7a591a910e2923fe3a65de4f6195fde --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/lrn_ops.cc @@ -0,0 +1,196 @@ +/* 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 + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/padding.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +// Local response normalization +class LRNOp : public XlaOpKernel { + public: + explicit LRNOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("depth_radius", &depth_radius_)); + + // TODO(phawkins): handle non-float types for attributes. + OP_REQUIRES_OK(ctx, ctx->GetAttr("bias", &bias_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("alpha", &alpha_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("beta", &beta_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape in_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, in_shape.dims() == 4, + absl::InvalidArgumentError("in must be 4-dimensional")); + + xla::XlaBuilder* builder = ctx->builder(); + xla::XlaOp input = ctx->Input(0); + + // sqr_sum[a, b, c, d] = + // sum(input[a, b, c, d - depth_radius : d + depth_radius + 1] ** 2) + // output = input / (bias + alpha * sqr_sum) ** beta + + // We use a window of depth_radius_ * 2 + 1, to account for the current + // element and a depth_radius_ on either side. + auto accumulation_type = XlaHelpers::SumAccumulationType(input_type(0)); + auto converted = XlaHelpers::ConvertElementType(input, accumulation_type); + auto squared = xla::Mul(converted, converted); + auto reduce = xla::ReduceWindow( + squared, XlaHelpers::Zero(builder, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), + /* window_dimensions = */ {1, 1, 1, depth_radius_ * 2 + 1}, + /* window_strides = */ {1, 1, 1, 1}, xla::Padding::kSame); + auto sqr_sum = XlaHelpers::ConvertElementType(reduce, input_type(0)); + + auto scale = xla::Pow( + xla::Add( + XlaHelpers::FloatLiteral(builder, input_type(0), bias_), + xla::Mul(XlaHelpers::FloatLiteral(builder, input_type(0), alpha_), + sqr_sum)), + XlaHelpers::FloatLiteral(builder, input_type(0), -beta_)); + + ctx->SetOutput(0, xla::Mul(input, scale)); + } + + private: + int64_t depth_radius_; + float bias_; + float alpha_; + float beta_; +}; + +REGISTER_XLA_OP(Name("LRN"), LRNOp); + +class LRNGradOp : public XlaOpKernel { + public: + explicit LRNGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("depth_radius", &depth_radius_)); + + // TODO(phawkins): handle non-float types for attributes. + OP_REQUIRES_OK(ctx, ctx->GetAttr("bias", &bias_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("alpha", &alpha_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("beta", &beta_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape in_grads_shape = ctx->InputShape(0); + const TensorShape in_image_shape = ctx->InputShape(1); + const TensorShape out_image_shape = ctx->InputShape(2); + + OP_REQUIRES(ctx, in_grads_shape.dims() == 4 && in_image_shape.dims() == 4, + absl::InvalidArgumentError("inputs must be 4-dimensional")); + const int64_t batch = in_grads_shape.dim_size(0); + const int64_t rows = in_grads_shape.dim_size(1); + const int64_t cols = in_grads_shape.dim_size(2); + const int64_t depth = in_grads_shape.dim_size(3); + OP_REQUIRES( + ctx, + in_image_shape.dim_size(0) == batch && + in_image_shape.dim_size(1) == rows && + in_image_shape.dim_size(2) == cols && + in_image_shape.dim_size(3) == depth && + out_image_shape.dim_size(0) == batch && + out_image_shape.dim_size(1) == rows && + out_image_shape.dim_size(2) == cols && + out_image_shape.dim_size(3) == depth, + absl::InvalidArgumentError( + "input_grads, input_image, and out_image should have the same " + "shape")); + + xla::XlaBuilder* builder = ctx->builder(); + xla::XlaOp in_grads = ctx->Input(0); + xla::XlaOp in_image = ctx->Input(1); + xla::XlaOp out_image = ctx->Input(2); + + // This code is ported from tensorflow/core/kernels/lrn_op.cc. In Python + // pseudo-code, the Eigen code does this for each spatial position: + // grads = [0.0] * depth + // for j in range(depth): + // depth_begin = max(0, j - depth_radius) + // depth_end = min(depth, j + depth_radius + 1) + // + // norm = 0 + // for k in range(depth_begin, depth_end): + // norm += in_image[k] * in_image[k] + // norm = alpha * norm + bias + // + // for k in range(depth_begin, depth_end): + // dyi = -2.0 * alpha * beta * in_image[k] * out_image[j] / norm + // if k == j: + // dyi += norm ** (-beta) + // dyi *= out_grads[j] + // grads[k] += dyi + + auto accumulation_type = XlaHelpers::SumAccumulationType(input_type(0)); + auto converted = + XlaHelpers::ConvertElementType(in_image, accumulation_type); + auto squared = xla::Mul(converted, converted); + auto reduce = xla::ReduceWindow( + squared, XlaHelpers::Zero(builder, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), + /* window_dimensions = */ {1, 1, 1, depth_radius_ * 2 + 1}, + /* window_strides = */ {1, 1, 1, 1}, xla::Padding::kSame); + auto sqr_sum = XlaHelpers::ConvertElementType(reduce, input_type(0)); + + auto norm = xla::Add( + XlaHelpers::FloatLiteral(builder, input_type(0), bias_), + xla::Mul(XlaHelpers::FloatLiteral(builder, input_type(0), alpha_), + sqr_sum)); + + auto dy = + xla::Mul(xla::Mul(XlaHelpers::FloatLiteral(builder, input_type(0), + -2.0f * alpha_ * beta_), + xla::Div(out_image, norm)), + in_grads); + + auto converted_dy = XlaHelpers::ConvertElementType(dy, accumulation_type); + auto dy_reduce = xla::ReduceWindow( + converted_dy, XlaHelpers::Zero(builder, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), + /* window_dimensions = */ {1, 1, 1, depth_radius_ * 2 + 1}, + /* window_strides = */ {1, 1, 1, 1}, xla::Padding::kSame); + auto dy_reduced = XlaHelpers::ConvertElementType(dy_reduce, input_type(0)); + + xla::XlaOp gradients = + xla::Add(xla::Mul(in_image, dy_reduced), + xla::Mul(in_grads, + xla::Pow(norm, XlaHelpers::FloatLiteral( + builder, input_type(0), -beta_)))); + + ctx->SetOutput(0, gradients); + } + + private: + int64_t depth_radius_; + float bias_; + float alpha_; + float beta_; +}; + +REGISTER_XLA_OP(Name("LRNGrad"), LRNGradOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matmul_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matmul_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..eed05e053a39842f93fae14655402232bdcc0a52 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matmul_op.cc @@ -0,0 +1,137 @@ +/* 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. +==============================================================================*/ + +// XLA-specific MatMul Op. + +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tsl/platform/tensor_float_32_utils.h" + +namespace tensorflow { +namespace { + +constexpr std::array kMatmulTypes = { + {DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_COMPLEX128, + DT_INT32, DT_INT64, DT_INT16, DT_INT8}}; + +class MatMulOp : public XlaOpKernel { + public: + explicit MatMulOp(OpKernelConstruction* ctx, bool is_sparse = false) + : XlaOpKernel(ctx), + is_sparse_(is_sparse), + grad_a_(false), + grad_b_(false) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("transpose_a", &transpose_a_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("transpose_b", &transpose_b_)); + if (!is_sparse) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("grad_a", &grad_a_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("grad_b", &grad_b_)); + } + if (is_sparse) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("Ta", &a_type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tb", &b_type_)); + // SparseMatMul is actually dense matmul with a hint that one or + // both of the inputs may contain a lot of zeroes. On CPU these + // inputs are dynamically converted to sparse representation + // before multiplication. For now in XLA we ignore the hints + // and always do dense multiplication. + bool dummy_is_sparse; + OP_REQUIRES_OK(ctx, ctx->GetAttr("a_is_sparse", &dummy_is_sparse)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("b_is_sparse", &dummy_is_sparse)); + } + } + + ~MatMulOp() override = default; + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape a_shape = ctx->InputShape(0); + const TensorShape b_shape = ctx->InputShape(1); + + // Check that the dimensions of the two matrices are valid. + OP_REQUIRES(ctx, a_shape.dims() == b_shape.dims(), + absl::InvalidArgumentError(absl::StrCat( + "In[0] and In[1] has different ndims: ", + a_shape.DebugString(), " vs. ", b_shape.DebugString()))); + OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(a_shape), + absl::InvalidArgumentError( + absl::StrCat("In[0] is not a matrix. Instead it has shape ", + a_shape.DebugString()))); + OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(b_shape), + absl::InvalidArgumentError( + absl::StrCat("In[1] is not a matrix. Instead it has shape ", + b_shape.DebugString()))); + int first_index = transpose_a_ ? 0 : 1; + int second_index = transpose_b_ ? 1 : 0; + + OP_REQUIRES(ctx, + a_shape.dim_size(first_index) == b_shape.dim_size(second_index), + absl::InvalidArgumentError(absl::StrCat( + "Matrix size-incompatible: In[0]: ", a_shape.DebugString(), + ", In[1]: ", b_shape.DebugString()))); + + xla::XlaOp a = ctx->Input(0); + xla::XlaOp b = ctx->Input(1); + if (is_sparse_) { + if (a_type_ == DT_BFLOAT16) { + a = xla::ConvertElementType(a, xla::F32); + } + if (b_type_ == DT_BFLOAT16) { + b = xla::ConvertElementType(b, xla::F32); + } + } + xla::PrecisionConfig::Precision precision = + tsl::tensor_float_32_execution_enabled() + ? xla::PrecisionConfig::DEFAULT + : xla::PrecisionConfig::HIGHEST; + ctx->SetOutput(0, xla::BatchDot(a, transpose_a_, b, transpose_b_, precision, + std::nullopt, grad_a_, grad_b_)); + } + + private: + bool is_sparse_; + bool transpose_a_; + bool transpose_b_; + bool grad_a_; + bool grad_b_; + DataType a_type_; + DataType b_type_; +}; + +REGISTER_XLA_OP(Name("MatMul").TypeConstraint("T", kMatmulTypes), MatMulOp); + +class SparseMatMulOp : public MatMulOp { + public: + explicit SparseMatMulOp(OpKernelConstruction* ctx) : MatMulOp(ctx, true) {} + + ~SparseMatMulOp() override = default; +}; + +REGISTER_XLA_OP(Name("SparseMatMul"), SparseMatMulOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_band_part_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_band_part_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..76702ae6821238911c480905584a8a46454eaa4b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_band_part_op.cc @@ -0,0 +1,25 @@ +/* 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/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("MatrixBandPart"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_diag_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_diag_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..d852388702d86c19a093bcdeb53c5f23254ae518 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_diag_ops.cc @@ -0,0 +1,565 @@ +/* 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 +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "Eigen/Core" // from @eigen_archive +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// Calculates the diagonal length of a diagonal. +static inline int ComputeDiagLen(int diag_index, int num_rows, int num_cols) { + return std::min(num_rows + std::min(0, diag_index), + num_cols - std::max(0, diag_index)); +} + +// Checks if a diagonal is to be aligned left or right. +static inline bool IsLeftAligned(int diag_index, bool left_align_superdiagonal, + bool left_align_subdiagonal) { + return (diag_index >= 0 && left_align_superdiagonal) || + (diag_index <= 0 && left_align_subdiagonal); +} + +// Reads the diagonal packing alignment. +void ReadAlignment(OpKernelConstruction* context, + bool* left_align_superdiagonal, + bool* left_align_subdiagonal) { + std::string align; + OP_REQUIRES_OK(context, context->GetAttr("align", &align)); + + *left_align_superdiagonal = align == "LEFT_LEFT" || align == "LEFT_RIGHT"; + *left_align_subdiagonal = align == "LEFT_LEFT" || align == "RIGHT_LEFT"; +} + +// Reads or infers lower_diag_index and upper_diag_index from kernel's input +// parameter "k". Also validates their values. +std::pair ProcessDiagIndex(XlaOpKernelContext* context) { + int64_t lower_diag_index = 0; + int64_t upper_diag_index = 0; + TensorShape diag_index_shape = context->InputShape("k"); + + // Wrapping OP_REQUIRES* macros with a function because they can "return;" + // early (without values) which contradicts ProcessDiagIndex's signature. + auto validate_diag_indices = [&]() { + if (diag_index_shape.dims() == 0) { + OP_REQUIRES_OK(context, + context->ConstantInputAsIntScalar("k", &lower_diag_index)); + upper_diag_index = lower_diag_index; + } else { + std::vector diag_index; + OP_REQUIRES_OK(context, + context->ConstantInputAsIntVector("k", &diag_index)); + OP_REQUIRES( + context, !diag_index.empty() && diag_index.size() <= 2, + absl::InvalidArgumentError(absl::StrCat( + "diag_index must have only one or two elements, received ", + diag_index.size(), " elements."))); + lower_diag_index = diag_index[0]; + upper_diag_index = + (diag_index.size() > 1) ? diag_index[1] : lower_diag_index; + } + OP_REQUIRES( + context, lower_diag_index <= upper_diag_index, + absl::InvalidArgumentError(absl::StrCat( + "lower_diag_index must not be larger than upper_diag_index: ", + lower_diag_index, " > ", upper_diag_index))); + }; + validate_diag_indices(); + return {lower_diag_index, upper_diag_index}; +} + +// Makes sure lower_diag_index and upper_diag_index are consistent with the +// input matrix size. +void ValidateDiagIndexWithOutputMatrixSize(XlaOpKernelContext* context, + const int64_t lower_diag_index, + const int64_t upper_diag_index, + const int64_t num_rows, + const int64_t num_cols) { + // `lower_diag_index == 0` condition is added to handle matrix shape = 0. + OP_REQUIRES(context, + (-num_rows < lower_diag_index && lower_diag_index < num_cols) || + lower_diag_index == 0, + absl::InvalidArgumentError(absl::StrCat( + "lower_diag_index is out of bound: ", lower_diag_index, + " It must be between ", -num_rows, " and ", num_cols))); + OP_REQUIRES(context, + (-num_rows < upper_diag_index && upper_diag_index < num_cols) || + upper_diag_index == 0, + absl::InvalidArgumentError(absl::StrCat( + "upper_diag_index is out of bound: ", upper_diag_index, + " It must be between ", -num_rows, " and ", num_cols))); + OP_REQUIRES(context, lower_diag_index <= upper_diag_index, + absl::InvalidArgumentError(absl::StrCat( + "lower_diag_index must not be larger than upper_diag_index: ", + lower_diag_index, " > ", upper_diag_index))); +} + +// Kernel to set matrix diagonals. +xla::XlaOp SetMatrixDiag(const xla::XlaOp input, const xla::XlaOp diag, + const TensorShape& input_shape, + const int64_t diag_rank, const int64_t num_diags, + const int64_t lower_diag_index, + const int64_t upper_diag_index, + const int64_t max_diag_len, const int64_t num_rows, + const int64_t num_cols, + const bool left_align_superdiagonal, + const bool left_align_subdiagonal) { + // Creates a padding config. + const int input_rank = input_shape.dims(); + xla::PaddingConfig padding_config; + padding_config = xla::MakeNoPaddingConfig(input_rank - 1); + + // Processes one diagonal at a time: + // 1) Extracts a single diagonal (diag_slice). + // 2) Broadcasts its contents to fill the whole matrix (diag_broadcast). + // 3) Masks diag_broadcast to get the right diagonal shape. + // + // XLA can fuse multiple Broadcasts and Selects so this shouldn't be slow. + // + // For example, + // diag = [[0, 2, 3], k = (-1, 1), num_cols = 4, and align="RIGHT_LEFT". + // [4, 5, 6], + // [7, 8, 9]] + // The expected output is [[7, 4, 2, 0], + // [0, 8, 5, 3], + // [0, 0, 9, 6]]. + // The 1st diagonal is created by: + // 1) Extracting diag_slice = [0, 2, 3] which is right-aligned. + // 2) Padding the vector (in the same direction) to be as long as num_cols, + // diag_slice = [0, 0, 2, 3], + // then broadcasting diag_slice column-wise to a full matrix, + // diag_broadcast = [[0, 0, 2, 3], + // [0, 0, 2, 3], + // [0, 0, 2, 3]]. + // The padding value can be anything because it will not appear in the + // results after masking. Here, we use zero. + // 3) Masking diag_broadcast with a mask of the shape of the 1st diagonal. + // mask = [[0, 0, 1, 0], --> output = [[x, x, 2, x], + // [0, 0, 0, 1], [x, x, x, 3], + // [0, 0, 0, 0]] [x, x, x, x]], + // where x denotes the existing input contents. + std::vector broadcast_dimensions(input_rank - 1); + absl::c_iota(broadcast_dimensions, 0); + auto output = input; + for (int64_t diag_index = lower_diag_index; diag_index <= upper_diag_index; + ++diag_index) { + // Extracts a single diagonal. + auto diag_slice = diag; + if (num_diags > 1) { + // The result of SliceInDim has dims: [, 1, max_diag_len]. + // We call Collapse to make the dims: [, max_diag_len]. + const int64_t mapped_diag_index = upper_diag_index - diag_index; + diag_slice = xla::Collapse( + xla::SliceInDim(diag, mapped_diag_index, mapped_diag_index + 1, 1, + diag_rank - 2), + {diag_rank - 2, diag_rank - 1}); + } + + // Pad if necessary. + // - If the diagonal has the longest length, i.e., min(num_rows, num_cols), + // no padding is necessary. It is broadcast column-wise if it is a sub- + // diagonal, row-wise if superdiagonal. + // - Otherwise, pad and keep the old alignment (shorter diagonals in the + // input come pre-padded). max_len in the table refers to max_diag_len. + // ------------------------------------------------------------------- + // | Diag | Align | Broadcast | padding_low | padding_high | + // ------------------------------------------------------------------- + // | Super | Left | Row-wise | 0 | #rows - max_len | + // | | Right | Column-wise | #cols - max_len | 0 | + // ------------------------------------------------------------------- + // | Sub | Left | Column-wise | 0 | #cols - max_len | + // | | Right | Row-wise | #rows - max_len | 0 | + // ------------------------------------------------------------------- + if (num_cols - num_rows <= diag_index && diag_index <= 0) { + broadcast_dimensions.back() = input_rank - 1; // Column-wise. + } else if (0 <= diag_index && diag_index <= num_cols - num_rows) { + broadcast_dimensions.back() = input_rank - 2; // Row-wise. + } else { + int length_to_pad_to; + if ((diag_index > 0 && left_align_superdiagonal) || + (diag_index < 0 && !left_align_subdiagonal)) { + length_to_pad_to = num_rows; + broadcast_dimensions.back() = input_rank - 2; // Row-wise. + } else { + length_to_pad_to = num_cols; + broadcast_dimensions.back() = input_rank - 1; // Column-wise. + } + int padding_low = length_to_pad_to - max_diag_len; + int padding_high = 0; + if (IsLeftAligned(diag_index, left_align_superdiagonal, + left_align_subdiagonal)) { + std::swap(padding_low, padding_high); + } + padding_config.mutable_dimensions(input_rank - 2) + ->set_edge_padding_low(padding_low); + padding_config.mutable_dimensions(input_rank - 2) + ->set_edge_padding_high(padding_high); + + const xla::XlaOp zero = xla::ScalarLike(input, 0); + diag_slice = xla::Pad(diag_slice, zero, padding_config); + } + + // Broadcast and mask. + xla::XlaOp diag_broadcast = xla::BroadcastInDim( + diag_slice, input_shape.dim_sizes(), broadcast_dimensions); + const auto mask = xla::GetDiagonalMask(output, diag_index); + output = xla::Select(mask, diag_broadcast, output); + } + return output; +} + +} // namespace + +class MatrixDiagOp : public XlaOpKernel { + public: + explicit MatrixDiagOp(OpKernelConstruction* context) : XlaOpKernel(context) { + // MatrixDiagV3-specific. + if (context->HasAttr("align")) { + ReadAlignment(context, &left_align_superdiagonal_, + &left_align_subdiagonal_); + } + } + + void Compile(XlaOpKernelContext* context) override { + OP_REQUIRES(context, context->num_inputs() >= kNumV1Inputs, + absl::InvalidArgumentError( + "MatrixDiag op must have at least one input")); + const TensorShape diag_shape = context->InputShape(0); + OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(diag_shape), + absl::InvalidArgumentError(absl::StrCat( + "diagonal must be at least 1-dim, received shape: ", + diag_shape.DebugString()))); + + const DataType dtype = context->expected_output_dtype(0); + const xla::XlaOp zero = XlaHelpers::Zero(context->builder(), dtype); + + // Initializes MatrixDiagV2-specific variables. + // Input arguments providing the values of num_rows and num_cols can be + // absent (-1) and will be inferred later. + int64_t lower_diag_index = 0; + int64_t upper_diag_index = 0; + int64_t num_rows = -1; + int64_t num_cols = -1; + xla::XlaOp padding_value = zero; + + // MatrixDiag and MatrixDiagV2 both use this OpKernel. MatrixDiag only has + // one input, so we have to check the number of inputs before reading + // additional parameters for MatrixDiagV2. + if (context->num_inputs() > kNumV1Inputs) { + std::tie(lower_diag_index, upper_diag_index) = ProcessDiagIndex(context); + OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar(2, &num_rows)); + OP_REQUIRES_OK(context, context->ConstantInputAsIntScalar(3, &num_cols)); + padding_value = context->Input(4); + } + + // More size validations. + const int64_t diag_rank = diag_shape.dims(); + const int64_t max_diag_len = diag_shape.dim_size(diag_rank - 1); + const int64_t num_diags = upper_diag_index - lower_diag_index + 1; + OP_REQUIRES( + context, + num_diags == 1 || num_diags == diag_shape.dim_size(diag_rank - 2), + absl::InvalidArgumentError( + "The number of diagonals provided in the input does not " + "match the lower_diag_index and upper_diag_index range.")); + const int64_t min_num_rows = + max_diag_len - std::min(upper_diag_index, int64_t{0}); + const int64_t min_num_cols = + max_diag_len + std::max(lower_diag_index, int64_t{0}); + OP_REQUIRES(context, num_rows == -1 || num_rows >= min_num_rows, + absl::InvalidArgumentError("The number of rows is too small.")); + OP_REQUIRES( + context, num_cols == -1 || num_cols >= min_num_cols, + absl::InvalidArgumentError("The number of columns is too small.")); + + // Infers num_rows and num_cols. If both are unknown, assume that the output + // is square. Otherwise, use smallest possible values. + if (num_rows == -1 && num_cols == -1) { + num_rows = std::max(min_num_rows, min_num_cols); + num_cols = num_rows; + } else if (num_rows == -1) { + num_rows = min_num_rows; + } else if (num_cols == -1) { + num_cols = min_num_cols; + } + + // At least one of num_rows and num_cols must match its minimum length. + // Otherwise, we'll have some incomplete diagonals. + OP_REQUIRES(context, num_rows == min_num_rows || num_cols == min_num_cols, + absl::InvalidArgumentError( + "The number of rows or columns is not consistent with " + "the specified d_lower, d_upper, and diagonal.")); + + // Actual processing. + // Initializes the output tensor with padding_value. + TensorShape output_shape = diag_shape; + output_shape.RemoveLastDims((num_diags == 1) ? 1 : 2); + output_shape.AddDim(num_rows); + output_shape.AddDim(num_cols); + xla::XlaOp output = xla::Broadcast(padding_value, output_shape.dim_sizes()); + xla::XlaOp diag = context->Input(0); + context->SetOutput( + 0, SetMatrixDiag(output, diag, output_shape, diag_rank, num_diags, + lower_diag_index, upper_diag_index, max_diag_len, + num_rows, num_cols, left_align_superdiagonal_, + left_align_subdiagonal_)); + } + + private: + bool left_align_superdiagonal_ = true; + bool left_align_subdiagonal_ = true; + static constexpr int kNumV1Inputs = 1; +}; + +REGISTER_XLA_OP(Name("MatrixDiag"), MatrixDiagOp); +REGISTER_XLA_OP(Name("MatrixDiagV2") + .CompileTimeConstantInput("k") + .CompileTimeConstantInput("num_rows") + .CompileTimeConstantInput("num_cols") + .CompileTimeConstantInput("padding_value"), + MatrixDiagOp); +REGISTER_XLA_OP(Name("MatrixDiagV3") + .CompileTimeConstantInput("k") + .CompileTimeConstantInput("num_rows") + .CompileTimeConstantInput("num_cols") + .CompileTimeConstantInput("padding_value"), + MatrixDiagOp); + +class MatrixDiagPartOp : public XlaOpKernel { + public: + explicit MatrixDiagPartOp(OpKernelConstruction* context) + : XlaOpKernel(context), + is_gpu_(context->device_type().type_string() == DEVICE_GPU_XLA_JIT) { + // MatrixDiagPartV3-specific. + if (context->HasAttr("align")) { + ReadAlignment(context, &left_align_superdiagonal_, + &left_align_subdiagonal_); + } + } + + void Compile(XlaOpKernelContext* context) override { + const TensorShape input_shape = context->InputShape(0); + const int input_rank = input_shape.dims(); + + OP_REQUIRES(context, TensorShapeUtils::IsMatrixOrHigher(input_shape), + absl::InvalidArgumentError(absl::StrCat( + "input must be at least 2-dim, received shape: ", + input_shape.DebugString()))); + + const DataType dtype = context->expected_output_dtype(0); + const xla::XlaOp zero = XlaHelpers::Zero(context->builder(), dtype); + + // Initializes MatrixDiagPartV2-specific variables. + int64_t lower_diag_index = 0; + int64_t upper_diag_index = 0; + xla::XlaOp padding_value = zero; + + // MatrixDiagPart and MatrixDiagPartV2 both use this OpKernel. + // MatrixDiagPart only has one input, so we have to check the number of + // inputs before reading additional parameters in MatrixDiagV2. + if (context->num_inputs() > kNumV1Inputs) { + std::tie(lower_diag_index, upper_diag_index) = ProcessDiagIndex(context); + padding_value = context->Input(2); + } + + // Checks if diag sizes are consistent with input. + const int64_t num_rows = input_shape.dim_size(input_rank - 2); + const int64_t num_cols = input_shape.dim_size(input_rank - 1); + ValidateDiagIndexWithOutputMatrixSize(context, lower_diag_index, + upper_diag_index, num_rows, num_cols); + + // Creates output shape. + TensorShape output_shape = input_shape; + output_shape.RemoveLastDims(2); + const int num_diags = upper_diag_index - lower_diag_index + 1; + if (num_diags > 1) output_shape.AddDim(num_diags); + const int32_t max_diag_len = + std::min(num_rows + std::min(upper_diag_index, int64_t{0}), + num_cols - std::max(lower_diag_index, int64_t{0})); + output_shape.AddDim(max_diag_len); + + // Computes output. + xla::XlaOp input = context->Input(0); + std::vector diag_list; + xla::PaddingConfig padding_config = + xla::MakeNoPaddingConfig(input_rank - 1); + if (num_diags == 1) { + context->SetOutput( + 0, is_gpu_ ? xla::GetMatrixDiagonalViaGather(input, upper_diag_index) + : xla::GetMatrixDiagonal(input, upper_diag_index)); + return; + } + for (int diag_index = upper_diag_index; diag_index >= lower_diag_index; + --diag_index) { + xla::XlaOp single_diag = + is_gpu_ ? xla::GetMatrixDiagonalViaGather(input, diag_index) + : xla::GetMatrixDiagonal(input, diag_index); + const int64_t diag_len = ComputeDiagLen(diag_index, num_rows, num_cols); + const int64_t padding_len = max_diag_len - diag_len; + if (padding_len > 0) { + if (IsLeftAligned(diag_index, left_align_superdiagonal_, + left_align_subdiagonal_)) { + padding_config.mutable_dimensions(input_rank - 2) + ->set_edge_padding_low(0); + padding_config.mutable_dimensions(input_rank - 2) + ->set_edge_padding_high(padding_len); + } else { + padding_config.mutable_dimensions(input_rank - 2) + ->set_edge_padding_low(padding_len); + padding_config.mutable_dimensions(input_rank - 2) + ->set_edge_padding_high(0); + } + single_diag = xla::Pad(single_diag, padding_value, padding_config); + } + diag_list.emplace_back(single_diag); + } + auto concat = + xla::ConcatInDim(context->builder(), diag_list, input_rank - 2); + context->SetOutput(0, xla::Reshape(concat, output_shape.dim_sizes())); + } + + private: + const bool is_gpu_; + bool left_align_superdiagonal_ = true; + bool left_align_subdiagonal_ = true; + static constexpr int kNumV1Inputs = 1; +}; + +REGISTER_XLA_OP(Name("MatrixDiagPart"), MatrixDiagPartOp); +REGISTER_XLA_OP(Name("MatrixDiagPartV2") + .CompileTimeConstantInput("k") + .CompileTimeConstantInput("padding_value"), + MatrixDiagPartOp); +REGISTER_XLA_OP(Name("MatrixDiagPartV3") + .CompileTimeConstantInput("k") + .CompileTimeConstantInput("padding_value"), + MlirXlaOpKernel); + +class MatrixSetDiagOp : public XlaOpKernel { + public: + explicit MatrixSetDiagOp(OpKernelConstruction* context) + : XlaOpKernel(context) { + // MatrixSetDiagV3-specific. + if (context->HasAttr("align")) { + ReadAlignment(context, &left_align_superdiagonal_, + &left_align_subdiagonal_); + } + } + + void Compile(XlaOpKernelContext* context) override { + const TensorShape input_shape = context->InputShape(0); + const TensorShape diag_shape = context->InputShape(1); + const int input_rank = input_shape.dims(); + const int diag_rank = diag_shape.dims(); + + // Preliminary validation of sizes. + OP_REQUIRES(context, TensorShapeUtils::IsMatrixOrHigher(input_shape), + absl::InvalidArgumentError(absl::StrCat( + "input must be at least 2-dim, received shape: ", + input_shape.DebugString()))); + OP_REQUIRES(context, TensorShapeUtils::IsVectorOrHigher(diag_shape), + absl::InvalidArgumentError(absl::StrCat( + "diagonal must be at least 1-dim, received shape: ", + diag_shape.DebugString()))); + + // MatrixSetDiag and MatrixSetDiagV2 both use this OpKernel. MatrixSetDiag + // only has two inputs, so we have to check the number of inputs before + // reading additional parameters in MatrixSetDiagV2. + int64_t lower_diag_index = 0; + int64_t upper_diag_index = 0; + if (context->num_inputs() > kNumV1Inputs) { + std::tie(lower_diag_index, upper_diag_index) = ProcessDiagIndex(context); + } + + // Checks if diag sizes are consistent with input. + const int64_t num_rows = input_shape.dim_size(input_rank - 2); + const int64_t num_cols = input_shape.dim_size(input_rank - 1); + ValidateDiagIndexWithOutputMatrixSize(context, lower_diag_index, + upper_diag_index, num_rows, num_cols); + const Eigen::Index num_diags = upper_diag_index - lower_diag_index + 1; + OP_REQUIRES(context, + lower_diag_index == upper_diag_index || + (diag_shape.dim_size(input_rank - 2) == num_diags), + absl::InvalidArgumentError( + "The number of diagonals provided in `diag` " + "is not consistent with `lower_diag_index` and " + "`upper_diag_index`")); + + TensorShape expected_diag_shape = input_shape; + expected_diag_shape.RemoveLastDims(2); + if (num_diags > 1) expected_diag_shape.AddDim(num_diags); + const int32_t max_diag_len = + std::min(num_rows + std::min(upper_diag_index, int64_t{0}), + num_cols - std::max(lower_diag_index, int64_t{0})); + expected_diag_shape.AddDim(max_diag_len); + OP_REQUIRES( + context, expected_diag_shape == diag_shape, + absl::InvalidArgumentError(absl::StrCat( + "Either first dimensions of diagonal don't match input.shape[:-2], " + "or diagonal.shape[:-1] is not equal to the longests diagonal in " + "range [lower_diag_index:upper_diag_index].\nInput shape: ", + input_shape.DebugString(), + "\nDiagonal shape: ", diag_shape.DebugString(), + "\nExpected diagonal shape: ", expected_diag_shape.DebugString()))); + + // Actual processing. + xla::XlaOp input = context->Input(0); + xla::XlaOp diag = context->Input(1); + context->SetOutput( + 0, SetMatrixDiag(input, diag, input_shape, diag_rank, num_diags, + lower_diag_index, upper_diag_index, max_diag_len, + num_rows, num_cols, left_align_superdiagonal_, + left_align_subdiagonal_)); + } + + private: + bool left_align_superdiagonal_ = true; + bool left_align_subdiagonal_ = true; + static constexpr int kNumV1Inputs = 2; + MatrixSetDiagOp(const MatrixSetDiagOp&) = delete; + void operator=(const MatrixSetDiagOp&) = delete; +}; + +REGISTER_XLA_OP(Name("MatrixSetDiag"), MatrixSetDiagOp); +REGISTER_XLA_OP(Name("MatrixSetDiagV2").CompileTimeConstantInput("k"), + MatrixSetDiagOp); +REGISTER_XLA_OP(Name("MatrixSetDiagV3").CompileTimeConstantInput("k"), + MatrixSetDiagOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_inverse_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_inverse_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f7546749e9b01921cdd28ca80694ef7b21c104e3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_inverse_op.cc @@ -0,0 +1,80 @@ +/* Copyright 2019 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 + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/lib/qr.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class MatrixInverseOp : public XlaOpKernel { + public: + explicit MatrixInverseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint", &adjoint_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + int64_t ndims = input_shape.dims(); + OP_REQUIRES(ctx, ndims >= 2, + absl::InvalidArgumentError( + absl::StrCat("Input must have rank >= 2, got ", ndims))); + OP_REQUIRES( + ctx, input_shape.dim_size(ndims - 2) == input_shape.dim_size(ndims - 1), + absl::InvalidArgumentError( + absl::StrCat("Input matrices must be squares, got", + input_shape.dim_size(ndims - 2), + " != ", input_shape.dim_size(ndims - 1)))); + + xla::XlaOp input = xla::MaybeTransposeInMinorDims(ctx->Input(0), adjoint_); + + // TODO(b/111271662): Using LU decomposition instead of QR should be faster. + xla::XlaOp q, r; + QrExplicit(input, /*full_matrices=*/false, q, r); + + xla::XlaOp output = + xla::TriangularSolve(r, xla::TransposeInMinorDims(q), + /*left_side=*/true, + /*lower=*/false, /*unit_diagonal=*/false, + /*transpose_a=*/ + xla::TriangularSolveOptions::NO_TRANSPOSE); + ctx->SetOutput(0, output); + } + + private: + bool adjoint_; + + MatrixInverseOp(const MatrixInverseOp&) = delete; + void operator=(const MatrixInverseOp&) = delete; +}; + +// TODO(b/135640736): Allow this for integer and complex types. +REGISTER_XLA_OP(Name("MatrixInverse").TypeConstraint("T", kFloatTypes), + MatrixInverseOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_solve_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_solve_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f5ab8e3be73566823b492568de857604b0ecb131 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_solve_op.cc @@ -0,0 +1,86 @@ +/* Copyright 2019 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 + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/matrix.h" +#include "xla/hlo/builder/lib/qr.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class MatrixSolveOp : public XlaOpKernel { + public: + explicit MatrixSolveOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint", &adjoint_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape matrix_shape = ctx->InputShape(0); + int64_t matrix_ndims = matrix_shape.dims(); + OP_REQUIRES(ctx, matrix_ndims >= 2, + absl::InvalidArgumentError(absl::StrCat( + "Input matrix must have rank >= 2, got ", matrix_ndims))); + OP_REQUIRES(ctx, + matrix_shape.dim_size(matrix_ndims - 2) == + matrix_shape.dim_size(matrix_ndims - 1), + absl::InvalidArgumentError(absl::StrCat( + "Input matrices must be square, got", + matrix_shape.dim_size(matrix_ndims - 2), + " != ", matrix_shape.dim_size(matrix_ndims - 1)))); + + xla::XlaOp matrix = ctx->Input(0); + xla::XlaOp rhs = ctx->Input(1); + + // TODO(b/111271662): Using LU decomposition instead of QR should be faster. + xla::XlaOp q, r; + xla::QrExplicit(matrix, /*full_matrices=*/false, q, r); + + xla::XlaOp inv = + xla::TriangularSolve(r, xla::TransposeInMinorDims(q), + /*left_side=*/true, + /*lower=*/false, /*unit_diagonal=*/false, + /*transpose_a=*/ + xla::TriangularSolveOptions::NO_TRANSPOSE); + + xla::XlaOp output = + xla::BatchDot(inv, adjoint_, rhs, + /*transpose_y=*/false, xla::PrecisionConfig::HIGHEST); + ctx->SetOutput(0, output); + } + + private: + bool adjoint_; + + MatrixSolveOp(const MatrixSolveOp&) = delete; + void operator=(const MatrixSolveOp&) = delete; +}; + +// TODO(b/111271662): Support integer and complex types. +REGISTER_XLA_OP(Name("MatrixSolve").TypeConstraint("T", kFloatTypes), + MatrixSolveOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_triangular_solve_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_triangular_solve_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..a903e1cdd6b481db60d676cb3fafbfc3c4452231 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/matrix_triangular_solve_op.cc @@ -0,0 +1,123 @@ +/* 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 +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/bcast.h" +#include "tensorflow/core/util/matmul_bcast.h" + +namespace tensorflow { +namespace { + +class MatrixTriangularSolveOp : public XlaOpKernel { + public: + explicit MatrixTriangularSolveOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("lower", &lower_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint", &adjoint_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape lhs_shape = ctx->InputShape(0); + const TensorShape rhs_shape = ctx->InputShape(1); + + // By TensorFlow conventions the inputs may not have the same + // shapes, in which case they will be automatically broadcast if + // possible before mapping. Use the standard TensorFlow helper to + // compute valid broadcast shapes, but rely below on XLA to + // automatically perform the broadcast assuming its valid shapes are + // a superset of TensorFlow's valid shapes. + MatMulBCast bcast(BCast::FromShape(lhs_shape), BCast::FromShape(rhs_shape)); + if (!bcast.IsValid()) { + ctx->SetStatus(absl::InvalidArgumentError( + absl::StrCat("Incompatible shapes: ", lhs_shape.DebugString(), + " vs. ", rhs_shape.DebugString()))); + return; + } + + auto lhs_size = lhs_shape.dims(); + OP_REQUIRES( + ctx, + lhs_shape.dim_size(lhs_size - 1) == lhs_shape.dim_size(lhs_size - 2), + absl::InvalidArgumentError( + absl::StrCat("The coefficient matrix must be square in " + "the inner-most two dimensions: ", + lhs_shape.DebugString()))); + + xla::XlaOp a = ctx->Input(0); + xla::XlaOp b = ctx->Input(1); + std::tie(a, b) = Broadcast(a, lhs_shape, b, rhs_shape, bcast); + auto result = xla::TriangularSolve( + a, b, /*left_side=*/true, + /*lower=*/lower_, /*unit_diagonal=*/false, + /*transpose_a=*/ + adjoint_ ? xla::TriangularSolveOptions::ADJOINT + : xla::TriangularSolveOptions::NO_TRANSPOSE); + ctx->SetOutput(0, result); + } + + private: + static std::pair Broadcast( + xla::XlaOp lhs, const TensorShape& lhs_shape, xla::XlaOp rhs, + const TensorShape& rhs_shape, const MatMulBCast& broadcast_helper); + bool lower_; + bool adjoint_; +}; + +/* static */ std::pair +MatrixTriangularSolveOp::Broadcast(xla::XlaOp lhs, const TensorShape& lhs_shape, + xla::XlaOp rhs, const TensorShape& rhs_shape, + const MatMulBCast& broadcast_helper) { + // Get the batch shape. + int64_t m = lhs_shape.dim_size(lhs_shape.dims() - 1); + int64_t n = rhs_shape.dim_size(rhs_shape.dims() - 1); + + TensorShape lhs_broadcast_shape(broadcast_helper.output_batch_shape()); + lhs_broadcast_shape.AddDim(m); + lhs_broadcast_shape.AddDim(m); + auto lhs_output = BroadcastTo(lhs, lhs_broadcast_shape.dim_sizes()); + if (!lhs_output.ok()) { + xla::XlaOp error = lhs.builder()->ReportError(lhs_output.status()); + return {error, error}; + } + + TensorShape rhs_broadcast_shape(broadcast_helper.output_batch_shape()); + rhs_broadcast_shape.AddDim(m); + rhs_broadcast_shape.AddDim(n); + auto rhs_output = BroadcastTo(rhs, rhs_broadcast_shape.dim_sizes()); + if (!rhs_output.ok()) { + xla::XlaOp error = rhs.builder()->ReportError(rhs_output.status()); + return {error, error}; + } + return {lhs_output.value(), rhs_output.value()}; +} + +REGISTER_XLA_OP(Name("MatrixTriangularSolve"), MatrixTriangularSolveOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/mirror_pad_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/mirror_pad_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..700d692b9a377e9662b0437e58cfad4999bf7e84 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/mirror_pad_op.cc @@ -0,0 +1,226 @@ +/* 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 + +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/status_macros.h" +#include "xla/util.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/mirror_pad_mode.h" + +namespace tensorflow { +namespace { + +class MirrorPadOp : public XlaOpKernel { + public: + explicit MirrorPadOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + absl::StatusOr DoMirrorPad(const xla::XlaOp t, + const xla::Shape& original_shape, + const xla::LiteralSlice& pad_literal, + const MirrorPadMode mode, + xla::XlaBuilder* b) { + // The difference in the semantics of REFLECT and SYMMETRIC is that REFLECT + // will not mirror the border values while symmetric does. + // e.g. input is [1, 2, 3] and paddings is [0, 2], then the output is: + // - [1, 2, 3, 2, 1] in reflect mode + // - [1, 2, 3, 3, 2] in symmetric mode. + int64_t excluded_edges = mode == MirrorPadMode::REFLECT ? 1 : 0; + xla::XlaOp accum = t; + for (int64_t dimno = original_shape.dimensions().size() - 1; dimno >= 0; + --dimno) { + auto t_rev = xla::Rev(accum, {dimno}); + int64_t lhs_padding = pad_literal.Get({dimno, 0}); + int64_t rhs_padding = pad_literal.Get({dimno, 1}); + int64_t dim_size = original_shape.dimensions(dimno); + + // Padding amounts on each side must be no more than the size of the + // original shape. + TF_RET_CHECK(lhs_padding >= 0 && + lhs_padding <= dim_size - excluded_edges); + TF_RET_CHECK(rhs_padding >= 0 && + rhs_padding <= dim_size - excluded_edges); + + auto lhs_pad = + xla::SliceInDim(t_rev, dim_size - excluded_edges - lhs_padding, + dim_size - excluded_edges, 1, dimno); + auto rhs_pad = xla::SliceInDim(t_rev, excluded_edges, + excluded_edges + rhs_padding, 1, dimno); + accum = xla::ConcatInDim(b, {lhs_pad, accum, rhs_pad}, dimno); + } + return accum; + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape pad_shape = ctx->InputShape("paddings"); + + MirrorPadMode mode; + OP_REQUIRES_OK(ctx, GetNodeAttr(def(), "mode", &mode)); + OP_REQUIRES( + ctx, mode == MirrorPadMode::REFLECT || mode == MirrorPadMode::SYMMETRIC, + xla::Unimplemented("Unsupported MirrorPad mode. Only SYMMETRIC and " + "REFLECT modes are currently supported")); + + const int dims = input_shape.dims(); + OP_REQUIRES( + ctx, + TensorShapeUtils::IsMatrix(pad_shape) && pad_shape.dim_size(1) == 2, + errors::InvalidArgument("paddings must be a matrix with 2 columns: ", + pad_shape.DebugString())); + OP_REQUIRES( + ctx, dims == pad_shape.dim_size(0), + errors::InvalidArgument( + "The first dimension of paddings must be the rank of inputs", + pad_shape.DebugString(), " ", input_shape.DebugString())); + + // Evaluate the 'padding' constant input, reshaping to a matrix. + xla::Literal pad_literal; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsInt64Literal("paddings", &pad_literal)); + + xla::XlaBuilder* b = ctx->builder(); + auto in0 = ctx->Input("input"); + absl::StatusOr in0_shape = b->GetShape(in0); + OP_REQUIRES(ctx, in0_shape.ok(), in0_shape.status()); + absl::StatusOr accum_status = + DoMirrorPad(in0, in0_shape.value(), pad_literal, mode, b); + + OP_REQUIRES_OK(ctx, accum_status.status()); + + ctx->SetOutput(0, accum_status.value()); + } + + private: + MirrorPadOp(const MirrorPadOp&) = delete; + void operator=(const MirrorPadOp&) = delete; +}; + +REGISTER_XLA_OP(Name("MirrorPad").CompileTimeConstantInput("paddings"), + MirrorPadOp); + +class MirrorPadGradOp : public XlaOpKernel { + public: + explicit MirrorPadGradOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + absl::StatusOr DoMirrorPadGrad( + const xla::XlaOp t, const xla::Shape& original_shape, + const xla::LiteralSlice& pad_literal, const MirrorPadMode mode, + xla::XlaBuilder* b) { + // The difference in the semantics of REFLECT and SYMMETRIC is that REFLECT + // will not mirror the border values while symmetric does. + // e.g. input is [1, 2, 3] and paddings is [0, 2], then the output is: + // - [1, 2, 3, 2, 1] in reflect mode + // - [1, 2, 3, 3, 2] in symmetric mode. + int64_t excluded_edges = mode == MirrorPadMode::REFLECT ? 1 : 0; + xla::XlaOp grad = t; + for (int64_t dimno = original_shape.dimensions().size() - 1; dimno >= 0; + --dimno) { + int64_t lhs_padding = pad_literal.Get({dimno, 0}); + int64_t rhs_padding = pad_literal.Get({dimno, 1}); + int64_t dim_size = original_shape.dimensions(dimno); + int64_t result_dim_size = dim_size - lhs_padding - rhs_padding; + + // Padding amounts on each side must be no more than the size of the + // original shape. + TF_RET_CHECK(lhs_padding >= 0 && + lhs_padding <= dim_size - excluded_edges); + TF_RET_CHECK(rhs_padding >= 0 && + rhs_padding <= dim_size - excluded_edges); + + xla::XlaOp lhs_pad = xla::SliceInDim(grad, 0, lhs_padding, 1, dimno); + xla::XlaOp reverse_lhs_pad = xla::Rev(lhs_pad, {dimno}); + xla::XlaOp padded_lhs_pad = xla::PadInDim( + reverse_lhs_pad, xla::ScalarLike(reverse_lhs_pad, 0), dimno, + /*pad_lo=*/excluded_edges, + /*pad_hi=*/result_dim_size - lhs_padding - excluded_edges); + + xla::XlaOp rhs_pad = + xla::SliceInDim(grad, dim_size - rhs_padding, dim_size, 1, dimno); + xla::XlaOp reverse_rhs_pad = xla::Rev(rhs_pad, {dimno}); + xla::XlaOp padded_rhs_pad = xla::PadInDim( + reverse_rhs_pad, xla::ScalarLike(reverse_rhs_pad, 0), dimno, + /*pad_lo=*/result_dim_size - rhs_padding - excluded_edges, + /*pad_hi=*/excluded_edges); + + xla::XlaOp grad_core = + xla::SliceInDim(grad, lhs_padding, dim_size - rhs_padding, 1, dimno); + + grad = padded_lhs_pad + grad_core + padded_rhs_pad; + } + return grad; + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape pad_shape = ctx->InputShape("paddings"); + + MirrorPadMode mode; + OP_REQUIRES_OK(ctx, GetNodeAttr(def(), "mode", &mode)); + OP_REQUIRES( + ctx, mode == MirrorPadMode::REFLECT || mode == MirrorPadMode::SYMMETRIC, + xla::Unimplemented("Unsupported MirrorPadGrad mode. Only SYMMETRIC and " + "REFLECT modes are currently supported")); + + const int dims = input_shape.dims(); + OP_REQUIRES( + ctx, + TensorShapeUtils::IsMatrix(pad_shape) && pad_shape.dim_size(1) == 2, + errors::InvalidArgument("paddings must be a matrix with 2 columns: ", + pad_shape.DebugString())); + OP_REQUIRES( + ctx, dims == pad_shape.dim_size(0), + errors::InvalidArgument( + "The first dimension of paddings must be the rank of inputs", + pad_shape.DebugString(), " ", input_shape.DebugString())); + + // Evaluate the 'padding' constant input, reshaping to a matrix. + xla::Literal pad_literal; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsInt64Literal("paddings", &pad_literal)); + + xla::XlaBuilder* b = ctx->builder(); + auto in0 = ctx->Input("input"); + absl::StatusOr in0_shape = b->GetShape(in0); + OP_REQUIRES(ctx, in0_shape.ok(), in0_shape.status()); + absl::StatusOr accum_status = + DoMirrorPadGrad(in0, in0_shape.value(), pad_literal, mode, b); + + OP_REQUIRES_OK(ctx, accum_status.status()); + + ctx->SetOutput(0, accum_status.value()); + } + + private: + MirrorPadGradOp(const MirrorPadGradOp&) = delete; + void operator=(const MirrorPadGradOp&) = delete; +}; + +REGISTER_XLA_OP(Name("MirrorPadGrad").CompileTimeConstantInput("paddings"), + MirrorPadGradOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/next_after_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/next_after_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..f2154911370cabfb98f5019276e71afdbc64cd47 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/next_after_op.cc @@ -0,0 +1,41 @@ +/* Copyright 2019 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/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" + +namespace tensorflow { +namespace { + +class NextAfterOp : public XlaOpKernel { + public: + explicit NextAfterOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + auto lhs = ctx->Input(0); + auto rhs = ctx->Input(1); + OP_REQUIRES_OK(ctx, BroadcastOpsToSame(&lhs, &rhs)); + ctx->SetOutput(0, xla::NextAfter(lhs, rhs)); + } +}; +REGISTER_XLA_OP(Name("NextAfter"), NextAfterOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/no_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/no_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..9b8f82600fcb8b7ea31bd8a33c8d457d33608f9e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/no_op.cc @@ -0,0 +1,40 @@ +/* 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/xla_op_registry.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { + +namespace { + +class NoOp : public OpKernel { + public: + explicit NoOp(OpKernelConstruction* context) : OpKernel(context) {} + void Compute(OpKernelContext* context) override {} + bool IsExpensive() override { return false; } +}; + +} // namespace + +// XLA_* devices also register a "real" NoOp operator so we suppress the +// dummy operator using CompilationOnly(). +REGISTER_XLA_OP(Name("NoOp").CompilationOnly(), NoOp); + +// We register ControlTrigger as a no-op. This is correct since nodes seen +// by the XLA compiler are never dead. +REGISTER_XLA_OP(Name("ControlTrigger").CompilationOnly(), NoOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/one_hot_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/one_hot_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a2dd93f5305e44dac5e79eeb3b7a996bdd3b44c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/one_hot_op.cc @@ -0,0 +1,90 @@ +/* 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. +==============================================================================*/ + +// XLA implementation of OneHot operator. + +#include + +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class OneHotOp : public XlaOpKernel { + public: + explicit OneHotOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape indices_shape = ctx->InputShape(0); + const TensorShape depth_shape = ctx->InputShape(1); + const TensorShape on_value_shape = ctx->InputShape(2); + const TensorShape off_value_shape = ctx->InputShape(3); + + const int indices_dims = indices_shape.dims(); + const int output_dims = indices_dims + 1; + + // Preliminary validation of sizes. + OP_REQUIRES( + ctx, axis_ == -1 || (axis_ >= 0 && axis_ < output_dims), + errors::InvalidArgument("Expected axis to be -1 or between [0, ", + output_dims, "). But received: ", axis_)); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(depth_shape), + errors::InvalidArgument("depth must be a scalar, but got: ", + depth_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(on_value_shape), + errors::InvalidArgument("on_value must be a scalar, but got: ", + on_value_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(off_value_shape), + errors::InvalidArgument("off_value must be a scalar, but got: ", + off_value_shape.DebugString())); + + const int axis = (axis_ == -1) ? indices_dims : axis_; + + // The one-hot dimension. + int64_t depth; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &depth)); + OP_REQUIRES( + ctx, depth >= 0, + errors::InvalidArgument("depth must be non-negative, got: ", depth)); + + xla::XlaOp one_hot; + OP_REQUIRES_OK( + ctx, XlaHelpers::OneHot(ctx->builder(), depth, axis, input_type(0), + indices_shape, ctx->Input(0), ctx->Input(2), + ctx->Input(3), &one_hot)); + ctx->SetOutput(0, one_hot); + } + + private: + int32_t axis_; + + OneHotOp(const OneHotOp&) = delete; + void operator=(const OneHotOp&) = delete; +}; + +REGISTER_XLA_OP(Name("OneHot").CompileTimeConstantInput("depth"), OneHotOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pack_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pack_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..b21ee059460f4e4f4a1441d82837ad3a892261de --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pack_op.cc @@ -0,0 +1,84 @@ +/* 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. +==============================================================================*/ + +// XLA Pack operator. + +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class PackOp : public XlaOpKernel { + public: + explicit PackOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + std::vector values; + std::vector shapes; + OP_REQUIRES_OK(ctx, ctx->InputList("values", &values, &shapes)); + const int num = values.size(); + + OP_REQUIRES(ctx, num >= 0, + errors::InvalidArgument("Pack requires >= 1 arguments")); + + // Verify that all input shapes match + for (int i = 1; i < num; i++) { + OP_REQUIRES(ctx, shapes[0].IsSameSize(shapes[i]), + errors::InvalidArgument( + "Shapes of all inputs must match: values[0].shape = ", + shapes[0].DebugString(), " != values[", i, "].shape = ", + shapes[i].DebugString())); + } + + int expanded_num_dims = shapes[0].dims() + 1; + int axis = axis_; + if (axis < 0) axis += expanded_num_dims; + + OP_REQUIRES(ctx, 0 <= axis && axis < expanded_num_dims, + errors::InvalidArgument("axis = ", axis_, " not in [", + -expanded_num_dims, ", ", + expanded_num_dims, ")")); + + std::vector reshaped_inputs(num); + + TensorShape child_shape(shapes[0]); + child_shape.InsertDim(axis, 1); + + for (int i = 0; i < num; ++i) { + // Reshape the inputs to have an extra dimension of size 1. + reshaped_inputs[i] = xla::Reshape(values[i], child_shape.dim_sizes()); + } + + ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), reshaped_inputs, axis)); + } + + private: + int axis_; +}; + +REGISTER_XLA_OP(Name("Pack"), PackOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pad_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pad_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..69f050893e1da8c58a672e6847ec22a105c8ad01 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pad_op.cc @@ -0,0 +1,144 @@ +/* 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 + +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class PadOp : public XlaOpKernel { + public: + explicit PadOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape pad_shape = ctx->InputShape("paddings"); + const int dims = input_shape.dims(); + OP_REQUIRES( + ctx, + TensorShapeUtils::IsMatrix(pad_shape) && pad_shape.dim_size(1) == 2, + errors::InvalidArgument("paddings must be a matrix with 2 columns: ", + pad_shape.DebugString())); + OP_REQUIRES( + ctx, dims == pad_shape.dim_size(0), + errors::InvalidArgument( + "The first dimension of paddings must be the rank of inputs", + pad_shape.DebugString(), " ", input_shape.DebugString())); + + xla::XlaOp input = ctx->Input("input"); + if (dims == 0) { + // Tensor is rank 0. Return it unchanged. + ctx->SetOutput(0, input); + return; + } + + xla::Literal pad_literal; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal( + "paddings", &pad_literal, + xla::ValueInferenceMode::kUpperBound)); + + xla::Literal padding_dynamism_literal; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamism("paddings", &padding_dynamism_literal)); + + xla::PaddingConfig config; + for (int i = 0; i < dims; ++i) { + auto* dim = config.add_dimensions(); + int before = pad_literal.Get({i, 0}); + int after = pad_literal.Get({i, 1}); + OP_REQUIRES(ctx, before >= 0 && after >= 0, + errors::InvalidArgument( + "Paddings must be non-negative: ", before, " ", after)); + dim->set_edge_padding_low(before); + dim->set_edge_padding_high(after); + } + + // PadV2 added a "constant_values" input that indicates the pad value. + xla::XlaOp constant_values; + xla::XlaOp pad; + if (ctx->num_inputs() == 3) { + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(ctx->InputShape("constant_values")), + errors::InvalidArgument("constant_values must be a scalar.")); + pad = xla::Pad(input, ctx->Input("constant_values"), config); + } else { + auto zero = XlaHelpers::Zero(ctx->builder(), input_type(0)); + pad = xla::Pad(input, zero, config); + } + + for (int i = 0; i < dims; ++i) { + bool low_pad_is_dynamic = padding_dynamism_literal.Get({i, 0}); + + OP_REQUIRES( + ctx, !low_pad_is_dynamic, + errors::InvalidArgument("low_pad in Pad op has to be static.")); + bool high_pad_is_dynamic = padding_dynamism_literal.Get({i, 1}); + if (high_pad_is_dynamic) { + // When we have + // pad_width = MAX_WIDTH - size(t) + // op = pad(t, /*high_pad=*/pad_width) + // The bound of the result size should be MAX_WIDTH, instead of + // `bound(t) + bound(pad_width)` + // + // We do this by analyzing the expression + // size(op) = size(t) + MAX_WIDTH - size(t) + // and leave value inference to analyze it. + xla::XlaOp high_pad_size = + xla::Slice(ctx->Input("paddings"), {i, 1}, {i + 1, 2}, {1, 1}); + high_pad_size = xla::Reshape(high_pad_size, {}); + high_pad_size = xla::ConvertElementType(high_pad_size, xla::S32); + // Low pad has to be static. + xla::XlaOp low_pad_size = xla::ConstantR0( + ctx->builder(), pad_literal.Get({i, 0})); + xla::XlaOp input_size = xla::GetDimensionSize(input, i); + xla::XlaOp total_size = low_pad_size + input_size + high_pad_size; + auto size_upper_bound_status_or = + ctx->value_inference().AnalyzeConstant( + total_size, xla::ValueInferenceMode::kUpperBound); + OP_REQUIRES_OK(ctx, size_upper_bound_status_or.status()); + auto size_upper_bound = + size_upper_bound_status_or.value().Get({}); + OP_REQUIRES( + ctx, size_upper_bound.has_value(), + errors::InvalidArgument( + "Failed to infer upperbound of total size after padding.")); + // If we know a tighter upperbound, trim the output with the new + // upperbound. + pad = xla::SliceInDim(pad, 0, size_upper_bound.value(), 1, i); + pad = xla::SetDimensionSize(pad, total_size, i); + } + } + ctx->SetOutput(0, pad); + } +}; + +REGISTER_XLA_OP(Name("Pad").CompileTimeConstantInput("paddings"), PadOp); +REGISTER_XLA_OP(Name("PadV2").CompileTimeConstantInput("paddings"), PadOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pooling_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pooling_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..2d243cae34cd912674e18e33dd1a7f25e1f26591 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/pooling_ops.cc @@ -0,0 +1,780 @@ +/* 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. +==============================================================================*/ + +// XLA specific pooling ops. + +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/pooling.h" +#include "xla/hlo/builder/padding.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/determinism.h" +#include "tensorflow/core/util/padding.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +template +static absl::Status ValidateKernelSizes(const T& ksizes) { + for (size_t i = 0; i < ksizes.size(); ++i) { + if (ksizes[i] <= 0) { + return errors::InvalidArgument( + "Sliding window ksize field for dimension ", i, + " must be positive but is ", ksizes[i]); + } + } + return absl::OkStatus(); +} + +template +static absl::Status ValidateStrides(const T& strides) { + for (size_t i = 0; i < strides.size(); ++i) { + if (strides[i] <= 0) { + return errors::InvalidArgument( + "Sliding window stride field for dimension ", i, + " must be positive but is ", strides[i]); + } + } + return absl::OkStatus(); +} + +// Superclass of pooling ops. +class PoolingOp : public XlaOpKernel { + public: + PoolingOp(OpKernelConstruction* ctx, int num_spatial_dims, + const DataType reduction_type) + : XlaOpKernel(ctx), + num_spatial_dims_(num_spatial_dims), + reduction_type_(reduction_type) { + if (ctx->num_inputs() == 1) { + std::vector ksize_int; + std::vector stride_int; + OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_int)); + OP_REQUIRES(ctx, ksize_int.size() == num_dims(), + errors::InvalidArgument("Sliding window ksize field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_int)); + OP_REQUIRES(ctx, stride_int.size() == num_dims(), + errors::InvalidArgument("Sliding window stride field must " + "specify ", + num_dims(), " dimensions")); + for (int i = 0; i < num_dims(); ++i) { + ksize_.push_back(ksize_int[i]); + stride_.push_back(stride_int[i]); + } + } + Padding padding; + OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding)); + OP_REQUIRES(ctx, padding != EXPLICIT, + errors::Unimplemented( + "XLA does not support pooling ops with explicit padding.")); + padding_ = (padding == VALID) ? xla::Padding::kValid : xla::Padding::kSame; + + OP_REQUIRES_OK( + ctx, DataTypeToPrimitiveType(reduction_type_, &xla_reduction_type_)); + } + + int num_dims() const { return num_spatial_dims_ + 2; } + + protected: + absl::StatusOr> GetKernelSize(XlaOpKernelContext* ctx) { + std::vector ksize; + if (ctx->num_inputs() == 1) { + ksize = ksize_; + } else { + const TensorShape ksize_shape = ctx->InputShape(1); + // Validate input sizes. + if (!TensorShapeUtils::IsVector(ksize_shape)) { + return errors::InvalidArgument("ksize must be a vector, not shape ", + ksize_shape.DebugString()); + } + if (ksize_shape.num_elements() != num_dims()) { + return errors::InvalidArgument( + "Sliding window ksize field must " + "specify ", + num_dims(), " dimensions"); + } + auto status = ctx->ConstantInputAsIntVector(1, &ksize); + if (!status.ok()) { + return status; + } + } + TF_RETURN_IF_ERROR(ValidateKernelSizes(ksize)); + return ksize; + } + + absl::StatusOr> GetStride(XlaOpKernelContext* ctx) { + std::vector stride; + if (ctx->num_inputs() == 1) { + stride = stride_; + } else { + const TensorShape stride_shape = ctx->InputShape(2); + // Validate input sizes. + if (!TensorShapeUtils::IsVector(stride_shape)) { + return errors::InvalidArgument("stride must be a vector, not shape ", + stride_shape.DebugString()); + } + if (stride_shape.num_elements() != num_dims()) { + return errors::InvalidArgument( + "Sliding window stride field must " + "specify ", + num_dims(), " dimensions"); + } + auto status = ctx->ConstantInputAsIntVector(2, &stride); + if (!status.ok()) { + return status; + } + } + TF_RETURN_IF_ERROR(ValidateStrides(stride)); + return stride; + } + + protected: + const int num_spatial_dims_; + std::vector ksize_; + std::vector stride_; + xla::Padding padding_; + TensorFormat data_format_ = FORMAT_NHWC; + DataType reduction_type_; + xla::PrimitiveType xla_reduction_type_; +}; + +// Converts the tensor data format to the one required by the XLA pooling +// library. +xla::TensorFormat XlaTensorFormat(tensorflow::TensorFormat data_format, + int num_spatial_dims) { + int num_dims = num_spatial_dims + 2; + int batch_dimension = GetTensorBatchDimIndex(num_dims, data_format); + int feature_dimension = GetTensorFeatureDimIndex(num_dims, data_format); + absl::InlinedVector spatial_dimensions(num_spatial_dims); + for (int spatial_dim = 0; spatial_dim < num_spatial_dims; ++spatial_dim) { + spatial_dimensions[spatial_dim] = + GetTensorSpatialDimIndex(num_dims, data_format, spatial_dim); + } + return xla::TensorFormat(/*batch_dimension=*/batch_dimension, + /*feature_dimension=*/feature_dimension, + /*spatial_dimensions=*/spatial_dimensions); +} + +class MaxPoolOp : public PoolingOp { + public: + MaxPoolOp(OpKernelConstruction* ctx, int num_spatial_dims) + : PoolingOp(ctx, /*num_spatial_dims=*/num_spatial_dims, + /*reduction_type=*/ctx->input_type(0)) { + std::string data_format_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); + OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_), + errors::InvalidArgument("Invalid data format")); + OP_REQUIRES(ctx, data_format_ != FORMAT_NHWC_VECT_W, + errors::Unimplemented( + "XLA does not support the VECT_NHWC_VECT_W data format. " + "Returning unimplemented from MaxPool to keep " + "Tensorflow's intended optimized MaxPool here.")); + } + + void Compile(XlaOpKernelContext* ctx) override { + auto ksize_or_error = GetKernelSize(ctx); + OP_REQUIRES_OK(ctx, ksize_or_error.status()); + std::vector ksize = ksize_or_error.value(); + + auto stride_or_error = GetStride(ctx); + OP_REQUIRES_OK(ctx, stride_or_error.status()); + std::vector stride = stride_or_error.value(); + + xla::XlaOp input = ctx->Input(0); + + absl::StatusOr input_shape = ctx->builder()->GetShape(input); + OP_REQUIRES_OK(ctx, input_shape.status()); + + // For VECT_C max-pool ops, transpose to plain NCHW, do the max-pool, and + // transpose back. This isn't necessarily the most efficient algorithm, but + // it's ok for starters. + std::optional vect_width; + if (data_format_ == FORMAT_NCHW_VECT_C) { + vect_width = input_shape->dimensions().back(); + input = xla::Collapse(xla::Transpose(input, {0, 1, 4, 2, 3}), {1, 2}); + + input_shape = ctx->builder()->GetShape(input); + OP_REQUIRES_OK(ctx, input_shape.status()); + } + + OP_REQUIRES(ctx, input_shape->dimensions().size() == num_dims(), + errors::InvalidArgument("Input to ", type_string(), + " operator must have ", num_dims(), + " dimensions")); + auto pooling = xla::MaxPool( + input, ksize, stride, padding_, + XlaTensorFormat( + data_format_ == FORMAT_NCHW_VECT_C ? FORMAT_NCHW : data_format_, + input_shape->dimensions().size() - 2)); + + if (data_format_ == FORMAT_NCHW_VECT_C) { + absl::StatusOr result_shape = + ctx->builder()->GetShape(pooling); + OP_REQUIRES_OK(ctx, result_shape.status()); + + int64_t num_channels = result_shape->dimensions(1); + OP_REQUIRES( + ctx, num_channels % *vect_width == 0, + errors::FailedPrecondition("Result of NCHW_VECT_C op must have " + "channels multiple of ", + *vect_width, ", but was ", num_channels)); + + absl::InlinedVector new_dims( + result_shape->dimensions().begin(), result_shape->dimensions().end()); + new_dims[1] /= *vect_width; + new_dims.insert(new_dims.begin() + 2, *vect_width); + pooling = + xla::Transpose(xla::Reshape(pooling, new_dims), {0, 1, 3, 4, 2}); + } + + ctx->SetOutput(0, pooling); + } +}; + +class MaxPool2DOp : public MaxPoolOp { + public: + explicit MaxPool2DOp(OpKernelConstruction* ctx) + : MaxPoolOp(ctx, /*num_spatial_dims=*/2) {} +}; +REGISTER_XLA_OP(Name("MaxPool"), MaxPool2DOp); +REGISTER_XLA_OP(Name("MaxPoolV2") + .CompileTimeConstantInput("ksize") + .CompileTimeConstantInput("strides"), + MaxPool2DOp); + +class MaxPool3DOp : public MaxPoolOp { + public: + explicit MaxPool3DOp(OpKernelConstruction* ctx) + : MaxPoolOp(ctx, /*num_spatial_dims=*/3) {} +}; +REGISTER_XLA_OP(Name("MaxPool3D"), MaxPool3DOp); + +class AvgPoolOp : public PoolingOp { + public: + AvgPoolOp(OpKernelConstruction* ctx, int num_spatial_dims) + : PoolingOp(ctx, /*num_spatial_dims=*/num_spatial_dims, + /*reduction_type=*/ + XlaHelpers::SumAccumulationType(ctx->input_type(0))) { + std::string data_format_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); + OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_), + errors::InvalidArgument("Invalid data format")); + } + + void Compile(XlaOpKernelContext* ctx) override { + auto ksize_or_error = GetKernelSize(ctx); + OP_REQUIRES_OK(ctx, ksize_or_error.status()); + std::vector ksize = ksize_or_error.value(); + + auto stride_or_error = GetStride(ctx); + OP_REQUIRES_OK(ctx, stride_or_error.status()); + std::vector stride = stride_or_error.value(); + + const TensorShape input_shape = ctx->InputShape(0); + OP_REQUIRES(ctx, input_shape.dims() == num_dims(), + errors::InvalidArgument("Input to ", type_string(), + " operator must have ", num_dims(), + " dimensions")); + + auto xla_data_format = + XlaTensorFormat(data_format_, input_shape.dims() - 2); + auto spatial_padding = MakeSpatialPadding( + input_shape.dim_sizes(), ksize, stride, padding_, xla_data_format); + + // Convert the input to the reduction type. + auto converted_input = + ConvertElementType(ctx->Input(0), xla_reduction_type_); + auto pooling = + xla::AvgPool(converted_input, ksize, stride, spatial_padding, + xla_data_format, padding_ == xla::Padding::kValid); + // Convert the pooling result back to the input type before returning it. + ctx->SetOutput(0, ConvertElementType(pooling, ctx->input_xla_type(0))); + } +}; + +class AvgPool2DOp : public AvgPoolOp { + public: + explicit AvgPool2DOp(OpKernelConstruction* ctx) + : AvgPoolOp(ctx, /*num_spatial_dims=*/2) {} +}; +REGISTER_XLA_OP(Name("AvgPool"), AvgPool2DOp); + +REGISTER_XLA_OP(Name("AvgPool3D"), MlirXlaOpKernel); + +// The operation to compute MaxPool gradients. +// It takes three inputs: +// - The original input tensor +// - The original output tensor +// - Backprop tensor for output +// It produces one output: backprop tensor for input. +class MaxPoolGradOp : public XlaOpKernel { + public: + MaxPoolGradOp(OpKernelConstruction* ctx, int num_spatial_dims) + : XlaOpKernel(ctx), num_spatial_dims_(num_spatial_dims) { + if (ctx->num_inputs() == 3) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_)); + } + OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_)); + OP_REQUIRES(ctx, padding_ != EXPLICIT, + errors::Unimplemented( + "XLA does not support maxpoolgrad with explicit padding.")); + // When determinism is enabled, the use of SelectAndScatter causes a generic + // error to be raised. We raise a more informative error here before + // SelectAndScatter is used. + OP_REQUIRES( + ctx, !tensorflow::OpDeterminismRequired(), + errors::Unimplemented("GPU MaxPool gradient ops do not yet have a " + "deterministic XLA implementation.")); + } + + int num_dims() const { return num_spatial_dims_ + 2; } + + void Compile(XlaOpKernelContext* ctx) override { + if (ctx->num_inputs() != 3) { + OP_REQUIRES( + ctx, ctx->num_inputs() == 5, + errors::InvalidArgument("Must supply ksize and stride arguments.")); + const TensorShape ksize_shape = ctx->InputShape(3); + // Validate input sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ksize_shape), + errors::InvalidArgument("ksize must be a vector, not shape ", + ksize_shape.DebugString())); + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(3, &ksize_)); + + const TensorShape stride_shape = ctx->InputShape(4); + // Validate input sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(stride_shape), + errors::InvalidArgument("stride must be a vector, not shape ", + stride_shape.DebugString())); + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(4, &stride_)); + } + + OP_REQUIRES(ctx, ksize_.size() == num_dims(), + errors::InvalidArgument("Sliding window ksize field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ValidateKernelSizes(ksize_)); + OP_REQUIRES(ctx, stride_.size() == num_dims(), + errors::InvalidArgument("Sliding window strides field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ValidateStrides(stride_)); + + const TensorShape tensor_in_shape = ctx->InputShape(0); + const TensorShape tensor_out_shape = ctx->InputShape(1); + const TensorShape out_backprop_shape = ctx->InputShape(2); + + // For maxpooling, tensor_in should have num_dims() dimensions. + OP_REQUIRES(ctx, tensor_in_shape.dims() == num_dims(), + errors::InvalidArgument("tensor_in must be ", num_dims(), + "-dimensional")); + OP_REQUIRES(ctx, tensor_out_shape.dims() == num_dims(), + errors::InvalidArgument("tensor_out must be ", num_dims(), + "-dimensional")); + // For maxpooling, out_backprop should have num_dims() dimensions. + OP_REQUIRES(ctx, out_backprop_shape.dims() == num_dims(), + errors::InvalidArgument("out_backprop must be ", num_dims(), + "-dimensional")); + + // TODO(phawkins): The XLA version doesn't need tensor_out. Investigate + // whether this is a good time/space tradeoff. + auto input = ctx->Input(0); + auto out_backprop = ctx->Input(2); + // We ensured padding_ is not EXPLICIT in the constructor. + xla::Padding xla_padding = + (padding_ == VALID) ? xla::Padding::kValid : xla::Padding::kSame; + + // Create a MaxPool operation to check the expected resulting shape, and + // then throw away the operation because we don't actually need it here. + TensorShape expected_out_shape; + auto pooling = + xla::MaxPool(ctx->Input(0), ksize_, stride_, xla_padding, + XlaTensorFormat(data_format_, tensor_in_shape.dims() - 2)); + auto status_or_shape = pooling.builder()->GetShape(pooling); + OP_REQUIRES_OK(ctx, status_or_shape.status()); + OP_REQUIRES_OK(ctx, XLAShapeToTensorShape(status_or_shape.value(), + &expected_out_shape)); + OP_REQUIRES(ctx, expected_out_shape == out_backprop_shape, + errors::Unimplemented("The output dimensions do not match the " + "other input values.")); + + xla::PrimitiveType element_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(input_type(2), &element_type)); + xla::XlaOp init_value = XlaHelpers::Zero(ctx->builder(), input_type(2)); + auto select = CreateScalarGeComputation(element_type, ctx->builder()); + auto scatter = CreateScalarAddComputation(element_type, ctx->builder()); + xla::XlaOp gradients = + xla::SelectAndScatter(input, select, ksize_, stride_, xla_padding, + out_backprop, init_value, scatter); + + ctx->SetOutput(0, gradients); + } + + protected: + const int num_spatial_dims_; + std::vector ksize_; + std::vector stride_; + Padding padding_; + TensorFormat data_format_ = FORMAT_NHWC; +}; + +class MaxPool2DGradOp : public MaxPoolGradOp { + public: + explicit MaxPool2DGradOp(OpKernelConstruction* ctx) + : MaxPoolGradOp(ctx, /*num_spatial_dims=*/2) { + std::string data_format; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format)); + OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_), + errors::InvalidArgument("Invalid data format")); + } +}; +REGISTER_XLA_OP(Name("MaxPoolGrad"), MaxPool2DGradOp); +REGISTER_XLA_OP(Name("MaxPoolGradV2") + .CompileTimeConstantInput("ksize") + .CompileTimeConstantInput("strides"), + MaxPool2DGradOp); + +REGISTER_XLA_OP(Name("MaxPool3DGrad"), MlirXlaOpKernel); + +// Average-pooling gradient +class AvgPoolGradOp : public XlaOpKernel { + public: + AvgPoolGradOp(OpKernelConstruction* ctx, int num_spatial_dims) + : XlaOpKernel(ctx), num_spatial_dims_(num_spatial_dims) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_)); + OP_REQUIRES(ctx, ksize_.size() == num_dims(), + errors::InvalidArgument("Sliding window ksize field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ValidateKernelSizes(ksize_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_)); + OP_REQUIRES(ctx, stride_.size() == num_dims(), + errors::InvalidArgument("Sliding window strides field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ValidateStrides(stride_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_)); + OP_REQUIRES(ctx, padding_ != EXPLICIT, + errors::Unimplemented( + "XLA does not support avgpoolgrad with explicit padding.")); + OP_REQUIRES(ctx, ksize_[0] == 1 && stride_[0] == 1, + errors::Unimplemented( + "Pooling is not yet supported on the batch dimension.")); + + std::string data_format; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format)); + OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_), + errors::InvalidArgument("Invalid data format")); + } + + int num_dims() const { return num_spatial_dims_ + 2; } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape gradients_shape; + OP_REQUIRES_OK( + ctx, ctx->ConstantInputAsShape(0, &gradients_shape, + xla::ValueInferenceMode::kUpperBound)); + + const TensorShape out_backprop_shape = ctx->InputShape(1); + + // For avgpooling, tensor_in_shape should have num_dims() dimensions. + OP_REQUIRES(ctx, gradients_shape.dims() == num_dims(), + errors::InvalidArgument("orig_input_shape must be ", num_dims(), + "-dimensional")); + + // For avgpooling, out_backprop should have num_dims() dimensions. + OP_REQUIRES(ctx, out_backprop_shape.dims() == num_dims(), + errors::InvalidArgument("out_backprop must be ", num_dims(), + "-dimensional")); + + auto out_backprop = ctx->Input(1); + std::vector stride_int64s(stride_.begin(), stride_.end()); + xla::Padding xla_padding = + (padding_ == VALID) ? xla::Padding::kValid : xla::Padding::kSame; + xla::PrimitiveType xla_reduction_type; + auto reduction_type = XlaHelpers::SumAccumulationType(ctx->input_type(1)); + OP_REQUIRES_OK( + ctx, DataTypeToPrimitiveType(reduction_type, &xla_reduction_type)); + auto converted_out_backprop = + xla::ConvertElementType(out_backprop, xla_reduction_type); + auto xla_data_format = + XlaTensorFormat(data_format_, gradients_shape.dims() - 2); + auto padding_values = + MakeSpatialPadding(gradients_shape.dim_sizes(), ksize_, stride_int64s, + xla_padding, xla_data_format); + auto in_backprop = + xla::AvgPoolGrad(converted_out_backprop, gradients_shape.dim_sizes(), + ksize_, stride_int64s, padding_values, xla_data_format, + /*counts_include_padding=*/padding_ == VALID); + // Convert the pooling result back to the input type before returning it. + xla::PrimitiveType xla_out_backprop_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(ctx->input_type(1), + &xla_out_backprop_type)); + ctx->SetOutput(0, + xla::ConvertElementType(in_backprop, xla_out_backprop_type)); + } + + protected: + const int num_spatial_dims_; + std::vector ksize_; + std::vector stride_; + Padding padding_; + TensorFormat data_format_ = FORMAT_NHWC; +}; + +class AvgPool2DGradOp : public AvgPoolGradOp { + public: + explicit AvgPool2DGradOp(OpKernelConstruction* ctx) + : AvgPoolGradOp(ctx, /*num_spatial_dims=*/2) {} +}; +REGISTER_XLA_OP( + Name("AvgPoolGrad").CompileTimeConstantInput("orig_input_shape"), + AvgPool2DGradOp); + +class AvgPool3DGradOp : public AvgPoolGradOp { + public: + explicit AvgPool3DGradOp(OpKernelConstruction* ctx) + : AvgPoolGradOp(ctx, /*num_spatial_dims=*/3) {} +}; +REGISTER_XLA_OP( + Name("AvgPool3DGrad").CompileTimeConstantInput("orig_input_shape"), + AvgPool3DGradOp); + +class MaxPoolGradGradOp : public XlaOpKernel { + public: + MaxPoolGradGradOp(OpKernelConstruction* ctx, int num_spatial_dims) + : XlaOpKernel(ctx), num_spatial_dims_(num_spatial_dims) { + if (ctx->num_inputs() == 3) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("ksize", &ksize_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("strides", &stride_)); + } + OP_REQUIRES_OK(ctx, ctx->GetAttr("padding", &padding_)); + OP_REQUIRES( + ctx, padding_ != EXPLICIT, + errors::Unimplemented( + "XLA does not support maxpoolgradgrad with explicit padding.")); + } + + int num_dims() const { return num_spatial_dims_ + 2; } + + void Compile(XlaOpKernelContext* ctx) override { + if (ctx->num_inputs() != 3) { + OP_REQUIRES( + ctx, ctx->num_inputs() == 5, + errors::InvalidArgument("Must supply ksize and stride arguments.")); + const TensorShape ksize_shape = ctx->InputShape(3); + // Validate input sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(ksize_shape), + errors::InvalidArgument("ksize must be a vector, not shape ", + ksize_shape.DebugString())); + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(3, &ksize_)); + + const TensorShape stride_shape = ctx->InputShape(4); + // Validate input sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(stride_shape), + errors::InvalidArgument("stride must be a vector, not shape ", + stride_shape.DebugString())); + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(4, &stride_)); + } + + OP_REQUIRES(ctx, ksize_.size() == num_dims(), + errors::InvalidArgument("Sliding window ksize field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ValidateKernelSizes(ksize_)); + OP_REQUIRES(ctx, stride_.size() == num_dims(), + errors::InvalidArgument("Sliding window strides field must " + "specify ", + num_dims(), " dimensions")); + OP_REQUIRES_OK(ctx, ValidateStrides(stride_)); + + const TensorShape tensor_in_shape = ctx->InputShape(0); + const TensorShape tensor_out_shape = ctx->InputShape(1); + const TensorShape out_backprop_shape = ctx->InputShape(2); + + // For maxpooling, tensor_in should have num_dims() dimensions. + OP_REQUIRES(ctx, tensor_in_shape.dims() == num_dims(), + errors::InvalidArgument("tensor_in must be ", num_dims(), + "-dimensional")); + OP_REQUIRES(ctx, tensor_out_shape.dims() == num_dims(), + errors::InvalidArgument("tensor_out must be ", num_dims(), + "-dimensional")); + // For maxpooling, out_backprop should have num_dims() dimensions. + OP_REQUIRES(ctx, out_backprop_shape.dims() == num_dims(), + errors::InvalidArgument("out_backprop must be ", num_dims(), + "-dimensional")); + + // What we want to compute: + // Given y = MaxPool(x), and xs_grad = MaxPoolGrad(x, y, ys_grad) + // MaxPoolGradGrad computes {ys_grad}_grad given x, y, and {xs_grad}_grad. + // + // In the regular TF op, this amounts to selecting for each window the + // incoming backprop value from xs_grad_grad that corresponds to the maximal + // value in the corresponding window of x. + // + // TODO(b/73062247): What we really want is a ReduceWindow with different + // arrays for index selection vs return value selection--a select-to-gather. + // + // Here, we implement a bitwise hack: we use the hi 16 bits of input for + // separate max pooling alongside each of the hi and lo 16 bits of + // out_backprop packed into 16 lo bits, which we then glue back together at + // the end to get a full 32 bits of gradient. + // + // This could select the wrong backprop value for two x values that are + // equally maximal up to the first 16 bits, in which case we are taking the + // latter. + // + // Note that in principle we could use 32 separate maxpools to recover each + // of 32 bits of the gradient while preserving 31 bits of input for the max + // pooling criteria; here, we just truncate to the first 16 bits of input. + + auto input = ctx->Input(0); + auto out_backprop = ctx->Input(2); + + auto b = ctx->builder(); + + auto sixteen = xla::ConstantR0(b, 16); + // in (f32) -> round to 7 mantissa bits (bf16)-> 16-high-bit u32. + // + // NOTE: Use a ReducePrecision operation instead of a cast to BF16 and back + // to F32 since the XLA compiler may ignore narrowing casts to floating + // point types if the debug option xla_allow_excess_precision is set. + auto in_hi = xla::BitcastConvertType( + xla::ReducePrecision(input, /*exponent_bits=*/8, /*mantissa_bits=*/7), + xla::U32); + auto bp_int = xla::BitcastConvertType(out_backprop, xla::U32); + auto bp_hi = xla::ShiftRightLogical(bp_int, sixteen); + auto bp_lo = + xla::ShiftRightLogical(xla::ShiftLeft(bp_int, sixteen), sixteen); + auto in_hi_bp_hi = xla::Add(in_hi, bp_hi); // Want an unsigned add. + auto in_hi_bp_lo = xla::Add(in_hi, bp_lo); // Want an unsigned add. + + auto init_value = xla::MinValue(b, xla::F32); + // We will reduce by taking the maximal value up to 16 bits (ignoring the lo + // 16 bits of packed-in hi/lo backprop value). + auto rb = b->CreateSubBuilder("GreaterOrEqOf_ByFirst16Bits"); + { + // F32 parameters to satisfy lowering type restriction for reduce opcode. + const xla::Shape scalar = xla::ShapeUtil::MakeShape(xla::F32, {}); + auto lhs = xla::Parameter(rb.get(), 0, scalar, "lhs"); + auto rhs = xla::Parameter(rb.get(), 1, scalar, "rhs"); + auto sixteen = xla::ConstantR0(rb.get(), 16); + auto lhs_criteria = + xla::ShiftLeft(xla::ShiftRightLogical( + xla::BitcastConvertType(lhs, xla::S32), sixteen), + sixteen); + auto rhs_criteria = + xla::ShiftLeft(xla::ShiftRightLogical( + xla::BitcastConvertType(rhs, xla::S32), sixteen), + sixteen); + // Must use a F32 comparison, because S32 would not work for negatives. + xla::Select(xla::Ge(xla::BitcastConvertType(lhs_criteria, xla::F32), + xla::BitcastConvertType(rhs_criteria, xla::F32)), + lhs, rhs); + } + auto reduce = rb->BuildAndNoteError(); + xla::Padding xla_padding = + (padding_ == VALID) ? xla::Padding::kValid : xla::Padding::kSame; + auto pooled_hi = + xla::ReduceWindow(xla::BitcastConvertType(in_hi_bp_hi, xla::F32), + init_value, reduce, ksize_, stride_, xla_padding); + auto pooled_lo = + xla::ReduceWindow(xla::BitcastConvertType(in_hi_bp_lo, xla::F32), + init_value, reduce, ksize_, stride_, xla_padding); + auto grads_hi = + xla::ShiftLeft(xla::BitcastConvertType(pooled_hi, xla::U32), sixteen); + auto grads_lo = xla::ShiftRightLogical( + xla::ShiftLeft(xla::BitcastConvertType(pooled_lo, xla::U32), sixteen), + sixteen); + auto grads = xla::Add(grads_hi, grads_lo); // Want an unsigned add. + + xla::PrimitiveType element_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(input_type(2), &element_type)); + ctx->SetOutput(0, xla::BitcastConvertType(grads, element_type)); + } + + protected: + const int num_spatial_dims_; + std::vector ksize_; + std::vector stride_; + Padding padding_; + TensorFormat data_format_ = FORMAT_NHWC; +}; + +class MaxPool2DGradGradOp : public MaxPoolGradGradOp { + public: + explicit MaxPool2DGradGradOp(OpKernelConstruction* ctx) + : MaxPoolGradGradOp(ctx, /*num_spatial_dims=*/2) { + std::string data_format; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format)); + OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_), + errors::InvalidArgument("Invalid data format")); + } +}; +REGISTER_XLA_OP(Name("MaxPoolGradGrad").TypeConstraint("T", DT_FLOAT), + MaxPool2DGradGradOp); +REGISTER_XLA_OP(Name("MaxPoolGradGradV2") + .TypeConstraint("T", DT_FLOAT) + .CompileTimeConstantInput("ksize") + .CompileTimeConstantInput("strides"), + MaxPool2DGradGradOp); + +class MaxPool3DGradGradOp : public MaxPoolGradGradOp { + public: + explicit MaxPool3DGradGradOp(OpKernelConstruction* ctx) + : MaxPoolGradGradOp(ctx, /*num_spatial_dims=*/3) { + std::string data_format; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format)); + OP_REQUIRES(ctx, FormatFromString(data_format, &data_format_), + errors::InvalidArgument("Invalid data format")); + } +}; +REGISTER_XLA_OP(Name("MaxPool3DGradGrad").TypeConstraint("T", DT_FLOAT), + MaxPool3DGradGradOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/qr_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/qr_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..394b2957fbc5b89fe351c5fb9f5d1fa81faa2eb5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/qr_op.cc @@ -0,0 +1,47 @@ +/* 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/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/qr.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" + +namespace tensorflow { +namespace { + +class QROp : public XlaOpKernel { + public: + explicit QROp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("full_matrices", &full_matrices_)); + } + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp q, r; + xla::QrExplicit(ctx->Input(0), full_matrices_, q, r); + ctx->SetOutput(0, q); + ctx->SetOutput(1, r); + } + + private: + // If true, compute full-sized q and r. If false, compute only the leading P + // columns of q. + bool full_matrices_; +}; + +REGISTER_XLA_OP(Name("Qr"), QROp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..38e1fb2380ca4128f364614a1d53f71cb072d2fa --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/quantize_and_dequantize_op.cc @@ -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. +==============================================================================*/ + +#include +#include +#include + +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +enum QuantizerRoundMode { + // Round half up: if the fraction of y is exactly 0.5, then + // round(y) = y + 0.5 + // E.g., -5.5 gets rounded to -5, -5.4 goes to -5, + // 5.4 goes to 5, and 5.5 goes to 6. + ROUND_HALF_UP, + // Round half to even: if the fraction of y is exactly 0.5, then round(y) is + // the nearest even integer to y. + // E.g., 23.5 gets rounded to 24, 24.5 gets rounded to 24, while -23.5 becomes + // -24, and -24.5 gets rounded to 24. + ROUND_HALF_TO_EVEN, +}; + +class QuantizeAndDequantizeOp : public XlaOpKernel { + public: + explicit QuantizeAndDequantizeOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("signed_input", &signed_input_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("range_given", &range_given_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("narrow_range", &narrow_range_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_)); + round_mode_ = ROUND_HALF_TO_EVEN; + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + const DataType data_type = ctx->input_type(0); + + xla::PrimitiveType xla_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(data_type, &xla_type)); + + xla::XlaBuilder* b = ctx->builder(); + + // The implementation follows + // tensorflow/core/kernels/quantize_and_dequantize_op.h closely. + xla::XlaOp min_range, max_range; + if (range_given_) { + min_range = ctx->Input(1); + max_range = ctx->Input(2); + } else { + const xla::XlaComputation* fmax = ctx->GetOrCreateMax(data_type); + const xla::XlaComputation* fmin = ctx->GetOrCreateMin(data_type); + if (axis_ == -1) { + min_range = ReduceAll(input, xla::MaxValue(b, xla_type), *fmin); + max_range = ReduceAll(input, xla::MinValue(b, xla_type), *fmax); + } else { + std::vector dimensions_to_reduce; + TensorShape input_shape = ctx->InputShape(0); + int64_t input_rank = input_shape.dims(); + OP_REQUIRES(ctx, input_rank >= 1, + errors::Unimplemented("QuantizeAndDequantizeOp with axis " + "!= -1 requires minimum rank 1")); + OP_REQUIRES( + ctx, axis_ >= 0 && axis_ < input_rank, + errors::Unimplemented("QuantizeAndDequantizeOp with invalid axis")); + dimensions_to_reduce.reserve(input_rank - 1); + for (int64_t i = 0; i < input_rank; ++i) { + if (i != axis_) { + dimensions_to_reduce.push_back(i); + } + } + min_range = Reduce(input, xla::MaxValue(b, xla_type), *fmin, + dimensions_to_reduce); + max_range = Reduce(input, xla::MinValue(b, xla_type), *fmax, + dimensions_to_reduce); + } + } + + xla::XlaOp num_bits; + if (num_bits_ < 0) { + OP_REQUIRES( + ctx, ctx->num_inputs() == 4, + errors::Internal("Expected 4 inputs to QuantizeAndDequantize")); + num_bits = ctx->Input(3); + } else { + num_bits = xla::ConstantR0(b, num_bits_); + } + + const xla::XlaOp zero = XlaHelpers::Zero(b, data_type); + const xla::XlaOp one = XlaHelpers::One(b, data_type); + const xla::XlaOp two = XlaHelpers::FloatLiteral(b, data_type, 2.0); + const xla::XlaOp half = XlaHelpers::FloatLiteral(b, data_type, 0.5); + + // Calculate the range for the simulated integer quantization: + // e.g. [-128,127] for signed = true, num_bits = 8, + // or [0, 255] for signed = false, num_bits = 8. + // We do this in floating point for hardware that does not have 64-bit + // integer support. + xla::XlaOp min_quantized, max_quantized; + if (signed_input_) { + if (narrow_range_) { + min_quantized = -Pow(two, ConvertElementType( + num_bits - xla::ConstantR0(b, 1), + xla_type)) + + one; + } else { + min_quantized = + -Pow(two, ConvertElementType( + num_bits - xla::ConstantR0(b, 1), xla_type)); + } + max_quantized = + Pow(two, ConvertElementType(num_bits - xla::ConstantR0(b, 1), + xla_type)) - + one; + } else { + min_quantized = zero; + max_quantized = Pow(two, ConvertElementType(num_bits, xla_type)) - one; + } + + // Determine the maximum scaling factor that would scale + // [min_range, max_range] to not exceed [min_quantized, max_quantized], + // while keeping 0 unchanged. + xla::XlaOp scale_from_min_side = + Select(Gt(min_quantized * min_range, zero), min_quantized / min_range, + xla::MaxFiniteValue(b, xla_type)); + xla::XlaOp scale_from_max_side = + Select(Gt(max_quantized * max_range, zero), max_quantized / max_range, + xla::MaxFiniteValue(b, xla_type)); + + // Note: Avoids changing the side of the range that determines scale. + xla::XlaOp cond = Lt(scale_from_min_side, scale_from_max_side); + xla::XlaOp scale = Select(cond, scale_from_min_side, scale_from_max_side); + xla::XlaOp inverse_scale = + Select(cond, min_range / min_quantized, max_range / max_quantized); + min_range = Select(cond, min_range, min_quantized * inverse_scale); + max_range = Select(cond, max_quantized * inverse_scale, max_range); + + // The instruction min_range has the shape of the axis, which is also the + // shape for max_range, scale and inverse_scale. + xla::Shape axis_shape = b->GetShape(min_range).value(); + // The XLA client library can handle implicit broadcast from scalar. Add + // explicit broadcast if the axis has a non-scalar shape. + if (!xla::ShapeUtil::IsScalar(axis_shape)) { + xla::Shape input_shape = b->GetShape(input).value(); + absl::Span input_dimensions = input_shape.dimensions(); + auto convert_to_input_shape = [&](const xla::XlaOp op) { + return xla::BroadcastInDim(op, input_dimensions, {axis_}); + }; + min_range = convert_to_input_shape(min_range); + max_range = convert_to_input_shape(max_range); + scale = convert_to_input_shape(scale); + inverse_scale = convert_to_input_shape(inverse_scale); + } + + if (range_given_) { + // Note: The clamping here is to avoid overflow in the quantized type. + // The semantics of the op does not guarantee to clamp to the specified + // min_range and max_range - because we may have changed either min_range + // or max_range. + // No need to clamp to min_range and max_range if range_given_ == false as + // in that case they were measured from the tensor. + input = Clamp(min_range, input, max_range); + } + xla::XlaOp result; + switch (round_mode_) { + case ROUND_HALF_TO_EVEN: { + result = xla::RoundToEven(input * scale) * inverse_scale; + break; + } + case ROUND_HALF_UP: { + result = Floor(input * scale + half) * inverse_scale; + break; + } + } + ctx->SetOutput(0, result); + } + + protected: + int64_t num_bits_ = -1; + int axis_; + bool signed_input_; + bool range_given_; + bool narrow_range_; + QuantizerRoundMode round_mode_; +}; + +class QuantizeAndDequantizeV2Op : public QuantizeAndDequantizeOp { + public: + explicit QuantizeAndDequantizeV2Op(OpKernelConstruction* ctx) + : QuantizeAndDequantizeOp(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("num_bits", &num_bits_)); + OP_REQUIRES(ctx, num_bits_ > 0 && num_bits_ < (signed_input_ ? 62 : 63), + errors::InvalidArgument("num_bits is out of range: ", num_bits_, + " with signed_input_ ", signed_input_)); + std::string round_mode_string; + OP_REQUIRES_OK(ctx, ctx->GetAttr("round_mode", &round_mode_string)); + OP_REQUIRES( + ctx, + (round_mode_string == "HALF_UP" || round_mode_string == "HALF_TO_EVEN"), + errors::InvalidArgument("Round mode string must be " + "'HALF_UP' or " + "'HALF_TO_EVEN', is '" + + round_mode_string + "'")); + if (round_mode_string == "HALF_UP") { + round_mode_ = ROUND_HALF_UP; + } else if (round_mode_string == "HALF_TO_EVEN") { + round_mode_ = ROUND_HALF_TO_EVEN; + } + } +}; + +REGISTER_XLA_OP(Name("QuantizeAndDequantizeV2"), QuantizeAndDequantizeV2Op); +REGISTER_XLA_OP(Name("QuantizeAndDequantizeV3"), QuantizeAndDequantizeOp); +REGISTER_XLA_OP(Name("QuantizeAndDequantizeV4"), QuantizeAndDequantizeV2Op); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..18d8bd443e7e2830685ab3449b1214cd623e0c5d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops.cc @@ -0,0 +1,269 @@ +/* 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. +==============================================================================*/ + +// XLA implementations of Random ops +// TODO(misard,phawkins): handle random number generator seeds/states correctly. +// TODO(misard,phawkins): add tests. + +#include +#include + +#include "absl/log/log.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/lib/random.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class RandomUniformOp : public XlaOpKernel { + public: + explicit RandomUniformOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape( + 0, &shape, xla::ValueInferenceMode::kUpperBound)); + + const DataType dtype = output_type(0); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype, shape, &xla_shape)); + + xla::XlaBuilder* b = ctx->builder(); + LOG_FIRST_N(WARNING, 1) + << "Warning: Using tf.random.uniform with XLA compilation will ignore " + "seeds; consider using tf.random.stateless_uniform instead if " + "reproducible behavior is desired. " + << name(); + xla::XlaOp result = xla::RngUniform(XlaHelpers::Zero(b, dtype), + XlaHelpers::One(b, dtype), xla_shape); + auto result_status_or = + SetAllDimensionSizes(&ctx->value_inference(), result, ctx->Input(0)); + OP_REQUIRES_OK(ctx, result_status_or.status()); + result = result_status_or.value(); + ctx->SetOutput(0, result); + } + + private: + RandomUniformOp(const RandomUniformOp&) = delete; + void operator=(const RandomUniformOp&) = delete; +}; + +REGISTER_XLA_OP(Name("RandomUniform").CompileTimeConstantInput("shape"), + RandomUniformOp); + +REGISTER_XLA_OP(Name("RandomShuffle"), MlirXlaOpKernel); + +class RandomUniformIntOp : public XlaOpKernel { + public: + explicit RandomUniformIntOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, + TensorShapeToXLAShape(input_type(1), shape, &xla_shape)); + + const TensorShape minval_shape = ctx->InputShape(1); + const TensorShape maxval_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(minval_shape), + errors::InvalidArgument("minval must be 0-D, got shape ", + minval_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(maxval_shape), + errors::InvalidArgument("maxval must be 0-D, got shape ", + maxval_shape.DebugString())); + + auto minval = ctx->Input(1); + auto maxval = ctx->Input(2); + LOG_FIRST_N(WARNING, 1) + << "Warning: Using tf.random.uniform with XLA compilation will ignore " + "seeds; consider using tf.random.stateless_uniform instead if " + "reproducible behavior is desired. " + << name(); + ctx->SetOutput(0, xla::RngUniform(minval, maxval, xla_shape)); + } + + private: + RandomUniformIntOp(const RandomUniformIntOp&) = delete; + void operator=(const RandomUniformIntOp&) = delete; +}; + +REGISTER_XLA_OP(Name("RandomUniformInt").CompileTimeConstantInput("shape"), + RandomUniformIntOp); + +class RandomStandardNormalOp : public XlaOpKernel { + public: + explicit RandomStandardNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const DataType dtype = output_type(0); + + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape( + 0, &shape, xla::ValueInferenceMode::kUpperBound)); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype, shape, &xla_shape)); + + xla::XlaBuilder* b = ctx->builder(); + + // Normal distribution with a mean of 0 and a standard deviation of 1: + xla::XlaOp result = xla::RngNormal(XlaHelpers::Zero(b, dtype), + XlaHelpers::One(b, dtype), xla_shape); + auto result_status_or = + SetAllDimensionSizes(&ctx->value_inference(), result, ctx->Input(0)); + OP_REQUIRES_OK(ctx, result_status_or.status()); + result = result_status_or.value(); + ctx->SetOutput(0, result); + } + + private: + RandomStandardNormalOp(const RandomStandardNormalOp&) = delete; + void operator=(const RandomStandardNormalOp&) = delete; +}; + +REGISTER_XLA_OP(Name("RandomStandardNormal").CompileTimeConstantInput("shape"), + RandomStandardNormalOp); + +class TruncatedNormalOp : public XlaOpKernel { + public: + explicit TruncatedNormalOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const DataType dtype = output_type(0); + + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype, shape, &xla_shape)); + + xla::XlaBuilder* b = ctx->builder(); + + xla::XlaOp one = xla::One(b, xla_shape.element_type()); + xla::XlaOp min_positive = + xla::MinPositiveNormalValue(b, xla_shape.element_type()); + LOG_FIRST_N(WARNING, 1) + << "Warning: Using tf.random.truncated_normal with XLA " + "compilation will ignore seeds; consider using " + "tf.random.stateless_truncated_normal instead if " + "reproducible behavior is desired. " + << name(); + auto uniform = xla::RngUniform(min_positive, one, xla_shape); + ctx->SetOutput(0, TruncatedNormal(uniform)); + } +}; + +REGISTER_XLA_OP(Name("TruncatedNormal") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_FLOAT, DT_DOUBLE}), + TruncatedNormalOp); + +// Broadcast a ParameterizedTruncatedNormal parameter to the output shape. If +// the parameter is a vector of shape [num_batches], then it is broadcast along +// dimension 0 to ([num_batches] x samples_per_batch). Otherwise it is a scalar +// or has shape [1], in which case the single value is broadcast. +static absl::StatusOr BroadcastParameters( + xla::XlaOp params, TensorShape& output_shape) { + // broadcast to [samples1, ..., num_batches] + int rank = output_shape.dims(); + std::vector bcast_shape; + for (int i = 1; i < rank; ++i) { + bcast_shape.push_back(output_shape.dim_size(i)); + } + bcast_shape.push_back(output_shape.dim_size(0)); + TF_ASSIGN_OR_RETURN(xla::XlaOp bcast_params, + BroadcastTo(params, bcast_shape)); + + // transpose to [num_batches, samples1, ...] + std::vector permutation; + permutation.push_back(rank - 1); + for (int i = 0; i < rank - 1; ++i) { + permutation.push_back(i); + } + return xla::Transpose(bcast_params, permutation); +} + +class ParameterizedTruncatedNormalOp : public XlaOpKernel { + public: + explicit ParameterizedTruncatedNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const DataType dtype = output_type(0); + + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype, shape, &xla_shape)); + OP_REQUIRES(ctx, xla_shape.dimensions().size() >= 1, + errors::InvalidArgument( + "shape parameter must have rank >= 1, received (", + xla::ShapeUtil::HumanString(xla_shape), ")")); + + xla::XlaBuilder* b = ctx->builder(); + + xla::XlaOp one = xla::One(b, xla_shape.element_type()); + xla::XlaOp min_positive = + xla::MinPositiveNormalValue(b, xla_shape.element_type()); + LOG_FIRST_N(WARNING, 1) + << "Warning: Using tf.random.truncated_normal with XLA " + "compilation will ignore seeds; consider using " + "tf.random.stateless_truncated_normal instead if " + "reproducible behavior is desired. " + << name(); + xla::XlaOp uniform = xla::RngUniform(min_positive, one, xla_shape); + + auto result = b->ReportErrorOrReturn([&]() -> absl::StatusOr { + TF_ASSIGN_OR_RETURN(xla::XlaOp means, + BroadcastParameters(ctx->Input(1), shape)); + TF_ASSIGN_OR_RETURN(xla::XlaOp stddevs, + BroadcastParameters(ctx->Input(2), shape)); + TF_ASSIGN_OR_RETURN(xla::XlaOp minvals, + BroadcastParameters(ctx->Input(3), shape)); + TF_ASSIGN_OR_RETURN(xla::XlaOp maxvals, + BroadcastParameters(ctx->Input(4), shape)); + return ParameterizedTruncatedNormal(uniform, means, stddevs, minvals, + maxvals); + }); + + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP(Name("ParameterizedTruncatedNormal") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_FLOAT, DT_DOUBLE}), + ParameterizedTruncatedNormalOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..b5aa8c480b4881c396fcf0c80bf9559e77b5195d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops_util.cc @@ -0,0 +1,228 @@ +/* Copyright 2020 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/kernels/random_ops_util.h" + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/kernels/rng_converter_utils.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/prng.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/rng_alg.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/kernels/stateless_random_ops_v2.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +namespace { + +xla::XlaOp GetCounter(xla::RandomAlgorithm const& alg, xla::XlaOp state) { + return xla::Slice(state, {RNG_KEY_SIZE}, + {RNG_KEY_SIZE + xla::GetCounterSize(alg)}, {1}); +} + +absl::StatusOr ResolveAlg( + int alg_id, absl::string_view device_type_string) { + switch (alg_id) { + case RNG_ALG_PHILOX: + return xla::RandomAlgorithm::RNG_PHILOX; + case RNG_ALG_THREEFRY: + return xla::RandomAlgorithm::RNG_THREE_FRY; + case RNG_ALG_AUTO_SELECT: + return DefaultRngAlgForDeviceType(device_type_string); + default: + return absl::InvalidArgumentError( + absl::StrCat("Unsupported algorithm id: ", alg_id)); + } +} + +xla::RngOutput StatelessRngUniformV2(xla::RandomAlgorithm const& alg, + xla::XlaOp key, xla::XlaOp counter, + const xla::Shape& shape, xla::XlaOp minval, + xla::XlaOp maxval) { + xla::XlaBuilder* builder = key.builder(); + xla::PrimitiveType type = shape.element_type(); + using std::placeholders::_1; + using std::placeholders::_2; + using std::placeholders::_3; + auto generator = std::bind(BitGenerator, alg, _1, _2, _3); + switch (type) { + case xla::F16: + case xla::F32: + case xla::F64: + return xla::UniformFloatingPointDistribution(key, counter, generator, + minval, maxval, shape); + case xla::S32: + case xla::S64: + case xla::U32: + case xla::U64: + return xla::UniformIntDistribution(key, counter, generator, minval, + maxval, shape); + break; + default: + return {builder->ReportError(xla::Unimplemented( + "Types other than F16, F32, S32, S64, U32 and U64 are not " + "implemented by " + "StatelessRngUniformV2; got %s", + xla::primitive_util::LowercasePrimitiveTypeName(type))), + counter}; + } +} + +} // namespace + +xla::RngOutput BitGenerator(xla::RandomAlgorithm const& alg, xla::XlaOp key, + xla::XlaOp counter, const xla::Shape& shape) { + key = BitcastConvertType(key, xla::U64); + counter = BitcastConvertType(counter, xla::U64); + xla::XlaOp state = xla::ConcatInDim(key.builder(), {key, counter}, 0); + xla::XlaOp result = xla::RngBitGenerator(alg, state, shape); + auto new_counter = GetCounter(alg, xla::GetTupleElement(result, 0)); + new_counter = BitcastConvertType(new_counter, xla::S64); + return xla::RngOutput{/*value=*/xla::GetTupleElement(result, 1), + /*state=*/new_counter}; +} +xla::XlaOp GetU64FromS32Seeds(xla::XlaOp seed0, xla::XlaOp seed1) { + // Here, the seeds are cast to unsigned type of the same width to have leading + // zeros in the 64 bit representation. + xla::XlaOp u64_seed0 = + ConvertElementType(ConvertElementType(seed0, xla::U32), xla::U64); + xla::XlaOp u64_seed1 = + ConvertElementType(ConvertElementType(seed1, xla::U32), xla::U64); + return u64_seed0 | + (u64_seed1 << ConstantR0WithType(seed0.builder(), xla::U64, 32)); +} + +absl::StatusOr GetAlgId(XlaOpKernelContext* ctx, int alg_input_idx) { + TF_ASSIGN_OR_RETURN(auto alg_shape, ctx->InputXlaShape(alg_input_idx)); + if (alg_shape.dimensions().size() != 0) { + return absl::InvalidArgumentError( + absl::StrCat("The algorithm argument must be of shape [], not ", + alg_shape.ToString())); + } + auto alg_dtype = ctx->input_type(alg_input_idx); + if (alg_dtype != DT_INT32 && alg_dtype != DT_INT64) { + return absl::InvalidArgumentError(absl::StrCat( + "The algorithm argument must have dtype int32 or int64, not ", + DataTypeString(alg_dtype))); + } + xla::Literal alg_literal; + TF_RETURN_IF_ERROR(ctx->ConstantInput(alg_input_idx, &alg_literal)); + if (alg_dtype == DT_INT32) { + return alg_literal.Get({}); + } else { + return alg_literal.Get({}); + } +} + +absl::StatusOr AlgorithmFromInput( + XlaOpKernelContext* ctx, int alg_input_idx, + absl::string_view device_type_string) { + TF_ASSIGN_OR_RETURN(auto alg_id, GetAlgId(ctx, alg_input_idx)); + return ResolveAlg(alg_id, device_type_string); +} + +xla::XlaOp MaybeSliceCounter(xla::RandomAlgorithm const& alg, + TensorShape const& counter_shape, + xla::XlaOp counter) { + auto input_counter_size = counter_shape.dim_size(0); + auto real_counter_size = xla::GetCounterSize(alg); + if (input_counter_size > real_counter_size) { + counter = xla::Slice(counter, {0}, {real_counter_size}, {1}); + } + return counter; +} + +DataType MaybeConvertBF16ToF32(DataType const& dtype) { + if (dtype == DT_BFLOAT16) { + // We'll go through F32 to generate BF16. + // TODO(b/256243456): Generate BF16 directly from U16. + return DT_FLOAT; + } + return dtype; +} + +absl::StatusOr BuildUniformRandoms( + XlaOpKernelContext* ctx, DataType dtype, std::string device_type_string, + TensorShape shape, + std::function lo_fn, + std::function hi_fn) { + xla::XlaBuilder* builder = ctx->builder(); + auto rng_dtype = MaybeConvertBF16ToF32(dtype); + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + + xla::PrimitiveType rng_primitive_type = xla_shape.element_type(); + xla::XlaOp lo = lo_fn(builder, rng_primitive_type); + xla::XlaOp hi = hi_fn(builder, rng_primitive_type); + + return BuildUniformRandoms(ctx, dtype, device_type_string, xla_shape, lo, hi); +} + +absl::StatusOr BuildUniformRandoms(XlaOpKernelContext* ctx, + DataType dtype, + std::string device_type_string, + xla::Shape xla_shape, + xla::XlaOp lo, xla::XlaOp hi) { + xla::XlaOp key = ctx->Input(kRandomKeyInputIdx); + xla::XlaOp counter = ctx->Input(kRandomCounterInputIdx); + + TF_ASSIGN_OR_RETURN( + xla::RandomAlgorithm alg, + AlgorithmFromInput(ctx, kRandomAlgInputIdx, device_type_string)); + TensorShape counter_shape = ctx->InputShape(kRandomCounterInputIdx); + TF_RETURN_IF_ERROR(CheckKeyCounterShape( + GetCounterSize(alg), ctx->InputShape(kRandomKeyInputIdx), counter_shape)); + counter = MaybeSliceCounter(alg, counter_shape, counter); + + xla::RngOutput result = + StatelessRngUniformV2(alg, key, counter, xla_shape, lo, hi); + return result.value; +} +} // namespace tensorflow + +namespace xla { + +int GetCounterSize(RandomAlgorithm const& alg) { + switch (alg) { + case RandomAlgorithm::RNG_PHILOX: + return 2; + case RandomAlgorithm::RNG_THREE_FRY: // fall through + case RandomAlgorithm::RNG_DEFAULT: // fall through + default: + return 1; + } +} + +} // namespace xla diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops_util.h new file mode 100644 index 0000000000000000000000000000000000000000..5ed0c49c2e97f634afeaddbd8f52fa26b393827f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/random_ops_util.h @@ -0,0 +1,96 @@ +/* Copyright 2019 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_KERNELS_RANDOM_OPS_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_RANDOM_OPS_UTIL_H_ + +#include + +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/lib/prng.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +inline constexpr int kRandomKeyInputIdx = 1; +inline constexpr int kRandomCounterInputIdx = 2; +inline constexpr int kRandomAlgInputIdx = 3; + +// Returns a tensor containing 'shape' random values uniformly distributed in +// the range [minval, maxval). The raw random bits are generated by the given +// `bit_generator` and converted to the requested data type and range. This +// routine requires 2 32-bit integer seeds and currently only supports 'shape's +// of type F32, S32 and S64. +xla::XlaOp StatelessRngUniform(absl::string_view device_type_string, + xla::XlaOp seeds, const xla::Shape& shape, + xla::XlaOp minval, xla::XlaOp maxval); + +// Converts to bfloat16 if `dtype` equals DT_BFLOAT16, no-op otherwise. +// It masks the last 16 bit. With normal rounding, values near "maxval" would be +// converted to "maxval" which is out of range ["minval", "maxval"). In +// addition, the distribution near the limit is not uniform. +xla::XlaOp MaybeConvertF32ToBF16(xla::XlaOp input, DataType dtype); + +// Combines two signed 32-bit seeds into a single unsigned 64 bit seed. +xla::XlaOp GetU64FromS32Seeds(xla::XlaOp seed0, xla::XlaOp seed1); + +absl::StatusOr GetAlgId(XlaOpKernelContext* ctx, int alg_input_idx); + +xla::RngOutput BitGenerator(xla::RandomAlgorithm const& alg, xla::XlaOp key, + xla::XlaOp counter, const xla::Shape& shape); + +// Gets user specified RNG algorithm. +absl::StatusOr AlgorithmFromInput( + XlaOpKernelContext* ctx, int alg_input_idx, + absl::string_view device_type_string); + +xla::XlaOp MaybeSliceCounter(xla::RandomAlgorithm const& alg, + TensorShape const& counter_shape, + xla::XlaOp counter); + +DataType MaybeConvertBF16ToF32(DataType const& dtype); + +// Builds uniform randoms from a stateless RNG with given data type and device +// type, in the given low and high range, where low and high are expressed in +// XLA functions. +absl::StatusOr BuildUniformRandoms( + XlaOpKernelContext* ctx, DataType dtype, std::string device_type_string, + TensorShape shape, + std::function lo, + std::function hi); + +// Overloads BuildUniformRandoms where low and high range are expressed in XLA +// ops. +absl::StatusOr BuildUniformRandoms(XlaOpKernelContext* ctx, + DataType dtype, + std::string device_type_string, + xla::Shape xla_shape, + xla::XlaOp lo, xla::XlaOp hi); +} // namespace tensorflow + +namespace xla { + +int GetCounterSize(RandomAlgorithm const& alg); + +} // namespace xla + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_RANDOM_OPS_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduce_window_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduce_window_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..c59d6835c810824d26c269c1ee892a53eb68f0a1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduce_window_op.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/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaReduceWindow") + .CompileTimeConstantInput("window_dimensions") + .CompileTimeConstantInput("window_strides") + .CompileTimeConstantInput("base_dilations") + .CompileTimeConstantInput("window_dilations") + .CompileTimeConstantInput("padding"), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..b731eaee449c90815388b7487a8b314b19fa058c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops.cc @@ -0,0 +1,208 @@ +/* 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. +==============================================================================*/ + +// XLA-specific reduction Ops. + +#include "tensorflow/compiler/tf2xla/kernels/reduction_ops.h" + +#include +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace { + +class SumOp : public XlaReductionOp { + public: + explicit SumOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, + XlaHelpers::SumAccumulationType(ctx->input_type(0))) {} + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::Zero(builder, xla_reduction_type_); + } + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::Add(scalar_lhs, scalar_rhs); + } +}; + +REGISTER_XLA_OP(Name("Sum").CompileTimeConstantInput("reduction_indices"), + SumOp); + +class ProdOp : public XlaReductionOp { + public: + explicit ProdOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, + XlaHelpers::SumAccumulationType(ctx->input_type(0))) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::One(builder, xla_reduction_type_); + } + + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::Mul(scalar_lhs, scalar_rhs); + } +}; + +REGISTER_XLA_OP(Name("Prod").CompileTimeConstantInput("reduction_indices"), + ProdOp); + +class MinOp : public XlaReductionOp { + public: + explicit MinOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, ctx->input_type(0)) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::MaxValue(builder, xla_reduction_type_); + } + + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::Min(scalar_lhs, scalar_rhs); + } +}; + +REGISTER_XLA_OP(Name("Min").CompileTimeConstantInput("reduction_indices"), + MinOp); + +class MaxOp : public XlaReductionOp { + public: + explicit MaxOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, ctx->input_type(0)) { + OP_REQUIRES_OK(ctx, PrimitiveTypeCheck(xla_reduction_type_)); + } + + static absl::Status PrimitiveTypeCheck( + xla::PrimitiveType xla_reduction_type) { + if (xla_reduction_type == xla::C64 || xla_reduction_type == xla::C128 || + xla_reduction_type == xla::TUPLE || + xla_reduction_type == xla::OPAQUE_TYPE) { + return errors::InvalidArgument( + "Unsupported PrimitiveType in MaxOp: '", + xla::PrimitiveType_Name(xla_reduction_type), "'"); + } else { + return absl::OkStatus(); + } + } + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::MinValue(builder, xla_reduction_type_); + } + + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::Max(scalar_lhs, scalar_rhs); + } +}; + +REGISTER_XLA_OP(Name("Max").CompileTimeConstantInput("reduction_indices"), + MaxOp); + +class MeanOp : public XlaReductionOp { + public: + explicit MeanOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, + XlaHelpers::SumAccumulationType(ctx->input_type(0))) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::Zero(builder, xla_reduction_type_); + } + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::Add(scalar_lhs, scalar_rhs); + } + + xla::XlaOp BuildFinalizer( + xla::XlaBuilder* builder, const xla::XlaOp& input, + const xla::XlaOp& reduce_output, + const std::vector& dimensions_to_reduce) override { + if (dimensions_to_reduce.empty()) { + return reduce_output; + } + xla::XlaOp result = reduce_output; + xla::Shape bounded_shape = builder->GetShape(input).value(); + int64_t divisor_value = bounded_shape.dimensions(dimensions_to_reduce[0]); + auto divisor = xla::GetDimensionSize(input, dimensions_to_reduce[0]); + for (int i = 1; i < dimensions_to_reduce.size(); i++) { + int64_t size_value = bounded_shape.dimensions(dimensions_to_reduce[i]); + auto size = xla::GetDimensionSize(input, dimensions_to_reduce[i]); + if (size_value * divisor_value > std::numeric_limits::max()) { + result = result / xla::ConvertElementType(divisor, xla_reduction_type_); + divisor_value = size_value; + divisor = size; + } else { + divisor = xla::Mul(divisor, size); + divisor_value = size_value * divisor_value; + } + } + divisor = xla::ConvertElementType(divisor, xla_reduction_type_); + return XlaHelpers::ConvertElementType(result / divisor, input_type(0)); + } +}; + +REGISTER_XLA_OP(Name("Mean").CompileTimeConstantInput("reduction_indices"), + MeanOp); + +class AllOp : public XlaReductionOp { + public: + explicit AllOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, ctx->input_type(0)) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::ConstantR0(builder, true); + } + + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::And(scalar_lhs, scalar_rhs); + } +}; + +REGISTER_XLA_OP(Name("All").CompileTimeConstantInput("reduction_indices"), + AllOp); + +class AnyOp : public XlaReductionOp { + public: + explicit AnyOp(OpKernelConstruction* ctx) + : XlaReductionOp(ctx, ctx->input_type(0)) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::ConstantR0(builder, false); + } + + void BuildReducer(xla::XlaBuilder* builder, const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) override { + xla::Or(scalar_lhs, scalar_rhs); + } +}; + +REGISTER_XLA_OP(Name("Any").CompileTimeConstantInput("reduction_indices"), + AnyOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..968ec1dad82b35c12ecf97b87f9e3d1b8b59f748 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops.h @@ -0,0 +1,78 @@ +/* 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. +==============================================================================*/ + +// XLA-specific base classes for Reduction Ops. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_KERNELS_REDUCTION_OPS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_REDUCTION_OPS_H_ + +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { + +// Reduction operations. The base class contains pure virtual methods +// to override: description is a textual description of the mapped +// function; InitialValue constructs the base case for the reduction; +// BuildReducer adds the implementation of the reduction lambda to a +// xla::XlaBuilder and BuildFinalizer adds the +// implementation of the finalizer lambda (if there is one) to a +// xla::XlaBuilder. +class XlaReductionOp : public XlaOpKernel { + public: + XlaReductionOp(OpKernelConstruction* ctx, DataType reduction_type); + ~XlaReductionOp() override = default; + + // Return the base case for the reduction. + virtual xla::XlaOp InitialValue(xla::XlaBuilder* builder) = 0; + + // Implement the (scalar,scalar)->scalar lambda that should be + // applied to each pair of elements to be reduced. The desired + // computation should be added to 'builder' and + // '(scalar_lhs,scalar_rhs)' are the function's inputs. + virtual void BuildReducer(xla::XlaBuilder* builder, + const xla::XlaOp& scalar_lhs, + const xla::XlaOp& scalar_rhs) = 0; + + // Applies a transformation to the output of the reduction. The desired + // computation should be added to 'builder'. Argument 'input' is the original + // input of the reduction; 'reduce_output' is the output of the reduction. + // Returns the transformed reduction output. Defaults to returning + // 'reduce_output' converted to the input type. + virtual xla::XlaOp BuildFinalizer( + xla::XlaBuilder* builder, const xla::XlaOp& input, + const xla::XlaOp& reduce_output, + const std::vector& dimensions_to_reduce); + + void Compile(XlaOpKernelContext* ctx) override; + + private: + // True if the number of dimensions should be maintained. + bool keep_dims_; + + protected: + DataType reduction_type_; + xla::PrimitiveType xla_reduction_type_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_REDUCTION_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops_common.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops_common.cc new file mode 100644 index 0000000000000000000000000000000000000000..03f0750e6405aa7ceb5fabd729220f73a22cf319 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reduction_ops_common.cc @@ -0,0 +1,146 @@ +/* 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. +==============================================================================*/ + +// XLA-specific reduction Ops. + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/kernels/reduction_ops.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/literal.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { + +XlaReductionOp::XlaReductionOp(OpKernelConstruction* ctx, + DataType reduction_type) + : XlaOpKernel(ctx), reduction_type_(reduction_type) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("keep_dims", &keep_dims_)); + OP_REQUIRES_OK( + ctx, DataTypeToPrimitiveType(reduction_type_, &xla_reduction_type_)); +} + +// The default finalizer converts the results back into the input type. This can +// be overridden. +xla::XlaOp XlaReductionOp::BuildFinalizer( + xla::XlaBuilder* /*builder*/, const xla::XlaOp& /*input*/, + const xla::XlaOp& reduce_output, + const std::vector& /*dimensions_to_reduce*/) { + return XlaHelpers::ConvertElementType(reduce_output, input_type(0)); +} + +void XlaReductionOp::Compile(XlaOpKernelContext* ctx) { + const TensorShape data_shape = ctx->InputShape(0); + const TensorShape axes_tensor_shape = ctx->InputShape(1); + VLOG(1) << "ReductionOp: " << ctx->op_kernel().name(); + + if (axes_tensor_shape.num_elements() == 0) { + // The reduction axes is an empty vector, which means there are no + // axes to reduce so just pass the input directly through to the + // output. + ctx->SetOutput(0, ctx->Input(0)); + return; + } + + OP_REQUIRES(ctx, axes_tensor_shape.dims() <= 1, + errors::InvalidArgument( + "Expected scalar or vector as index argument, got ", + axes_tensor_shape.DebugString())); + + // Evaluate the constant, reshaping to a 1-vector if it is a scalar. + std::vector axes; + xla::Literal axes_literal; + OP_REQUIRES_OK(ctx, ctx->ConstantInputReshapedToIntVector(1, &axes)); + + VLOG(1) << "data shape: " << data_shape.DebugString(); + VLOG(1) << "axes : " << absl::StrJoin(axes, ","); + + absl::InlinedVector bitmap(data_shape.dims(), false); + std::vector xla_axes; + auto num_elements = axes_tensor_shape.num_elements(); + xla_axes.reserve(num_elements); + for (int64_t i = 0; i < num_elements; ++i) { + int64_t index = axes[i]; + OP_REQUIRES(ctx, + !(index < -data_shape.dims() || index >= data_shape.dims()), + errors::InvalidArgument("Invalid reduction dimension (", index, + " for input with ", data_shape.dims(), + " dimension(s)")); + index = (index + data_shape.dims()) % data_shape.dims(); + OP_REQUIRES( + ctx, !bitmap[index], + errors::InvalidArgument( + "Invalid reduction arguments: Axes contains duplicate dimension: ", + index)); + bitmap[index] = true; + xla_axes.push_back(index); + } + + std::vector final_shape; + for (int i = 0; i < data_shape.dims(); ++i) { + if (!bitmap[i]) { + // If we are not reducing along dimension i. + int64_t dim = data_shape.dim_size(i); + final_shape.push_back(dim); + } else if (keep_dims_) { + // We are reducing along dimension i, but we want to keep the + // same number of dimensions, so we set the dimension of i to + // '1'. + final_shape.push_back(1); + } + } + + std::string desc = ctx->op_kernel().name(); + + xla::XlaBuilder* const b = ctx->builder(); + // Construct the builder for the reduction lambda. + xla::XlaBuilder r(absl::StrCat(desc, "-reduction")); + xla::PrimitiveType type; + CHECK_OK(DataTypeToPrimitiveType(reduction_type_, &type)); + + auto data = xla::ConvertElementType(ctx->Input(0), type); + // Call virtual method to get the initial value. + auto initial = xla::ConvertElementType(InitialValue(b), type); + // Make two scalar parameters of the desired type for the lambda. + auto rx = xla::Parameter(&r, 0, xla::ShapeUtil::MakeShape(type, {}), "x"); + auto ry = xla::Parameter(&r, 1, xla::ShapeUtil::MakeShape(type, {}), "y"); + // Call virtual method to build the reduction lambda. + BuildReducer(&r, rx, ry); + xla::XlaComputation reduction_computation = r.Build().value(); + + auto reduce = xla::Reduce(data, initial, reduction_computation, xla_axes); + auto finalized = BuildFinalizer(b, data, reduce, xla_axes); + auto result = keep_dims_ ? xla::Reshape(finalized, final_shape) : finalized; + ctx->SetOutput(0, result); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/relu_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/relu_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..507a654391b1e22a3521568bec53887b9594446f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/relu_op.cc @@ -0,0 +1,102 @@ +/* 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. +==============================================================================*/ + +// Native XLA implementations of XLA Relu Ops + +#include "tensorflow/compiler/tf2xla/kernels/relu_op.h" + +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" + +namespace xla { +XlaOp Relu(XlaOp x) { return Max(ScalarLike(x, 0), x); } + +XlaOp Relu6(XlaOp x) { + auto zero = ScalarLike(x, 0); + auto six = ScalarLike(x, 6); + return Clamp(zero, x, six); +} +} // namespace xla + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("Relu"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Relu6"), MlirXlaOpKernel); + +class LeakyReluOp : public XlaOpKernel { + public: + explicit LeakyReluOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("alpha", &alpha_)); + } + void Compile(XlaOpKernelContext* ctx) override { + auto features = ctx->Input("features"); + auto prod_with_alpha = features * xla::ScalarLike(features, alpha_); + auto gt_zero = xla::Gt(features, xla::ScalarLike(features, 0)); + auto output = xla::Select(gt_zero, features, prod_with_alpha); + ctx->SetOutput(0, output); + } + float alpha_; +}; +REGISTER_XLA_OP(Name("LeakyRelu"), LeakyReluOp); + +REGISTER_XLA_OP(Name("ReluGrad"), MlirXlaOpKernel); + +class Relu6GradOp : public XlaOpKernel { + public: + explicit Relu6GradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + // Return the lhs (incoming gradient) if the rhs (input feature) > 0, + // otherwise return 0. + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + const TensorShape shape = ctx->InputShape(0); + const auto zero = + xla::Broadcast(XlaHelpers::Zero(b, input_type(0)), shape.dim_sizes()); + const auto six = xla::Broadcast( + XlaHelpers::IntegerLiteral(b, input_type(0), 6), shape.dim_sizes()); + auto out = xla::Select( + xla::And(xla::Lt(ctx->Input(1), six), xla::Gt(ctx->Input(1), zero)), + ctx->Input(0), zero); + ctx->SetOutput(0, out); + } +}; +REGISTER_XLA_OP(Name("Relu6Grad"), Relu6GradOp); + +class LeakyReluGradOp : public XlaOpKernel { + public: + explicit LeakyReluGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("alpha", &alpha_)); + } + void Compile(XlaOpKernelContext* ctx) override { + auto gradients = ctx->Input("gradients"); + auto features = ctx->Input("features"); + auto output = + xla::Select(xla::Gt(features, xla::ScalarLike(features, 0)), gradients, + gradients * xla::ScalarLike(gradients, alpha_)); + ctx->SetOutput(0, output); + } + float alpha_; +}; +REGISTER_XLA_OP(Name("LeakyReluGrad"), LeakyReluGradOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/relu_op.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/relu_op.h new file mode 100644 index 0000000000000000000000000000000000000000..151bdaa7242c15bbc45396002f2a9e7207c0ab54 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/relu_op.h @@ -0,0 +1,26 @@ +/* Copyright 2019 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_KERNELS_RELU_OP_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_RELU_OP_H_ + +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" + +namespace xla { +XlaOp Relu(XlaOp x); +XlaOp Relu6(XlaOp x); +} // namespace xla + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_RELU_OP_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/replica_id_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/replica_id_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..698d802dfb9d1f3497e79ae11bfc219bf660368a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/replica_id_op.cc @@ -0,0 +1,25 @@ +/* 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/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaReplicaId"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_addon_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_addon_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..39709289e0036365b43e3d75ecfde4e715cbb75d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_addon_ops.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/compiler/tf2xla/kernels/resampler_ops.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("Addons>Resampler") + .TypeConstraint("T", {DT_HALF, DT_FLOAT, DT_DOUBLE}), + ResamplerOp); + +REGISTER_XLA_OP(Name("Addons>ResamplerGrad") + .TypeConstraint("T", {DT_HALF, DT_FLOAT, DT_DOUBLE}), + ResamplerGradOp); +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..82602e54527e8105b6c56b8223c3ecb35b021663 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_ops.cc @@ -0,0 +1,674 @@ +/* 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/tf2xla/kernels/resampler_ops.h" + +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +using xla::XlaOp; + +// Calculates the bilinear weight tensor, given basis ratio (px, py) of the +// sampling position: +// W = [(1-px)*(1-py), px*(1-py), (1-px)*py, px*py] +// 'ratio' tensor has dimensions [batch, dim_0, ...dim_n, 2]. +// +// The returned tensor has dimensions [batch, dim_0, ... dim_n, 4]. +XlaOp BilinearWeights(XlaOpKernelContext* ctx, XlaOp ratio, + const TensorShape warp_shape, + xla::PrimitiveType xla_type) { + auto first_term = xla::ConstantR2( + ctx->builder(), {{1.0, 1.0}, {0.0, 1.0}, {1.0, 0.0}, {0.0, 0.0}}); + first_term = xla::ConvertElementType(first_term, xla_type); + + auto warp_dims = warp_shape.dim_sizes(); + std::vector broadcast_dims(warp_dims.begin(), warp_dims.end() - 1); + broadcast_dims.push_back(4); + broadcast_dims.push_back(2); + + const int64_t broadcast_dims_size = broadcast_dims.size(); + + std::vector last_two_dims_indices = {(broadcast_dims_size - 2), + (broadcast_dims_size - 1)}; + + auto broadcast_first_term = + xla::BroadcastInDim(first_term, broadcast_dims, last_two_dims_indices); + + // Ratio is of the same dimension as warp, which is [batch, dim_0,... dim_n, + // 2], we broadcast ratio tensor to 'broadcast_dim' by keeping the + // [batch, dim_0,...dim_n] dimensions and the [2] dimension as the last + // dimension. + std::vector ratio_broadcast_indices(broadcast_dims.size()); + std::iota(ratio_broadcast_indices.begin(), ratio_broadcast_indices.end(), 0); + ratio_broadcast_indices.erase(ratio_broadcast_indices.end() - 2); + + auto broadcast_ratio = + xla::BroadcastInDim(ratio, broadcast_dims, ratio_broadcast_indices); + + auto first_term_subtract_weights = broadcast_first_term - broadcast_ratio; + + // Now we have [(1-px, 1-py), (-px, 1-py), (1-px, -py), (px, py)], need to + // flip the signs of the second and the third term. + auto sign_change = xla::ConstantR2( + ctx->builder(), {{1.0, 1.0}, {-1.0, 1.0}, {-1.0, 1.0}, {1.0, 1.0}}); + sign_change = xla::ConvertElementType(sign_change, xla_type); + + auto broadcast_sign_change = + xla::BroadcastInDim(sign_change, broadcast_dims, last_two_dims_indices); + + auto flipped = first_term_subtract_weights * broadcast_sign_change; + + // Build up the final bilinear weight tensor by multiply reduction, which + // gives: + // [(1-px)*(1-py), px*(1-py), (1-px)*py, px*py] + // for each 4 neighboring pixels where px and py are the weight of the target + // pixel we are sampling from. + return xla::Reduce( + flipped, xla::One(ctx->builder(), xla_type), + xla::CreateScalarMultiplyComputation(xla_type, ctx->builder()), + {broadcast_dims_size - 1}); +} + +// Concatenates the batch indices to the (x, y) coordinate indices. +// This is done by first creating an Iota tensor that represents the current +// batch it is in, then concatenate with the givin (coordinate) indices. +// +// The resulting tensor has dimension (batch, dim_0, ... dim_n, 3) where +// the last dimension of size 3 in turn is [batch_number, x, y]. +// The [batch_number, x, y] dimension is needed because the indices +// [x,y] alone cannot allow the xla::Gather operation to gather from the input +// data, which is of dimension [batch, height(y), width(x), channel] with +// 'batch' being the first dimension. +XlaOp ConcatenateIota(xla::XlaBuilder* b, XlaOp indices, + const TensorShape& warp_shape) { + // We need to create an iota tensor with the same batch dimension. + std::vector dimensions; + dimensions.reserve(warp_shape.dims()); + for (auto dim : warp_shape) { + dimensions.push_back(dim.size); + } + // Except the last dimension, which is of size 1. + dimensions.back() = 1; + + auto batch_indices = + xla::Iota(b, xla::ShapeUtil::MakeShape(xla::S32, dimensions), + /*iota_dimension=*/0); + + return xla::ConcatInDim(b, {batch_indices, indices}, dimensions.size() - 1); +} + +// Gathers the 2x2 neighbors of the input starting_indices, and return a +// tensor of dimension [batch, dim_0, ... dim_n, 4, data_channels]. +// 'gather_indices' is of dimension [batch, dim_0, ..., dim_n, 3] where the last +// dimension of size 3 is (batch_no, x, y). +XlaOp Gather2by2Neighbors(xla::XlaBuilder* b, XlaOp data, XlaOp gather_indices, + int64_t data_channels, int warp_dims) { + xla::GatherDimensionNumbers gather_dim_numbers; + const int64_t neighbor_data_dimensions = warp_dims + 2; + // Since the Gather output dimensions are [batch, dim_0, ... dim_n, 2, 2, + // data_channels], the offset dimensions for Gather is the last 3 dimensions. + gather_dim_numbers.add_offset_dims(neighbor_data_dimensions - 3); + gather_dim_numbers.add_offset_dims(neighbor_data_dimensions - 2); + gather_dim_numbers.add_offset_dims(neighbor_data_dimensions - 1); + // The last dimension of 'gather_indices' is the starting indices for gather. + gather_dim_numbers.set_index_vector_dim(warp_dims - 1); + gather_dim_numbers.add_collapsed_slice_dims(0); + gather_dim_numbers.add_start_index_map(0); + // Since input is of dimension [batch, height(y), width(x), channel], and warp + // is of dimension [batch, x, y], the ordering of x, y here needs to be + // swapped when gathering. + gather_dim_numbers.add_start_index_map(2); + gather_dim_numbers.add_start_index_map(1); + // Data dimensions are [batch, x, y, channel]. + // Output dimensions are [batch, dim_0, ... dim_n, 2, 2, data_channels]. + auto neighbors_data = xla::Gather(data, gather_indices, gather_dim_numbers, + /*slice_sizes=*/{1, 2, 2, data_channels}); + // Collapse the ...,2,2,... dimensions into ...,4,... + return xla::Collapse(neighbors_data, {warp_dims - 1, warp_dims}); +} + +// Scatter 'updates' tensor to 'grad_data' based on 'indices'. Returns the +// resulting tensor of dimension: [batch, dim_0, ...dim_n, 2, 2, data_channels]. +// This function can also be seen as the inverse of 'Gather2by2Neighbors'. +XlaOp ScatterToGradData(XlaOpKernelContext* ctx, XlaOp grad_data, XlaOp indices, + XlaOp updates, int64_t warp_dims, + xla::PrimitiveType xla_type) { + xla::ScatterDimensionNumbers scatter_dim_numbers; + const int64_t neighbor_data_dimensions = warp_dims + 2; + // Since the Scatter output dimensions are [batch, dim_0, ... dim_n, 2, 2, + // data_channels], the update window dimensions is the last 3 dimensions. + scatter_dim_numbers.add_update_window_dims(neighbor_data_dimensions - 3); + scatter_dim_numbers.add_update_window_dims(neighbor_data_dimensions - 2); + scatter_dim_numbers.add_update_window_dims(neighbor_data_dimensions - 1); + scatter_dim_numbers.set_index_vector_dim(warp_dims - 1); + + scatter_dim_numbers.add_inserted_window_dims(0); + scatter_dim_numbers.add_scatter_dims_to_operand_dims(0); + // Since input is of dimension [batch, height(y), width(x), channel], and warp + // is of dimension [batch, x, y], the ordering of x, y here needs to be + // swapped when scattering. + scatter_dim_numbers.add_scatter_dims_to_operand_dims(2); + scatter_dim_numbers.add_scatter_dims_to_operand_dims(1); + + return xla::Scatter(grad_data, indices, updates, + xla::CreateScalarAddComputation(xla_type, ctx->builder()), + scatter_dim_numbers); +} + +// Bounds samples to 0 if the warp image indices are out of the (-1, image_size) +// bound. +// The resulting dimension is given by 'result_dims'. +XlaOp BoundSamples(XlaOpKernelContext* ctx, XlaOp warp, + xla::PrimitiveType warp_type, TensorShape warp_shape, + std::vector result_dims, + std::vector broadcasted_dims, int64_t last_warp_dim, + xla::Shape data_shape, XlaOp sample) { + auto is_gt_minus_one = + xla::Gt(warp, + xla::ConvertElementType( + xla::ConstantR1(ctx->builder(), {-1, -1}), warp_type), + /*broadcast_dimensions=*/{warp_shape.dims() - 1}); + auto is_lt_image_size = xla::Lt( + warp, + xla::ConvertElementType( + xla::ConstantR1( + ctx->builder(), + {/*width=*/static_cast(data_shape.dimensions(2)), + /*height=*/static_cast(data_shape.dimensions(1))}), + warp_type), + /*broadcast_dimensions=*/{warp_shape.dims() - 1}); + + auto is_in_bound_padded_x_y = xla::And(is_gt_minus_one, is_lt_image_size); + // Reduce along last dimension. The resulting dimension is: + // [batch, dim_0, ...dim_n]. + auto is_in_bound = xla::Reduce( + is_in_bound_padded_x_y, xla::ConstantR0(ctx->builder(), true), + xla::CreateScalarAndComputation(xla::PrimitiveType::PRED, ctx->builder()), + {last_warp_dim}); + + // Broadcast 'is_in_bound' to the same dimension as 'result_dims'. + auto broadcasted_is_in_bound = + xla::BroadcastInDim(is_in_bound, result_dims, broadcasted_dims); + + // Set out of bound samples to zero. + auto zeros = + xla::Broadcast(xla::Zero(ctx->builder(), warp_type), result_dims); + return xla::Select(broadcasted_is_in_bound, sample, zeros); +} + +// Build computation the backprop into input 'data'. +// Where input: +// grad_output is of dimension [batch, dim_0, ...dim_n, channel] +// ratio is of dimension [batch, dim_0, ...dim_n, 2] +// gather_indices is of dimension [batch, dim_0, ...dim_n, 3] +// data_shape is of dimension [batch, x(width), y(height), channel] +// +// Output: +// scatter-add to each 2x2 grad_data neighbor: +// grad_data[fx, fy, chan] += output_grad * dx * dy +// grad_data[cx, fy, chan] += output_grad * (1 - dx) * dy +// grad_data[fx, cy, chan] += output_grad * dx * (1 - dy) +// grad_data[cx, cy, chan] += output_grad * (1 - dx) * (1 - dy) +// where (dx, dy) is (1 - ratio). If (dx, dy) is out of bound, then the their +// contribution is 0 to 'grad_data'. +XlaOp CalculateGradData(XlaOpKernelContext* ctx, XlaOp grad_output, XlaOp ratio, + XlaOp gather_indices, XlaOp warp, + xla::PrimitiveType warp_type, TensorShape warp_shape, + int64_t last_warp_dim, int64_t data_channels, + xla::Shape data_shape) { + // Weights tensor has dimension [batch, dim_0, ... dim_n, 4]. + auto weights = BilinearWeights(ctx, ratio, warp_shape, warp_type); + + auto warp_dims = warp_shape.dim_sizes(); + std::vector warp_dims_without_last_dims(warp_dims.begin(), + warp_dims.end() - 1); + + std::vector reshaped_weights_dims = warp_dims_without_last_dims; + // Reshape the last dimension of size 4 to two dimensions [2, 2]. + reshaped_weights_dims.push_back(2); + reshaped_weights_dims.push_back(2); + std::vector reshape_dims(warp_shape.dims()); + std::iota(reshape_dims.begin(), reshape_dims.end(), 0); + // The dimension is [batch, dim_0,..., dim_n, 2, 2]. + auto reshaped_weights = + xla::Reshape(xla::Transpose(weights, /*permutation=*/reshape_dims), + /*dimensions=*/reshaped_weights_dims); + + std::vector weights_with_channels_dims = reshaped_weights_dims; + weights_with_channels_dims.push_back(data_channels); + std::vector reshaped_weights_indices(reshaped_weights_dims.size()); + std::iota(reshaped_weights_indices.begin(), reshaped_weights_indices.end(), + 0); + + // Set out of bound weights to 0. + // The dimension of the reshaped_weight: [batch, dim_0, ...dim_n, 2, 2]. + std::vector reshaped_result_dims(warp_dims.begin(), + warp_dims.end() - 1); + reshaped_result_dims.push_back(2); + reshaped_result_dims.push_back(2); + std::vector broadcasted_dims(warp_dims.size() - 1); + std::iota(broadcasted_dims.begin(), broadcasted_dims.end(), 0); + reshaped_weights = BoundSamples(ctx, warp, warp_type, warp_shape, + reshaped_result_dims, broadcasted_dims, + last_warp_dim, data_shape, reshaped_weights); + + // The dimension is [batch, dim_0, ..., dim_n, 2, 2, data_channel]. + auto broadcast_reshaped_weights = xla::BroadcastInDim( + reshaped_weights, weights_with_channels_dims, reshaped_weights_indices); + + std::vector grad_output_indices(warp_dims_without_last_dims.size()); + std::iota(grad_output_indices.begin(), grad_output_indices.end(), 0); + grad_output_indices.push_back(weights_with_channels_dims.size() - 1); + XlaOp broadcast_grad_output = xla::BroadcastInDim( + grad_output, weights_with_channels_dims, grad_output_indices); + + auto grad_output_multiply_weights = + broadcast_grad_output * broadcast_reshaped_weights; + + auto grad_data = xla::ConstantLiteral( + ctx->builder(), xla::Literal::CreateFromShape(data_shape)); + + // Pad grad data then slice it back. + // + // After left and right column 0-padding, the new dimension of padded data + // will be [batch, x+2, y+2, channel]. + auto padded_grad_data = + xla::Pad(grad_data, xla::Zero(ctx->builder(), warp_type), + xla::MakeEdgePaddingConfig({{0, 0}, {1, 1}, {1, 1}, {0, 0}})); + + auto shifting_value = xla::ConstantR1( + ctx->builder(), {/*batch=*/0, /*x(width)=*/1, /*y(height)=*/1}); + auto shifted_gather_indices = + xla::Add(gather_indices, shifting_value, {last_warp_dim}); + + auto updated_grad_data = ScatterToGradData( + ctx, padded_grad_data, shifted_gather_indices, + grad_output_multiply_weights, warp_shape.dims(), warp_type); + + const int64_t batch_size = data_shape.dimensions(0); + const int64_t width = data_shape.dimensions(1); + const int64_t height = data_shape.dimensions(2); + // Slice out the result accounting for the padding. + return xla::Slice( + updated_grad_data, /*start_indices=*/{0, 1, 1, 0}, + /*limit_indices=*/{batch_size, width + 1, height + 1, data_channels}, + /*strides=*/{1, 1, 1, 1}); +} + +// Build computation for the backprop into input 'warp'. +// Where input: +// warp is of dimension [batch, dim_0, ...dim_n, 2] +// grad_output is of dimension [batch, dim_0, ...dim_n, channel] +// ratio is of dimension [batch, dim_0, ...dim_n, 2] +// gather_indices is of dimension [batch, dim_0, ...dim_n, 3] where the last +// dimension of size 3 is for {batch, x(width), y(height)}. +// data is of dimension [batch, x, y, channel] +// +// Output (simplified by ignoring the batch dimensions): +// Since the forward path has: +// output = dot(weights * neighbors) +// The backprop into warp will therefore be: +// grad_warp = output_grad * d_output / d_warp +// = output_grad * (d_weights / d_warp * neighbors + d_neighbors / +// d_warp * weight) +// Where: +// d_weights / d_warp_x = [-(1 - py), (1 - py), -py, py] +// d_weights / d_warp_y = [-(1 - px), -px, (1-px), px] +// and +// d_neighbors / d_warp_x = 0 +// +// Therefore: +// grad_warp_x = py * (img_cxcy - img_fxcy) + (1-py) * (img_cxfy-img_fxfy) +// grad_warp_y = px * (img_cxcy - img_cxfy) + (1-px) * (img_fxcy-img_fxfy) +// +// where (px, py) is warp, (fx, fy) is the top left corner and (cx, cy) is the +// bottom right corner in a 2x2 neighborhood. +XlaOp CalculateGradWarp(XlaOpKernelContext* ctx, XlaOp grad_output, XlaOp ratio, + XlaOp gather_indices, XlaOp data, + TensorShape warp_shape, int64_t data_channels, + xla::PrimitiveType data_type, xla::Shape data_shape) { + auto warp_dims = warp_shape.dim_sizes(); + std::vector warp_dims_without_last_dims(warp_dims.begin(), + warp_dims.end() - 1); + + // With dimension [batch, dim_0, ...dim_n, 4] + std::vector neighbor_broadcast_dims = warp_dims_without_last_dims; + neighbor_broadcast_dims.push_back(4); + + // With dimension [batch, dim_0, ...dim_n, 4] + auto neighbor_broadcast_shape = + xla::ShapeUtil::MakeShape(data_type, neighbor_broadcast_dims); + + const int64_t last_warp_dim = warp_shape.dims() - 1; + + // Pad data with 0, before gathering such that 0 will be returned for samples + // in the range of (-1, 0) or (image_dimension-1, image_dimension). + // After left and right column 0-padding, the new dimension of padded data + // will be [batch, x+2, y+2, channel]. + auto padded_data = + xla::Pad(data, xla::Zero(ctx->builder(), data_type), + xla::MakeEdgePaddingConfig({{0, 0}, {1, 1}, {1, 1}, {0, 0}})); + + auto shifting_value = xla::ConstantR1( + ctx->builder(), {/*batch=*/0, /*x(width)=*/1, /*y(height)=*/1}); + auto shifted_gather_indices = + xla::Add(gather_indices, shifting_value, {last_warp_dim}); + + // The dimension is [batch, dim_0, ... dim_n, 4, data_channels] + auto neighbors_data = + Gather2by2Neighbors(ctx->builder(), padded_data, shifted_gather_indices, + data_channels, warp_shape.dims()); + + // Since we will be creating the dot product of: + // lhs: [batch, dim_0, ...dim_n, 4] + // and + // rhs: [batch, dim_0, ...dim_n, 4, data_channels] + // we choose the last dimension of lhs and the second last dimension of rhs, + // with size 4, as the contracting dimension. + xla::DotDimensionNumbers dot_dims; + for (int i = 0; i < warp_shape.dims() - 1; ++i) { + dot_dims.add_lhs_batch_dimensions(i); + dot_dims.add_rhs_batch_dimensions(i); + } + dot_dims.add_lhs_contracting_dimensions(warp_shape.dims() - 1); + dot_dims.add_rhs_contracting_dimensions(warp_shape.dims() - 1); + + // img_cxcy - img_fxcy + auto bottom_right_minus_bottom_left = xla::DotGeneral( + xla::BroadcastInDim( + xla::ConvertElementType( + xla::ConstantR1(ctx->builder(), {0, 0, -1, 1}), data_type), + neighbor_broadcast_dims, {last_warp_dim}), + neighbors_data, dot_dims, /*precision_config=*/nullptr); + + // img_cxfy - img_fxfy + auto top_right_minus_top_left = xla::DotGeneral( + xla::BroadcastInDim( + xla::ConvertElementType( + xla::ConstantR1(ctx->builder(), {-1, 1, 0, 0}), data_type), + neighbor_broadcast_dims, {last_warp_dim}), + neighbors_data, dot_dims, /*precision_config=*/nullptr); + + // img_cxcy - img_cxfy + auto bottom_right_minus_top_right = xla::DotGeneral( + xla::BroadcastInDim( + xla::ConvertElementType( + xla::ConstantR1(ctx->builder(), {0, -1, 0, 1}), data_type), + neighbor_broadcast_dims, {last_warp_dim}), + neighbors_data, dot_dims, /*precision_config=*/nullptr); + + // img_fxcy - img_fxfy + auto bottom_left_minus_top_left = xla::DotGeneral( + xla::BroadcastInDim( + xla::ConvertElementType( + xla::ConstantR1(ctx->builder(), {-1, 0, 1, 0}), data_type), + neighbor_broadcast_dims, {last_warp_dim}), + neighbors_data, dot_dims, /*precision_config=*/nullptr); + + // Slice out x and y. + auto weight_x = xla::SliceInDim(ratio, /*start_index=*/0, /*limit_index=*/1, + /*stride=*/1, /*dimno=*/last_warp_dim); + auto weight_y = xla::SliceInDim(ratio, /*start_index=*/1, /*limit_index=*/2, + /*stride=*/1, /*dimno=*/last_warp_dim); + + // Build 1 - y and 1 - x. + auto one_minus_y = xla::One(ctx->builder(), data_type) - weight_y; + auto one_minus_x = xla::One(ctx->builder(), data_type) - weight_x; + + auto x_before_reduce = + grad_output * weight_y * bottom_right_minus_bottom_left + + one_minus_y * top_right_minus_top_left; + + std::vector reshaped_sizes = warp_dims_without_last_dims; + reshaped_sizes.push_back(1); + + // Reduce-add along the channel dimension. + auto x_result = + xla::Reduce(x_before_reduce, xla::Zero(ctx->builder(), data_type), + xla::CreateScalarAddComputation(data_type, ctx->builder()), + {last_warp_dim}); + // Reshape before concatenating with y values. + XlaOp reshaped_x = xla::Reshape(x_result, reshaped_sizes); + + auto y_before_reduce = grad_output * weight_x * bottom_right_minus_top_right + + one_minus_x * bottom_left_minus_top_left; + // Reduce-add along the channel dimension. + auto y_result = + xla::Reduce(y_before_reduce, xla::Zero(ctx->builder(), data_type), + + xla::CreateScalarAddComputation(data_type, ctx->builder()), + {last_warp_dim}); + XlaOp reshaped_y = xla::Reshape(y_result, reshaped_sizes); + + return xla::ConcatInDim(ctx->builder(), {reshaped_x, reshaped_y}, + last_warp_dim); +} +} // namespace + +ResamplerOp::ResamplerOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + +void ResamplerOp::Compile(XlaOpKernelContext* ctx) { + TensorShape data_shape = ctx->InputShape("data"); + OP_REQUIRES(ctx, data_shape.dims() == 4, + errors::InvalidArgument("data must be 4-dimensional", + data_shape.DebugString())); + const int64_t data_channels = data_shape.dim_size(3); + xla::PrimitiveType data_type = ctx->input_xla_type(0); + + TensorShape warp_shape = ctx->InputShape("warp"); + OP_REQUIRES(ctx, warp_shape.dims() >= 2, + errors::InvalidArgument("warp must be at least 2-dimensional", + warp_shape.DebugString())); + for (int size : warp_shape.dim_sizes()) { + OP_REQUIRES(ctx, size > 0, + errors::InvalidArgument("warp sizes must be positive, got [", + size, "]")); + } + const int64_t last_warp_dim = warp_shape.dims() - 1; + // Last dimension of warp shape must be of size 2. + OP_REQUIRES(ctx, warp_shape.dim_size(last_warp_dim) == 2, + errors::InvalidArgument( + "the last dimension of warp must be exactly size 2.")); + xla::PrimitiveType warp_type = ctx->input_xla_type(1); + + XlaOp data = ctx->Input("data"); + XlaOp warp = ctx->Input("warp"); + + // Find the coordinates of the top left corner for the 2x2 region to be + // sampled from. The dimensions are [batch, dim_0, ... dim_n, 2] where the + // last dimension of size 2 in turn is [x, y]. + XlaOp top_left = xla::ConvertElementType(warp, xla::S32); + + auto gather_indices = ConcatenateIota(ctx->builder(), top_left, warp_shape); + + // The dimension is [batch, dim_0, ... dim_n, 4, data_channels] + auto neighbors_data = Gather2by2Neighbors( + ctx->builder(), data, gather_indices, data_channels, warp_shape.dims()); + + // Dimensions are [batch, dim_0, ... dim_n, 2]. + XlaOp ratio = warp - xla::ConvertElementType(top_left, data_type); + + // Obtain the bilinear blending weights, the dimension is [batch, dim_0, + // ...dim_n, 4]. + auto weights = BilinearWeights(ctx, ratio, warp_shape, data_type); + + // Since we will be creating the dot product of: + // lhs: [batch, dim_0, ...dim_n, 4] + // and + // rhs: [batch, dim_0, ...dim_n, 4, data_channels] + // we choose the last dimension of lhs and the second last dimension of rhs, + // with size 4, as the contracting dimension. + xla::DotDimensionNumbers dot_dims; + for (int i = 0; i < warp_shape.dims() - 1; ++i) { + dot_dims.add_lhs_batch_dimensions(i); + dot_dims.add_rhs_batch_dimensions(i); + } + dot_dims.add_lhs_contracting_dimensions(warp_shape.dims() - 1); + dot_dims.add_rhs_contracting_dimensions(warp_shape.dims() - 1); + + // The dimension is [batch, dim_0, ...dim_n, data_channels]. + auto blended_pixels = xla::DotGeneral(weights, neighbors_data, dot_dims, + /*precision_config=*/nullptr); + + // Handle out of boundary cases by constructing a predicate mask array based + // on the in-bound condition, and output 0 for the blended pixel value if + // out-bound. The dimension is the same as top_left: [batch, dim_0, + // ...dim_n, 2] where the last dimension of size 2 is the [x, y] coordinate. + + auto is_ge_zero = xla::Ge(warp, xla::ZerosLike(warp)); + + auto is_lt_image_size = xla::Lt( + warp, + xla::ConvertElementType( + xla::ConstantR1( + ctx->builder(), + {/*width=*/static_cast(data_shape.dim_size(2) - 1), + /*height=*/static_cast(data_shape.dim_size(1) - 1)}), + warp_type), + /*broadcast_dimensions=*/{warp_shape.dims() - 1}); + + auto is_in_bound_x_y = xla::And(is_ge_zero, is_lt_image_size); + // Reduce along last dimension. The resulting dimension is: + // [batch, dim_0, ...dim_n]. + auto is_in_bound = xla::Reduce( + is_in_bound_x_y, xla::ConstantR0(ctx->builder(), true), + xla::CreateScalarAndComputation(xla::PrimitiveType::PRED, ctx->builder()), + {last_warp_dim}); + + // Broadcast 'is_in_bound' to the same dimension as 'blended_pixels', which + // is the dimension of the result: + // [batch, dim_0, ...dim_n, data_channels]. + auto warp_dims = warp_shape.dim_sizes(); + std::vector result_dims(warp_dims.begin(), warp_dims.end() - 1); + result_dims.push_back(data_channels); + + std::vector broadcasted_dims(warp_dims.size() - 1); + std::iota(broadcasted_dims.begin(), broadcasted_dims.end(), 0); + auto broadcasted_is_in_bound = + xla::BroadcastInDim(is_in_bound, result_dims, broadcasted_dims); + + // Set out of bound samples to zero. + auto zeros = + xla::Broadcast(xla::Zero(ctx->builder(), data_type), result_dims); + auto result = xla::Select(broadcasted_is_in_bound, blended_pixels, zeros); + + ctx->SetOutput(0, result); +} + +REGISTER_XLA_OP(Name("Resampler"), ResamplerOp); + +ResamplerGradOp::ResamplerGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + DataType output_dtype; + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &output_dtype)); +} + + // TODO(b/112295522): note that sampling from image boundary is not currently + // being handled properly. +void ResamplerGradOp::Compile(XlaOpKernelContext* ctx) { + TensorShape data_shape_tf = ctx->InputShape("data"); + OP_REQUIRES(ctx, data_shape_tf.dims() == 4, + errors::InvalidArgument("data must be 4-dimensional", + data_shape_tf.DebugString())); + const int64_t data_channels = data_shape_tf.dim_size(3); + xla::PrimitiveType data_type = ctx->input_xla_type(0); + + TensorShape warp_shape = ctx->InputShape("warp"); + OP_REQUIRES(ctx, warp_shape.dims() >= 2, + errors::InvalidArgument("warp must be at least 2-dimensional", + warp_shape.DebugString())); + for (int size : warp_shape.dim_sizes()) { + OP_REQUIRES(ctx, size > 0, + errors::InvalidArgument("warp sizes must be positive, got [", + size, "]")); + } + // Last dimension of warp shape must be of size 2. + const int64_t last_warp_dim = warp_shape.dims() - 1; + OP_REQUIRES(ctx, warp_shape.dim_size(last_warp_dim) == 2, + errors::InvalidArgument( + "the last dimension of warp must be exactly size 2.")); + xla::PrimitiveType warp_type = ctx->input_xla_type(1); + + TensorShape output_grad_shape = ctx->InputShape("grad_output"); + OP_REQUIRES( + ctx, output_grad_shape.dims() >= 2, + errors::InvalidArgument("output_grad must be at least 2-dimensional", + output_grad_shape.DebugString())); + + // Dimensions are [batch, x, y, channel]. + XlaOp data = ctx->Input("data"); + xla::Shape data_shape = TensorShapeToXLAShape(data_type, data_shape_tf); + + // Dimensions are [batch, dim_0, ...dim_n, 2]. + XlaOp warp = ctx->Input("warp"); + // Dimensions are [batch, dim_0, ...dim_n, channel]. + XlaOp grad_output = ctx->Input("grad_output"); + + // Find the top left corner coordinate for the region to be sampled from. + // The dimensions are [batch, dim_0, ... dim_n, 2] where the last dimension + // of size 2 in turn is [x, y]. + XlaOp top_left = xla::ConvertElementType(xla::Floor(warp), xla::S32); + + // Dimensions are [batch, dim_0, ... dim_n, 2]. + XlaOp ratio = warp - xla::ConvertElementType(top_left, warp_type); + + // Indices for gathering neighboring pixels. + auto gather_indices = ConcatenateIota(ctx->builder(), top_left, warp_shape); + + auto grad_data = CalculateGradData(ctx, grad_output, ratio, gather_indices, + warp, warp_type, warp_shape, last_warp_dim, + data_channels, data_shape); + + auto grad_warp = + CalculateGradWarp(ctx, grad_output, ratio, gather_indices, data, + warp_shape, data_channels, data_type, data_shape); + auto warp_dims = warp_shape.dim_sizes(); + std::vector result_dims(warp_dims.begin(), warp_dims.end() - 1); + result_dims.push_back(2); + std::vector broadcasted_dims(warp_dims.size() - 1); + std::iota(broadcasted_dims.begin(), broadcasted_dims.end(), 0); + auto grad_warp_bounded = + BoundSamples(ctx, warp, warp_type, warp_shape, result_dims, + broadcasted_dims, last_warp_dim, data_shape, grad_warp); + + ctx->SetOutput(0, grad_data); + ctx->SetOutput(1, grad_warp_bounded); +} + +REGISTER_XLA_OP(Name("ResamplerGrad"), ResamplerGradOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..786e0e45e38051d450255b466dac1ca2af7a78d7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/resampler_ops.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_COMPILER_TF2XLA_KERNELS_RESAMPLER_OPS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_RESAMPLER_OPS_H_ + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { + +// XLA op kernel for both contrib and addon flavors of TenforFlow Resampler +class ResamplerOp : public XlaOpKernel { + public: + explicit ResamplerOp(OpKernelConstruction* ctx); + void Compile(XlaOpKernelContext* ctx) override; +}; + +// XLA op kernel for both contrib and addon flavors of TenforFlow Resampler +// gradient. +class ResamplerGradOp : public XlaOpKernel { + public: + explicit ResamplerGradOp(OpKernelConstruction* ctx); + void Compile(XlaOpKernelContext* ctx) override; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_RESAMPLER_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reshape_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reshape_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ec4b06790122f15791aea2d7e546f01cbdfb37b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reshape_op.cc @@ -0,0 +1,209 @@ +/* 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. +==============================================================================*/ + +// XLA-specific reshape Op. + +#include +#include + +#include "absl/log/log.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class ReshapeOp : public XlaOpKernel { + public: + explicit ReshapeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape input_shape = ctx->InputShape(0); + auto input_xla_shape = ctx->InputXlaShape(0); + const TensorShape sizes_shape = ctx->InputShape(1); + // Preliminary validation of sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(sizes_shape), + errors::InvalidArgument("sizes input must be 1-D, not shape ", + sizes_shape.DebugString())); + const int64_t num_dims = sizes_shape.num_elements(); + + std::vector shape_input; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntVector( + 1, &shape_input, xla::ValueInferenceMode::kUpperBound)); + // Compute the output shape. Determine product of specified + // dimensions, and find the index of the unspecified one if there + // is one. + TensorShape shape; + int64_t product = 1; + int unknown_index = -1; + bool shape_has_zero_dim = false; + for (int d = 0; d < num_dims; ++d) { + const int64_t size = shape_input[d]; + if (size == -1) { + OP_REQUIRES( + ctx, unknown_index == -1, + errors::InvalidArgument("only one input size may be -1, not both ", + unknown_index, " and ", d)); + unknown_index = d; + shape.AddDim(1); + } else if (size == 0) { + // We don't include zero-sized dimension in product, so that we can + // still calculate number of elements for non-zero-sized dimensions and + // therefore infer their shapes. + shape.AddDim(size); + shape_has_zero_dim = true; + } else { + OP_REQUIRES(ctx, size >= 0, + errors::InvalidArgument( + "size ", d, " must be non-negative, not ", size)); + shape.AddDim(size); + product *= size; + } + } + auto input = ctx->Input(0); + if (unknown_index != -1) { + int64_t input_num_elements = 1; + bool input_has_zero_dim = false; + for (int dim = 0; dim < input_shape.dims(); dim++) { + // For zero dimension, we don't count it into `input_num_elements` + // unless `sizes` has no zero dimension, so we are still able to + // infer shapes for other dimensions. + if (input_shape.dim_size(dim) > 0 || !shape_has_zero_dim) { + input_num_elements *= input_shape.dim_size(dim); + } else { + input_has_zero_dim = true; + } + } + + int64_t missing = input_num_elements / product; + if (!input_has_zero_dim) { + if (input_xla_shape->is_static() || + input_xla_shape->dimensions().size() != 1) { + OP_REQUIRES( + ctx, product * missing == input_num_elements, + errors::InvalidArgument( + "Input to reshape is a tensor with ", input_num_elements, + " values, but the requested shape requires a multiple of ", + product)); + } else { + // For 1D shape, we can safely insert extra padding in the end to make + // sure the input is multiple of the product of the known dimensions. + // (We can probably do that for >1D shapes but that involves + // factorizing the number of missing elements.) + int64_t padded_input_num = + xla::CeilOfRatio(input_num_elements, product) * product; + missing = padded_input_num / product; + input = xla::PadInDim( + input, xla::Zero(ctx->builder(), input_xla_shape->element_type()), + 0, 0, padded_input_num - input_num_elements); + input_shape.set_dim(0, padded_input_num); + } + } + shape.set_dim(unknown_index, missing); + } + OP_REQUIRES(ctx, shape.num_elements() == input_shape.num_elements(), + errors::InvalidArgument("Input to reshape is a tensor with ", + input_shape.num_elements(), + " values, but the requested shape has ", + shape.num_elements())); + + VLOG(2) << "Reshape from " << input_shape.DebugString() << " to " + << shape.DebugString() << ", unknown_index=" << unknown_index; + if (input_xla_shape->is_static()) { + ctx->SetOutput(0, xla::Reshape(input, shape.dim_sizes())); + return; + } + + std::vector output_dim_sizes; + std::vector dims_are_dynamic; + const auto& dims = shape.dims(); + dims_are_dynamic.reserve(dims); + output_dim_sizes.reserve(dims); + for (int64_t i = 0; i < dims; ++i) { + output_dim_sizes.push_back( + xla::Reshape(xla::Slice(ctx->Input(1), {i}, {i + 1}, {1}), {})); + } + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPredVector(1, &dims_are_dynamic)); + if (unknown_index == -1) { + // No unknown index. + ctx->SetOutput( + 0, xla::DynamicReshape(input, output_dim_sizes, shape.dim_sizes(), + dims_are_dynamic)); + return; + } + auto common_factors = + xla::CommonFactors(input_shape.dim_sizes(), shape.dim_sizes()); + + // Find common_factors that the input belongs to. + for (int64_t i = 0; i < common_factors.size() - 1; ++i) { + auto start = common_factors[i]; + auto end = common_factors[i + 1]; + bool input_is_dynamic = false; + // product of all input dims in this group. E.g., in + // reshape(Tensor([2, 3, 3]), [3, -1, 3]) product of the group + // containing -1 will be 6. + xla::XlaOp product = xla::One(ctx->builder(), xla::S32); + for (int64_t dim = start.first; dim < end.first; ++dim) { + if (input_xla_shape->is_dynamic_dimension(dim)) { + input_is_dynamic = true; + } + product = xla::Mul(product, xla::GetDimensionSize(input, dim)); + } + bool unknown_dim_in_group = false; + // The real size for the -1 dimension in a reshape. E.g., in + // reshape(Tensor([2, 3, 3]), [3, -1, 3]) this will be 2. + xla::XlaOp unknown_dim_size = product; + for (int64_t dim = start.second; dim < end.second; ++dim) { + if (dim == unknown_index) { + unknown_dim_in_group = true; + } else { + unknown_dim_size = xla::Div(unknown_dim_size, output_dim_sizes[dim]); + } + } + + if (unknown_dim_in_group) { + // If input dim is dynamic, output dim at the -1 position must be + // dynamic. Similarly, if input dim is static, output dim has to be + // static at the -1 dimension. + dims_are_dynamic[unknown_index] = input_is_dynamic; + output_dim_sizes[unknown_index] = unknown_dim_size; + + ctx->SetOutput( + 0, xla::DynamicReshape(input, output_dim_sizes, shape.dim_sizes(), + dims_are_dynamic)); + VLOG(2) << "Reshape from " << ctx->InputXlaShape(0)->ToString() + << " to " << xla::VectorString(shape.dim_sizes()) + << ", dynamic_dims=" << xla::VectorString(dims_are_dynamic); + return; + } + } + } +}; + +REGISTER_XLA_OP(Name("Reshape").CompileTimeConstantInput("shape"), ReshapeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/retval_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/retval_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..47b1ea71fc0e7be07e7d7ca1291d8357d7ec42b8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/retval_op.cc @@ -0,0 +1,75 @@ +/* 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/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +// This TensorFlow op indicates that its input should be treated as a +// specific return value from a function. +class RetvalOp : public XlaOpKernel { + public: + explicit RetvalOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("index", &index_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const Tensor& input = ctx->op_kernel_context()->input(0); + + // Types that cannot be copied using memcpy (like DT_VARIANT types that + // represent Tensor Lists) are wrapped in a DT_UINT8 and hence the type + // mismatches. Skip the test in such cases. See + // XlaOpKernelContext::SetOutputExpression for details. + if (DataTypeCanUseMemcpy(dtype_)) { + OP_REQUIRES(ctx, input.dtype() == dtype_, + errors::InvalidArgument( + "Type mismatch: actual ", DataTypeString(input.dtype()), + " vs. expect ", DataTypeString(dtype_))); + } + auto frame = ctx->call_frame(); + if (frame) { + // If 'frame' is non-null, this is an inner function call inside a JIT + // compilation. + OP_REQUIRES_OK(ctx, frame->SetRetval(index_, input)); + } else { + ctx->xla_context()->SetRetval(index_, ctx->InputExpression(0)); + } + } + + private: + // The index of this return value in the returned tuple. + int index_; + DataType dtype_; + + RetvalOp(const RetvalOp&) = delete; + void operator=(const RetvalOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("_Retval").AllowResourceTypes().AllowVariantTypes().CompilationOnly(), + RetvalOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reverse_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reverse_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..8c874474063ca4bcf22be4b0dd44a5a4e3850c12 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reverse_op.cc @@ -0,0 +1,126 @@ +/* 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. +==============================================================================*/ + +// XLA-specific reverse Op. + +#include +#include + +#include "absl/container/inlined_vector.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class ReverseOp : public XlaOpKernel { + public: + explicit ReverseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // r = tf.reverse(x, revdims) + const TensorShape x_shape = ctx->InputShape(0); + const TensorShape revd_shape = ctx->InputShape(1); + // Validate input sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(revd_shape), + errors::InvalidArgument("axes must be a vector, not shape ", + revd_shape.DebugString())); + OP_REQUIRES(ctx, revd_shape.num_elements() == x_shape.dims(), + errors::InvalidArgument("axes ", revd_shape.DebugString(), + " must have same number of elements as" + " than input tensor has dimensions ", + x_shape.DebugString(), ".")); + if (revd_shape.num_elements() == 0) { + ctx->SetOutput(0, ctx->Input(0)); + return; + } + // XlaBuilder::Rev() requires concrete values for dimensions arg. + xla::Literal lax; + OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &lax)); + + std::vector dimensions; + for (int d = 0; d < x_shape.dims(); ++d) { + if (lax.Get({d})) { + dimensions.push_back(d); + } + } + + ctx->SetOutput(0, xla::Rev(ctx->Input(0), dimensions)); + } +}; + +REGISTER_XLA_OP(Name("Reverse").CompileTimeConstantInput("dims"), ReverseOp); + +class ReverseV2Op : public XlaOpKernel { + public: + explicit ReverseV2Op(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // r = tf.reverse(x, axes) + const TensorShape x_shape = ctx->InputShape(0); + const TensorShape axes_shape = ctx->InputShape(1); + // Validate input sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(axes_shape), + errors::InvalidArgument("axes must be a vector, not shape ", + axes_shape.DebugString())); + OP_REQUIRES(ctx, axes_shape.num_elements() <= x_shape.dims(), + errors::InvalidArgument("axes ", axes_shape.DebugString(), + " can not have more elements" + " than input tensor has dimensions ", + x_shape.DebugString(), ".")); + // Reverse is a no-op if axes argument is empty. + if (axes_shape.num_elements() == 0) { + ctx->SetOutput(0, ctx->Input(0)); + return; + } + // XlaBuilder::Rev() requires concrete values for dimensions arg. + std::vector 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. + absl::InlinedVector witnessed_axes(x_shape.dims(), false); + + for (int d = 0; d < axes.size(); ++d) { + 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)); + } +}; + +REGISTER_XLA_OP(Name("ReverseV2").CompileTimeConstantInput("axis"), + ReverseV2Op); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reverse_sequence_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reverse_sequence_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..58696ead905bf81a57f5ccc19917961c0b006a74 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/reverse_sequence_op.cc @@ -0,0 +1,144 @@ +/* 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 + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class ReverseSequenceOp : public XlaOpKernel { + public: + explicit ReverseSequenceOp(OpKernelConstruction* context) + : XlaOpKernel(context) { + OP_REQUIRES_OK(context, context->GetAttr("batch_dim", &batch_dim_)); + OP_REQUIRES_OK(context, context->GetAttr("seq_dim", &seq_dim_)); + } + + void Compile(XlaOpKernelContext* context) override { + const TensorShape input_shape = context->InputShape(0); + const TensorShape seq_lens_shape = context->InputShape(1); + + OP_REQUIRES(context, TensorShapeUtils::IsVector(seq_lens_shape), + errors::InvalidArgument("seq_lengths must be 1-dim, not ", + seq_lens_shape.dims())); + OP_REQUIRES(context, batch_dim_ != seq_dim_, + errors::InvalidArgument("batch_dim == seq_dim == ", seq_dim_)); + OP_REQUIRES(context, seq_dim_ >= 0, + errors::InvalidArgument("seq_dim must be >=0, got ", seq_dim_)); + OP_REQUIRES( + context, seq_dim_ < input_shape.dims(), + errors::InvalidArgument("seq_dim must be < input rank", " ( ", seq_dim_, + " vs. ", input_shape.dims(), ")")); + OP_REQUIRES( + context, batch_dim_ >= 0, + errors::InvalidArgument("batch_dim must be >=0, got ", batch_dim_)); + OP_REQUIRES( + context, batch_dim_ < input_shape.dims(), + errors::InvalidArgument("batch_dim must be < input rank", " ( ", + batch_dim_, " vs. ", input_shape.dims(), ")")); + OP_REQUIRES( + context, + seq_lens_shape.num_elements() == input_shape.dim_size(batch_dim_), + errors::InvalidArgument("Length of seq_lengths != input.dims(", + batch_dim_, "), ", "(", + seq_lens_shape.num_elements(), " vs. ", + input_shape.dim_size(batch_dim_), ")")); + + xla::XlaBuilder* builder = context->builder(); + const auto input = context->Input(0); + const auto seq_lens = context->Input(1); + + const int64_t batch_size = input_shape.dim_size(batch_dim_); + if (batch_size == 0) { + context->SetOutput(0, input); + return; + } + + const xla::PrimitiveType seq_lens_type = context->input_xla_type(1); + const int64_t max_seq_len = input_shape.dim_size(seq_dim_); + + // Create [batch, sequence, 2] tensor that contains the indices where the + // real data belongs + xla::XlaOp back = xla::Sub(seq_lens, xla::ScalarLike(seq_lens, 1)); + xla::XlaOp batch_idx = xla::Iota( + builder, + xla::ShapeUtil::MakeShape(seq_lens_type, {batch_size, max_seq_len, 1}), + /*iota_dimension=*/0); + xla::XlaOp forward_idx = xla::Iota( + builder, + xla::ShapeUtil::MakeShape(seq_lens_type, {batch_size, max_seq_len, 1}), + /*iota_dimension=*/1); + xla::XlaOp reverse_idx = xla::Sub(back, forward_idx, {0}); + reverse_idx = xla::Select(xla::Lt(reverse_idx, xla::ZerosLike(reverse_idx)), + forward_idx, reverse_idx); + if (batch_dim_ > seq_dim_) { + // The output of the XLA gather op keeps indices dimensions in the same + // order as they appear in the input. If the batch_dim_ needs to be after + // the seq_dim_ in the output, it also needs to be that way in the input + // so we transpose. + batch_idx = xla::Transpose(batch_idx, {1, 0, 2}); + forward_idx = xla::Transpose(forward_idx, {1, 0, 2}); + reverse_idx = xla::Transpose(reverse_idx, {1, 0, 2}); + } + xla::XlaOp start_indices = + xla::ConcatInDim(builder, {batch_idx, reverse_idx}, + /*dimension=*/2); + + xla::GatherDimensionNumbers dnums; + dnums.set_index_vector_dim(2); + // The first and second element in the third dimension of reverse_idx are + // the batch_dim_ offset and the seq_dim_ offset respectively. + dnums.add_start_index_map(batch_dim_); + dnums.add_start_index_map(seq_dim_); + + // batch_dim_ and seq_dim_ are collapsed and the other dimensions are kept + // in the gather. + for (int i = 0; i < input_shape.dims(); ++i) { + if (i != batch_dim_ && i != seq_dim_) { + dnums.add_offset_dims(i); + } else { + dnums.add_collapsed_slice_dims(i); + } + } + + auto slice_sizes = input_shape.dim_sizes(); + slice_sizes[batch_dim_] = 1; + slice_sizes[seq_dim_] = 1; + + context->SetOutput(0, + xla::Gather(input, start_indices, dnums, slice_sizes)); + } + + private: + int32_t batch_dim_; + int32_t seq_dim_; +}; + +REGISTER_XLA_OP(Name("ReverseSequence"), ReverseSequenceOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..f59e5417a9cc9923af4330324f62dd1acd2ac08c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.cc @@ -0,0 +1,51 @@ +/* Copyright 2023 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/kernels/rng_converter_utils.h" + +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/rng_alg.h" + +namespace tensorflow { + +Algorithm ToTensorflowAlgorithm(xla::RandomAlgorithm alg) { + switch (alg) { + case xla::RandomAlgorithm::RNG_PHILOX: + return RNG_ALG_PHILOX; + case xla::RandomAlgorithm::RNG_THREE_FRY: + return RNG_ALG_THREEFRY; + case xla::RandomAlgorithm::RNG_DEFAULT: // fall through + default: + // The output counter will have the maximal size, so it's safe to let + // downstream RNG ops choose the algorithm. + return RNG_ALG_AUTO_SELECT; + } +} + +xla::RandomAlgorithm DefaultRngAlgForDeviceType( + absl::string_view device_type_string) { + // The Philox algorithm may cause performance regression on other devices. + // Turn on the Philox algorithm for the CPU and GPU backends only. + if (device_type_string == DEVICE_GPU_XLA_JIT || + device_type_string == DEVICE_CPU_XLA_JIT) { + return xla::RandomAlgorithm::RNG_PHILOX; + } else { + return xla::RandomAlgorithm::RNG_DEFAULT; + } +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..20c07f006db7fad056e945335cb7466dcd7abc7a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils.h @@ -0,0 +1,34 @@ +/* Copyright 2023 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_KERNELS_RNG_CONVERTER_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_RNG_CONVERTER_UTILS_H_ + +#include "absl/strings/string_view.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/rng_alg.h" + +namespace tensorflow { + +// Given the XLA::RandomAlgorithm, return the Tensorflow equivalent. +Algorithm ToTensorflowAlgorithm(xla::RandomAlgorithm alg); + +// Given the device type, return the default XLA::RandomAlgorithm +xla::RandomAlgorithm DefaultRngAlgForDeviceType( + absl::string_view device_type_string); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_RNG_CONVERTER_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a3066890df62bc3907f12e6e7ff88540a0cae2a9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/rng_converter_utils_test.cc @@ -0,0 +1,50 @@ +/* Copyright 2023 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/kernels/rng_converter_utils.h" + +#include +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/rng_alg.h" + +namespace tensorflow { +namespace { + +TEST(RngConverterUtilsTest, DefaultRngForCPUEqualsGPU) { + EXPECT_EQ(DefaultRngAlgForDeviceType(DEVICE_CPU_XLA_JIT), + DefaultRngAlgForDeviceType(DEVICE_GPU_XLA_JIT)); +} + +TEST(RngConverterUtilsTest, UnknownDeviceIsDefault) { + EXPECT_EQ(DefaultRngAlgForDeviceType(/*device_type_string=*/"UNKNOWN DEVICE"), + xla::RandomAlgorithm::RNG_DEFAULT); +} + +TEST(RngConverterUtilsTest, TensorflowAutoSelects) { + EXPECT_EQ(ToTensorflowAlgorithm(xla::RandomAlgorithm::RNG_DEFAULT), + tensorflow::RNG_ALG_AUTO_SELECT); +} + +TEST(RngConverterUtilsTest, ToTensorflow) { + EXPECT_EQ(ToTensorflowAlgorithm(xla::RandomAlgorithm::RNG_PHILOX), + tensorflow::RNG_ALG_PHILOX); + + EXPECT_EQ(ToTensorflowAlgorithm(xla::RandomAlgorithm::RNG_THREE_FRY), + tensorflow::RNG_ALG_THREEFRY); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/roll_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/roll_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..289164d63a496517a78da994e35e83d8d90f610f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/roll_op.cc @@ -0,0 +1,111 @@ +/* Copyright 2019 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 +#include + +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/slicing.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +namespace { + +class RollOp : public XlaOpKernel { + public: + explicit RollOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + xla::XlaOp shift = ctx->Input(1); + const TensorShape shift_shape = ctx->InputShape(1); + const TensorShape axis_shape = ctx->InputShape(2); + + int64_t input_dims = input_shape.dims(); + OP_REQUIRES(ctx, input_dims >= 1, + errors::InvalidArgument("input must be 1-D or higher")); + OP_REQUIRES(ctx, shift_shape.dims() <= 1, + errors::InvalidArgument( + "shift must be a scalar or a 1-D vector. Found: ", + shift_shape.DebugString())); + OP_REQUIRES(ctx, axis_shape.dims() <= 1, + errors::InvalidArgument( + "axis must be a scalar or a 1-D vector. Found: ", + shift_shape.DebugString())); + OP_REQUIRES( + ctx, shift_shape == axis_shape, + errors::InvalidArgument("shift and axis must have the same size")); + + xla::Literal axis; + OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &axis)); + + xla::XlaOp output = ctx->Input(0); + xla::PrimitiveType shift_type = ctx->input_xla_type(1); + int64_t num_axes = axis_shape.dims() == 0 ? 1 : axis_shape.dim_size(0); + for (int64_t i = 0; i != num_axes; ++i) { + int64_t cur_axis = axis_shape.dims() == 0 ? *axis.GetIntegralAsS64({}) + : *axis.GetIntegralAsS64({i}); + OP_REQUIRES(ctx, cur_axis >= -input_dims && cur_axis < input_dims, + errors::InvalidArgument( + absl::StrCat("axis ", cur_axis, " is out of range [-", + input_dims, ", ", input_dims, ")."))); + if (cur_axis < 0) { + cur_axis += input_dims; + } + + xla::XlaOp offset = + shift_shape.dims() == 0 + ? shift + : xla::Reshape(xla::SliceInDim(shift, /*start_index=*/i, + /*limit_index=*/i + 1, + /*stride=*/1, /*dimno=*/0), + {}); + xla::XlaOp axis_size = xla::ConstantR0WithType( + ctx->builder(), shift_type, input_shape.dim_size(cur_axis)); + // Adjust large offsets into [0, axis_size). This also makes negative + // offsets positive. + offset = ((offset % axis_size) + axis_size) % axis_size; + + // Stack two copies of the dimension, then slice from the calculated + // offset. + xla::XlaOp concat = + xla::ConcatInDim(ctx->builder(), {output, output}, cur_axis); + std::vector start_indices( + input_shape.dims(), xla::Zero(ctx->builder(), shift_type)); + start_indices[cur_axis] = axis_size - offset; + output = + xla::DynamicSlice(concat, start_indices, input_shape.dim_sizes()); + } + ctx->SetOutput(0, output); + } + + private: + RollOp(const RollOp&) = delete; + void operator=(const RollOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Roll").CompileTimeConstantInput("axis"), RollOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/scan_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/scan_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..aa8dce32e2f256ad3a5931f40a393140ae46064f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/scan_ops.cc @@ -0,0 +1,168 @@ +/* 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 +#include +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +constexpr std::array kScanOpTypes = { + {DT_HALF, DT_BFLOAT16, DT_FLOAT, DT_DOUBLE, DT_INT32, DT_INT64}}; + +enum class Reducer { kProduct, kSum, kLogSumExp }; + +class ScanOp : public XlaOpKernel { + public: + ScanOp(OpKernelConstruction* ctx, Reducer reducer) + : XlaOpKernel(ctx), reducer_(reducer) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("reverse", &reverse_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("exclusive", &exclusive_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + const TensorShape tensor_axis_shape = ctx->InputShape(1); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(tensor_axis_shape), + errors::InvalidArgument("ScanOp: axis must be a scalar, not ", + tensor_axis_shape.DebugString())); + + int64_t axis; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(1, &axis)); + if (axis < 0) { + axis += input_shape.dims(); + } + OP_REQUIRES( + ctx, FastBoundsCheck(axis, input_shape.dims()), + errors::InvalidArgument("ScanOp: Expected scan axis in the range [", + -input_shape.dims(), ", ", input_shape.dims(), + "), but got ", axis)); + + DataType dtype = XlaHelpers::SumAccumulationType(ctx->input_type(0)); + + if (input_shape.num_elements() == 0) { + // Exit early if there is nothing to compute. + ctx->SetOutput(0, ctx->Input(0)); + return; + } + + xla::XlaBuilder* builder = ctx->builder(); + + std::vector window_strides(input_shape.dims(), 1); + std::vector window_dims(input_shape.dims(), 1); + window_dims[axis] = input_shape.dim_size(axis); + + std::vector> padding(input_shape.dims(), + {0, 0}); + padding[axis].first = input_shape.dim_size(axis) - 1; + // In exclusive mode, add an extra padding element so there is a complete + // window of padding before the data starts. + if (exclusive_) { + ++padding[axis].first; + } + if (reverse_) { + std::swap(padding[axis].first, padding[axis].second); + } + + xla::XlaOp init; + const xla::XlaComputation* reducer; + switch (reducer_) { + case Reducer::kSum: + init = XlaHelpers::Zero(builder, dtype); + reducer = ctx->GetOrCreateAdd(dtype); + break; + case Reducer::kProduct: + init = XlaHelpers::One(builder, dtype); + reducer = ctx->GetOrCreateMul(dtype); + break; + case Reducer::kLogSumExp: + init = XlaHelpers::FloatLiteral(builder, dtype, -INFINITY); + reducer = ctx->GetOrCreateLogAddExp(dtype); + break; + } + auto output = xla::ReduceWindowWithGeneralPadding( + XlaHelpers::ConvertElementType(ctx->Input(0), dtype), init, *reducer, + window_dims, window_strides, + /*base_dilations=*/{}, /*window_dilations=*/{}, padding); + output = XlaHelpers::ConvertElementType(output, ctx->input_type(0)); + + // In exclusive mode, we have computed an extra element containing the sum + // of all the input elements. Slice off this extra "last" element. + if (exclusive_) { + if (reverse_) { + output = + xla::SliceInDim(output, 1, input_shape.dim_size(axis) + 1, 1, axis); + + } else { + output = + xla::SliceInDim(output, 0, input_shape.dim_size(axis), 1, axis); + } + } + ctx->SetOutput(0, output); + } + + private: + const Reducer reducer_; + bool reverse_; + bool exclusive_; +}; + +class CumsumOp : public ScanOp { + public: + explicit CumsumOp(OpKernelConstruction* ctx) : ScanOp(ctx, Reducer::kSum) {} +}; +REGISTER_XLA_OP(Name("Cumsum") + .TypeConstraint("T", kScanOpTypes) + .CompileTimeConstantInput("axis"), + CumsumOp); + +class CumprodOp : public ScanOp { + public: + explicit CumprodOp(OpKernelConstruction* ctx) + : ScanOp(ctx, Reducer::kProduct) {} +}; +REGISTER_XLA_OP(Name("Cumprod") + .TypeConstraint("T", kScanOpTypes) + .CompileTimeConstantInput("axis"), + CumprodOp); + +class CumulativeLogsumexpOp : public ScanOp { + public: + explicit CumulativeLogsumexpOp(OpKernelConstruction* ctx) + : ScanOp(ctx, Reducer::kLogSumExp) {} +}; +REGISTER_XLA_OP(Name("CumulativeLogsumexp") + .TypeConstraint("T", kScanOpTypes) + .CompileTimeConstantInput("axis"), + CumulativeLogsumexpOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/scatter_nd_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/scatter_nd_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..744586c59cfd2e9678fc66e290378d12de363bdd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/scatter_nd_op.cc @@ -0,0 +1,266 @@ +/* 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 +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/lib/scatter.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace { + +// Check whether updates.shape = indices.shape[:batch_dim] + +// buffer_shape[num_index_dims:] +absl::Status ValidateUpdateShape(const TensorShape& buffer_shape, + const TensorShape& indices_shape, + const TensorShape& updates_shape, + bool broadcast_scalar_update) { + if (indices_shape.dims() < 1) { + return errors::InvalidArgument( + "indices shape must have >= 1 dimension; got ", + indices_shape.DebugString()); + } + + const int64_t num_index_dims = + indices_shape.dim_size(indices_shape.dims() - 1); + const int64_t batch_dim = indices_shape.dims() - 1; + + auto shape_err = [&]() { + return errors::InvalidArgument( + "Must have updates.shape = indices.shape[:batch_dim] + ", + "buffer_shape[num_index_dims:], got updates.shape: ", + updates_shape.DebugString(), + ", indices.shape: ", indices_shape.DebugString(), + ", buffer_shape: ", buffer_shape.DebugString(), + ", num_index_dims: ", num_index_dims, ", and batch_dim: ", batch_dim); + }; + + if (updates_shape.dims() == 0 && broadcast_scalar_update) { + return absl::OkStatus(); + } + + if (updates_shape.dims() < batch_dim) return shape_err(); + if (buffer_shape.dims() < + num_index_dims + (updates_shape.dims() - batch_dim)) { + return shape_err(); + } + if (updates_shape.dims() != + batch_dim + buffer_shape.dims() - num_index_dims) { + return shape_err(); + } + for (int d = 0; d < batch_dim; ++d) { + if (updates_shape.dim_size(d) != indices_shape.dim_size(d)) { + return shape_err(); + } + } + for (int d = 0; d < updates_shape.dims() - batch_dim; ++d) { + if (updates_shape.dim_size(d + batch_dim) != + buffer_shape.dim_size(d + num_index_dims)) { + return shape_err(); + } + } + return absl::OkStatus(); +} + +class ScatterNdOp : public XlaOpKernel { + public: + explicit ScatterNdOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + DataType dtype = context->input_type(1); + + TensorShape indices_shape = context->InputShape(0); + TensorShape updates_shape = context->InputShape(1); + + TensorShape buffer_shape; + OP_REQUIRES_OK(context, context->ConstantInputAsShape(2, &buffer_shape)); + + OP_REQUIRES( + context, TensorShapeUtils::IsVectorOrHigher(buffer_shape), + errors::InvalidArgument("Output must be at least 1-D, ", + "got shape: ", buffer_shape.DebugString())); + + OP_REQUIRES( + context, + buffer_shape.num_elements() > 0 || (indices_shape.num_elements() == 0 && + updates_shape.num_elements() == 0), + errors::InvalidArgument( + "Indices and updates specified for empty output. indices shape: ", + indices_shape.DebugString())); + + OP_REQUIRES_OK( + context, ValidateUpdateShape(buffer_shape, indices_shape, updates_shape, + /*broadcast_scalar_update=*/false)); + + xla::XlaBuilder* builder = context->builder(); + auto buffer = xla::Broadcast(XlaHelpers::Zero(builder, dtype), + buffer_shape.dim_sizes()); + auto indices = context->Input(0); + auto updates = context->Input(1); + auto combine = + context->input_xla_type(1) == xla::PRED ? CombineBool : CombineNum; + auto result = XlaScatter(buffer, updates, indices, + /*indices_are_vectors=*/true, + /*indices_are_sorted=*/false, + /*combiner=*/combine, builder); + OP_REQUIRES_OK(context, result.status()); + context->SetOutput(0, result.value()); + } + + private: + static xla::XlaOp CombineNum(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + (void)builder; + return xla::Add(x, y); + } + static xla::XlaOp CombineBool(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + (void)builder; + return xla::Or(x, y); + } +}; + +REGISTER_XLA_OP(Name("ScatterNd").CompileTimeConstantInput("shape"), + ScatterNdOp); + +void CompileTensorScatter( + XlaOpKernelContext* context, + const std::function& + combiner, + bool broadcast_scalar_update) { + TensorShape buffer_shape = context->InputShape(0); + TensorShape indices_shape = context->InputShape(1); + TensorShape updates_shape = context->InputShape(2); + + OP_REQUIRES( + context, TensorShapeUtils::IsVectorOrHigher(buffer_shape), + errors::InvalidArgument("Output must be at least 1-D, ", + "got shape: ", buffer_shape.DebugString())); + + OP_REQUIRES( + context, + buffer_shape.num_elements() > 0 || (indices_shape.num_elements() == 0 && + updates_shape.num_elements() == 0), + errors::InvalidArgument( + "Indices and updates specified for empty output. indices shape: ", + indices_shape.DebugString())); + + OP_REQUIRES_OK(context, + ValidateUpdateShape(buffer_shape, indices_shape, updates_shape, + broadcast_scalar_update)); + + xla::XlaBuilder* builder = context->builder(); + auto buffer = context->Input(0); + auto indices = context->Input(1); + auto updates = context->Input(2); + auto result = XlaScatter(buffer, updates, indices, + /*indices_are_vectors=*/true, + /*indices_are_sorted=*/false, combiner, builder); + OP_REQUIRES_OK(context, result.status()); + context->SetOutput(0, result.value()); +} + +class TensorScatterAddOp : public XlaOpKernel { + public: + explicit TensorScatterAddOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + CompileTensorScatter( + context, + [](xla::XlaOp x, xla::XlaOp y, xla::XlaBuilder*) { + return xla::Add(x, y); + }, + /*broadcast_scalar_update=*/true); + } +}; + +class TensorScatterMaxOp : public XlaOpKernel { + public: + explicit TensorScatterMaxOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + CompileTensorScatter( + context, + [](xla::XlaOp x, xla::XlaOp y, xla::XlaBuilder*) { + return xla::Max(x, y); + }, + /*broadcast_scalar_update=*/false); + } +}; + +class TensorScatterMinOp : public XlaOpKernel { + public: + explicit TensorScatterMinOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + CompileTensorScatter( + context, + [](xla::XlaOp x, xla::XlaOp y, xla::XlaBuilder*) { + return xla::Min(x, y); + }, + /*broadcast_scalar_update=*/false); + } +}; + +class TensorScatterSubOp : public XlaOpKernel { + public: + explicit TensorScatterSubOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + CompileTensorScatter( + context, + [](xla::XlaOp x, xla::XlaOp y, xla::XlaBuilder*) { + return xla::Sub(x, y); + }, + /*broadcast_scalar_update=*/false); + } +}; + +class TensorScatterUpdateOp : public XlaOpKernel { + public: + explicit TensorScatterUpdateOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + CompileTensorScatter( + context, [](xla::XlaOp, xla::XlaOp y, xla::XlaBuilder*) { return y; }, + /*broadcast_scalar_update=*/true); + } +}; + +REGISTER_XLA_OP(Name("TensorScatterAdd"), TensorScatterAddOp); +REGISTER_XLA_OP(Name("TensorScatterMax"), TensorScatterMaxOp); +REGISTER_XLA_OP(Name("TensorScatterMin"), TensorScatterMinOp); +REGISTER_XLA_OP(Name("TensorScatterSub"), TensorScatterSubOp); +REGISTER_XLA_OP(Name("TensorScatterUpdate"), TensorScatterUpdateOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/segment_reduction_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/segment_reduction_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa6224bee1027622ce8ae5ef2623069cf6ca5552 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/segment_reduction_ops.cc @@ -0,0 +1,233 @@ +/* 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 +#include + +#include "tensorflow/compiler/tf2xla/lib/scatter.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class SegmentReduce : public XlaOpKernel { + public: + explicit SegmentReduce(OpKernelConstruction* ctx, bool indices_are_sorted) + : XlaOpKernel(ctx), indices_are_sorted_(indices_are_sorted) { + DataType dtype; + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype, &type_)); + } + + // The initial value to initialize elements of the output to. + virtual xla::XlaOp InitialValue(xla::XlaBuilder* builder) = 0; + + // A function to combine two scalars with the same index (e.g., sum). + virtual xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) = 0; + + // Whether to pre-filter/replace NaNs in updates logic. + virtual bool FilterNaNs() const { return false; } + + void Compile(XlaOpKernelContext* ctx) override { + // output = unsorted_segment_sum(data, indices, num_segments) + // Compute a tensor such that: + // output[i] = sum over {j where indices[j] == i} of data[j] + // output[i] == 0 if i does not appear in indices + // + // Contrast with segment_sum(), which assumes indices are sorted and that + // max(indices)+1 is the desired size of the output. Note that + // segment_sum_v2 also takes num_segments as an input and can be supported + // similarly. + // + // The returned output tensor has the same type as data, and the same shape + // as data with the first indices.rank dimensions are replaced + // by a single dimension with size num_segments. + auto data = ctx->Input(0); + TensorShape data_shape = ctx->InputShape(0); + + auto indices = ctx->Input(1); + TensorShape indices_shape = ctx->InputShape(1); + + int64_t num_segments; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntScalar( + 2, &num_segments, xla::ValueInferenceMode::kUpperBound)); + OP_REQUIRES(ctx, data_shape.dims() >= indices_shape.dims(), + errors::InvalidArgument(type_string(), + " requires that indices' rank be" + " less than or equal to data's rank.")); + // Validate that indices.shape is a prefix of data.shape. + for (int d = 0; d < indices_shape.dims(); ++d) { + OP_REQUIRES( + ctx, (data_shape.dim_size(d) == indices_shape.dim_size(d)), + errors::InvalidArgument(type_string(), + " requires indices shape to be prefix" + " of data_shape, but dimension ", + d, " differs ", data_shape.dim_size(d), + " vs. ", indices_shape.dim_size(d))); + } + xla::XlaBuilder* builder = ctx->builder(); + // data shape = [indices_shape, segment_shape] + // buffer shape = [num_segment, segment_shape] + // We now create the buffer shape by reverse enginerring data shape into + // indices shape and segment shape. + TensorShape buffer_shape = data_shape; + buffer_shape.RemoveDimRange(0, indices_shape.dims()); + buffer_shape.InsertDim(0, num_segments); + + auto buffer = + xla::Broadcast(InitialValue(builder), buffer_shape.dim_sizes()); + + // Build dynamic dim sizes for buffer, as well as whether each dimension + // size is dynamic or static. We build two parts: num_sgement part and + // segment_shape part. + std::vector buffer_dims; + std::vector buffer_dims_are_dynamic; + // Build the "num_segment" part. + bool num_segments_is_dynamic; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPred(2, &num_segments_is_dynamic)); + + buffer_dims.insert(buffer_dims.begin(), ctx->Input(2)); + buffer_dims_are_dynamic.insert(buffer_dims_are_dynamic.begin(), + num_segments_is_dynamic); + // Build the segment shape part. + for (int64_t i = indices_shape.dims(); i < data_shape.dims(); ++i) { + buffer_dims.push_back(xla::GetDimensionSize(data, i)); + buffer_dims_are_dynamic.push_back( + ctx->InputXlaShape(0)->is_dynamic_dimension(i)); + } + + for (int64_t i = 0; i < buffer_dims.size(); ++i) { + if (buffer_dims_are_dynamic[i]) { + // For each dynamic dimension, call set-dimension-size on it. + buffer = xla::SetDimensionSize(buffer, buffer_dims[i], i); + } + } + + if (FilterNaNs() && xla::primitive_util::IsFloatingPointType(type_)) { + data = xla::Select(xla::IsNan(data), InitialValue(builder), data); + } + + auto combiner = [this](xla::XlaOp a, xla::XlaOp b, + xla::XlaBuilder* builder) { return Combine(a, b); }; + + auto result = XlaScatter(buffer, /*updates=*/data, indices, + /*indices_are_vectors=*/false, indices_are_sorted_, + combiner, builder); + OP_REQUIRES_OK(ctx, result.status()); + ctx->SetOutput(0, result.value()); + } + + protected: + xla::PrimitiveType type_; + bool indices_are_sorted_; +}; + +template +class SegmentSum : public SegmentReduce { + public: + explicit SegmentSum(OpKernelConstruction* ctx) + : SegmentReduce(ctx, indices_are_sorted) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::Zero(builder, type_); + }; + xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override { return a + b; }; +}; + +REGISTER_XLA_OP(Name("SegmentSumV2").CompileTimeConstantInput("num_segments"), + SegmentSum); +REGISTER_XLA_OP( + Name("UnsortedSegmentSum").CompileTimeConstantInput("num_segments"), + SegmentSum); + +template +class SegmentProd : public SegmentReduce { + public: + explicit SegmentProd(OpKernelConstruction* ctx) + : SegmentReduce(ctx, indices_are_sorted) {} + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::One(builder, type_); + }; + xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override { return a * b; }; +}; + +REGISTER_XLA_OP( + Name("UnsortedSegmentProd").CompileTimeConstantInput("num_segments"), + SegmentProd); +REGISTER_XLA_OP(Name("SegmentProdV2").CompileTimeConstantInput("num_segments"), + SegmentProd); + +template +class SegmentMin : public SegmentReduce { + public: + explicit SegmentMin(OpKernelConstruction* ctx) + : SegmentReduce(ctx, indices_are_sorted) {} + + bool FilterNaNs() const override { return true; } + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::MaxFiniteValue(builder, type_); + }; + xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override { + return xla::Min(a, b); + }; +}; + +REGISTER_XLA_OP( + Name("UnsortedSegmentMin").CompileTimeConstantInput("num_segments"), + SegmentMin); +REGISTER_XLA_OP(Name("SegmentMinV2").CompileTimeConstantInput("num_segments"), + SegmentMin); + +template +class SegmentMax : public SegmentReduce { + public: + explicit SegmentMax(OpKernelConstruction* ctx) + : SegmentReduce(ctx, indices_are_sorted) {} + + bool FilterNaNs() const override { return true; } + + xla::XlaOp InitialValue(xla::XlaBuilder* builder) override { + return xla::MinFiniteValue(builder, type_); + }; + xla::XlaOp Combine(xla::XlaOp a, xla::XlaOp b) override { + return xla::Max(a, b); + }; +}; + +REGISTER_XLA_OP( + Name("UnsortedSegmentMax").CompileTimeConstantInput("num_segments"), + SegmentMax); +REGISTER_XLA_OP(Name("SegmentMaxV2").CompileTimeConstantInput("num_segments"), + SegmentMax); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/select_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/select_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..53c53e37ab52364935335298fa9b7b96d8bf385a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/select_op.cc @@ -0,0 +1,141 @@ +/* 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 +#include + +#include "absl/algorithm/container.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/bcast.h" + +namespace tensorflow { +namespace { + +class SelectOp : public XlaOpKernel { + public: + explicit SelectOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape cond_shape = ctx->InputShape(0); + const TensorShape then_shape = ctx->InputShape(1); + const TensorShape else_shape = ctx->InputShape(2); + + OP_REQUIRES( + ctx, then_shape.IsSameSize(else_shape), + errors::InvalidArgument( + "'then' and 'else' must have the same size. but received: ", + then_shape.DebugString(), " vs. ", else_shape.DebugString())); + + auto cond_handle = ctx->Input(0); + auto then_handle = ctx->Input(1); + auto else_handle = ctx->Input(2); + + bool broadcasting = !cond_shape.IsSameSize(then_shape); + bool cond_is_scalar = TensorShapeUtils::IsScalar(cond_shape); + if (broadcasting && !cond_is_scalar) { + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(cond_shape), + errors::InvalidArgument( + "'cond' must be a scalar or a vector, but saw shape: ", + cond_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsVectorOrHigher(then_shape), + errors::InvalidArgument( + "'then' must be at least a vector, but saw shape: ", + then_shape.DebugString())); + OP_REQUIRES(ctx, then_shape.dim_size(0) == cond_shape.num_elements(), + errors::InvalidArgument("Number of batches of 'then' must " + "match size of 'cond', but saw: ", + then_shape.dim_size(0), " vs. ", + cond_shape.num_elements())); + + // Broadcast into the dimensions on the right. + std::vector broadcast_dimensions(cond_shape.dims()); + absl::c_iota(broadcast_dimensions, 0); + cond_handle = xla::BroadcastInDim(cond_handle, then_shape.dim_sizes(), + broadcast_dimensions); + } + ctx->SetOutput(0, xla::Select(cond_handle, then_handle, else_handle)); + } + + private: + SelectOp(const SelectOp&) = delete; + void operator=(const SelectOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Select"), MlirXlaOpKernel); + +class SelectOpV2 : public XlaOpKernel { + public: + explicit SelectOpV2(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape cond_shape = ctx->InputShape(0); + const TensorShape then_shape = ctx->InputShape(1); + const TensorShape else_shape = ctx->InputShape(2); + + // Compute the output shape from the broadcast of the two data inputs, with + // the broadcast of the conditional. + // Then Broadcast all three inputs to the output shape and emit a select. + + BCast bcast_then_else(BCast::FromShape(then_shape), + BCast::FromShape(else_shape), + /*fewer_dims_optimization=*/false); + if (!bcast_then_else.IsValid()) { + ctx->SetStatus(errors::InvalidArgument( + "Incompatible shapes: ", then_shape.DebugString(), " vs. ", + else_shape.DebugString())); + return; + } + BCast bcast(bcast_then_else.output_shape(), BCast::FromShape(cond_shape), + /*fewer_dims_optimization=*/false); + if (!bcast.IsValid()) { + ctx->SetStatus(errors::InvalidArgument( + "Incompatible shapes: ", + BCast::ToShape(bcast_then_else.output_shape()).DebugString(), " vs. ", + cond_shape.DebugString())); + return; + } + + auto bcasted_cond = BroadcastTo(ctx->Input(0), bcast.output_shape()); + OP_REQUIRES_OK(ctx, bcasted_cond.status()); + auto cond_handle = bcasted_cond.value(); + + auto bcasted_then = BroadcastTo(ctx->Input(1), bcast.output_shape()); + OP_REQUIRES_OK(ctx, bcasted_then.status()); + auto then_handle = bcasted_then.value(); + + auto bcasted_else = BroadcastTo(ctx->Input(2), bcast.output_shape()); + OP_REQUIRES_OK(ctx, bcasted_else.status()); + auto else_handle = bcasted_else.value(); + + ctx->SetOutput(0, xla::Select(cond_handle, then_handle, else_handle)); + } + + private: + SelectOpV2(const SelectOpV2&) = delete; + void operator=(const SelectOpV2&) = delete; +}; + +REGISTER_XLA_OP(Name("SelectV2"), SelectOpV2); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sendrecv_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sendrecv_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..bcd8cd870de4116f619ed286069cc0f43c82f567 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sendrecv_ops.cc @@ -0,0 +1,92 @@ +/* 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 + +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class SendOp : public XlaOpKernel { + public: + explicit SendOp(OpKernelConstruction* ctx); + void Compile(XlaOpKernelContext* ctx) override; + + private: + std::string tensor_name_; + + SendOp(const SendOp&) = delete; + void operator=(const SendOp&) = delete; +}; + +SendOp::SendOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name_)); +} + +void SendOp::Compile(XlaOpKernelContext* ctx) { + XlaCompiler* compiler = ctx->compiler(); + xla::ChannelHandle channel; + OP_REQUIRES_OK(ctx, compiler->GetChannelHandle(tensor_name_, &channel)); + xla::Send(ctx->Input(0), channel); +} + +REGISTER_XLA_OP(Name("XlaSend"), SendOp); + +class RecvOp : public XlaOpKernel { + public: + explicit RecvOp(OpKernelConstruction* ctx); + void Compile(XlaOpKernelContext* ctx) override; + + private: + std::string tensor_name_; + xla::Shape shape_; + + RecvOp(const RecvOp&) = delete; + void operator=(const RecvOp&) = delete; +}; + +RecvOp::RecvOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_name", &tensor_name_)); + + TensorShape tensor_shape; + DataType dtype; + OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &tensor_shape)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype)); + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype, tensor_shape, &shape_)); +} + +void RecvOp::Compile(XlaOpKernelContext* ctx) { + XlaCompiler* compiler = ctx->compiler(); + xla::ChannelHandle channel; + OP_REQUIRES_OK(ctx, compiler->GetChannelHandle(tensor_name_, &channel)); + ctx->SetOutput(0, xla::Recv(ctx->builder(), shape_, channel)); +} + +REGISTER_XLA_OP(Name("XlaRecv"), RecvOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sequence_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sequence_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..8cd06a489cd9ab8b59aeb4730fd3085bfaaeb9c1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sequence_ops.cc @@ -0,0 +1,201 @@ +/* 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. +==============================================================================*/ + +// XLA-specific sequence and range Ops. + +#include +#include + +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/primitive_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// The type-specific part of the implementation of Range. +template +absl::StatusOr CreateRangeTensor( + const xla::LiteralSlice& start_literal, + const xla::LiteralSlice& limit_literal, + const xla::LiteralSlice& delta_literal, xla::XlaBuilder* builder) { + T start = start_literal.Get({}); + T limit = limit_literal.Get({}); + T delta = delta_literal.Get({}); + + if (delta == 0) { + return errors::InvalidArgument("Requires delta != 0: ", delta); + } + if (delta > 0) { + if (start > limit) { + return errors::InvalidArgument( + "Requires start <= limit when delta > 0: ", start, "/", limit); + } + } else { + if (start < limit) { + return errors::InvalidArgument( + "Requires start >= limit when delta < 0: ", start, "/", limit); + } + } + int64_t size = + (std::is_integral::value + ? static_cast( + limit == start + ? 0 + : (std::abs(limit - start) - 1) / std::abs(delta) + 1) + : std::ceil(std::abs((limit - start) / delta))); + + return xla::ConstantR0(builder, start) + + xla::ConstantR0(builder, delta) * + xla::Iota(builder, xla::primitive_util::NativeToPrimitiveType(), + size); +} + +class RangeOp : public XlaOpKernel { + public: + explicit RangeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape start_in_shape = ctx->InputShape(0); + const TensorShape limit_in_shape = ctx->InputShape(1); + const TensorShape delta_in_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape), + errors::InvalidArgument("start must be a scalar, not shape ", + start_in_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(limit_in_shape), + errors::InvalidArgument("limit must be a scalar, not shape ", + limit_in_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(delta_in_shape), + errors::InvalidArgument("delta must be a scalar, not shape ", + delta_in_shape.DebugString())); + xla::Literal start, limit, delta; + OP_REQUIRES_OK(ctx, ctx->ConstantInput( + 0, &start, xla::ValueInferenceMode::kLowerBound)); + OP_REQUIRES_OK(ctx, ctx->ConstantInput( + 1, &limit, xla::ValueInferenceMode::kUpperBound)); + OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &delta)); + + DataType type = input_type(0); + absl::StatusOr output; + switch (type) { + case DT_INT32: + output = + CreateRangeTensor(start, limit, delta, ctx->builder()); + break; + case DT_INT64: + output = + CreateRangeTensor(start, limit, delta, ctx->builder()); + break; + case DT_FLOAT: + output = CreateRangeTensor(start, limit, delta, ctx->builder()); + break; + case DT_DOUBLE: + output = CreateRangeTensor(start, limit, delta, ctx->builder()); + break; + default: + output = errors::InvalidArgument("Invalid type for Range ", + DataTypeString(type)); + } + OP_REQUIRES_OK(ctx, output.status()); + bool start_is_dynamic = false; + OP_REQUIRES_OK(ctx, + ctx->ResolveInputDynamismIntoPred(0, &start_is_dynamic)); + bool limit_is_dynamic = false; + OP_REQUIRES_OK(ctx, + ctx->ResolveInputDynamismIntoPred(1, &limit_is_dynamic)); + + if (start_is_dynamic || limit_is_dynamic) { + xla::XlaOp delta = ctx->Input(2); + xla::XlaOp limit = ctx->Input(1); + xla::XlaOp start = ctx->Input(0); + if (type == DT_INT32 || type == DT_INT64) { + auto dynamic_size = (xla::Abs(limit - start) + xla::Abs(delta) - + xla::One(ctx->builder(), ctx->input_xla_type(0))) / + xla::Abs(delta); + dynamic_size = xla::ConvertElementType(dynamic_size, xla::S32); + output = xla::SetDimensionSize(output.value(), dynamic_size, 0); + } else { + auto dynamic_size = (xla::Ceil(xla::Abs((limit - start) / delta))); + dynamic_size = xla::ConvertElementType(dynamic_size, xla::S32); + output = xla::SetDimensionSize(output.value(), dynamic_size, 0); + } + } + + ctx->SetOutput(0, output.value()); + } +}; + +REGISTER_XLA_OP(Name("Range") + .CompileTimeConstantInput("start") + .CompileTimeConstantInput("limit") + .CompileTimeConstantInput("delta"), + RangeOp); + +class LinSpaceOp : public XlaOpKernel { + public: + explicit LinSpaceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape start_in_shape = ctx->InputShape("start"); + const TensorShape stop_in_shape = ctx->InputShape("stop"); + const TensorShape num_in_shape = ctx->InputShape("num"); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(start_in_shape), + errors::InvalidArgument("start must be a scalar, not shape ", + start_in_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(stop_in_shape), + errors::InvalidArgument("stop must be a scalar, not shape ", + stop_in_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(num_in_shape), + errors::InvalidArgument("num must be a scalar, not shape ", + num_in_shape.DebugString())); + + int64_t num; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("num", &num)); + OP_REQUIRES(ctx, num > 0, + errors::InvalidArgument("Requires num > 0: ", num)); + xla::XlaOp start = ctx->Input("start"); + xla::XlaOp stop = ctx->Input("stop"); + xla::XlaOp iota = xla::Iota(ctx->builder(), ctx->output_xla_type(0), num); + xla::XlaOp step = + (stop - start) / xla::ScalarLike(start, (num > 1 ? num - 1 : num)); + xla::XlaOp result = iota * step + start; + if (num > 1) { + // According to linspace spec, start has to be the first element and end + // has to be last element. + xla::XlaOp mask = xla::Iota(ctx->builder(), xla::S64, num); + xla::XlaOp eq = xla::Eq(mask, xla::ScalarLike(mask, num - 1)); + result = xla::Select(eq, stop, result); + } + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP(Name("LinSpace").CompileTimeConstantInput("num"), LinSpaceOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..1e97d6038df7c702508fe14403b51710030a0077 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_op.cc @@ -0,0 +1,465 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Shape Ops. + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_set.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/kernels/shape_util.h" +#include "tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/shape.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class ShapeOp : public XlaOpKernel { + public: + explicit ShapeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + std::vector operands; + const int rank = input_shape.dims(); + if (rank != 0) { + for (int64_t i = 0; i < rank; ++i) { + operands.push_back(xla::Broadcast( + xla::ConvertElementType(xla::GetDimensionSize(ctx->Input(0), i), + ctx->output_xla_type(0)), + {1})); + } + + ctx->SetOutput(0, xla::ConcatInDim(ctx->builder(), operands, 0)); + } else { + // Rank 0 won't have dynamic size dimension, use constant output. + Tensor shape_constant(out_dtype_, TensorShape({input_shape.dims()})); + OP_REQUIRES_OK(ctx, TensorShapeToConstant(input_shape, &shape_constant)); + ctx->SetConstantOutput(0, shape_constant); + } + } + + private: + DataType out_dtype_; +}; + +REGISTER_XLA_OP(Name("Shape").CompilationOnly().IsMetadataOp(), ShapeOp); + +class XlaSetBoundOp : public XlaOpKernel { + public: + explicit XlaSetBoundOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape bound_shape = ctx->InputShape("bound"); + + OP_REQUIRES( + ctx, + ctx->InputType("bound") == DT_INT32 && + ctx->InputType("input") == DT_INT32, + errors::InvalidArgument( + "XlaSetBound can only set bound for int32 scalar value: got", + input_shape.DebugString())); + + OP_REQUIRES( + ctx, input_shape.dims() == 0, + errors::InvalidArgument("XlaSetBound should only be used to set a " + "bound to the an int32 scalar value: got", + input_shape.DebugString())); + + OP_REQUIRES( + ctx, bound_shape.dims() == 0, + errors::InvalidArgument("XlaSetBound should only be used to set a " + "bound to the an int32 scalar value: got", + bound_shape.DebugString())); + int64_t bound; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("bound", &bound)); + xla::Literal bound_literal = xla::LiteralUtil::CreateR0(bound); + xla::XlaOp result = xla::CustomCall( + ctx->builder(), "SetBound", {ctx->Input("input")}, + ctx->InputXlaShape("input").value(), "", false, {}, &bound_literal); + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP(Name("XlaSetBound").CompileTimeConstantInput("bound"), + XlaSetBoundOp); + +class XlaSetDynamicDimensionSizeOp : public XlaOpKernel { + public: + explicit XlaSetDynamicDimensionSizeOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape dim_index_shape = ctx->InputShape("dim_index"); + const TensorShape size_shape = ctx->InputShape("size"); + + OP_REQUIRES(ctx, + ctx->InputType("dim_index") == DT_INT32 && + ctx->InputType("size") == DT_INT32, + errors::InvalidArgument("dim_index and size has to be int32 for" + "XlaSetDynamicDimensionSizeOp")); + + OP_REQUIRES( + ctx, dim_index_shape.dims() == 0 && size_shape.dims() == 0, + errors::InvalidArgument("XlaSetDynamicDimensionSizeOp's dim_index and " + "size has to be int32 scalar value")); + int64_t dim_index; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("dim_index", &dim_index)); + + xla::XlaOp result = + xla::SetDimensionSize(ctx->Input(0), ctx->Input("size"), dim_index); + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP( + Name("XlaSetDynamicDimensionSize").CompileTimeConstantInput("dim_index"), + XlaSetDynamicDimensionSizeOp); + +class XlaRemoveDynamicDimensionSizeOp : public XlaOpKernel { + public: + explicit XlaRemoveDynamicDimensionSizeOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape dim_index_shape = ctx->InputShape("dim_index"); + + OP_REQUIRES(ctx, ctx->InputType("dim_index") == DT_INT32, + errors::InvalidArgument("dim_index has to be int32 for" + "XlaRemoveDynamicDimensionSizeOp")); + + OP_REQUIRES( + ctx, dim_index_shape.dims() == 0, + errors::InvalidArgument("XlaRemoveDynamicDimensionSizeOp's dim_index " + "has to be int32 scalar value")); + int64_t dim_index; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("dim_index", &dim_index)); + + xla::XlaOp result = xla::RemoveDynamicDimension(ctx->Input(0), dim_index); + ctx->SetOutput(0, result); + } +}; + +REGISTER_XLA_OP( + Name("XlaRemoveDynamicDimensionSize").CompileTimeConstantInput("dim_index"), + XlaRemoveDynamicDimensionSizeOp); + +class ShapeNOp : public XlaOpKernel { + public: + explicit ShapeNOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + for (int i = 0; i < ctx->num_inputs(); ++i) { + const TensorShape input_shape = ctx->InputShape(i); + std::vector operands; + + const int rank = input_shape.dims(); + if (rank != 0) { + // Each dimension can be dynamic, so use GetDimensionSize to get the + // runtime dimension. + for (int64_t dim = 0; dim < rank; ++dim) { + operands.push_back(xla::Broadcast( + xla::ConvertElementType(xla::GetDimensionSize(ctx->Input(i), dim), + ctx->output_xla_type(i)), + {1})); + } + + ctx->SetOutput(i, xla::ConcatInDim(ctx->builder(), operands, 0)); + } else { + // Rank 0 won't have dynamic size dimension, use constant output. + Tensor shape_constant(out_dtype_, TensorShape({input_shape.dims()})); + OP_REQUIRES_OK(ctx, + TensorShapeToConstant(input_shape, &shape_constant)); + ctx->SetConstantOutput(i, shape_constant); + } + } + } + + bool IsExpensive() override { return false; } + + private: + DataType out_dtype_; +}; +REGISTER_XLA_OP(Name("ShapeN").CompilationOnly().IsMetadataOp(), ShapeNOp); + +class RankOp : public XlaOpKernel { + public: + explicit RankOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + const int rank = input_shape.dims(); + Tensor rank_constant(DT_INT32, TensorShape({})); + rank_constant.scalar()() = rank; + + ctx->SetConstantOutput(0, rank_constant); + } +}; + +REGISTER_XLA_OP(Name("Rank").CompilationOnly().IsMetadataOp(), RankOp); + +class SizeOp : public XlaOpKernel { + public: + explicit SizeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + xla::XlaBuilder* builder = ctx->builder(); + auto size = xla::One(builder, ctx->output_xla_type(0)); + + const int rank = input_shape.dims(); + for (int64_t dim = 0; dim < rank; ++dim) { + OP_REQUIRES( + ctx, + FastBoundsCheck(input_shape.dim_size(dim), + std::numeric_limits::max()), + absl::InvalidArgumentError(absl::StrCat( + "Size Op: XLA supported tensors must have <= int32max elements " + "on all dimensions, found ", + input_shape.dim_size(dim), " elements on dimension ", dim))); + + size = xla::Mul(size, xla::ConvertElementType( + xla::GetDimensionSize(ctx->Input(0), dim), + ctx->output_xla_type(0))); + } + + ctx->SetOutput(0, size); + } +}; + +REGISTER_XLA_OP(Name("Size").CompilationOnly().IsMetadataOp(), SizeOp); + +class ExpandDimsOp : public XlaOpKernel { + public: + explicit ExpandDimsOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape dim_shape = ctx->InputShape("dim"); + + std::vector dims; + OP_REQUIRES_OK(ctx, ctx->ConstantInputReshapedToIntVector("dim", &dims)); + OP_REQUIRES(ctx, dims.size() == 1, + errors::InvalidArgument(absl::StrCat( + "dim input to ExpandDims must be a scalar; got ", + dim_shape.DebugString()))); + int dim = dims[0]; + + OP_REQUIRES(ctx, + (dim >= -1 - input_shape.dims() && dim <= input_shape.dims()), + errors::InvalidArgument("Tried to expand dim index ", dim, + " for tensor with ", input_shape.dims(), + " dimensions.")); + + auto existing_dims = input_shape.dim_sizes(); + // Safe - # elements in tensor dims bounded. + const int existing_dims_size = static_cast(existing_dims.size()); + std::vector new_shape(existing_dims_size); + for (size_t i = 0; i < new_shape.size(); ++i) { + new_shape[i] = existing_dims[i]; + } + + // We emulate numpy's interpretation of the dim axis when + // -input.dims() >= dim <= input.dims(). + if (dim < 0) { + dim += existing_dims.size() + 1; + } + + // Clamp to the end if needed. + dim = std::min(dim, existing_dims_size); + new_shape.emplace(new_shape.begin() + dim, 1); + + ctx->SetOutput(0, xla::Reshape(ctx->Input("input"), new_shape)); + } +}; +REGISTER_XLA_OP(Name("ExpandDims").CompileTimeConstantInput("dim"), + ExpandDimsOp); + +class SqueezeOp : public XlaOpKernel { + public: + explicit SqueezeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + std::vector squeeze_dims; + OP_REQUIRES_OK(ctx, ctx->GetAttr("squeeze_dims", &squeeze_dims)); + squeeze_dims_.insert(squeeze_dims.begin(), squeeze_dims.end()); + } + + void Compile(XlaOpKernelContext* ctx) override { + absl::StatusOr input_shape = + ctx->builder()->GetShape(ctx->Input(0)); + OP_REQUIRES_OK(ctx, input_shape.status()); + xla::Shape shape = input_shape.value(); + int64_t rank = shape.dimensions().size(); + + absl::flat_hash_set wrapped_squeeze_dims; + wrapped_squeeze_dims.reserve(squeeze_dims_.size()); + std::vector new_shape; + // Validate squeeze dims against the input. + for (int32_t dim : squeeze_dims_) { + OP_REQUIRES( + ctx, (dim >= -rank && dim < rank), + errors::InvalidArgument("Tried to squeeze dim index ", dim, + " for tensor with ", rank, " dimensions.")); + // If dim is < 0, we wrap around (-1 means the last element). + if (dim < 0) { + dim = rank + dim; + } + + wrapped_squeeze_dims.insert(dim); + } + + for (int i = 0; i < rank; ++i) { + auto existing_dim = shape.dimensions(i); + + // If squeeze_set is non-empty, only squeeze those dimensions. + if (!wrapped_squeeze_dims.empty()) { + 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)); + } else { + // This dimension is not being squeezed. + new_shape.push_back(existing_dim); + } + } else { + OP_REQUIRES( + ctx, !shape.is_dynamic_dimension(i), + errors::InvalidArgument("Squeeze op does not support bounded " + "dynamic dimensions. Input shape: ", + shape.ToString())); + // Copy over all non-1-length dimensions. + if (existing_dim != 1) { + new_shape.push_back(existing_dim); + } + } + } + + ctx->SetOutput(0, xla::Reshape(ctx->Input(0), new_shape)); + } + + private: + absl::flat_hash_set squeeze_dims_; +}; + +REGISTER_XLA_OP(Name("Squeeze"), SqueezeOp); + +class ZerosLikeOp : public XlaOpKernel { + public: + explicit ZerosLikeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + if (IsTensorListInput(ctx, 0)) { + // Input is a TensorList. + + // Check the TensorList input is initialized. + xla::XlaOp list = ctx->Input(0); + bool is_initialized; + OP_REQUIRES_OK(ctx, IsTensorListInitialized(list, &is_initialized)); + OP_REQUIRES( + ctx, is_initialized, + errors::InvalidArgument( + "TensorList input for ZerosLike op is an uninitialized list")); + + auto list_shape_or = ctx->builder()->GetShape(list); + OP_REQUIRES_OK(ctx, list_shape_or.status()); + const xla::Shape& list_shape = list_shape_or.value(); + std::vector> list_dynamic_dims; + list_dynamic_dims.reserve(list_shape.tuple_shapes().size() - 1); + for (int i = 0; i < list_shape.tuple_shapes().size() - 1; ++i) { + // Set dynamic dimension size to 0 for initialization value. + std::vector dynamic_dims; + const xla::Shape& shape = list_shape.tuple_shapes(i); + auto sub_element = xla::GetTupleElement(list, i); + dynamic_dims.reserve(shape.dimensions().size()); + for (int64_t dim = 0; dim < shape.dimensions().size(); ++dim) { + dynamic_dims.push_back(xla::GetDimensionSize(sub_element, dim)); + } + list_dynamic_dims.push_back(dynamic_dims); + } + xla::XlaOp new_list; + OP_REQUIRES_OK( + ctx, CreateZerosTensorListWithShape(ctx->builder(), list_shape, + list_dynamic_dims, &new_list)); + + xla::XlaOp push_index; + OP_REQUIRES_OK(ctx, GetTensorListPushIndex(list, &push_index)); + + xla::XlaOp result; + OP_REQUIRES_OK(ctx, + SetTensorListPushIndex(new_list, push_index, &result)); + ctx->SetTensorListOutput(0, result); + } else { + auto zero = XlaHelpers::Zero(ctx->builder(), input_type(0)); + xla::XlaOp input = ctx->Input(0); + auto input_shape = ctx->InputXlaShape(0).value(); + auto result = xla::Broadcast(zero, input_shape.dimensions()); + + // Setting up dynamic dimensions of the broadcast. + for (int64_t i = 0; i < input_shape.dimensions().size(); ++i) { + if (input_shape.is_dynamic_dimension(i)) { + xla::XlaOp input_dynamic_dim = xla::GetDimensionSize(input, i); + result = xla::SetDimensionSize(result, input_dynamic_dim, i); + } + } + + ctx->SetOutput(0, result); + } + } +}; + +REGISTER_XLA_OP(Name("ZerosLike").AllowVariantTypes(), ZerosLikeOp); + +class OnesLikeOp : public XlaOpKernel { + public: + explicit OnesLikeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + + auto one = XlaHelpers::One(ctx->builder(), input_type(0)); + ctx->SetOutput(0, xla::Broadcast(one, input_shape.dim_sizes())); + } +}; + +REGISTER_XLA_OP(Name("OnesLike"), OnesLikeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..a7c78041c34d41176f42e13b618e88c07083863c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_util.cc @@ -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. +==============================================================================*/ + +#include "tensorflow/compiler/tf2xla/kernels/shape_util.h" + +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +absl::Status TensorShapeToConstant(const TensorShape& input_shape, + Tensor* shape_constant) { + const int dims = input_shape.dims(); + if (shape_constant->dtype() == DT_INT32) { + auto vec = shape_constant->vec(); + for (int i = 0; i < dims; ++i) { + int64_t dim_size = input_shape.dim_size(i); + if (!FastBoundsCheck(dim_size, std::numeric_limits::max())) { + return errors::InvalidArgument( + "Shape with out_type=int32 does not support tensors > int32max", + " but dim ", i, " is ", dim_size); + } + vec(i) = static_cast(dim_size); + } + } else { + auto vec = shape_constant->vec(); + for (int i = 0; i < dims; ++i) { + int64_t dim_size = input_shape.dim_size(i); + vec(i) = dim_size; + } + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_util.h new file mode 100644 index 0000000000000000000000000000000000000000..e6300eadcc8604020ee3ee47b218c55af3c328ae --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/shape_util.h @@ -0,0 +1,37 @@ +/* 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_KERNELS_SHAPE_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_SHAPE_UTIL_H_ + +#include + +#include "absl/status/status.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +// Converts a TensorShape to a constant Tensor. +// +// The input TensorShape input_shape is used to populate the elements of +// shape_constant, which is modified in place. +absl::Status TensorShapeToConstant(const TensorShape& input_shape, + Tensor* shape_constant); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_SHAPE_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sharding_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sharding_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..7f39e8b6e06d3441fd6b1ab71a16720b403e37f7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sharding_op.cc @@ -0,0 +1,76 @@ +/* Copyright 2019 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 +#include +#include + +#include "tensorflow/compiler/tf2xla/sharding_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/sharding_op_util.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" + +namespace tensorflow { +namespace { + +class ShardingOp : public XlaOpKernel { + public: + explicit ShardingOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + std::vector unspecified_dims; + OP_REQUIRES_OK(ctx, ctx->GetAttr("unspecified_dims", &unspecified_dims)); + for (int32_t i32 : unspecified_dims) { + unspecified_dims_.push_back(i32); + } + } + + ~ShardingOp() override = default; + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input; + { + // The builder might create a broadcast from a constant, so we clear + // sharding for the input. + xla::XlaScopedShardingAssignment no_sharding(ctx->builder(), + std::nullopt); + input = ctx->Input(0); + } + auto shape_or = ctx->builder()->GetShape(input); + OP_REQUIRES_OK(ctx, shape_or.status()); + + xla::XlaOp output = xla::CustomCall( + ctx->builder(), /*call_target_name=*/"Sharding", {input}, + shape_or.value(), + /*opaque=*/ + xla::sharding_op_util::EncodeAttributes(unspecified_dims_)); + if (ctx->compiler()->options().use_shardy_partitioner) { + OP_REQUIRES_OK(ctx, addSdyShardingFrontendAttribute( + ctx->builder(), output, shape_or.value())); + } + ctx->SetOutput(0, output); + } + + private: + ShardingOp(const ShardingOp&) = delete; + void operator=(const ShardingOp&) = delete; + std::vector unspecified_dims_; +}; + +REGISTER_XLA_OP(Name("XlaSharding"), ShardingOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sharding_util_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sharding_util_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa93bf76fae643955d47fe90eacea48f0a11d9f1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sharding_util_ops.cc @@ -0,0 +1,474 @@ +/* Copyright 2021 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 +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/errors.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +constexpr absl::string_view kNumSplitsAttrName = "num_splits"; +constexpr absl::string_view kNumConcatsAttrName = "num_concats"; + +template +absl::Status GetAndValidateAttributes(OpKernelConstruction* ctx, + std::vector& num_partitions, + int& num_slices, + std::vector& paddings, + bool& has_paddings) { + absl::string_view num_partitions_attr_name = + Split ? kNumSplitsAttrName : kNumConcatsAttrName; + TF_RETURN_IF_ERROR(ctx->GetAttr(num_partitions_attr_name, &num_partitions)); + + int num_dims_to_split = 0; + for (int i = 0, e = num_partitions.size(); i < e; ++i) { + const auto& split = num_partitions[i]; + if (split <= 0) { + return errors::InvalidArgument("'", num_partitions_attr_name, + "' at index ", i, + " must be positive, but got ", split, "."); + } + if (split > 1) { + ++num_dims_to_split; + } + num_slices *= split; + } + + int n; + TF_RETURN_IF_ERROR(ctx->GetAttr("N", &n)); + if (n != num_slices) { + return errors::InvalidArgument( + "'N' must match number of slices ", num_slices, " from '", + num_partitions_attr_name, "', but got ", n, "."); + } + + TF_RETURN_IF_ERROR(ctx->GetAttr("paddings", &paddings)); + const int expected_rank = num_partitions.size(); + if (!paddings.empty()) { + if (paddings.size() != expected_rank) { + return errors::InvalidArgument( + "'paddings' length must match '", num_partitions_attr_name, + "' length ", expected_rank, ", but got ", paddings.size(), "."); + } + + for (int dim = 0; dim < expected_rank; ++dim) { + if (paddings[dim] < 0) { + return errors::InvalidArgument( + "'padding' must be all non-negative, but got ", paddings[dim], + " at index ", dim, "."); + } + if (paddings[dim] > 0) { + has_paddings = true; + } + } + } else { + paddings.assign(expected_rank, 0); + } + + return absl::OkStatus(); +} + +std::vector GetSliceIndices(absl::Span num_partitions, + absl::Span slice_shape, + const int index) { + DCHECK_EQ(num_partitions.size(), slice_shape.size()); + + std::vector slice_indices(num_partitions.size()); + + if (num_partitions.empty()) { + return slice_indices; + } + + auto divisor = [&](const int dim) { + int divisor = 1; + for (int i = num_partitions.size() - 1; i > dim; --i) { + divisor *= num_partitions[i]; + } + return divisor; + }; + + for (int dim = num_partitions.size() - 1; dim > 0; --dim) { + slice_indices[dim] = + ((index / divisor(dim)) % num_partitions[dim]) * slice_shape[dim]; + } + slice_indices[0] = (index / divisor(0)) * slice_shape[0]; + + return slice_indices; +} + +constexpr absl::string_view kTensorName = "'input' tensor"; +constexpr absl::string_view kResourceName = "'resource' variable tensor"; + +template +class XlaSplitNDBaseOp : public XlaOpKernel { + public: + explicit XlaSplitNDBaseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, + GetAndValidateAttributes(ctx, num_splits_, num_slices_, + paddings_, has_paddings_)); + } + + protected: + absl::Status CompileInternal(XlaOpKernelContext* ctx, const xla::XlaOp input, + const TensorShape& input_shape, + const DataType input_dtype) { + xla::PrimitiveType type; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(input_dtype, &type)); + + absl::string_view input_name = Resource ? kResourceName : kTensorName; + const int rank = input_shape.dims(); + + if (rank != num_splits_.size()) { + return errors::InvalidArgument( + input_name, " rank must be the same as 'num_splits' length ", + num_splits_.size(), ", but got rank ", rank, "."); + } + + for (int dim = 0; dim < rank; ++dim) { + if ((input_shape.dim_size(dim) + paddings_[dim]) % num_splits_[dim] != + 0) { + return errors::InvalidArgument( + input_name, " shape dimension ", dim, " (", + input_shape.dim_size(dim), ") with padding ", paddings_[dim], + " must be evenly divisible by 'num_splits' ", num_splits_[dim], + "."); + } + } + + if (num_slices_ == 1 && has_paddings_) { + xla::PaddingConfig padding_config; + for (int dim = 0; dim < rank; ++dim) { + auto* padding_dim = padding_config.add_dimensions(); + padding_dim->set_edge_padding_low(0); + padding_dim->set_edge_padding_high(paddings_[dim]); + padding_dim->set_interior_padding(0); + } + ctx->SetOutput( + /*index=*/0, + xla::Pad(input, + xla::ConstantR0WithType(ctx->builder(), type, /*value=*/0), + padding_config)); + return absl::OkStatus(); + } else if (num_slices_ == 1) { + ctx->SetOutput(/*index=*/0, input); + return absl::OkStatus(); + } + + // Slice shape with optional padding. + std::vector slice_shape(rank); + for (int dim = 0; dim < rank; ++dim) { + slice_shape[dim] = + (input_shape.dim_size(dim) + paddings_[dim]) / num_splits_[dim]; + } + + const std::vector slice_strides(rank, 1); + + for (int i = 0; i < num_slices_; ++i) { + int num_complete_pad_dims = 0; + int num_partial_pad_dims = 0; + std::vector slice_start_indices = + GetSliceIndices(num_splits_, slice_shape, i); + std::vector slice_limit_indices(slice_shape.size()); + xla::PaddingConfig slice_padding_config; + for (int dim = 0; dim < rank; ++dim) { + auto* padding_dim = slice_padding_config.add_dimensions(); + padding_dim->set_edge_padding_low(0); + padding_dim->set_edge_padding_high(0); + padding_dim->set_interior_padding(0); + } + + // Calculate paddings necessary for slice instead of padding input and + // slicing subsequently to reduce temporary memory allocation. + for (int dim = 0; dim < rank; ++dim) { + const int64_t dim_size = input_shape.dim_size(dim); + if (slice_start_indices[dim] >= dim_size) { + // Complete padding. + slice_start_indices[dim] = dim_size; + slice_limit_indices[dim] = dim_size; + slice_padding_config.mutable_dimensions(dim)->set_edge_padding_high( + slice_shape[dim]); + ++num_complete_pad_dims; + } else if (slice_start_indices[dim] + slice_shape[dim] > dim_size) { + // Partial padding. + slice_limit_indices[dim] = dim_size; + slice_padding_config.mutable_dimensions(dim)->set_edge_padding_high( + slice_start_indices[dim] + slice_shape[dim] - dim_size); + ++num_partial_pad_dims; + } else { + slice_limit_indices[dim] = + slice_start_indices[dim] + slice_shape[dim]; + } + } + + if (num_complete_pad_dims == rank) { + ctx->SetOutput(i, xla::Broadcast(xla::ConstantR0WithType( + ctx->builder(), type, /*value=*/0), + slice_shape)); + } else if (num_complete_pad_dims > 0 || num_partial_pad_dims > 0) { + ctx->SetOutput( + i, + xla::Pad(xla::Slice(input, slice_start_indices, slice_limit_indices, + slice_strides), + xla::ConstantR0WithType(ctx->builder(), type, /*value=*/0), + slice_padding_config)); + } else { + ctx->SetOutput(i, xla::Slice(input, slice_start_indices, + slice_limit_indices, slice_strides)); + } + } + return absl::OkStatus(); + } + + private: + std::vector num_splits_; + int num_slices_ = 1; + std::vector paddings_; + bool has_paddings_ = false; +}; + +class XlaSplitNDOp : public XlaSplitNDBaseOp { + public: + explicit XlaSplitNDOp(OpKernelConstruction* ctx) + : XlaSplitNDBaseOp(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES_OK(ctx, + this->CompileInternal(ctx, ctx->Input(0), ctx->InputShape(0), + ctx->input_type(0))); + } +}; + +REGISTER_XLA_OP(Name("XlaSplitND"), XlaSplitNDOp); + +class ReadVariableXlaSplitNDOp : public XlaSplitNDBaseOp { + public: + explicit ReadVariableXlaSplitNDOp(OpKernelConstruction* ctx) + : XlaSplitNDBaseOp(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + DataType variable_input_dtype; + TensorShape variable_input_shape; + OP_REQUIRES_OK( + ctx, ctx->GetVariableTypeAndShape(/*index=*/0, &variable_input_dtype, + &variable_input_shape)); + OP_REQUIRES( + ctx, variable_input_dtype == dtype_, + errors::InvalidArgument("'T' must match 'resource' variable dtype ", + DataTypeString(variable_input_dtype), + ", but got ", dtype_)); + + xla::XlaOp handle; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(/*index=*/0, dtype_, + /*shape=*/nullptr, &handle)); + + OP_REQUIRES_OK( + ctx, this->CompileInternal(ctx, handle, variable_input_shape, dtype_)); + } + + private: + DataType dtype_; +}; + +REGISTER_XLA_OP(Name("ReadVariableXlaSplitND"), ReadVariableXlaSplitNDOp); + +class XlaConcatNDBaseOp : public XlaOpKernel { + public: + explicit XlaConcatNDBaseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK( + ctx, GetAndValidateAttributes(ctx, num_concats_, num_slices_, + paddings_, has_paddings_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + protected: + absl::StatusOr CompileInternal(XlaOpKernelContext* ctx) { + xla::PrimitiveType type; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype_, &type)); + + std::vector input_handles; + std::vector input_shapes; + std::vector output_shape; + TF_RETURN_IF_ERROR(GetInputsAndOutputShape(ctx, input_handles, input_shapes, + output_shape)); + + const int rank = output_shape.size(); + + if (num_slices_ == 1 && has_paddings_) { + return xla::Slice(input_handles[0], + /*start_indices=*/std::vector(rank, 0), + /*limit_indices=*/output_shape, + /*strides=*/std::vector(rank, 1)); + } else if (num_slices_ == 1) { + return input_handles[0]; + } + + auto slice_shape = input_shapes[0].dim_sizes(); + xla::XlaOp output = xla::Broadcast( + xla::ConstantR0WithType(ctx->builder(), type, /*value=*/0), + output_shape); + const std::vector input_slice_start_indices(rank, 0); + const std::vector slice_strides(rank, 1); + + for (int i = 0; i < num_slices_; ++i) { + std::vector slice_start_indices = + GetSliceIndices(num_concats_, slice_shape, i); + + int num_complete_pad_dims = 0; + int num_partial_pad_dims = 0; + std::vector slice_limit_indices(rank); + + // Calculate paddings necessary to strip from slice. + for (int dim = 0; dim < rank; ++dim) { + const int64_t dim_size = output_shape[dim]; + if (slice_start_indices[dim] >= dim_size) { + // Complete padding. + slice_start_indices[dim] = dim_size; + slice_limit_indices[dim] = dim_size; + ++num_complete_pad_dims; + } else if (slice_start_indices[dim] + slice_shape[dim] > dim_size) { + // Partial padding. + slice_limit_indices[dim] = dim_size; + ++num_partial_pad_dims; + } else { + slice_limit_indices[dim] = + slice_start_indices[dim] + slice_shape[dim]; + } + } + + if (num_complete_pad_dims == rank) { + continue; + } + + xla::XlaOp input_slice = input_handles[i]; + if (num_complete_pad_dims > 0 || num_partial_pad_dims > 0) { + std::vector input_slice_limit_indices(rank); + for (int dim = 0; dim < rank; ++dim) { + input_slice_limit_indices[dim] = + slice_limit_indices[dim] - slice_start_indices[dim]; + } + input_slice = xla::Slice(input_slice, input_slice_start_indices, + input_slice_limit_indices, slice_strides); + } + + std::vector update_slice_start_indices; + update_slice_start_indices.reserve(rank); + for (int64_t start_index : slice_start_indices) { + update_slice_start_indices.push_back( + xla::ConstantR0(ctx->builder(), start_index)); + } + output = xla::DynamicUpdateSlice(output, input_slice, + update_slice_start_indices); + } + + return output; + } + + DataType dtype_; + + private: + absl::Status GetInputsAndOutputShape(XlaOpKernelContext* ctx, + std::vector& input_handles, + std::vector& input_shapes, + std::vector& output_shape) { + TF_RETURN_IF_ERROR(ctx->InputList("inputs", &input_handles, &input_shapes)); + + const TensorShape& slice_shape = input_shapes[0]; + if (slice_shape.dims() != num_concats_.size()) { + return errors::InvalidArgument( + "'inputs' rank must be the same as 'num_concats' length ", + num_concats_.size(), ", but got rank ", slice_shape.dims(), "."); + } + for (int i = 1; i < num_slices_; ++i) { + const TensorShape& slice_shape_i = input_shapes[i]; + if (slice_shape != slice_shape_i) { + return errors::InvalidArgument( + "'inputs' must all have the same expected shape ", slice_shape, + ", but got ", slice_shape_i, " at index ", i, "."); + } + } + + const int rank = input_shapes[0].dims(); + for (int dim = 0; dim < rank; ++dim) { + const int max_dim_size = slice_shape.dim_size(dim) * num_concats_[dim]; + if (paddings_[dim] > max_dim_size) { + return errors::InvalidArgument( + "'paddings' must not exceed expected output shape dimension ", + max_dim_size, " at index ", dim, ", but got ", paddings_[dim], "."); + } + output_shape.push_back(max_dim_size - paddings_[dim]); + } + + return absl::OkStatus(); + } + + std::vector num_concats_; + int num_slices_ = 1; + std::vector paddings_; + bool has_paddings_ = false; +}; + +class XlaConcatNDOp : public XlaConcatNDBaseOp { + public: + explicit XlaConcatNDOp(OpKernelConstruction* ctx) : XlaConcatNDBaseOp(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + auto output_or = this->CompileInternal(ctx); + OP_REQUIRES_OK(ctx, output_or.status()); + ctx->SetOutput(/*index=*/0, output_or.value()); + } +}; + +REGISTER_XLA_OP(Name("XlaConcatND"), XlaConcatNDOp); + +class AssignVariableXlaConcatNDOp : public XlaConcatNDBaseOp { + public: + explicit AssignVariableXlaConcatNDOp(OpKernelConstruction* ctx) + : XlaConcatNDBaseOp(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + auto output_or = this->CompileInternal(ctx); + OP_REQUIRES_OK(ctx, output_or.status()); + OP_REQUIRES_OK(ctx, + ctx->AssignVariable("resource", dtype_, output_or.value())); + } +}; + +REGISTER_XLA_OP(Name("AssignVariableXlaConcatND"), AssignVariableXlaConcatNDOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/slice_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/slice_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..a8499409442fa2e013fc43565dfc551b3b6909e7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/slice_op.cc @@ -0,0 +1,217 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Slice Op. + +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class SliceOp : public XlaOpKernel { + public: + explicit SliceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + const TensorShape begin_tensor_shape = ctx->InputShape(1); + const TensorShape size_tensor_shape = ctx->InputShape(2); + + const int input_dims = input_shape.dims(); + OP_REQUIRES( + ctx, + TensorShapeUtils::IsVector(begin_tensor_shape) && + TensorShapeUtils::IsVector(size_tensor_shape) && + begin_tensor_shape.num_elements() == input_dims && + size_tensor_shape.num_elements() == input_dims, + errors::InvalidArgument( + "Expected begin and size arguments to be 1-D tensors of size ", + input_dims, ", but got shapes ", begin_tensor_shape.DebugString(), + " and ", size_tensor_shape.DebugString(), " instead.")); + + std::vector begin; + std::vector size; + const bool all_begins_are_constant = + ctx->ConstantInputAsIntVector(1, &begin).ok(); + const bool all_sizes_are_constant = + ctx->ConstantInputAsIntVector(2, &size).ok(); + if (all_begins_are_constant && all_sizes_are_constant) { + std::vector wrapped_size(size.size()); + // `begin` is a compile-time constant. + for (int i = 0; i < input_dims; ++i) { + if (size[i] == -1) { + // A size[i] of -1 means "all elements from begin[i] to dim_size(i)". + wrapped_size[i] = input_shape.dim_size(i) - begin[i]; + } else { + wrapped_size[i] = size[i]; + } + } + + for (int i = 0; i < input_dims; ++i) { + int64_t b = begin[i]; + int64_t s = wrapped_size[i]; + if (input_shape.dim_size(i) == 0) { + OP_REQUIRES(ctx, b == 0 && s == 0, + errors::InvalidArgument( + "Expected begin[", i, "] == 0 (got ", b, + ") and size[", i, "] == 0 ", "(got ", s, ") when ", + "input_shape.dim_size(", i, ") == 0")); + } else { + OP_REQUIRES(ctx, 0 <= b && b <= input_shape.dim_size(i), + errors::InvalidArgument("Expected begin[", i, "] in [0, ", + input_shape.dim_size(i), + "], but got ", b)); + OP_REQUIRES(ctx, 0 <= s && b + s <= input_shape.dim_size(i), + errors::InvalidArgument("Expected size[", i, "] in [0, ", + input_shape.dim_size(i) - b, + "], but ", "got ", s)); + } + } + + std::vector limits; + limits.reserve(begin.size()); + for (int i = 0; i < begin.size(); ++i) { + limits.push_back(begin[i] + wrapped_size[i]); + } + std::vector strides(begin.size(), 1); + auto slice = xla::Slice(ctx->Input(0), begin, limits, strides); + // Check for slice on dynamic dimensions. + std::vector size_is_dynamic; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPredVector(2, &size_is_dynamic)); + + for (int64_t i = 0; i < size.size(); ++i) { + if (size_is_dynamic[i]) { + if (size[i] != -1) { + // If there is a dynamic dimension, properly set dimension size of + // the slice. + auto dynamic_size = + xla::Reshape(xla::Slice(ctx->Input(2), {i}, {i + 1}, {1}), {}); + + slice = xla::SetDimensionSize(slice, dynamic_size, i); + } + } + } + ctx->SetOutput(0, slice); + } else { + // When a size is -1, we take rest of the dimension according to + // https://www.tensorflow.org/api_docs/python/tf/slice. + // This essentially makes size as dynamic. + bool constant_size_is_minus_one = false; + // `begin` or `size` is not a compile-time constant. + if (all_sizes_are_constant) { + for (int i = 0; i < input_dims; ++i) { + if (size[i] < 0) { + OP_REQUIRES(ctx, size[i] == -1, + errors::InvalidArgument( + "Negative size of slice operator can only be -1")); + constant_size_is_minus_one = true; + } + + OP_REQUIRES(ctx, size[i] <= input_shape.dim_size(i), + errors::InvalidArgument("Expected size[", i, "] in [0, ", + input_shape.dim_size(i), + "], but ", "got ", size[i])); + } + } + + absl::InlinedVector begin_indices; + begin_indices.reserve(input_dims); + xla::XlaOp begin = ctx->Input("begin"); + for (int i = 0; i < input_dims; i++) { + begin_indices.push_back( + xla::Reshape(xla::Slice(begin, {i}, {i + 1}, {1}), {})); + } + if (all_sizes_are_constant && !constant_size_is_minus_one) { + xla::XlaOp input = ctx->Input(0); + ctx->SetOutput(0, xla::DynamicSlice(input, begin_indices, size)); + } else { + // Size is not constant, use input size as upperbound and then set + // dimension size on it. + + // First pad input with input size to avoid OOB -- dynamic slice with + // OOB slice produces undesired results. + xla::PaddingConfig padding_config; + xla::XlaOp input = ctx->Input(0); + for (int64_t i = 0; i < input_dims; ++i) { + auto* dims = padding_config.add_dimensions(); + dims->set_edge_padding_low(0); + dims->set_edge_padding_high(input_shape.dim_size(i)); + dims->set_interior_padding(0); + input = xla::RemoveDynamicDimension(input, i); + } + auto padded_input = + xla::Pad(input, xla::Zero(ctx->builder(), ctx->input_xla_type(0)), + padding_config); + // Slice full size out of the input starting from the offsets. + auto sliced = xla::DynamicSlice(padded_input, begin_indices, + input_shape.dim_sizes()); + for (int i = 0; i < input_dims; i++) { + xla::XlaOp dynamic_size = + xla::Reshape(xla::Slice(ctx->Input(2), {i}, {i + 1}, {1}), {}); + if (constant_size_is_minus_one && size[i] == -1) { + // size = input_.dim_size(i) - begin[i] + dynamic_size = xla::ConstantR0(ctx->builder(), + input_shape.dim_size(i)) - + begin_indices[i]; + } + auto constant_size = ctx->value_inference().AnalyzeConstant( + dynamic_size, xla::ValueInferenceMode::kValue); + OP_REQUIRES_OK(ctx, constant_size.status()); + if (constant_size->AllValid()) { + // Slice size on this dimension is constant. This branch is + // triggered when some dimensions's slice sizes are constant while + // some are dynamic. + sliced = xla::SliceInDim( + sliced, 0, constant_size->Get({}).value(), 1, i); + } else { + // We gave a generous bound (same as input) to the output, try reset + // the bound if a tighter one can be found. + auto status = xla::SetDimensionSizeWithRebound( + &ctx->value_inference(), sliced, dynamic_size, i); + OP_REQUIRES_OK(ctx, status.status()); + sliced = status.value(); + } + } + ctx->SetOutput(0, sliced); + } + } + } +}; + +REGISTER_XLA_OP(Name("Slice") + .CompileTimeConstantInput("begin") + .CompileTimeConstantInput("size"), + SliceOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/softmax_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/softmax_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..26bb72f30540432bfdfe0ba02e38ff39fc62e09c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/softmax_op.cc @@ -0,0 +1,191 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Ops for softmax. + +#include +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("Softmax"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("LogSoftmax"), MlirXlaOpKernel); + +std::pair CrossEntropyWithLogits( + XlaOpKernelContext* ctx, DataType type, xla::PrimitiveType xla_type, + xla::XlaOp logits, xla::XlaOp labels) { + const xla::XlaComputation& max_func = *ctx->GetOrCreateMax(type); + + const int kBatchDim = 0; + const int kClassDim = 1; + + xla::XlaBuilder* b = ctx->builder(); + // Find the max in each batch, resulting in a tensor of shape [batch] + auto logits_max = + xla::Reduce(logits, xla::MinValue(b, xla_type), max_func, {kClassDim}); + + // Subtract the max in batch b from every element in batch b. + // Broadcasts along the batch dimension. + auto shifted_logits = xla::Sub(logits, logits_max, {kBatchDim}); + + // exp(logits - max_logits) + auto exp_shifted_logits = xla::Exp(shifted_logits); + + // sum_{class} (exp(logits - max_logits)) + const DataType accumulation_type = XlaHelpers::SumAccumulationType(type); + auto converted = + XlaHelpers::ConvertElementType(exp_shifted_logits, accumulation_type); + auto reduce = + xla::Reduce(converted, XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), {kClassDim}); + auto sum_exp = XlaHelpers::ConvertElementType(reduce, type); + + // log(sum(exp(logits - max_logits))) + auto log_sum_exp = xla::Log(sum_exp); + + // sum(-labels * + // ((logits - max_logits) - log(sum(exp(logits - max_logits))))) + // along classes + // (The subtraction broadcasts along the batch dimension.) + auto sub = xla::Sub(shifted_logits, log_sum_exp, {kBatchDim}); + // Make sure the multiplication doesn't result in -inf * 0. + auto safe_sub = xla::Select(xla::Eq(labels, xla::ZerosLike(labels)), + xla::ZerosLike(sub), sub); + auto mul = xla::Mul(xla::Neg(labels), safe_sub); + + auto sum = xla::Reduce(XlaHelpers::ConvertElementType(mul, accumulation_type), + XlaHelpers::Zero(b, accumulation_type), + *ctx->GetOrCreateAdd(accumulation_type), {kClassDim}); + auto loss = XlaHelpers::ConvertElementType(sum, type); + + // backprop: prob - labels, where + // prob = exp(logits - max_logits) / sum(exp(logits - max_logits)) + // (where the division broadcasts along the batch dimension) + xla::XlaOp backprop = + xla::Sub(xla::Div(exp_shifted_logits, sum_exp, {kBatchDim}), labels); + return {loss, backprop}; +} + +class SoftmaxXentWithLogitsOp : public XlaOpKernel { + public: + explicit SoftmaxXentWithLogitsOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const DataType type = input_type(0); + const xla::PrimitiveType xla_type = ctx->input_xla_type(0); + auto logits = ctx->Input(0); + auto labels = ctx->Input(1); + + OP_REQUIRES_OK(ctx, BroadcastOpsToSame(&logits, &labels)); + + xla::XlaOp loss, backprop; + std::tie(loss, backprop) = + CrossEntropyWithLogits(ctx, type, xla_type, logits, labels); + ctx->SetOutput(0, loss); + ctx->SetOutput(1, backprop); + } +}; + +REGISTER_XLA_OP(Name("SoftmaxCrossEntropyWithLogits"), SoftmaxXentWithLogitsOp); + +class SparseSoftmaxXentWithLogitsOp : public XlaOpKernel { + public: + explicit SparseSoftmaxXentWithLogitsOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape logits_shape = ctx->InputShape(0); + const TensorShape labels_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, TensorShapeUtils::IsMatrix(logits_shape), + errors::InvalidArgument("logits must be 2-D, but got shape ", + logits_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(labels_shape), + errors::InvalidArgument("labels must be 1-D, but got shape ", + labels_shape.DebugString())); + OP_REQUIRES(ctx, logits_shape.dim_size(0) == labels_shape.dim_size(0), + errors::InvalidArgument( + "logits and labels must have the same first dimension, " + "got logits shape ", + logits_shape.DebugString(), " and labels shape ", + labels_shape.DebugString())); + OP_REQUIRES(ctx, logits_shape.dim_size(1) > 0, + errors::InvalidArgument( + "Must have at least one class, but got logits shape ", + logits_shape.DebugString())); + + int64_t batch_size = logits_shape.dim_size(0); + int64_t depth = logits_shape.dim_size(1); + + const DataType logits_type = input_type(0); + const xla::PrimitiveType xla_logits_type = ctx->input_xla_type(0); + const DataType indices_type = input_type(1); + + xla::XlaOp indices = ctx->Input(1); + + xla::XlaBuilder* builder = ctx->builder(); + xla::XlaOp labels; + OP_REQUIRES_OK(ctx, + XlaHelpers::OneHot( + builder, depth, /*axis=*/1, input_type(1), labels_shape, + indices, XlaHelpers::One(builder, logits_type), + XlaHelpers::Zero(builder, logits_type), &labels)); + + // If any of the indices are out of range, we must populate the labels with + // NaNs to obey the interface contract of + // tf.nn.sparse_softmax_cross_entropy_with_logits. + // Builds a vector of {batch_size} that is 0 if the index is in range, or + // NaN otherwise; then add that vector to the labels to force out-of-range + // values to NaNs. + xla::XlaOp nan_or_zero = xla::Select( + xla::And(xla::Le(XlaHelpers::Zero(builder, indices_type), indices), + xla::Lt(indices, XlaHelpers::IntegerLiteral( + builder, indices_type, depth))), + xla::Broadcast(XlaHelpers::Zero(builder, logits_type), {batch_size}), + xla::Broadcast(XlaHelpers::FloatLiteral(builder, logits_type, NAN), + {batch_size})); + labels = xla::Add(labels, nan_or_zero, {0}); + + xla::XlaOp loss, backprop; + std::tie(loss, backprop) = CrossEntropyWithLogits( + ctx, logits_type, xla_logits_type, ctx->Input(0), labels); + ctx->SetOutput(0, loss); + ctx->SetOutput(1, backprop); + } +}; + +REGISTER_XLA_OP(Name("SparseSoftmaxCrossEntropyWithLogits"), + SparseSoftmaxXentWithLogitsOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sort_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sort_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..fddd89f4c8b01dd4e8a04772ead8ea8e80ee8cb7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sort_ops.cc @@ -0,0 +1,48 @@ +/* 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/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/comparators.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaSort"), MlirXlaOpKernel); + +class XlaKeyValueSortOp : public XlaOpKernel { + public: + explicit XlaKeyValueSortOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + xla::XlaOp result = xla::Sort( + {context->Input("keys"), context->Input("values")}, + xla::CreateScalarLtComputation( + {context->InputXlaType("keys"), context->InputXlaType("values")}, + context->builder())); + context->SetOutput(0, xla::GetTupleElement(result, 0)); + context->SetOutput(1, xla::GetTupleElement(result, 1)); + } +}; + +REGISTER_XLA_OP(Name("XlaKeyValueSort"), XlaKeyValueSortOp); +REGISTER_XLA_OP(Name("XlaVariadicSort").CompileTimeConstantInput("dimension"), + MlirXlaOpKernel); +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spacetobatch_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spacetobatch_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..30d0648e1c6707252f214f1a2f41f43b0fad84ec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spacetobatch_op.cc @@ -0,0 +1,221 @@ +/* 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 +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/overflow.h" + +namespace tensorflow { +namespace { + +void SpaceToBatch(XlaOpKernelContext* ctx, const xla::XlaOp input, + DataType input_dtype, const TensorShape& input_tensor_shape, + absl::Span block_shape, + const xla::Literal& paddings) { + const int input_rank = input_tensor_shape.dims(); + const absl::InlinedVector input_shape = + input_tensor_shape.dim_sizes(); + const int block_rank = block_shape.size(); + + OP_REQUIRES( + ctx, input_rank >= 1 + block_rank, + errors::InvalidArgument("input rank should be >= ", 1 + block_rank, + " instead of ", input_rank)); + absl::Span remainder_shape(input_shape); + remainder_shape.remove_prefix(1 + block_rank); + + OP_REQUIRES( + ctx, + paddings.shape().dimensions().size() == 2 && + block_rank == xla::ShapeUtil::GetDimension(paddings.shape(), 0) && + 2 == xla::ShapeUtil::GetDimension(paddings.shape(), 1), + errors::InvalidArgument("paddings should have shape [", block_rank, + ", 2] instead of ", + xla::ShapeUtil::HumanString(paddings.shape()))); + + xla::XlaBuilder* b = ctx->builder(); + + // 1. Zero-pad the start and end of dimensions `[1, ..., M]` of the + // input according to `paddings` to produce `padded` of shape `padded_shape`. + xla::PaddingConfig padding_config; + std::vector padded_shape(input_shape.begin(), input_shape.end()); + int64_t block_num_elems = 1LL; + padding_config.add_dimensions(); // Don't pad the batch dimension. + for (int i = 0; i < block_rank; ++i) { + auto* dim = padding_config.add_dimensions(); + int64_t pad_start = paddings.Get({i, 0}); + int64_t pad_end = paddings.Get({i, 1}); + OP_REQUIRES(ctx, pad_start >= 0 && pad_end >= 0, + errors::InvalidArgument("Paddings must be non-negative")); + OP_REQUIRES(ctx, block_shape[i] >= 1, + errors::InvalidArgument( + "All values in block_shape must be positive, got value, ", + block_shape[i], " at index ", i, ".")); + dim->set_edge_padding_low(pad_start); + dim->set_edge_padding_high(pad_end); + padded_shape[1 + i] += pad_start + pad_end; + block_num_elems = MultiplyWithoutOverflow(block_num_elems, block_shape[i]); + } + // Don't pad the remainder dimensions. + for (int i = 0; i < remainder_shape.size(); ++i) { + padding_config.add_dimensions(); + } + OP_REQUIRES(ctx, block_num_elems > 0, + errors::InvalidArgument( + "The product of the block dimensions must be positive")); + const int64_t batch_size = input_shape[0]; + const int64_t output_dim = + MultiplyWithoutOverflow(batch_size, block_num_elems); + if (output_dim < 0) { + OP_REQUIRES( + ctx, output_dim >= 0, + errors::InvalidArgument("Negative output dimension size caused by " + "overflow when multiplying ", + batch_size, " and ", block_num_elems)); + } + + xla::XlaOp padded = + xla::Pad(input, XlaHelpers::Zero(b, input_dtype), padding_config); + + // 2. Reshape `padded` to `reshaped_padded` of shape: + // + // [batch] + + // [padded_shape[1] / block_shape[0], + // block_shape[0], + // ..., + // padded_shape[M] / block_shape[M-1], + // block_shape[M-1]] + + // remaining_shape + std::vector reshaped_padded_shape(input_rank + block_rank); + reshaped_padded_shape[0] = batch_size; + for (int i = 0; i < block_rank; ++i) { + OP_REQUIRES(ctx, padded_shape[1 + i] % block_shape[i] == 0, + errors::InvalidArgument("padded_shape[", 1 + i, + "]=", padded_shape[1 + i], + " is not divisible by block_shape[", i, + "]=", block_shape[i])); + + reshaped_padded_shape[1 + i * 2] = padded_shape[1 + i] / block_shape[i]; + reshaped_padded_shape[1 + i * 2 + 1] = block_shape[i]; + } + std::copy(remainder_shape.begin(), remainder_shape.end(), + reshaped_padded_shape.begin() + 1 + 2 * block_rank); + + xla::XlaOp reshaped_padded = xla::Reshape(padded, reshaped_padded_shape); + + // 3. Permute dimensions of `reshaped_padded` to produce + // `permuted_reshaped_padded` of shape: + // + // block_shape + + // [batch] + + // [padded_shape[1] / block_shape[0], + // ..., + // padded_shape[M] / block_shape[M-1]] + + // remaining_shape + std::vector permutation(reshaped_padded_shape.size()); + for (int i = 0; i < block_rank; ++i) { + permutation[i] = 1 + 2 * i + 1; + permutation[block_rank + 1 + i] = 1 + 2 * i; + } + permutation[block_rank] = 0; + std::iota(permutation.begin() + 1 + block_rank * 2, permutation.end(), + 1 + block_rank * 2); + xla::XlaOp permuted_reshaped_padded = + xla::Transpose(reshaped_padded, permutation); + + // 4. Reshape `permuted_reshaped_padded` to flatten `block_shape` into the + // batch dimension, producing an output tensor of shape: + // + // [batch * prod(block_shape)] + + // [padded_shape[1] / block_shape[0], + // ..., + // padded_shape[M] / block_shape[M-1]] + + // remaining_shape + // Determine the length of the prefix of block dims that can be combined + // into the batch dimension due to having no padding and block_shape=1. + std::vector output_shape(input_rank); + output_shape[0] = output_dim; + for (int i = 0; i < block_rank; ++i) { + output_shape[1 + i] = padded_shape[1 + i] / block_shape[i]; + } + std::copy(remainder_shape.begin(), remainder_shape.end(), + output_shape.begin() + 1 + block_rank); + + xla::XlaOp output = xla::Reshape(permuted_reshaped_padded, output_shape); + ctx->SetOutput(0, output); +} + +class SpaceToBatchNDOp : public XlaOpKernel { + public: + explicit SpaceToBatchNDOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + std::vector block_shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &block_shape)); + + xla::Literal paddings; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal(2, &paddings)); + + SpaceToBatch(ctx, ctx->Input(0), input_type(0), ctx->InputShape(0), + block_shape, paddings); + } +}; +REGISTER_XLA_OP(Name("SpaceToBatchND") + .CompileTimeConstantInput("paddings") + .CompileTimeConstantInput("block_shape"), + SpaceToBatchNDOp); + +class SpaceToBatchOp : public XlaOpKernel { + public: + explicit SpaceToBatchOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("block_size", &block_size_)); + OP_REQUIRES( + ctx, block_size_ > 1, + errors::InvalidArgument("Block size should be > 1: ", block_size_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::Literal paddings; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsInt64Literal(1, &paddings)); + + SpaceToBatch(ctx, ctx->Input(0), input_type(0), ctx->InputShape(0), + {block_size_, block_size_}, paddings); + } + + private: + int block_size_; +}; +REGISTER_XLA_OP(Name("SpaceToBatch").CompileTimeConstantInput("paddings"), + SpaceToBatchOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spacetodepth_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spacetodepth_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..2187e0584c9c9487500029cdfcc86b03f0f7a8db --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spacetodepth_op.cc @@ -0,0 +1,200 @@ +/* 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 +#include +#include + +#include "absl/log/check.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/lib/data_format.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { +namespace { + +class SpaceToDepthOp : public XlaOpKernel { + public: + explicit SpaceToDepthOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + std::string data_format_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("data_format", &data_format_str)); + OP_REQUIRES(ctx, FormatFromString(data_format_str, &data_format_), + errors::InvalidArgument("Invalid data format")); + + OP_REQUIRES_OK(ctx, ctx->GetAttr("block_size", &block_size_)); + OP_REQUIRES( + ctx, block_size_ > 1, + errors::InvalidArgument("Block size should be > 1: ", block_size_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + + TensorFormat data_format = data_format_; + // If the data is in a vectorized format, reformat it into a non-vectorized + // version first. We'll undo the transformation later. + if (data_format == FORMAT_NCHW_VECT_C) { + data_format = FORMAT_NCHW; + auto input_reshaped = NCHW_VECT_CToNCHW(input); + OP_REQUIRES_OK(ctx, input_reshaped.status()); + input = input_reshaped.value(); + } + + OP_REQUIRES(ctx, data_format == FORMAT_NCHW || data_format == FORMAT_NHWC, + errors::InvalidArgument("Unsupported data format ", + ToString(data_format_))); + + xla::XlaBuilder* builder = input.builder(); + auto input_xla_shape = builder->GetShape(input); + OP_REQUIRES_OK(ctx, input_xla_shape.status()); + absl::Span input_shape = + input_xla_shape.value().dimensions(); + int input_rank = input_shape.size(); + + static const int kRequiredDims = 4; + OP_REQUIRES(ctx, kRequiredDims == input_rank, + errors::InvalidArgument("Input rank should be ", kRequiredDims, + "; got ", input_rank)); + + int feature_dim = GetTensorFeatureDimIndex(input_rank, data_format); + int num_spatial_dims = GetTensorSpatialDims(input_rank, data_format); + + std::vector reshaped_shape; + std::vector transpose_order; + std::vector output_shape; + reshaped_shape.reserve(input_rank); + transpose_order.reserve(input_rank); + output_shape.reserve(input_rank); + if (data_format == FORMAT_NHWC) { + int64_t block_elems = 1; + for (int i = 0; i < num_spatial_dims; ++i) { + OP_REQUIRES(ctx, input_shape[1 + i] % block_size_ == 0, + errors::InvalidArgument( + "input shape[", 1 + i, "]=", input_shape[1 + i], + " is not divisible by block_size=", block_size_)); + block_elems *= block_size_; + } + + reshaped_shape.push_back(input_shape[0]); + for (int i = 0; i < num_spatial_dims; ++i) { + reshaped_shape.push_back(input_shape[1 + i] / block_size_); + reshaped_shape.push_back(block_size_); + } + reshaped_shape.push_back(input_shape[feature_dim]); + + transpose_order.push_back(0); + for (int i = 0; i < num_spatial_dims; ++i) { + transpose_order.push_back(i * 2 + 1); + } + for (int i = 0; i < num_spatial_dims; ++i) { + transpose_order.push_back(i * 2 + 2); + } + transpose_order.push_back(feature_dim + num_spatial_dims); + + output_shape.push_back(input_shape[0]); + for (int i = 0; i < num_spatial_dims; ++i) { + output_shape.push_back(input_shape[1 + i] / block_size_); + } + output_shape.push_back(input_shape[feature_dim] * block_elems); + } else { + // FORMAT_NCHW + int64_t block_elems = 1; + for (int i = 0; i < num_spatial_dims; ++i) { + OP_REQUIRES(ctx, input_shape[2 + i] % block_size_ == 0, + errors::InvalidArgument( + "input shape[", 2 + i, "]=", input_shape[2 + i], + " is not divisible by block_size=", block_size_)); + block_elems *= block_size_; + } + + reshaped_shape.push_back(input_shape[0]); + reshaped_shape.push_back(input_shape[feature_dim]); + for (int i = 0; i < num_spatial_dims; ++i) { + reshaped_shape.push_back(input_shape[2 + i] / block_size_); + reshaped_shape.push_back(block_size_); + } + + transpose_order.push_back(0); + for (int i = 0; i < num_spatial_dims; ++i) { + transpose_order.push_back(i * 2 + 3); + } + transpose_order.push_back(feature_dim); + for (int i = 0; i < num_spatial_dims; ++i) { + transpose_order.push_back(i * 2 + 2); + } + + output_shape.push_back(input_shape[0]); + output_shape.push_back(input_shape[feature_dim] * block_elems); + for (int i = 0; i < num_spatial_dims; ++i) { + output_shape.push_back(input_shape[2 + i] / block_size_); + } + } + + // Note: comments are given in NHWC format; NCHW is similar with a different + // dimension order. + // 1. Reshape `input` to `reshaped` of shape: + // + // [batch, + // input_shape[1] / block_size_, block_size_, + // input_shape[2] / block_size_, block_size_, + // depth] + xla::XlaOp reshaped = xla::Reshape(input, reshaped_shape); + + // 2. Permute dimensions of `reshaped` to produce + // `permuted_reshaped` of shape: + // + // [batch, + // input_shape[1] / block_size_, + // input_shape[2] / block_size_, + // block_size_, block_size_, + // depth] + xla::XlaOp permuted_reshaped = xla::Transpose(reshaped, transpose_order); + + // 3. Reshape `permuted_reshaped` to flatten `block_shape` into the + // batch dimension, producing an output tensor of shape: + // + // [batch, + // input_shape[1] / block_size_, + // input_shape[2] / block_size_, + // block_size_ * block_size_ * depth] + // + xla::XlaOp output = xla::Reshape(permuted_reshaped, output_shape); + + // If this used to be a vectorized format turn it back now. + if (data_format != data_format_) { + DCHECK(data_format == FORMAT_NCHW && data_format_ == FORMAT_NCHW_VECT_C); + auto output_reshaped = NCHWToNCHW_VECT_C(output); + OP_REQUIRES_OK(ctx, output_reshaped.status()); + output = output_reshaped.value(); + } + + ctx->SetOutput(0, output); + } + + private: + TensorFormat data_format_; + int block_size_; +}; +REGISTER_XLA_OP(Name("SpaceToDepth"), SpaceToDepthOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sparse_to_dense_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sparse_to_dense_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..bf0efdffb6fdf90568191271445a0a2a71a8427f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/sparse_to_dense_op.cc @@ -0,0 +1,114 @@ +/* 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. +==============================================================================*/ + +#include +#include + +#include "tensorflow/compiler/tf2xla/lib/scatter.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +// Operator to convert sparse representations to dense. +class SparseToDenseOp : public XlaOpKernel { + public: + explicit SparseToDenseOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + // sparse_indices + const TensorShape indices_shape = context->InputShape(0); + OP_REQUIRES(context, indices_shape.dims() <= 2, + errors::InvalidArgument( + "sparse_indices should be a scalar, vector, or matrix, " + "got shape ", + indices_shape.DebugString())); + const int64_t num_elems = + indices_shape.dims() > 0 ? indices_shape.dim_size(0) : 1; + const int64_t num_dims = + indices_shape.dims() > 1 ? indices_shape.dim_size(1) : 1; + + // output_shape + TensorShape output_shape; + OP_REQUIRES_OK(context, + context->ConstantInputAsShape( + 1, &output_shape, xla::ValueInferenceMode::kUpperBound)); + OP_REQUIRES(context, output_shape.dims() == num_dims, + errors::InvalidArgument( + "output_shape has incorrect number of elements: ", + output_shape.num_elements(), " should be: ", num_dims)); + + // sparse_values + const TensorShape sparse_values_shape = context->InputShape(2); + const int64_t num_values = sparse_values_shape.num_elements(); + OP_REQUIRES( + context, + sparse_values_shape.dims() == 0 || + (sparse_values_shape.dims() == 1 && num_values == num_elems), + errors::InvalidArgument("sparse_values has incorrect shape ", + sparse_values_shape.DebugString(), + ", should be [] or [", num_elems, "]")); + + // default_value + const TensorShape default_value_shape = context->InputShape(3); + OP_REQUIRES(context, TensorShapeUtils::IsScalar(default_value_shape), + errors::InvalidArgument("default_value should be a scalar.")); + + xla::XlaOp indices = context->Input(0); + xla::XlaOp sparse_values = context->Input(2); + xla::XlaOp default_value = context->Input(3); + + if (sparse_values_shape.dims() == 0 && num_elems != 1) { + sparse_values = Broadcast(sparse_values, {num_elems}); + } + xla::XlaBuilder* builder = context->builder(); + auto buffer = Broadcast(default_value, output_shape.dim_sizes()); + std::vector dynamic_dims; + OP_REQUIRES_OK( + context, context->ResolveInputDynamismIntoPredVector(1, &dynamic_dims)); + + for (int64_t i = 0; i < dynamic_dims.size(); ++i) { + // If a dimension is dynamic, call set-dimension-size on the output. + if (dynamic_dims[i]) { + auto dynamic_dim_size = + xla::Slice(context->Input(1), {i}, {i + 1}, {1}); + dynamic_dim_size = xla::Reshape(dynamic_dim_size, {}); + dynamic_dim_size = xla::ConvertElementType(dynamic_dim_size, xla::S32); + buffer = xla::SetDimensionSize(buffer, dynamic_dim_size, i); + } + } + auto result = XlaScatter(buffer, sparse_values, indices, + /*indices_are_vectors=*/indices_shape.dims() > 1, + /*indices_are_sorted=*/false, + /*combiner=*/{}, builder); + context->SetOutput(0, builder->ReportErrorOrReturn(result)); + } +}; + +REGISTER_XLA_OP(Name("SparseToDense").CompileTimeConstantInput("output_shape"), + SparseToDenseOp); + +} // namespace + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/split_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/split_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..6b82ae49b1db9f5c44bbf8f9991d39db533d7869 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/split_op.cc @@ -0,0 +1,230 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Ops for split. + +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class SplitOp : public XlaOpKernel { + public: + explicit SplitOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const int32_t num_split = num_outputs(); + const TensorShape split_dim_shape = ctx->InputShape("split_dim"); + const TensorShape input_shape = ctx->InputShape(1); + + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(split_dim_shape), + errors::InvalidArgument("split_dim must be a scalar but has rank ", + split_dim_shape.dims())); + int64_t split_dim_orig; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(0, &split_dim_orig)); + + int32_t split_dim = split_dim_orig < 0 ? split_dim_orig + input_shape.dims() + : split_dim_orig; + OP_REQUIRES(ctx, 0 <= split_dim && split_dim < input_shape.dims(), + errors::InvalidArgument("-input rank(-", input_shape.dims(), + ") <= split_dim < input rank (", + input_shape.dims(), "), but got ", + split_dim_orig)); + + OP_REQUIRES( + ctx, num_split > 0, + errors::InvalidArgument( + "Number of ways to split should be > 0, but got ", num_split)); + + xla::XlaBuilder* builder = ctx->builder(); + xla::XlaOp input = ctx->Input(1); + auto shape_or = builder->GetShape(input); + OP_REQUIRES_OK(ctx, shape_or.status()); + + xla::Shape xla_shape = shape_or.value(); + OP_REQUIRES( + ctx, !xla_shape.is_dynamic_dimension(split_dim), + errors::InvalidArgument( + "Split op doesn't support split for the dynamic dimension")); + + OP_REQUIRES( + ctx, xla_shape.dimensions(split_dim) % num_split == 0, + errors::InvalidArgument( + "Number of ways to split should evenly divide the split " + "dimension, but got split_dim ", + split_dim_orig, " (size = ", input_shape.dim_size(split_dim), ") ", + "and num_split ", num_split)); + + // All the slices are the same size: this is the size along the + // split dimension. + const int32_t slice_size = input_shape.dim_size(split_dim) / num_split; + + // The vectors we will use to define the slice. The entry for the + // split dimensions varies for each output. + std::vector begin(input_shape.dims(), 0); + std::vector limits(input_shape.dims()); + std::vector strides(input_shape.dims(), 1); + for (int i = 0; i < input_shape.dims(); ++i) { + // Initially set up the limits to be the full size of the input: + // the split dimension is filled in below. + int64_t dim = input_shape.dim_size(i); + limits[i] = dim; + } + + // Create each of the outputs. + for (int i = 0; i < num_split; ++i) { + // Slice out the ith split from the split dimension. + begin[split_dim] = i * slice_size; + limits[split_dim] = (i + 1) * slice_size; + ctx->SetOutput(i, xla::Slice(input, begin, limits, strides)); + } + } +}; + +REGISTER_XLA_OP(Name("Split").CompileTimeConstantInput("split_dim"), SplitOp); + +class SplitVOp : public XlaOpKernel { + public: + explicit SplitVOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const int32_t num_split = num_outputs(); + const TensorShape input_shape = ctx->InputShape(0); + const TensorShape index_shape = ctx->InputShape(2); + + OP_REQUIRES(ctx, index_shape.num_elements() == 1, + errors::InvalidArgument( + "split_dim_tensor must have exactly one element.")); + + int64_t split_dim_orig; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(2, &split_dim_orig)); + int64_t split_dim = split_dim_orig < 0 ? split_dim_orig + input_shape.dims() + : split_dim_orig; + OP_REQUIRES(ctx, 0 <= split_dim && split_dim < input_shape.dims(), + errors::InvalidArgument("-input rank(-", input_shape.dims(), + ") <= split_dim < input rank (", + input_shape.dims(), "), but got ", + split_dim_orig)); + + xla::XlaOp input = ctx->Input(0); + + OP_REQUIRES(ctx, input_shape.dims() > 0, + errors::InvalidArgument("Can't split a 0 dimensional input")); + + OP_REQUIRES( + ctx, num_split > 0, + errors::InvalidArgument( + "Number of ways to split should be > 0, but got ", num_split)); + + // Check that sizes are correct. + int total_split_size = 0; + int neg_one_dim = -1; + const TensorShape split_size_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, + split_size_shape.dims() == 1 && + split_size_shape.num_elements() == num_split, + errors::InvalidArgument( + "shape of tensor describing " + " the output must have dimension 1 and the same " + " number of elements as the output. Got ", + split_size_shape.dims(), "-D and ", + split_size_shape.num_elements(), " elements")); + // Get the dimension of this split. + std::vector split_sizes; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &split_sizes)); + + for (int i = 0; i < num_split; ++i) { + int64_t slice_size = split_sizes[i]; + OP_REQUIRES(ctx, slice_size >= -1, + errors::InvalidArgument("Split size at index ", i, + " must be >= -1, Got: ", slice_size)); + if (slice_size == -1) { + OP_REQUIRES( + ctx, neg_one_dim == -1, + errors::InvalidArgument("Only one dimensions can have a value of" + "-1. Second one found at dimension ", + i)); + neg_one_dim = i; + } else { + total_split_size += slice_size; + } + } + + xla::XlaBuilder* builder = ctx->builder(); + auto shape_or = builder->GetShape(input); + OP_REQUIRES_OK(ctx, shape_or.status()); + + // TODO(b/265880112): Support this using the SetDimensionSize op. + xla::Shape xla_shape = shape_or.value(); + OP_REQUIRES( + ctx, !xla_shape.is_dynamic_dimension(split_dim), + errors::Unimplemented("SplitV op doesn't yet support dynamic split " + "dimension.")); + + OP_REQUIRES( + ctx, + (neg_one_dim == -1 && + total_split_size == xla_shape.dimensions(split_dim)) || + (neg_one_dim >= 0 && + total_split_size <= xla_shape.dimensions(split_dim)), + errors::InvalidArgument("Determined shape must either match " + "input shape along split_dim exactly if " + "fully specified, or be less than the size of " + "the input along split_dim if not fully " + "specified. Got: ", + total_split_size)); + + if (neg_one_dim >= 0) { + split_sizes[neg_one_dim] = + input_shape.dim_size(split_dim) - total_split_size; + } + + // The vectors we will use to define the slice. The entry for the + // split dimensions varies for each output. + std::vector begin(input_shape.dims(), 0); + auto dim_sizes = input_shape.dim_sizes(); + std::vector limits(dim_sizes.begin(), dim_sizes.end()); + std::vector strides(input_shape.dims(), 1); + for (int i = 0; i < num_split; ++i) { + TensorShape output_shape(input_shape); + int slice_size = split_sizes[i]; + output_shape.set_dim(split_dim, slice_size); + + // Slice out the ith split from the split dimension. + limits[split_dim] = begin[split_dim] + slice_size; + ctx->SetOutput(i, xla::Slice(input, begin, limits, strides)); + begin[split_dim] = limits[split_dim]; + } + } +}; + +REGISTER_XLA_OP(Name("SplitV") + .CompileTimeConstantInput("split_dim") + .CompileTimeConstantInput("size_splits"), + SplitVOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spmd_manual_sharding_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spmd_manual_sharding_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..fcad12b82400c0c79cc60537635d47df9453b08c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/spmd_manual_sharding_ops.cc @@ -0,0 +1,135 @@ +/* Copyright 2020 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 +#include +#include + +#include "tensorflow/compiler/mlir/tensorflow/utils/xla_sharding_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + + +class XlaSpmdFullToShardShapeOp : public XlaOpKernel { + public: + explicit XlaSpmdFullToShardShapeOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("manual_sharding", &manual_sharding_str_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dim", &single_dim_)); + std::vector unspecified_dims; + OP_REQUIRES_OK(ctx, ctx->GetAttr("unspecified_dims", &unspecified_dims)); + for (int32_t i32 : unspecified_dims) { + unspecified_dims_.push_back(i32); + } + } + + ~XlaSpmdFullToShardShapeOp() override = default; + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + + xla::OpSharding sharding; + if (tensorflow::DecodeShardingAttribute(manual_sharding_str_, sharding) + .failed()) { + OP_REQUIRES_OK(ctx, + xla::InvalidArgument("manual_sharding attribute was not a " + "valid encoded xla::OpSharding " + "proto.")); + } + + auto status_or_output = ConvertSpmdFullToShardShape( + ctx->builder(), + /*input=*/input, /*single_dim=*/single_dim_, + /*manual_sharding=*/sharding, /*unspecified_dims=*/unspecified_dims_); + OP_REQUIRES_OK(ctx, status_or_output.status()); + ctx->SetOutput(0, status_or_output.value()); + } + + private: + std::string manual_sharding_str_; + int32_t single_dim_; + std::vector unspecified_dims_; + XlaSpmdFullToShardShapeOp(const XlaSpmdFullToShardShapeOp&) = delete; + void operator=(const XlaSpmdFullToShardShapeOp&) = delete; +}; + +class XlaSpmdShardToFullShapeOp : public XlaOpKernel { + public: + explicit XlaSpmdShardToFullShapeOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("full_shape", &full_shape_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("manual_sharding", &manual_sharding_str_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dim", &single_dim_)); + std::vector unspecified_dims; + OP_REQUIRES_OK(ctx, ctx->GetAttr("unspecified_dims", &unspecified_dims)); + for (int32_t i32 : unspecified_dims) { + unspecified_dims_.push_back(i32); + } + } + + ~XlaSpmdShardToFullShapeOp() override = default; + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + auto status_or_input_shape = ctx->InputXlaShape(0); + OP_REQUIRES_OK(ctx, status_or_input_shape.status()); + const xla::Shape output_shape = TensorShapeToXLAShape( + /*type=*/status_or_input_shape.value().element_type(), + /*tensor_shape=*/full_shape_); + + xla::OpSharding sharding; + if (tensorflow::DecodeShardingAttribute(manual_sharding_str_, sharding) + .failed()) { + OP_REQUIRES_OK(ctx, + xla::InvalidArgument("manual_sharding attribute was not a " + "valid encoded xla::OpSharding " + "proto.")); + } + + auto status_or_output = ConvertSpmdShardToFullShape( + ctx->builder(), + /*input=*/input, /*output_shape=*/output_shape, + /*single_dim=*/single_dim_, + /*manual_sharding=*/sharding, /*unspecified_dims=*/unspecified_dims_); + OP_REQUIRES_OK(ctx, status_or_output.status()); + ctx->SetOutput(0, status_or_output.value()); + } + + private: + TensorShape full_shape_; + std::string manual_sharding_str_; + int32_t single_dim_; + std::vector unspecified_dims_; + XlaSpmdShardToFullShapeOp(const XlaSpmdShardToFullShapeOp&) = delete; + void operator=(const XlaSpmdShardToFullShapeOp&) = delete; +}; + +REGISTER_XLA_OP(Name("XlaSpmdFullToShardShape"), XlaSpmdFullToShardShapeOp); +REGISTER_XLA_OP(Name("XlaSpmdShardToFullShape"), XlaSpmdShardToFullShapeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stack_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stack_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..c4479f7bdf440a3f9502e7691d09e2d8afbc8570 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stack_ops.cc @@ -0,0 +1,254 @@ +/* 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. +==============================================================================*/ + +// XLA Stack operators. + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +absl::Status GetStackShape(xla::XlaBuilder* builder, XlaResource* resource, + TensorShape* stack_shape) { + auto shape_or_status = builder->GetShape(resource->value()); + if (!shape_or_status.ok()) { + return shape_or_status.status(); + } + xla::Shape shape = shape_or_status.value(); + TF_RET_CHECK(shape.IsTuple()); + return XLAShapeToTensorShape(xla::ShapeUtil::GetTupleElementShape(shape, 0), + stack_shape); +} + +// Since the element shape is not provided to the Stack operator, +// we lazily initialize the Stack at the time of the first write. +// +// If a Stack `resource` has not been initialized, constructs storage for the +// Stack with elements of `elem_shape`. For both initialized and +// uninitialized Stacks, checks that the tensor has a type compatible with +// 'dtype' and shape compatible with 'elem_shape'. +// +// TODO(phawkins): consider changing the API of the stack operators to +// allow an optional element shape at stack construction time. +absl::Status MaybeInitializeStack(xla::XlaBuilder* builder, + XlaResource* resource, DataType dtype, + const TensorShape& elem_shape) { + if (resource->type() != dtype) { + return errors::InvalidArgument( + "Stack dtype is ", DataTypeString(resource->type()), + " but op has dtype ", DataTypeString(dtype), "."); + } + + TensorShape stack_shape; + TF_RETURN_IF_ERROR(stack_shape.AddDimWithStatus(resource->max_array_size())); + stack_shape.AppendShape(elem_shape); + + if (!resource->initialized()) { + // Stack has not been initialized. + TF_RETURN_IF_ERROR(resource->SetTypeAndShape(dtype, elem_shape)); + TF_RETURN_IF_ERROR(resource->SetZeroValue(builder)); + } else { + // Checks the expected shape matches the actual shape. + TensorShape actual_shape; + TF_RETURN_IF_ERROR(GetStackShape(builder, resource, &actual_shape)); + if (stack_shape != actual_shape) { + return errors::InvalidArgument( + "Mismatched Stack shapes: ", stack_shape.DebugString(), " vs ", + actual_shape.DebugString()); + } + } + return absl::OkStatus(); +} + +class StackOp : public XlaOpKernel { + public: + explicit StackOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("elem_type", &dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("stack_name", &stack_name_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + int64_t max_size; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(0, &max_size)); + OP_REQUIRES( + ctx, max_size >= 0, + errors::InvalidArgument( + "XLA compilation requires a fixed stack size upper bound. If " + "you are using tf.while_loop, set the maximum_iterations parameter " + "to fix this issue.")); + + // We defer initializing the Stack resource until we see the first push. + // Otherwise we do not know the shape of the stack elements. + XlaResource* resource = + ctx->xla_context()->AddResource(XlaResource::CreateStack( + /*name=*/absl::StrCat("Stack: ", stack_name_), dtype_, max_size)); + ctx->SetResourceOutput(0, resource); + } + + private: + DataType dtype_; + std::string stack_name_; + + StackOp(const StackOp&) = delete; + void operator=(const StackOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("StackV2").CompileTimeConstantInput("max_size").CompilationOnly(), + StackOp); + +class StackPushOp : public XlaOpKernel { + public: + explicit StackPushOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + TensorShape elem_shape = ctx->InputShape(1); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + + // Initializes the Stack, if the element shape was not already known. + OP_REQUIRES_OK(ctx, MaybeInitializeStack(b, resource, dtype_, elem_shape)); + + xla::XlaOp ta = xla::GetTupleElement(resource->value(), 0); + xla::XlaOp index = xla::GetTupleElement(resource->value(), 1); + xla::XlaOp value = ctx->Input(1); + + // start_indices of the DynamicUpdateSlice are [index, 0, 0, ..., 0]. + std::vector start_indices(elem_shape.dims() + 1, + xla::ConstantR0(b, 0)); + start_indices[0] = index; + + TensorShape slice_shape = elem_shape; + slice_shape.InsertDim(0, 1LL); + auto update = xla::Reshape(value, slice_shape.dim_sizes()); + + // TODO(phawkins): We don't check the index is in bounds --- there is no + // error mechanism in XLA. + OP_REQUIRES_OK(ctx, + resource->SetValue(xla::Tuple( + b, {xla::DynamicUpdateSlice(ta, update, start_indices), + xla::Add(index, xla::ConstantR0(b, 1))}))); + + ctx->SetOutput(0, value); + } + + private: + DataType dtype_; + + StackPushOp(const StackPushOp&) = delete; + void operator=(const StackPushOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StackPushV2").CompilationOnly(), StackPushOp); + +class StackPopOp : public XlaOpKernel { + public: + explicit StackPopOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("elem_type", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + + // There is a somewhat subtle issue here: here "uninitialized" means we have + // not yet seen a pop in the order that we compile operators, not the order + // that we run them. However, in practice the two orders should be the same + // for the sole user of the stack operators (loop gradients). + OP_REQUIRES(ctx, resource->initialized(), + errors::InvalidArgument("Stack pop on uninitialized stack")); + + TensorShape stack_shape; + OP_REQUIRES_OK(ctx, GetStackShape(b, resource, &stack_shape)); + + xla::XlaOp state = resource->value(); + xla::XlaOp ta = xla::GetTupleElement(state, 0); + xla::XlaOp index = xla::GetTupleElement(state, 1); + + index = Sub(index, xla::ConstantR0(b, 1)); + OP_REQUIRES_OK(ctx, resource->SetValue(xla::Tuple(b, {ta, index}))); + + // start_indices of the DynamicSlice are [index, 0, 0, ..., 0]. + std::vector start_indices(stack_shape.dims(), + xla::ConstantR0(b, 0)); + start_indices[0] = index; + + auto slice_shape = stack_shape.dim_sizes(); + slice_shape[0] = 1LL; + + // TODO(phawkins): We don't check the index is in bounds --- there is no + // error mechanism in XLA. + xla::XlaOp read = xla::DynamicSlice(ta, start_indices, slice_shape); + + // Remove the leading '1' dimension. + std::vector value_shape(slice_shape.begin() + 1, + slice_shape.end()); + ctx->SetOutput(0, xla::Reshape(read, value_shape)); + } + + private: + DataType dtype_; + + StackPopOp(const StackPopOp&) = delete; + void operator=(const StackPopOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StackPopV2").CompilationOnly(), StackPopOp); + +class StackCloseOp : public XlaOpKernel { + public: + explicit StackCloseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // Do nothing. + } + + private: + StackCloseOp(const StackCloseOp&) = delete; + void operator=(const StackCloseOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StackCloseV2").CompilationOnly(), StackCloseOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateful_random_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateful_random_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..46e9678d27a08807aaaadea6ed02fb3988649e71 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateful_random_ops.cc @@ -0,0 +1,520 @@ +/* Copyright 2019 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/stateful_random_ops.h" + +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/kernels/random_ops_util.h" +#include "tensorflow/compiler/tf2xla/lib/random.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/prng.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/rng_alg.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +xla::BitGeneratorTy BitGen(xla::RandomAlgorithm alg) { + switch (alg) { + case xla::RandomAlgorithm::RNG_PHILOX: + return [=](xla::XlaOp key, xla::XlaOp state, const xla::Shape& shape) { + state = + xla::ConcatInDim(key.builder(), {xla::Reshape(key, {1}), state}, 0); + xla::XlaOp result = xla::RngBitGenerator(alg, state, shape); + xla::XlaOp data = xla::GetTupleElement(result, 1); + xla::XlaOp new_state = + xla::Slice(xla::GetTupleElement(result, 0), {1}, {3}, {1}); + return xla::RngOutput{data, new_state}; + }; + case xla::RandomAlgorithm::RNG_THREE_FRY: // fall through + case xla::RandomAlgorithm::RNG_DEFAULT: // fall through + default: + return [=](xla::XlaOp key, xla::XlaOp state, const xla::Shape& shape) { + state = xla::ConcatScalars(key.builder(), {key, state}); + xla::XlaOp result = xla::RngBitGenerator(alg, state, shape); + xla::XlaOp data = xla::GetTupleElement(result, 1); + xla::XlaOp new_state = xla::Reshape( + xla::Slice(xla::GetTupleElement(result, 0), {1}, {2}, {1}), {}); + return xla::RngOutput{data, new_state}; + }; + } +} + +xla::RngOutput StatefulRngUniform(xla::RandomAlgorithm alg, xla::XlaOp key, + xla::XlaOp initial_state, + const xla::Shape& shape, xla::XlaOp minval, + xla::XlaOp maxval) { + xla::PrimitiveType type = shape.element_type(); + switch (type) { + case xla::F32: + case xla::F64: + return xla::UniformFloatingPointDistribution( + key, initial_state, BitGen(alg), minval, maxval, shape); + case xla::U32: + case xla::S32: + case xla::U64: + case xla::S64: + return UniformIntDistribution(key, initial_state, BitGen(alg), minval, + maxval, shape); + default: + return {key.builder()->ReportError(xla::Unimplemented( + "Types other than F32, U32, S32, U64 and S64 " + "are not implemented by " + "StatefulRngUniform; got %s", + xla::primitive_util::LowercasePrimitiveTypeName(type))), + initial_state}; + } +} + +xla::RngOutput StatefulRngUniformFullInt(xla::RandomAlgorithm alg, + xla::XlaOp key, + xla::XlaOp initial_state, + const xla::Shape& shape) { + xla::PrimitiveType type = shape.element_type(); + xla::RngOutput output = BitGen(alg)(key, initial_state, shape); + switch (type) { + case xla::U32: + case xla::U64: + return output; + case xla::S32: + case xla::S64: + output.value = BitcastConvertType(output.value, type); + return output; + default: + return { + key.builder()->ReportError(xla::Unimplemented( + "Types other than U32, S32, U64 and S64 are not implemented by " + "StatefulRngUniformFullInt; got: %s", + xla::primitive_util::LowercasePrimitiveTypeName(type))), + initial_state}; + } +} + +using SamplerReturnType = absl::StatusOr; + +int64_t GetMinStateSize(xla::RandomAlgorithm alg) { + switch (alg) { + case xla::RandomAlgorithm::RNG_PHILOX: + return PHILOX_MIN_STATE_SIZE; + case xla::RandomAlgorithm::RNG_THREE_FRY: // fall through + case xla::RandomAlgorithm::RNG_DEFAULT: // fall through + default: + return THREEFRY_MIN_STATE_SIZE; + } +} + +absl::Status CheckStateShape(xla::RandomAlgorithm alg, + const TensorShape& shape) { + if (shape.dims() != 1) { + return errors::InvalidArgument( + "RNG state must have one and only one dimension, not ", shape.dims()); + } + auto state_size = shape.dim_size(0); + auto min_state_size = GetMinStateSize(alg); + if (state_size < min_state_size) { + return errors::InvalidArgument("The size of the state must be at least ", + min_state_size, "; got ", state_size); + } + return absl::OkStatus(); +} + +absl::StatusOr ResolveAlg(int alg_id) { + switch (alg_id) { + case RNG_ALG_PHILOX: + return xla::RandomAlgorithm::RNG_PHILOX; + case RNG_ALG_THREEFRY: + return xla::RandomAlgorithm::RNG_THREE_FRY; + case RNG_ALG_AUTO_SELECT: + // For AUTO_SELECT, we'll manage the counter as if it's for Philox. + return xla::RandomAlgorithm::RNG_PHILOX; + default: + return errors::InvalidArgument("Unsupported algorithm id: ", alg_id); + } +} + +absl::StatusOr GetAlg(XlaOpKernelContext* ctx, + int alg_input_idx) { + TF_ASSIGN_OR_RETURN(auto alg_id, GetAlgId(ctx, alg_input_idx)); + return ResolveAlg(alg_id); +} + +std::pair CounterAndKeyFromVariable( + xla::RandomAlgorithm alg, xla::XlaOp var) { + auto counter_size = GetCounterSize(alg); + auto counter = + BitcastConvertType(xla::Slice(var, {0}, {counter_size}, {1}), xla::U64); + if (counter_size == 1) { + counter = xla::Reshape(counter, {}); + } + // Slicing by [-1:] may be slightly better than by + // [counter_size:counter_size+1], but -1 requires var_size. + auto key = BitcastConvertType( + xla::Slice(var, {counter_size}, {counter_size + 1}, {1}), xla::U64); + key = xla::Reshape(key, {}); + return std::make_pair(counter, key); +} + +xla::XlaOp CounterAndKeyToVariable(xla::RandomAlgorithm alg, xla::XlaOp state, + xla::XlaOp key) { + auto builder = state.builder(); + switch (alg) { + case xla::RandomAlgorithm::RNG_PHILOX: + return ConcatInDim(builder, {state, xla::Reshape(key, {1})}, 0); + case xla::RandomAlgorithm::RNG_THREE_FRY: // fall through + case xla::RandomAlgorithm::RNG_DEFAULT: // fall through + default: + return ConcatScalars(builder, {state, key}); + } +} + +// A helper function containing the common part of several kernels below. +// Precondition: 'algorithm' and 'shape' are compile-time constants. +absl::Status CompileImpl( + XlaOpKernelContext* ctx, int state_input_idx, int alg_input_idx, + int shape_input_idx, + std::function const& sampler) { + TF_ASSIGN_OR_RETURN(auto alg, GetAlg(ctx, alg_input_idx)); + + xla::XlaOp var; + TensorShape var_shape; + TF_RETURN_IF_ERROR(ctx->ReadVariableInput( + state_input_idx, STATE_ELEMENT_DTYPE, &var_shape, &var)); + TF_RETURN_IF_ERROR(CheckStateShape(alg, var_shape)); + TensorShape shape; + TF_RETURN_IF_ERROR(ctx->ConstantInputAsShape(shape_input_idx, &shape)); + xla::XlaOp state; + xla::XlaOp key; + std::tie(state, key) = CounterAndKeyFromVariable(alg, var); + auto status_or_value = sampler(alg, state, key, shape); + if (!status_or_value.ok()) { + return status_or_value.status(); + } + xla::RngOutput value_state = std::move(status_or_value).value(); + state = value_state.state; + ctx->SetOutput(0, value_state.value); + var = CounterAndKeyToVariable(alg, state, key); + xla::PrimitiveType state_element_type; + TF_RETURN_IF_ERROR( + DataTypeToPrimitiveType(STATE_ELEMENT_DTYPE, &state_element_type)); + var = BitcastConvertType(var, state_element_type); + TF_RETURN_IF_ERROR( + ctx->AssignVariable(state_input_idx, STATE_ELEMENT_DTYPE, var)); + return absl::OkStatus(); +} + +class StatefulUniformOp : public XlaOpKernel { + public: + explicit StatefulUniformOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* builder = ctx->builder(); + auto sampler = [builder, this](xla::RandomAlgorithm alg, xla::XlaOp state, + xla::XlaOp key, + TensorShape shape) -> SamplerReturnType { + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + xla::PrimitiveType rng_primitive_type = xla_shape.element_type(); + xla::RngOutput uniform_state = StatefulRngUniform( + alg, key, state, xla_shape, + xla::ConstantR0WithType(builder, rng_primitive_type, 0.0), + xla::ConstantR0WithType(builder, rng_primitive_type, 1.0)); + xla::XlaOp uniform = uniform_state.value; + state = uniform_state.state; + uniform = MaybeConvertF32ToBF16(uniform, dtype_); + return {{uniform, state}}; + }; + OP_REQUIRES_OK(ctx, + CompileImpl(ctx, /*state_input_idx=*/0, /*alg_input_idx=*/1, + /*shape_input_idx=*/2, sampler)); + } + + private: + DataType dtype_; + + StatefulUniformOp(const StatefulUniformOp&) = delete; + void operator=(const StatefulUniformOp&) = delete; +}; + +// TODO(wangpeng): Support plain float16 to get rid of the `TypeConstraint`. +REGISTER_XLA_OP(Name("StatefulUniform") + .CompileTimeConstantInput("algorithm") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_DOUBLE, DT_FLOAT, DT_HALF, + DT_BFLOAT16}), + StatefulUniformOp); + +class StatefulStandardNormalOp : public XlaOpKernel { + public: + explicit StatefulStandardNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + auto sampler = + // Needs explicit lambda return type because it fails to be inferred. + [this](xla::RandomAlgorithm alg, xla::XlaOp state, xla::XlaOp key, + TensorShape shape) -> SamplerReturnType { + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + xla::RngOutput value_state = xla::NormalFloatingPointDistribution( + key, state, BitGen(alg), xla_shape); + xla::XlaOp normal = MaybeConvertF32ToBF16(value_state.value, dtype_); + return {{normal, value_state.state}}; + }; + OP_REQUIRES_OK(ctx, + CompileImpl(ctx, /*state_input_idx=*/0, /*alg_input_idx=*/1, + /*shape_input_idx=*/2, sampler)); + } + + private: + DataType dtype_; + + StatefulStandardNormalOp(const StatefulStandardNormalOp&) = delete; + void operator=(const StatefulStandardNormalOp&) = delete; +}; + +// TODO(wangpeng): Support plain float16 to get rid of the `TypeConstraint`. +REGISTER_XLA_OP(Name("StatefulStandardNormalV2") + .CompileTimeConstantInput("algorithm") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_DOUBLE, DT_FLOAT, DT_HALF, + DT_BFLOAT16}), + StatefulStandardNormalOp); + +class StatefulTruncatedNormalOp : public XlaOpKernel { + public: + explicit StatefulTruncatedNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* builder = ctx->builder(); + auto sampler = + // Needs explicit lambda return type because it fails to be inferred. + [builder, this](xla::RandomAlgorithm alg, xla::XlaOp state, + xla::XlaOp key, + TensorShape shape) -> SamplerReturnType { + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + + xla::RngOutput uniform_result = StatefulRngUniform( + alg, key, state, xla_shape, + xla::MinPositiveNormalValue(builder, xla_shape.element_type()), + xla::One(builder, xla_shape.element_type())); + xla::XlaOp uniform = uniform_result.value; + state = uniform_result.state; + xla::XlaOp truncated_normal = TruncatedNormal(uniform); + truncated_normal = MaybeConvertF32ToBF16(truncated_normal, dtype_); + return {{truncated_normal, state}}; + }; + OP_REQUIRES_OK(ctx, + CompileImpl(ctx, /*state_input_idx=*/0, /*alg_input_idx=*/1, + /*shape_input_idx=*/2, sampler)); + } + + private: + DataType dtype_; + + StatefulTruncatedNormalOp(const StatefulTruncatedNormalOp&) = delete; + void operator=(const StatefulTruncatedNormalOp&) = delete; +}; + +// TODO(wangpeng): Support plain float16 to get rid of the `TypeConstraint`. +REGISTER_XLA_OP(Name("StatefulTruncatedNormal") + .CompileTimeConstantInput("algorithm") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_DOUBLE, DT_FLOAT, DT_HALF, + DT_BFLOAT16}), + StatefulTruncatedNormalOp); + +class StatefulUniformIntOp : public XlaOpKernel { + public: + explicit StatefulUniformIntOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp minval = ctx->Input(3); + xla::XlaOp maxval = ctx->Input(4); + auto sample_with_threefry = [minval, maxval, this]( + xla::RandomAlgorithm alg, xla::XlaOp state, + xla::XlaOp key, + TensorShape shape) -> SamplerReturnType { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dtype_, shape, &xla_shape)); + return StatefulRngUniform(alg, key, state, xla_shape, minval, maxval); + }; + OP_REQUIRES_OK(ctx, + CompileImpl(ctx, /*state_input_idx=*/0, /*alg_input_idx=*/1, + /*shape_input_idx=*/2, sample_with_threefry)); + } + + private: + DataType dtype_; + + StatefulUniformIntOp(const StatefulUniformIntOp&) = delete; + void operator=(const StatefulUniformIntOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatefulUniformInt") + .CompileTimeConstantInput("algorithm") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", + {DT_INT32, DT_UINT32, DT_INT64, DT_UINT64}), + StatefulUniformIntOp); + +class StatefulUniformFullIntOp : public XlaOpKernel { + public: + explicit StatefulUniformFullIntOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + auto sample_with_threefry = [this](xla::RandomAlgorithm alg, + xla::XlaOp state, xla::XlaOp key, + TensorShape shape) -> SamplerReturnType { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dtype_, shape, &xla_shape)); + return StatefulRngUniformFullInt(alg, key, state, xla_shape); + }; + OP_REQUIRES_OK(ctx, + CompileImpl(ctx, /*state_input_idx=*/0, /*alg_input_idx=*/1, + /*shape_input_idx=*/2, sample_with_threefry)); + } + + private: + DataType dtype_; + + StatefulUniformFullIntOp(const StatefulUniformFullIntOp&) = delete; + void operator=(const StatefulUniformFullIntOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatefulUniformFullInt") + .CompileTimeConstantInput("algorithm") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", + {DT_INT32, DT_UINT32, DT_INT64, DT_UINT64}), + StatefulUniformFullIntOp); + +xla::XlaOp IncreaseCounter(xla::RandomAlgorithm const& alg, xla::XlaOp counter, + xla::XlaOp delta) { + // Multiplying 256 to be consistent with the CPU/GPU kernels + delta = delta * ConstantR0WithType(delta.builder(), xla::U64, 256); + switch (alg) { + case xla::RandomAlgorithm::RNG_PHILOX: + return xla::PhiloxIncreaseCounter(counter, delta); + case xla::RandomAlgorithm::RNG_THREE_FRY: // fall through + case xla::RandomAlgorithm::RNG_DEFAULT: // fall through + default: + return counter + delta; + } +} + +xla::XlaOp PadRight(xla::XlaOp a, int n) { + return xla::Pad(a, xla::ScalarLike(a, 0), + xla::MakeEdgePaddingConfig({{0, n}})); +} + +template +class RngSkipOp : public XlaOpKernel { + public: + explicit RngSkipOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const int state_input_idx = 0; + const int alg_input_idx = 1; + const int delta_input_idx = 2; + xla::XlaOp var; + TensorShape var_shape; + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput(state_input_idx, STATE_ELEMENT_DTYPE, + &var_shape, &var)); + // GetAlg will treat RNG_ALG_AUTO_SELECT as RNG_ALG_PHILOX. + OP_REQUIRES_VALUE(auto alg, ctx, GetAlg(ctx, alg_input_idx)); + OP_REQUIRES_OK(ctx, CheckStateShape(alg, var_shape)); + if (read_old_value) { + auto counter_size = GetCounterSize(alg); + xla::XlaOp output = var; + if (RNG_MAX_COUNTER_SIZE > counter_size) { + // Because the size of `var` depends on the algorithm while we want the + // output to have a fixed size (to help shape inference), we fix the + // output size to be the maximal state size among algorithms, and right- + // pad it with zeros if var's size is smaller than that. + output = PadRight(output, RNG_MAX_COUNTER_SIZE - counter_size); + } + ctx->SetOutput(0, output); + } + xla::XlaOp counter; + xla::XlaOp key; + std::tie(counter, key) = CounterAndKeyFromVariable(alg, var); + xla::XlaOp delta = ctx->Input(delta_input_idx); + delta = BitcastConvertType(delta, xla::U64); + auto new_counter = IncreaseCounter(alg, counter, delta); + var = CounterAndKeyToVariable(alg, new_counter, key); + xla::PrimitiveType state_element_type; + OP_REQUIRES_OK( + ctx, DataTypeToPrimitiveType(STATE_ELEMENT_DTYPE, &state_element_type)); + var = BitcastConvertType(var, state_element_type); + OP_REQUIRES_OK( + ctx, ctx->AssignVariable(state_input_idx, STATE_ELEMENT_DTYPE, var)); + } + + private: + RngSkipOp(const RngSkipOp&) = delete; + void operator=(const RngSkipOp&) = delete; +}; + +REGISTER_XLA_OP(Name("RngSkip").CompileTimeConstantInput("algorithm"), + RngSkipOp<>); + +using RngReadAndSkipOp = RngSkipOp; + +REGISTER_XLA_OP(Name("RngReadAndSkip").CompileTimeConstantInput("alg"), + RngReadAndSkipOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateless_random_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateless_random_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..1ad76acfcacfb7ffa051fddd4ed4bf3fcb8dac20 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateless_random_ops.cc @@ -0,0 +1,469 @@ +/* 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 +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/kernels/random_ops_util.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/lib/random.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/prng.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +namespace { + +xla::BitGeneratorTy GetBitGeneratorForDevice( + absl::string_view device_type_string) { + // The Philox algorithm may cause performance regression on other devices. + // Turn on the Philox algorithm for the CPU and GPU backends only. + if (device_type_string == DEVICE_GPU_XLA_JIT || + device_type_string == DEVICE_CPU_XLA_JIT) { + return [=](xla::XlaOp key, xla::XlaOp state, const xla::Shape& shape) { + std::tie(state, key) = xla::ScramblePhiloxKey(key); + xla::XlaOp philox_state = + xla::ConcatInDim(key.builder(), {xla::Reshape(key, {1}), state}, 0); + xla::XlaOp result = xla::RngBitGenerator(xla::RandomAlgorithm::RNG_PHILOX, + philox_state, shape); + return xla::RngOutput{/*value=*/xla::GetTupleElement(result, 1), + /*state=*/xla::GetTupleElement(result, 0)}; + }; + } + return [=](xla::XlaOp key, xla::XlaOp state, const xla::Shape& shape) { + state = xla::ConcatScalars(key.builder(), {key, state}); + xla::XlaOp result = + xla::RngBitGenerator(xla::RandomAlgorithm::RNG_DEFAULT, state, shape); + return xla::RngOutput{/*value=*/xla::GetTupleElement(result, 1), + /*state=*/xla::GetTupleElement(result, 0)}; + }; +} + +} // namespace + +xla::XlaOp MaybeConvertF32ToBF16(xla::XlaOp input, DataType dtype) { + if (dtype == DT_BFLOAT16) { + xla::XlaBuilder* builder = input.builder(); + // TODO(b/256243456): Instead of doing + // `ConvertElementType(BitcastConvertType(u32, F32), BF16)` we should do + // `BitcastConvertType(ConvertElementType(u32, U16), BF16)`, to avoid the + // unclear `ConvertElementType(f32, BF16)` behavior. + xla::XlaOp output = xla::BitcastConvertType(input, xla::U32) & + xla::ConstantR0(builder, 0xFFFF0000); + return xla::ConvertElementType(xla::BitcastConvertType(output, xla::F32), + xla::BF16); + } else { + return input; + } +} + +xla::XlaOp StatelessRngUniform(absl::string_view device_type_string, + xla::XlaOp seeds, const xla::Shape& shape, + xla::XlaOp minval, xla::XlaOp maxval) { + xla::XlaBuilder* builder = seeds.builder(); + + xla::XlaOp seed0 = xla::Reshape(xla::Slice(seeds, {0}, {1}, {1}), {}); + xla::XlaOp seed1 = xla::Reshape(xla::Slice(seeds, {1}, {2}, {1}), {}); + xla::XlaOp key = GetU64FromS32Seeds(seed0, seed1); + xla::XlaOp initial_state = xla::ConstantR0WithType(builder, xla::U64, 0); + xla::PrimitiveType type = shape.element_type(); + switch (type) { + case xla::F16: + case xla::F32: + case xla::F64: + return xla::UniformFloatingPointDistribution( + key, initial_state, + GetBitGeneratorForDevice(device_type_string), minval, maxval, + shape) + .value; + case xla::S32: + case xla::S64: + return UniformIntDistribution( + key, initial_state, + GetBitGeneratorForDevice(device_type_string), minval, maxval, + shape) + .value; + break; + default: + return builder->ReportError(xla::Unimplemented( + "Types other than F16, F32, S32 and S64 are not implemented by " + "StatelessRngUniform; got %s", + xla::primitive_util::LowercasePrimitiveTypeName(type))); + } +} + +namespace { + +xla::XlaOp StatelessRngUniformFullInt(absl::string_view device_type_string, + xla::XlaOp seeds, + const xla::Shape& shape) { + xla::XlaBuilder* builder = seeds.builder(); + + xla::XlaOp seed0 = xla::Reshape(xla::Slice(seeds, {0}, {1}, {1}), {}); + xla::XlaOp seed1 = xla::Reshape(xla::Slice(seeds, {1}, {2}, {1}), {}); + xla::XlaOp key = GetU64FromS32Seeds(seed0, seed1); + xla::XlaOp initial_state = xla::ConstantR0WithType(builder, xla::U64, 0); + xla::PrimitiveType type = shape.element_type(); + xla::RngOutput output = + GetBitGeneratorForDevice(device_type_string)(key, initial_state, shape); + switch (type) { + case xla::U32: + case xla::U64: + return output.value; + case xla::S32: + case xla::S64: + return BitcastConvertType(output.value, type); + default: + return builder->ReportError(xla::Unimplemented( + "Types other than U32, S32, U64 and S64 are not implemented by " + "StatelessRngUniformFullInt; got: %s", + xla::primitive_util::LowercasePrimitiveTypeName(type))); + } +} + +class StatelessRandomUniformOp : public XlaOpKernel { + public: + explicit StatelessRandomUniformOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* builder = ctx->builder(); + + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + TensorShape seed_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, seed_shape.dims() == 1 && seed_shape.dim_size(0) == 2, + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + xla::XlaOp seed = ctx->Input(1); + + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + xla::PrimitiveType rng_primitive_type = xla_shape.element_type(); + + xla::XlaOp uniform = StatelessRngUniform( + device_type_string_, seed, xla_shape, + xla::ConstantR0WithType(builder, rng_primitive_type, 0.0), + xla::ConstantR0WithType(builder, rng_primitive_type, 1.0)); + uniform = MaybeConvertF32ToBF16(uniform, dtype_); + ctx->SetOutput(0, uniform); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomUniformOp(const StatelessRandomUniformOp&) = delete; + void operator=(const StatelessRandomUniformOp&) = delete; +}; + +// TODO(phawkins): generalize to non-float, non-int32 seed types. +REGISTER_XLA_OP(Name("StatelessRandomUniform") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", + {DT_DOUBLE, DT_FLOAT, DT_HALF, DT_BFLOAT16}) + .TypeConstraint("Tseed", DT_INT32), + StatelessRandomUniformOp); + +class StatelessRandomUniformIntOp : public XlaOpKernel { + public: + explicit StatelessRandomUniformIntOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + TensorShape seed_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, seed_shape.dims() == 1 && seed_shape.dim_size(0) == 2, + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + TensorShape minval_shape = ctx->InputShape(2); + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(minval_shape), + absl::InvalidArgumentError(absl::StrCat( + "minval must be scalar, got shape ", minval_shape.DebugString()))); + TensorShape maxval_shape = ctx->InputShape(3); + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(maxval_shape), + absl::InvalidArgumentError(absl::StrCat( + "minval must be scalar, got shape ", maxval_shape.DebugString()))); + + xla::XlaOp seed = ctx->Input(1); + xla::XlaOp minval = ctx->Input(2); + xla::XlaOp maxval = ctx->Input(3); + + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype_, shape, &xla_shape)); + xla::XlaOp uniform = StatelessRngUniform(device_type_string_, seed, + xla_shape, minval, maxval); + + ctx->SetOutput(0, uniform); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomUniformIntOp(const StatelessRandomUniformIntOp&) = delete; + void operator=(const StatelessRandomUniformIntOp&) = delete; +}; + +// TODO(phawkins): generalize to non-int32 seed types. +REGISTER_XLA_OP(Name("StatelessRandomUniformInt") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_INT32, DT_INT64}) + .TypeConstraint("Tseed", DT_INT32), + StatelessRandomUniformIntOp); + +class StatelessRandomUniformFullIntOp : public XlaOpKernel { + public: + explicit StatelessRandomUniformFullIntOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + TensorShape seed_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, seed_shape.dims() == 1 && seed_shape.dim_size(0) == 2, + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + + xla::XlaOp seed = ctx->Input(1); + + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype_, shape, &xla_shape)); + xla::XlaOp uniform = + StatelessRngUniformFullInt(device_type_string_, seed, xla_shape); + + ctx->SetOutput(0, uniform); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomUniformFullIntOp(const StatelessRandomUniformFullIntOp&) = + delete; + void operator=(const StatelessRandomUniformFullIntOp&) = delete; +}; + +// TODO(phawkins): generalize to non-int32 seed types. +REGISTER_XLA_OP(Name("StatelessRandomUniformFullInt") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_INT32, DT_INT64}) + .TypeConstraint("Tseed", DT_INT32), + StatelessRandomUniformFullIntOp); + +class StatelessRandomNormalOp : public XlaOpKernel { + public: + explicit StatelessRandomNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + TensorShape seed_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, seed_shape == TensorShape({2}), + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + xla::XlaOp seed = ctx->Input(1); + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + + xla::XlaBuilder* builder = seed.builder(); + xla::XlaOp seed0 = xla::Reshape(xla::Slice(seed, {0}, {1}, {1}), {}); + xla::XlaOp seed1 = xla::Reshape(xla::Slice(seed, {1}, {2}, {1}), {}); + xla::XlaOp initial_state = xla::ConstantR0WithType(builder, xla::U64, 0); + + xla::XlaOp key = GetU64FromS32Seeds(seed0, seed1); + xla::XlaOp normal = + xla::NormalFloatingPointDistribution( + key, initial_state, GetBitGeneratorForDevice(device_type_string_), + xla_shape) + .value; + normal = MaybeConvertF32ToBF16(normal, dtype_); + ctx->SetOutput(0, normal); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomNormalOp(const StatelessRandomNormalOp&) = delete; + void operator=(const StatelessRandomNormalOp&) = delete; +}; + +// TODO(phawkins): generalize to non-float, non-int32 seed types. +REGISTER_XLA_OP(Name("StatelessRandomNormal") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", + {DT_DOUBLE, DT_FLOAT, DT_HALF, DT_BFLOAT16}) + .TypeConstraint("Tseed", DT_INT32), + StatelessRandomNormalOp); + +class StatelessTruncatedNormalOp : public XlaOpKernel { + public: + explicit StatelessTruncatedNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + TensorShape seed_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, seed_shape == TensorShape({2}), + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + xla::XlaOp seed = ctx->Input(1); + xla::XlaBuilder* builder = ctx->builder(); + + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + xla::XlaOp uniform = StatelessRngUniform( + device_type_string_, seed, xla_shape, + xla::MinPositiveNormalValue(builder, xla_shape.element_type()), + xla::One(builder, xla_shape.element_type())); + xla::XlaOp truncated_normal = TruncatedNormal(uniform); + truncated_normal = MaybeConvertF32ToBF16(truncated_normal, dtype_); + ctx->SetOutput(0, truncated_normal); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessTruncatedNormalOp(const StatelessTruncatedNormalOp&) = delete; + void operator=(const StatelessTruncatedNormalOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessTruncatedNormal") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", + {DT_DOUBLE, DT_FLOAT, DT_HALF, DT_BFLOAT16}) + .TypeConstraint("Tseed", DT_INT32), + StatelessTruncatedNormalOp); + +class StatelessParameterizedTruncatedNormalOp : public XlaOpKernel { + public: + explicit StatelessParameterizedTruncatedNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + TensorShape seed_shape = ctx->InputShape(1); + OP_REQUIRES( + ctx, seed_shape == TensorShape({2}), + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + xla::XlaOp seed = ctx->Input(1); + xla::XlaBuilder* builder = ctx->builder(); + + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + + auto bcasted_means = BroadcastTo(ctx->Input(2), shape.dim_sizes()); + OP_REQUIRES_OK(ctx, bcasted_means.status()); + auto means = bcasted_means.value(); + + auto bcasted_stddevs = BroadcastTo(ctx->Input(3), shape.dim_sizes()); + OP_REQUIRES_OK(ctx, bcasted_stddevs.status()); + auto stddevs = bcasted_stddevs.value(); + + auto bcasted_minvals = BroadcastTo(ctx->Input(4), shape.dim_sizes()); + OP_REQUIRES_OK(ctx, bcasted_minvals.status()); + auto minvals = bcasted_minvals.value(); + + auto bcasted_maxvals = BroadcastTo(ctx->Input(5), shape.dim_sizes()); + OP_REQUIRES_OK(ctx, bcasted_maxvals.status()); + auto maxvals = bcasted_maxvals.value(); + + xla::XlaOp uniform = StatelessRngUniform( + device_type_string_, seed, xla_shape, + xla::MinPositiveNormalValue(builder, xla_shape.element_type()), + xla::One(builder, xla_shape.element_type())); + xla::XlaOp truncated_normal = + ParameterizedTruncatedNormal(uniform, means, stddevs, minvals, maxvals); + truncated_normal = MaybeConvertF32ToBF16(truncated_normal, dtype_); + ctx->SetOutput(0, truncated_normal); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessParameterizedTruncatedNormalOp( + const StatelessParameterizedTruncatedNormalOp&) = delete; + void operator=(const StatelessParameterizedTruncatedNormalOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessParameterizedTruncatedNormal") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", + {DT_DOUBLE, DT_FLOAT, DT_HALF, DT_BFLOAT16}) + .TypeConstraint("Tseed", DT_INT32), + StatelessParameterizedTruncatedNormalOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateless_random_ops_v2.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateless_random_ops_v2.cc new file mode 100644 index 0000000000000000000000000000000000000000..a2b89281a4fac936e2276f1427ba4e717c44466a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stateless_random_ops_v2.cc @@ -0,0 +1,450 @@ +/* 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/core/kernels/stateless_random_ops_v2.h" + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/kernels/random_ops_util.h" +#include "tensorflow/compiler/tf2xla/kernels/rng_converter_utils.h" +#include "tensorflow/compiler/tf2xla/lib/random.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/lib/prng.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/rng_alg.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +namespace { +std::tuple GetKeyCounter( + absl::string_view device_type_string, xla::XlaOp key) { + // The Philox algorithm may cause performance regression on other devices. + // Turn on the Philox algorithm for the CPU and GPU backends only. + if (device_type_string == DEVICE_GPU_XLA_JIT || + device_type_string == DEVICE_CPU_XLA_JIT) { + auto counter_key = xla::ScramblePhiloxKey(key); + return std::make_tuple(counter_key.second, counter_key.first); + } else { + auto counter_shape = + xla::ShapeUtil::MakeShape(xla::U64, {RNG_MAX_COUNTER_SIZE}); + auto counter = xla::Zeros(key.builder(), counter_shape); + return std::make_tuple(key, counter); + } +} +} // namespace + +namespace { + +xla::RngOutput StatelessRngUniformFullInt(xla::RandomAlgorithm const& alg, + xla::XlaOp key, xla::XlaOp counter, + const xla::Shape& shape) { + xla::XlaBuilder* builder = key.builder(); + + xla::PrimitiveType type = shape.element_type(); + xla::RngOutput output = BitGenerator(alg, key, counter, shape); + switch (type) { + case xla::U32: + case xla::U64: + return output; + case xla::S32: + case xla::S64: + return xla::RngOutput{BitcastConvertType(output.value, type), + output.state}; + default: + return { + builder->ReportError(xla::Unimplemented( + "Types other than U32, S32, U64 and S64 are not implemented by " + "StatelessRngUniformFullInt; got: %s", + xla::primitive_util::LowercasePrimitiveTypeName(type))), + output.state}; + } +} + +class StatelessRandomUniformOp : public XlaOpKernel { + public: + explicit StatelessRandomUniformOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape( + 0, &shape, xla::ValueInferenceMode::kUpperBound)); + absl::StatusOr randoms_or = BuildUniformRandoms( + ctx, dtype_, device_type_string_, shape, xla::Zero, xla::One); + OP_REQUIRES_OK(ctx, randoms_or.status()); + xla::XlaOp uniform = MaybeConvertF32ToBF16(randoms_or.value(), dtype_); + + // If the input shape is constant, no need to set dimension sizes. + // TODO(hinsu): Simplify this once MLIR bridge can handle bounded types. + TensorShape static_shape; + absl::Status status = ctx->ConstantInputAsShape(0, &static_shape); + if (status.ok()) { + ctx->SetOutput(0, uniform); + return; + } + + auto result_or = xla::SetAllDimensionSizes(&ctx->value_inference(), uniform, + ctx->Input(0)); + OP_REQUIRES_OK(ctx, result_or.status()); + ctx->SetOutput(0, result_or.value()); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomUniformOp(const StatelessRandomUniformOp&) = delete; + void operator=(const StatelessRandomUniformOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessRandomUniformV2") + .CompileTimeConstantInput("shape") + .CompileTimeConstantInput("alg") + .TypeConstraint("dtype", {DT_DOUBLE, DT_FLOAT, DT_HALF, + DT_BFLOAT16}), + StatelessRandomUniformOp); + +class StatelessRandomUniformIntOp : public XlaOpKernel { + public: + explicit StatelessRandomUniformIntOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + const int minval_input_idx = 4; + const int maxval_input_idx = 5; + TensorShape minval_shape = ctx->InputShape(minval_input_idx); + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(minval_shape), + absl::InvalidArgumentError(absl::StrCat( + "minval must be scalar, got shape ", minval_shape.DebugString()))); + TensorShape maxval_shape = ctx->InputShape(maxval_input_idx); + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(maxval_shape), + absl::InvalidArgumentError(absl::StrCat( + "maxval must be scalar, got shape ", maxval_shape.DebugString()))); + xla::XlaOp minval = ctx->Input(minval_input_idx); + xla::XlaOp maxval = ctx->Input(maxval_input_idx); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype_, shape, &xla_shape)); + + absl::StatusOr result_or = BuildUniformRandoms( + ctx, dtype_, device_type_string_, xla_shape, minval, maxval); + OP_REQUIRES_OK(ctx, result_or.status()); + ctx->SetOutput(0, result_or.value()); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomUniformIntOp(const StatelessRandomUniformIntOp&) = delete; + void operator=(const StatelessRandomUniformIntOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessRandomUniformIntV2") + .CompileTimeConstantInput("shape") + .CompileTimeConstantInput("alg") + .TypeConstraint("dtype", + {DT_INT32, DT_INT64, DT_UINT32, DT_UINT64}), + StatelessRandomUniformIntOp); + +class StatelessRandomUniformFullIntOp : public XlaOpKernel { + public: + explicit StatelessRandomUniformFullIntOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + + xla::XlaOp key = ctx->Input(kRandomKeyInputIdx); + xla::XlaOp counter = ctx->Input(kRandomCounterInputIdx); + + OP_REQUIRES_VALUE( + auto alg, ctx, + AlgorithmFromInput(ctx, kRandomAlgInputIdx, device_type_string_)); + + auto counter_shape = ctx->InputShape(kRandomCounterInputIdx); + OP_REQUIRES_OK(ctx, + CheckKeyCounterShape(xla::GetCounterSize(alg), + ctx->InputShape(kRandomKeyInputIdx), + counter_shape)); + + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(dtype_, shape, &xla_shape)); + + counter = MaybeSliceCounter(alg, counter_shape, counter); + auto result = StatelessRngUniformFullInt(alg, key, counter, xla_shape); + ctx->SetOutput(0, result.value); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomUniformFullIntOp(const StatelessRandomUniformFullIntOp&) = + delete; + void operator=(const StatelessRandomUniformFullIntOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessRandomUniformFullIntV2") + .CompileTimeConstantInput("shape") + .CompileTimeConstantInput("alg") + .TypeConstraint("dtype", + {DT_INT32, DT_INT64, DT_UINT32, DT_UINT64}), + StatelessRandomUniformFullIntOp); + +class StatelessRandomNormalOp : public XlaOpKernel { + public: + explicit StatelessRandomNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape( + 0, &shape, xla::ValueInferenceMode::kUpperBound)); + + xla::XlaOp key = ctx->Input(kRandomKeyInputIdx); + xla::XlaOp counter = ctx->Input(kRandomCounterInputIdx); + + OP_REQUIRES_VALUE( + auto alg, ctx, + AlgorithmFromInput(ctx, kRandomAlgInputIdx, device_type_string_)); + + auto counter_shape = ctx->InputShape(kRandomCounterInputIdx); + OP_REQUIRES_OK(ctx, + CheckKeyCounterShape(xla::GetCounterSize(alg), + ctx->InputShape(kRandomKeyInputIdx), + counter_shape)); + + auto rng_dtype = MaybeConvertBF16ToF32(dtype_); + xla::Shape xla_shape; + OP_REQUIRES_OK(ctx, TensorShapeToXLAShape(rng_dtype, shape, &xla_shape)); + + using std::placeholders::_1; + using std::placeholders::_2; + using std::placeholders::_3; + auto generator = std::bind(BitGenerator, alg, _1, _2, _3); + counter = MaybeSliceCounter(alg, counter_shape, counter); + auto result = xla::NormalFloatingPointDistribution(key, counter, generator, + xla_shape); + auto normal = MaybeConvertF32ToBF16(result.value, dtype_); + + // If the input shape is constant, no need to set dimension sizes. + // TODO(hinsu): Simplify this once MLIR bridge can handle bounded types. + TensorShape static_shape; + absl::Status status = ctx->ConstantInputAsShape(0, &static_shape); + if (status.ok()) { + ctx->SetOutput(0, normal); + return; + } + + auto result_or = xla::SetAllDimensionSizes(&ctx->value_inference(), normal, + ctx->Input(0)); + OP_REQUIRES_OK(ctx, result_or.status()); + ctx->SetOutput(0, result_or.value()); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessRandomNormalOp(const StatelessRandomNormalOp&) = delete; + void operator=(const StatelessRandomNormalOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessRandomNormalV2") + .CompileTimeConstantInput("shape") + .CompileTimeConstantInput("alg") + .TypeConstraint("dtype", {DT_DOUBLE, DT_FLOAT, DT_HALF, + DT_BFLOAT16}), + StatelessRandomNormalOp); + +class StatelessTruncatedNormalOp : public XlaOpKernel { + public: + explicit StatelessTruncatedNormalOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsShape(0, &shape)); + auto result_or = + BuildUniformRandoms(ctx, dtype_, device_type_string_, shape, + xla::MinPositiveNormalValue, xla::One); + OP_REQUIRES_OK(ctx, result_or.status()); + xla::XlaOp truncated_normal = TruncatedNormal(result_or.value()); + truncated_normal = MaybeConvertF32ToBF16(truncated_normal, dtype_); + ctx->SetOutput(0, truncated_normal); + } + + private: + DataType dtype_; + std::string device_type_string_; + + StatelessTruncatedNormalOp(const StatelessTruncatedNormalOp&) = delete; + void operator=(const StatelessTruncatedNormalOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessTruncatedNormalV2") + .CompileTimeConstantInput("shape") + .CompileTimeConstantInput("alg") + .TypeConstraint("dtype", {DT_DOUBLE, DT_FLOAT, DT_HALF, + DT_BFLOAT16}), + StatelessTruncatedNormalOp); + +class GetKeyCounterOp : public XlaOpKernel { + public: + explicit GetKeyCounterOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) {} + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape seed_shape = ctx->InputShape(0); + OP_REQUIRES( + ctx, seed_shape == TensorShape({2}), + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + xla::XlaOp seed = ctx->Input(0); + + xla::XlaOp seed0 = xla::Reshape(xla::Slice(seed, {0}, {1}, {1}), {}); + xla::XlaOp seed1 = xla::Reshape(xla::Slice(seed, {1}, {2}, {1}), {}); + xla::XlaOp key = GetU64FromS32Seeds(seed0, seed1); + auto key_counter = GetKeyCounter(device_type_string_, key); + key = std::get<0>(key_counter); + auto counter = std::get<1>(key_counter); + key = xla::Reshape(key, {RNG_KEY_SIZE}); + ctx->SetOutput(0, key); + ctx->SetOutput(1, counter); + } + + private: + std::string device_type_string_; + + GetKeyCounterOp(const GetKeyCounterOp&) = delete; + void operator=(const GetKeyCounterOp&) = delete; +}; + +// TODO(hinsu): Dis-allow unsupported int64 seed types. +REGISTER_XLA_OP(Name("StatelessRandomGetKeyCounter"), GetKeyCounterOp); + +class GetAlgOp : public XlaOpKernel { + public: + explicit GetAlgOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) {} + + void Compile(XlaOpKernelContext* ctx) override { + auto alg = DefaultRngAlgForDeviceType(device_type_string_); + auto builder = ctx->builder(); + ctx->SetOutput( + 0, ConstantR0(builder, static_cast(ToTensorflowAlgorithm(alg)))); + } + + private: + std::string device_type_string_; + + GetAlgOp(const GetAlgOp&) = delete; + void operator=(const GetAlgOp&) = delete; +}; + +REGISTER_XLA_OP(Name("StatelessRandomGetAlg"), GetAlgOp); + +class GetKeyCounterAlgOp : public XlaOpKernel { + public: + explicit GetKeyCounterAlgOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) {} + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape seed_shape = ctx->InputShape(0); + OP_REQUIRES( + ctx, seed_shape == TensorShape({2}), + absl::InvalidArgumentError(absl::StrCat( + "seed must have shape [2], not ", seed_shape.DebugString()))); + xla::XlaOp seed = ctx->Input(0); + + xla::XlaBuilder* builder = seed.builder(); + xla::XlaOp seed0 = xla::Reshape(xla::Slice(seed, {0}, {1}, {1}), {}); + xla::XlaOp seed1 = xla::Reshape(xla::Slice(seed, {1}, {2}, {1}), {}); + xla::XlaOp key = GetU64FromS32Seeds(seed0, seed1); + auto key_counter = GetKeyCounter(device_type_string_, key); + key = std::get<0>(key_counter); + auto counter = std::get<1>(key_counter); + auto alg = DefaultRngAlgForDeviceType(device_type_string_); + key = xla::Reshape(key, {RNG_KEY_SIZE}); + ctx->SetOutput(0, key); + ctx->SetOutput(1, counter); + ctx->SetOutput( + 2, ConstantR0(builder, static_cast(ToTensorflowAlgorithm(alg)))); + } + + private: + std::string device_type_string_; + + GetKeyCounterAlgOp(const GetKeyCounterAlgOp&) = delete; + void operator=(const GetKeyCounterAlgOp&) = delete; +}; + +// TODO(hinsu): Dis-allow unsupported int64 seed types. +REGISTER_XLA_OP(Name("StatelessRandomGetKeyCounterAlg"), GetKeyCounterAlgOp); + +REGISTER_XLA_OP(Name("XlaRngBitGenerator") + .CompileTimeConstantInput("algorithm") + .CompileTimeConstantInput("shape") + .TypeConstraint("dtype", {DT_UINT8, DT_UINT32, DT_UINT64}), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stochastic_cast_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stochastic_cast_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..2c02aa213533413ba133020809ea87821e24de2f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/stochastic_cast_op.cc @@ -0,0 +1,83 @@ +/* Copyright 2023 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/stochastic_cast_op.h" + +#include + +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/kernels/random_ops_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class StochasticCastToInt : public XlaOpKernel { + static constexpr int kInputIndex = 0; + + public: + explicit StochasticCastToInt(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + device_type_string_(ctx->device_type().type_string()) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tin", &from_type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tout", &to_type_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape shape; + shape = ctx->InputShape(kInputIndex); + absl::StatusOr randoms_or = BuildUniformRandoms( + ctx, from_type_, device_type_string_, shape, xla::Zero, xla::One); + OP_REQUIRES_OK(ctx, randoms_or.status()); + xla::XlaOp input = ctx->Input(kInputIndex); + if (from_type_ == DT_BFLOAT16) { + input = xla::ConvertElementType(input, xla::F32); + } + xla::XlaOp result = xla::Select( + xla::Lt(input, xla::ScalarLike(input, 0)), + xla::Floor(xla::Add(input, randoms_or.value())), + xla::Floor(xla::Sub(xla::Add(input, xla::ScalarLike(input, 1)), + randoms_or.value()))); + result = xla::Select(xla::Eq(input, xla::Floor(input)), input, result); + xla::PrimitiveType to_type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(to_type_, &to_type)); + result = xla::ConvertElementType(result, to_type); + ctx->SetOutput(0, result); + } + + private: + DataType from_type_; + DataType to_type_; + std::string device_type_string_; +}; + +REGISTER_XLA_OP(Name("StochasticCastToInt") + .CompileTimeConstantInput("alg") + .TypeConstraint("Tin", + {DT_DOUBLE, DT_FLOAT, DT_HALF, DT_BFLOAT16}) + .TypeConstraint("Tout", {DT_INT32, DT_INT16, DT_INT8}), + StochasticCastToInt); +// TODO(b/232442915): add path to stochastically cast big floats to small +// floats. +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/strided_slice_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/strided_slice_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..54707ecf068b34997811ad4cce47b454ab8cb0cc --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/strided_slice_op.cc @@ -0,0 +1,779 @@ +/* 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/core/util/strided_slice_op.h" + +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/inlined_vector.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { +using errors::InvalidArgument; + +class StridedSliceOp : public XlaOpKernel { + public: + explicit StridedSliceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_)); + } + + void EmitDynamicSlice(XlaOpKernelContext* ctx, + const absl::InlinedVector& strides, + PartialTensorShape partial_processing_shape, + PartialTensorShape partial_final_shape, + const StridedSliceShapeSpec& shape_spec, + const std::vector& begins_are_dynamic, + const std::vector& ends_are_dynamic) { + const TensorShape input_shape = ctx->InputShape(0); + xla::XlaOp slice = ctx->Input(0); + for (int64_t i = 0; i < ctx->InputShape("begin").dims(); ++i) { + OP_REQUIRES(ctx, strides[i] == 1, + errors::InvalidArgument( + "Strides have to be one when inputs are not constant.")); + } + // Infer static output shape, reconcile unknown dimension with input dim + // size. + for (int64_t i = 0; i < partial_final_shape.dims(); ++i) { + if (partial_final_shape.dim_size(i) == -1) { + // Use input shape to update unknown dimension of partial shape -- if a + // dimension is unknown, we use input shape as bound. + partial_final_shape.set_dim( + i, + input_shape.dim_size(shape_spec.output_to_processing_mapping[i])); + } + } + + TensorShape final_shape; + OP_REQUIRES( + ctx, partial_final_shape.AsTensorShape(&final_shape), + InvalidArgument("XLA can't deduce compile time constant output " + "shape for strided slice: ", + partial_final_shape.DebugString(), + ", output shape must be a compile-time constant")); + for (int64_t i = 0; i < partial_processing_shape.dims(); ++i) { + if (partial_processing_shape.dim_size(i) == -1) { + // Use input shape to update unknown dimension of partial shape -- if a + // dimension is unknown, we use input shape as bound. + partial_processing_shape.set_dim(i, input_shape.dim_size(i)); + } + } + TensorShape processing_shape; + OP_REQUIRES( + ctx, partial_processing_shape.AsTensorShape(&processing_shape), + InvalidArgument("XLA can't deduce compile time constant processing " + "shape for strided slice: ", + partial_processing_shape.DebugString(), + ", output shape must be a compile-time constant")); + // If there is dynamic begin/end (and if the dimension is not shrunk), we + // need to use dynamic shape infrastructure -- we slice the output with + // full size, then call SetDimensionSize on the output. However, if we + // slice with the full size at a non-zero dimension we may get OOB access. + // To avoid that, we first pad the input to 2x before calling slice. + xla::PaddingConfig padding_config; + bool need_padding = false; + std::vector result_dims_are_dynamic; + const auto& dims = input_shape.dims(); + result_dims_are_dynamic.reserve(dims); + for (int64_t i = 0; i < dims; ++i) { + int64_t sparse_index = shape_spec.processing_to_sparse_mapping[i]; + bool shrink_axis_set = (1 << i) & shape_spec.shrink_axis_dense_mask; + auto* dims = padding_config.add_dimensions(); + dims->set_edge_padding_low(0); + + dims->set_interior_padding(0); + if (((begins_are_dynamic.size() > sparse_index && + begins_are_dynamic[sparse_index]) || + (ends_are_dynamic.size() > sparse_index && + ends_are_dynamic[sparse_index])) && + !shrink_axis_set) { + // Need to slice this dimension so pad first. + dims->set_edge_padding_high(input_shape.dim_size(i)); + need_padding = true; + result_dims_are_dynamic.push_back(true); + } else { + dims->set_edge_padding_high(0); + result_dims_are_dynamic.push_back(false); + } + } + + if (need_padding) { + // Pad input to 2x to avoid OOB access. + slice = xla::Pad(slice, xla::Zero(ctx->builder(), ctx->input_xla_type(0)), + padding_config); + for (int64_t i = 0; i < result_dims_are_dynamic.size(); ++i) { + if (result_dims_are_dynamic[i]) { + slice = xla::RemoveDynamicDimension(slice, i); + } + } + } + std::vector start_indices; + std::vector slice_sizes_dynamic; + xla::Shape input_xla_shape = ctx->InputXlaShape(0).value(); + for (int64_t i = 0; i < input_shape.dims(); ++i) { + bool begin_mask = (1 << i) & shape_spec.begin_dense_mask; + bool end_mask = (1 << i) & shape_spec.end_dense_mask; + auto zero = xla::Zero(ctx->builder(), ctx->InputXlaType("begin")); + xla::XlaOp begin_index, end_index; + int64_t sparse_index = shape_spec.processing_to_sparse_mapping[i]; + bool xla_input_is_dynamic = input_xla_shape.is_dynamic_dimension(i); + xla::XlaOp dim_size; + if (xla_input_is_dynamic) { + dim_size = xla::GetDimensionSize(ctx->Input(0), i); + OP_REQUIRES(ctx, ctx->InputXlaType("begin") == xla::S32, + errors::InvalidArgument("'begin shape has to be int32 when " + "indices to slice op are dynamic")); + } else { + dim_size = + xla::ConstantR0WithType(ctx->builder(), ctx->InputXlaType("begin"), + input_xla_shape.dimensions(i)); + } + + auto scalar_must_be_non_negative = [ctx](xla::XlaOp value) -> bool { + // Check if the lower-bound of a value is always >= 0 + auto lower_bound = ctx->value_inference().AnalyzeConstant( + value, xla::ValueInferenceMode::kLowerBound); + if (!lower_bound.ok() || !lower_bound->AllValid()) { + // Can't infer a lower bound. + return false; + } + return lower_bound->Get({}) >= 0; + }; + if (begin_mask) { + begin_index = zero; + } else { + begin_index = xla::Slice(ctx->Input("begin"), {sparse_index}, + {sparse_index + 1}, {1}); + begin_index = xla::Reshape(begin_index, {}); + if (!scalar_must_be_non_negative(begin_index)) { + // begin could be negative. + auto index_negative = xla::Lt(begin_index, zero); + auto wrapped_index = xla::Add(dim_size, begin_index); + // Wrap negative indices around. + begin_index = xla::Select(index_negative, wrapped_index, begin_index); + } + } + if (result_dims_are_dynamic[i]) { + begin_index = xla::Max(xla::Min(begin_index, dim_size), zero); + } + start_indices.push_back(begin_index); + if (end_mask) { + end_index = dim_size; + } else { + end_index = xla::Slice(ctx->Input("end"), {sparse_index}, + {sparse_index + 1}, {1}); + end_index = xla::Reshape(end_index, {}); + if (!scalar_must_be_non_negative(end_index)) { + // end could be negative. + auto index_negative = xla::Lt(end_index, zero); + auto wrapped_index = xla::Add(dim_size, end_index); + end_index = xla::Select(index_negative, wrapped_index, end_index); + } + } + if (result_dims_are_dynamic[i]) { + end_index = xla::Max(xla::Min(end_index, dim_size), zero); + } + // This is safe to downcast as set dimension size makes sure that the dim + // in the input doesn't exceed INT32 max. + xla::XlaOp size = xla::Max(xla::Sub(end_index, begin_index), zero); + slice_sizes_dynamic.push_back(xla::ConvertElementType(size, xla::S32)); + } + + slice = + xla::DynamicSlice(slice, start_indices, processing_shape.dim_sizes()); + // new_axis_mask_, ellipsis_mask_ and shrink_axis_mask_ may add or remove + // size 1 dims of a shape. + slice = xla::Reshape(slice, final_shape.dim_sizes()); + for (int64_t i = 0; i < final_shape.dims(); ++i) { + int64_t processing_shape_dim = shape_spec.output_to_processing_mapping[i]; + // If processing_shape_dim is -1, it means the output dimension was newly + // added by new_axis_mask_, which doesn't show up in input. + if (processing_shape_dim != -1) { + // We gave a generous bounds (same as input) to the output for both + // static and dynamic dimensions, try reset the bound if a tighter one + // can be found. + auto status = xla::SetDimensionSizeWithRebound( + &ctx->value_inference(), slice, + slice_sizes_dynamic[processing_shape_dim], i); + OP_REQUIRES_OK(ctx, status.status()); + slice = status.value(); + } + } + ctx->SetOutput(0, slice); + } + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape(0); + const TensorShape begin_shape = ctx->InputShape("begin"); + OP_REQUIRES( + ctx, begin_shape.dims() == 1, + errors::InvalidArgument("'begin' input has to be a rank 1 vector")); + + absl::InlinedVector begin; + absl::InlinedVector end; + absl::InlinedVector strides; + + xla::Literal begin_literal, end_literal, strides_literal; + bool begin_is_constant = ctx->ConstantInput(1, &begin_literal).ok(); + bool end_is_constant = ctx->ConstantInput(2, &end_literal).ok(); + // Strides have to be static. + OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal)); + + Tensor begin_tensor, end_tensor, strides_tensor; + if (begin_is_constant) { + OP_REQUIRES_OK( + ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor)); + } + if (end_is_constant) { + OP_REQUIRES_OK( + ctx, LiteralToHostTensor(end_literal, index_type_, &end_tensor)); + } + OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_, + &strides_tensor)); + PartialTensorShape partial_processing_shape, partial_final_shape; + bool dummy = false; + StridedSliceShapeSpec shape_spec; + OP_REQUIRES_OK( + ctx, + ValidateStridedSliceOp( + begin_is_constant ? &begin_tensor : nullptr, + end_is_constant ? &end_tensor : nullptr, strides_tensor, + input_shape, begin_mask_, end_mask_, ellipsis_mask_, new_axis_mask_, + shrink_axis_mask_, &partial_processing_shape, &partial_final_shape, + &dummy, &dummy, &dummy, &begin, &end, &strides, &shape_spec)); + + xla::XlaOp slice = ctx->Input(0); + std::vector begins_are_dynamic; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPredVector(1, &begins_are_dynamic)); + std::vector ends_are_dynamic; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPredVector(2, &ends_are_dynamic)); + if (begin_is_constant && end_is_constant) { + TensorShape final_shape; + OP_REQUIRES( + ctx, partial_final_shape.AsTensorShape(&final_shape), + InvalidArgument("XLA can't deduce compile time constant output " + "shape for strided slice: ", + partial_final_shape.DebugString(), + ", output shape must be a compile-time constant")); + absl::InlinedVector dimensions_to_reverse; + absl::InlinedVector slice_begin, slice_end, slice_strides; + for (int i = 0; i < begin.size(); ++i) { + if (strides[i] > 0) { + slice_begin.push_back(begin[i]); + slice_end.push_back(std::max(end[i], begin[i])); + slice_strides.push_back(strides[i]); + } else { + // Negative stride: swap begin and end, add 1 because the interval + // is semi-open, and mark the dimension to be reversed. + slice_begin.push_back(input_shape.dim_size(i) - begin[i] - 1); + slice_end.push_back(std::max(input_shape.dim_size(i) - end[i] - 1, + input_shape.dim_size(i) - begin[i] - 1)); + slice_strides.push_back(-strides[i]); + dimensions_to_reverse.push_back(i); + } + } + if (!dimensions_to_reverse.empty()) { + slice = xla::Rev(slice, dimensions_to_reverse); + } + slice = xla::Slice(slice, slice_begin, slice_end, slice_strides); + auto operand_shape_or = ctx->builder()->GetShape(ctx->Input(0)); + OP_REQUIRES_OK(ctx, operand_shape_or.status()); + xla::Shape xla_shape = operand_shape_or.value(); + + bool begins_are_static = absl::c_all_of( + begins_are_dynamic, [](bool dynamic) { return !dynamic; }); + OP_REQUIRES(ctx, begins_are_static, + errors::InvalidArgument( + "XLA can't use dynamic begin values for slice.")); + bool ends_are_static = absl::c_all_of( + ends_are_dynamic, [](bool dynamic) { return !dynamic; }); + // Static output shape, return a static slice. + slice = xla::Reshape(slice, final_shape.dim_sizes()); + if (xla_shape.is_static() && ends_are_static) { + ctx->SetOutput(0, slice); + return; + } + + for (int64_t i = 0; i < final_shape.dims(); ++i) { + int64_t input_index = shape_spec.output_to_processing_mapping[i]; + if (input_index == -1) { + continue; + } + bool input_is_dynamic = xla_shape.is_dynamic_dimension(input_index); + + int64_t sparse_index = shape_spec.output_to_sparse_mapping[i]; + bool end_is_dynamic = + sparse_index == -1 ? false : ends_are_dynamic[sparse_index]; + bool backward_slice = + sparse_index == -1 ? false + : end_literal.Get({sparse_index}) < 0; + if (input_is_dynamic || end_is_dynamic) { + OP_REQUIRES( + ctx, strides[input_index] == 1, + errors::InvalidArgument("XLA has not implemented dynamic " + "sized slice with non-trival stride yet. " + "Please file a bug against XLA")); + // If there is a dynamic dimension, properly set dimension size of + // the result. + auto operand_size = xla::GetDimensionSize(ctx->Input(0), input_index); + if (backward_slice) { + // We consider slicing a dynamic tensor t with negative indices as + // a dynamic sized slice. E.g., t[: -n], the result length is + // shape(t) - n. + OP_REQUIRES(ctx, !end_is_dynamic, + errors::InvalidArgument( + "XLA has not implemented dynamic " + "sized slice with dynamic negative index %lld. ")); + operand_size = xla::Add( + operand_size, + xla::ConstantR0( + ctx->builder(), end_literal.Get({sparse_index}))); + } else { + // The end of slice with dynamic slice size is the min of operand + // shape and slice size. E.g., t[:end_size], result size is + // min(shape(t), end_size). + xla::XlaOp end_size; + if (end_is_dynamic) { + end_size = xla::Reshape(xla::Slice(ctx->Input(2), {sparse_index}, + {sparse_index + 1}, {1}), + {}); + } else { + end_size = + xla::ConstantR0(ctx->builder(), end[input_index]); + } + operand_size = xla::Min(operand_size, end_size); + } + slice = xla::SetDimensionSize( + slice, + xla::Sub(operand_size, xla::ConstantR0( + ctx->builder(), begin[input_index])), + i); + } + } + ctx->SetOutput(0, slice); + return; + } else { + EmitDynamicSlice(ctx, strides, partial_processing_shape, + partial_final_shape, shape_spec, begins_are_dynamic, + ends_are_dynamic); + } + } + + private: + int32_t begin_mask_, end_mask_; + int32_t ellipsis_mask_, new_axis_mask_, shrink_axis_mask_; + DataType index_type_; +}; + +REGISTER_XLA_OP(Name("StridedSlice") + .CompileTimeConstantInput("begin") + .CompileTimeConstantInput("end") + .CompileTimeConstantInput("strides"), + StridedSliceOp); + +class StridedSliceGradOp : public XlaOpKernel { + public: + explicit StridedSliceGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_)); + } + + // When the begin / end is unknown, compile the gradient into dynamic update + // slice into a broadcasted 0s. + // + // Broadcasted 0 + // +----------------------+ + // | +----+ | + // |<-begin->|grad|<-end->| <== Dynamic update grad into 0s. + // | +----+ | + // +----------------------+ + void CompileAsDynamicUpdateSlice(XlaOpKernelContext* ctx, + const TensorShape& input_shape, + const xla::Literal& strides_literal) { + bool dummy = false; + Tensor strides_tensor; + PartialTensorShape processing_shape, final_shape; + absl::InlinedVector begin; + absl::InlinedVector end; + absl::InlinedVector strides; + StridedSliceShapeSpec shape_spec; + OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_, + &strides_tensor)); + OP_REQUIRES_OK( + ctx, ValidateStridedSliceOp( + nullptr, nullptr, strides_tensor, input_shape, begin_mask_, + end_mask_, ellipsis_mask_, new_axis_mask_, shrink_axis_mask_, + &processing_shape, &final_shape, &dummy, &dummy, &dummy, + &begin, &end, &strides, &shape_spec)); + for (int64_t i = 0; i < processing_shape.dims(); ++i) { + OP_REQUIRES( + ctx, strides[i] == 1, + errors::InvalidArgument("Strides in strided slice grad have to be " + "one when inputs are not constant.")); + } + + xla::XlaOp grad = ctx->Input(4); + xla::Shape grad_shape = ctx->InputXlaShape(4).value(); + VLOG(1) << "xla grad shape" << grad_shape; + VLOG(1) << "xla final_shape" << final_shape; + VLOG(1) << "input_shape" << input_shape.DebugString(); + auto input_sizes = input_shape.dim_sizes(); + // For unknown output dim the bound of the output shape is input. Pad and + // double the size of input shape to leave enough buffer to avoid OOB + // dynamic update slice. + auto input_sizes_padded = input_shape.dim_sizes(); + bool need_padding = false; + for (int64_t i = 0; i < processing_shape.dims(); ++i) { + if (processing_shape.dim_size(i) == -1) { + input_sizes_padded[i] *= 2; + need_padding = true; + } + } + for (int64_t i = 0; i < grad_shape.dimensions().size(); ++i) { + // Use grad shape, which is known, to update unknown processing shape. + // Grad shape is the output of the ValidateStridedSliceOp function in + // forward pass, thus we use output_to_processing_mapping. + if (shape_spec.output_to_processing_mapping[i] != -1) { + processing_shape.set_dim(shape_spec.output_to_processing_mapping[i], + grad_shape.dimensions(i)); + } + } + + std::vector begins; + begins.reserve(processing_shape.dims()); + for (int64_t i = 0; i < input_shape.dims(); ++i) { + bool begin_mask = (1 << i) & shape_spec.begin_dense_mask; + // Similarly, use processing_to_sparse_mapping to find out corresponding + // begin dim of the gradient, as indices for dynamic update slice. + int64_t begin_dim = shape_spec.processing_to_sparse_mapping[i]; + xla::XlaOp begin_index; + auto zero = xla::Zero(ctx->builder(), ctx->InputXlaType("begin")); + if (begin_mask) { + begin_index = zero; + } else { + xla::XlaOp dim_size = xla::Slice(ctx->Input(0), {i}, {i + 1}, {1}); + dim_size = xla::Reshape(dim_size, {}); + begin_index = + xla::Slice(ctx->Input(1), {begin_dim}, {begin_dim + 1}, {1}); + begin_index = xla::Reshape(begin_index, {}); + auto index_negative = xla::Lt(begin_index, zero); + auto wrapped_index = xla::Add(dim_size, begin_index); + // Wrap negative indices around. + begin_index = xla::Select(index_negative, wrapped_index, begin_index); + } + begins.push_back(begin_index); + } + auto zero = XlaHelpers::Zero(ctx->builder(), ctx->expected_output_dtype(0)); + + zero = xla::Broadcast(zero, input_sizes_padded); + grad = xla::Reshape(grad, processing_shape.dim_sizes()); + grad = xla::DynamicUpdateSlice(zero, grad, begins); + if (need_padding) { + // We padded the input shape to avoid OOB when DUS. Now slice out the + // padding in the final result. + std::vector strides(input_shape.dims(), 1); + std::vector start_indices(input_shape.dims(), 0); + grad = xla::Slice(grad, start_indices, input_sizes, strides); + } + ctx->SetOutput(0, grad); + } + void Compile(XlaOpKernelContext* ctx) override { + TensorShape processing_shape, final_shape; + absl::InlinedVector begin; + absl::InlinedVector end; + absl::InlinedVector strides; + + TensorShape input_shape; + OP_REQUIRES_OK( + ctx, ctx->ConstantInputAsShape(0, &input_shape, + xla::ValueInferenceMode::kUpperBound)); + xla::Literal begin_literal, end_literal, strides_literal; + + bool begin_is_constant = ctx->ConstantInput(1, &begin_literal).ok(); + bool end_is_constant = ctx->ConstantInput(2, &end_literal).ok(); + OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal)); + if (!(begin_is_constant && end_is_constant)) { + CompileAsDynamicUpdateSlice(ctx, input_shape, strides_literal); + return; + } + Tensor begin_tensor, end_tensor, strides_tensor; + OP_REQUIRES_OK( + ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor)); + OP_REQUIRES_OK(ctx, + LiteralToHostTensor(end_literal, index_type_, &end_tensor)); + OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_, + &strides_tensor)); + + bool dummy = false; + OP_REQUIRES_OK( + ctx, ValidateStridedSliceOp( + &begin_tensor, &end_tensor, strides_tensor, input_shape, + begin_mask_, end_mask_, ellipsis_mask_, new_axis_mask_, + shrink_axis_mask_, &processing_shape, &final_shape, &dummy, + &dummy, &dummy, &begin, &end, &strides)); + + // Check to make sure dy is consistent with the original slice + const TensorShape dy_shape = ctx->InputShape(4); + OP_REQUIRES( + ctx, final_shape == dy_shape, + errors::InvalidArgument("shape of dy was ", dy_shape.DebugString(), + " instead of ", final_shape.DebugString())); + + OP_REQUIRES( + ctx, input_shape.dims() == processing_shape.dims(), + errors::Internal( + "input shape and processing shape must have same number of dims")); + + auto zero = XlaHelpers::Zero(ctx->builder(), ctx->expected_output_dtype(0)); + + xla::XlaOp grad = ctx->Input(4); + + // Undo any new/shrink axes. + grad = xla::Reshape(grad, processing_shape.dim_sizes()); + + // Pad the input gradients. + absl::InlinedVector dimensions_to_reverse; + xla::PaddingConfig padding_config; + + for (int i = 0; i < processing_shape.dims(); ++i) { + auto* dims = padding_config.add_dimensions(); + if (strides[i] > 0) { + dims->set_edge_padding_low(begin[i]); + dims->set_interior_padding(strides[i] - 1); + + // Pad the upper dimension up to the expected input shape. (It's + // not sufficient simply to use "end[i]" to compute the padding in + // cases where the stride does not divide evenly into the interval + // between begin[i] and end[i].) + int64_t size = + dims->edge_padding_low() + processing_shape.dim_size(i) + + (processing_shape.dim_size(i) - 1) * dims->interior_padding(); + dims->set_edge_padding_high(input_shape.dim_size(i) - size); + } else { + dimensions_to_reverse.push_back(i); + dims->set_edge_padding_high(input_shape.dim_size(i) - begin[i] - 1); + dims->set_interior_padding(-strides[i] - 1); + + // Pad the lower dimension up to the expected input shape. + int64_t size = + dims->edge_padding_high() + processing_shape.dim_size(i) + + (processing_shape.dim_size(i) - 1) * dims->interior_padding(); + dims->set_edge_padding_low(input_shape.dim_size(i) - size); + } + } + if (!dimensions_to_reverse.empty()) { + grad = xla::Rev(grad, dimensions_to_reverse); + } + grad = xla::Pad(grad, zero, padding_config); + + xla::XlaOp dynamic_shape = ctx->Input(0); + xla::Shape grad_shape = ctx->builder()->GetShape(grad).value(); + std::vector dynamic_input; + OP_REQUIRES_OK(ctx, + ctx->ResolveInputDynamismIntoPredVector(0, &dynamic_input)); + // Input of strided_slice_op has to have the same shape as output. + DCHECK_EQ(grad_shape.dimensions().size(), input_shape.dims()); + for (int64_t dim = 0; dim < input_shape.dims(); ++dim) { + DCHECK_EQ(grad_shape.dimensions(dim), input_shape.dim_size(dim)); + if (dynamic_input[dim]) { + // Input is a dynamic dimension, set the same dynamic dimension size in + // the output. + auto dim_size = xla::Slice(dynamic_shape, {dim}, {dim + 1}, {1}); + dim_size = xla::ConvertElementType(dim_size, xla::S32); + auto dim_size_scalar = xla::Reshape(dim_size, {}); + grad = xla::SetDimensionSize(grad, dim_size_scalar, dim); + } else if (grad_shape.is_dynamic_dimension(dim)) { + // Input is static but output is dynamic, respect input and remove any + // dynamic dim in the output. + grad = xla::RemoveDynamicDimension(grad, dim); + } + } + + ctx->SetOutput(0, grad); + } + + private: + int32_t begin_mask_, end_mask_; + int32_t ellipsis_mask_, new_axis_mask_, shrink_axis_mask_; + DataType index_type_; +}; + +REGISTER_XLA_OP(Name("StridedSliceGrad") + .CompileTimeConstantInput("shape") + .CompileTimeConstantInput("begin") + .CompileTimeConstantInput("end") + .CompileTimeConstantInput("strides"), + StridedSliceGradOp); + +class StridedSliceAssignOp : public XlaOpKernel { + public: + explicit StridedSliceAssignOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("begin_mask", &begin_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("end_mask", &end_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("ellipsis_mask", &ellipsis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("new_axis_mask", &new_axis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("shrink_axis_mask", &shrink_axis_mask_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("Index", &index_type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape final_shape; + absl::InlinedVector begin; + absl::InlinedVector end; + absl::InlinedVector strides; + + xla::Literal begin_literal, end_literal, strides_literal; + OP_REQUIRES_OK(ctx, ctx->ConstantInput(1, &begin_literal)); + OP_REQUIRES_OK(ctx, ctx->ConstantInput(2, &end_literal)); + OP_REQUIRES_OK(ctx, ctx->ConstantInput(3, &strides_literal)); + + Tensor begin_tensor, end_tensor, strides_tensor; + OP_REQUIRES_OK( + ctx, LiteralToHostTensor(begin_literal, index_type_, &begin_tensor)); + OP_REQUIRES_OK(ctx, + LiteralToHostTensor(end_literal, index_type_, &end_tensor)); + OP_REQUIRES_OK(ctx, LiteralToHostTensor(strides_literal, index_type_, + &strides_tensor)); + + TensorShape lhs_shape; + xla::XlaOp lhs; + if (ctx->input_type(0) == DT_RESOURCE) { + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &lhs_shape, &lhs)); + } else { + lhs_shape = ctx->InputShape(0); + lhs = ctx->Input(0); + } + + const TensorShape rhs_shape = ctx->InputShape(4); + + TensorShape dummy_processing_shape; + bool dummy = false; + OP_REQUIRES_OK(ctx, + ValidateStridedSliceOp( + &begin_tensor, &end_tensor, strides_tensor, lhs_shape, + begin_mask_, end_mask_, ellipsis_mask_, new_axis_mask_, + shrink_axis_mask_, &dummy_processing_shape, &final_shape, + &dummy, &dummy, &dummy, &begin, &end, &strides)); + + if (final_shape.num_elements() == 0 && rhs_shape.num_elements() == 0) { + // DynamicUpdateSlice does not allow 0-element updates. We should probably + // check that rhs_shape can be broadcast to final_shape, but that is + // probably better handled when implementing broadcasting more generally. + return; + } + + // TODO(aselle): This check is too strong, we only should need + // input_shape to be broadcastable to final_shape + OP_REQUIRES(ctx, final_shape == rhs_shape, + errors::Unimplemented( + "sliced l-value shape ", final_shape.DebugString(), + " does not match r-value shape ", rhs_shape.DebugString(), + ". Automatic broadcasting not yet implemented.")); + + xla::XlaOp rhs = ctx->Input(4); + + absl::InlinedVector dimensions_to_reverse; + absl::InlinedVector slice_begin; + absl::InlinedVector slice_dims; + for (int i = 0; i < begin.size(); ++i) { + // TODO(b/121179231): implement strides != 1 + OP_REQUIRES( + ctx, strides[i] == 1 || strides[i] == -1, + errors::Unimplemented("Strides != 1 or -1 are not yet implemented")); + if (strides[i] > 0) { + slice_begin.push_back( + xla::ConstantR0(ctx->builder(), begin[i])); + slice_dims.push_back(end[i] - begin[i]); + } else { + // Negative stride: swap begin and end, add 1 because the interval + // is semi-open, and mark the dimension to be reversed. + slice_begin.push_back( + xla::ConstantR0(ctx->builder(), end[i] + 1)); + slice_dims.push_back(begin[i] - end[i]); + dimensions_to_reverse.push_back(i); + } + } + + if (!dimensions_to_reverse.empty()) { + rhs = xla::Rev(rhs, dimensions_to_reverse); + } + rhs = xla::Reshape(rhs, slice_dims); + + lhs = xla::DynamicUpdateSlice(lhs, rhs, slice_begin); + + if (ctx->input_type(0) == DT_RESOURCE) { + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, lhs)); + } else { + ctx->SetOutput(0, lhs); + } + } + + private: + int32_t begin_mask_, end_mask_; + int32_t ellipsis_mask_, new_axis_mask_, shrink_axis_mask_; + DataType index_type_; + DataType dtype_; +}; + +REGISTER_XLA_OP(Name("ResourceStridedSliceAssign") + .CompileTimeConstantInput("begin") + .CompileTimeConstantInput("end") + .CompileTimeConstantInput("strides"), + StridedSliceAssignOp); + +REGISTER_XLA_OP(Name("TensorStridedSliceUpdate") + .CompileTimeConstantInput("begin") + .CompileTimeConstantInput("end") + .CompileTimeConstantInput("strides"), + StridedSliceAssignOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_array_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_array_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..a3513b9b74f653602edb4537d601894951621222 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_array_ops.cc @@ -0,0 +1,638 @@ +/* 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. +==============================================================================*/ + +// XLA TensorArray operators. + +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_types.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +// Since the element shape is not always provided to the TensorArrayV3 operator, +// we must support lazily initialization of the TensorArray at the time of the +// first write. +// If a TensorArray `resource` has not been initialized, constructs storage for +// the TensorArray with elements of `elem_shape`. For both initialized and +// uninitialized TensorArrays, checks that the tensor has a type compatible with +// 'dtype' and shape compatible with 'elem_shape'. +absl::Status MaybeInitializeTensorArray(xla::XlaBuilder* builder, + XlaResource* resource, DataType dtype, + const TensorShape& elem_shape) { + if (resource->kind() != XlaResource::kTensorArray) { + return errors::InvalidArgument("Unexpected non-TensorArray resource"); + } + + if (resource->type() != dtype) { + return errors::InvalidArgument( + "TensorArray dtype is ", DataTypeString(resource->type()), + " but op has dtype ", DataTypeString(dtype), "."); + } + + TF_RET_CHECK(resource->max_array_size() >= 0) + << resource->name() << " size " << resource->max_array_size(); + + if (!resource->initialized()) { + TF_RETURN_IF_ERROR(resource->SetTypeAndShape(dtype, elem_shape)); + TF_RETURN_IF_ERROR(resource->SetZeroValue(builder)); + } else { + // Checks the elem_shape matches the TensorArray shape. + auto shape_or_status = builder->GetShape(resource->value()); + if (!shape_or_status.ok()) { + return shape_or_status.status(); + } + TensorShape shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape_or_status.value(), &shape)); + + TensorShape ta_shape; + TF_RETURN_IF_ERROR(ta_shape.AddDimWithStatus(resource->max_array_size())); + ta_shape.AppendShape(elem_shape); + if (ta_shape != shape) { + return errors::InvalidArgument( + "Mismatched TensorArray sizes: ", ta_shape.DebugString(), " vs ", + shape.DebugString()); + } + } + return absl::OkStatus(); +} + +// Checks that the TensorArray 'resource' has been initialized, and has type +// 'dtype'. Sets 'shape' to the shape +absl::Status CheckTensorArrayIsInitialized(const std::string& op_name, + const XlaResource* resource, + DataType dtype) { + if (resource->kind() != XlaResource::kTensorArray) { + return errors::InvalidArgument( + "Unexpected non-TensorArray resource passed to ", op_name); + } + if (!resource->initialized()) { + return errors::InvalidArgument("Uninitialized TensorArray passed to ", + op_name); + } + if (resource->type() != dtype) { + return errors::InvalidArgument( + "TensorArray dtype is ", DataTypeString(resource->type()), + " but op has dtype ", DataTypeString(dtype), "."); + } + + return absl::OkStatus(); +} + +absl::Status GetTensorArrayShape(const XlaResource* resource, + xla::XlaBuilder* builder, TensorShape* shape) { + *shape = resource->shape(); + shape->InsertDim(0, resource->max_array_size()); + return absl::OkStatus(); +} + +// Like XlaBuilder::DynamicUpdateSlice, but adds 'update' to the +// relevant slice of 'operand'. +xla::XlaOp DynamicAddSlice(xla::XlaBuilder* builder, const xla::XlaOp operand, + const xla::XlaOp update, + absl::Span update_dims, + absl::Span start_indices, + DataType dtype) { + xla::XlaOp current = xla::DynamicSlice(operand, start_indices, update_dims); + xla::XlaOp sum = + dtype == DT_BOOL ? xla::Or(current, update) : xla::Add(current, update); + return xla::DynamicUpdateSlice(operand, sum, start_indices); +} + +class TensorArrayOp : public XlaOpKernel { + public: + explicit TensorArrayOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("element_shape", &element_shape_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + bool dynamic_size; + OP_REQUIRES_OK(ctx, ctx->GetAttr("dynamic_size", &dynamic_size)); + OP_REQUIRES( + ctx, !dynamic_size, + errors::Unimplemented( + "TensorArrays with dynamic size are not supported by XLA.")); + + OP_REQUIRES_OK(ctx, ctx->GetAttr("tensor_array_name", &tensor_array_name_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + int64_t size; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar(0, &size)); + OP_REQUIRES(ctx, size >= 0, + errors::InvalidArgument("TensorArray size must be >= 0")); + + xla::XlaBuilder* b = ctx->builder(); + + // Initializes the TensorArray value if we know the element shape. + // Otherwise, defer initialization to the first write. + xla::XlaOp value; + TensorShape shape; + if (element_shape_.IsFullyDefined()) { + CHECK(element_shape_.AsTensorShape(&shape)); + TensorShape ta_shape; + ta_shape.AddDim(size); + ta_shape.AppendShape(shape); + xla::XlaOp zero = XlaHelpers::Zero(b, dtype_); + value = xla::Broadcast(zero, ta_shape.dim_sizes()); + } + + XlaResource* var = + ctx->xla_context()->AddResource(XlaResource::CreateTensorArray( + /*name=*/absl::StrCat("TensorArray: ", tensor_array_name_), dtype_, + shape, /*initial_value=*/value, /*max_array_size=*/size)); + ctx->SetResourceOutput(0, var); + + Tensor flow(DT_FLOAT, TensorShape({})); + flow.scalar()() = 0.0f; + ctx->SetConstantOutput(1, flow); + } + + private: + PartialTensorShape element_shape_; + DataType dtype_; + std::string tensor_array_name_; + + TensorArrayOp(const TensorArrayOp&) = delete; + void operator=(const TensorArrayOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayV3").CompileTimeConstantInput("size"), + TensorArrayOp); + +class TensorArrayWriteOp : public XlaOpKernel { + public: + explicit TensorArrayWriteOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + TensorShape elem_shape = ctx->InputShape(2); + + // Initializes the TensorArray, if the element shape was not known at + // construction time. + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + OP_REQUIRES_OK(ctx, + MaybeInitializeTensorArray(b, resource, dtype_, elem_shape)); + + xla::XlaOp ta = resource->value(); + xla::XlaOp index = ctx->Input(1); + xla::XlaOp value = ctx->Input(2); + xla::XlaOp flow = ctx->Input(3); + + // start_indices of the DynamicUpdateSlice are [index, 0, 0, ..., 0]. + std::vector start_indices(elem_shape.dims() + 1, + xla::ConstantR0(b, 0)); + start_indices[0] = index; + + TensorShape slice_shape = elem_shape; + slice_shape.InsertDim(0, 1LL); + auto update = xla::Reshape(value, slice_shape.dim_sizes()); + + xla::XlaOp written; + if (resource->tensor_array_multiple_writes_aggregate()) { + written = DynamicAddSlice(b, ta, update, slice_shape.dim_sizes(), + start_indices, dtype_); + } else { + // TODO(b/117569591): Ideally we would report an error in the case that we + // see multiple writes to the same offset. Unfortunately there is no way + // to report errors at the moment, so we silently overwrite. + written = xla::DynamicUpdateSlice(ta, update, start_indices); + } + OP_REQUIRES_OK(ctx, resource->SetValue(written)); + ctx->SetOutput(0, flow); + } + + private: + DataType dtype_; + + TensorArrayWriteOp(const TensorArrayWriteOp&) = delete; + void operator=(const TensorArrayWriteOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayWriteV3"), TensorArrayWriteOp); + +class TensorArrayReadOp : public XlaOpKernel { + public: + explicit TensorArrayReadOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + + OP_REQUIRES_OK(ctx, + CheckTensorArrayIsInitialized(name(), resource, dtype_)); + TensorShape ta_shape; + OP_REQUIRES_OK(ctx, GetTensorArrayShape(resource, b, &ta_shape)); + + xla::XlaOp ta = resource->value(); + xla::XlaOp index = ctx->Input(1); + + // start_indices of the DynamicSlice are [index, 0, 0, ..., 0]. + std::vector start_indices(ta_shape.dims(), + xla::ConstantR0(b, 0)); + start_indices[0] = index; + + auto slice_shape = ta_shape.dim_sizes(); + slice_shape[0] = 1LL; + + xla::XlaOp read = xla::DynamicSlice(ta, start_indices, slice_shape); + + // Remove the leading '1' dimension. + std::vector value_shape(slice_shape.begin() + 1, + slice_shape.end()); + ctx->SetOutput(0, xla::Reshape(read, value_shape)); + } + + private: + DataType dtype_; + + TensorArrayReadOp(const TensorArrayReadOp&) = delete; + void operator=(const TensorArrayReadOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayReadV3"), TensorArrayReadOp); + +class TensorArrayGatherOp : public XlaOpKernel { + public: + explicit TensorArrayGatherOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + + OP_REQUIRES_OK(ctx, + CheckTensorArrayIsInitialized(name(), resource, dtype_)); + TensorShape ta_shape; + OP_REQUIRES_OK(ctx, GetTensorArrayShape(resource, b, &ta_shape)); + + const TensorShape indices_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, indices_shape.dims() == 1, + errors::InvalidArgument("indices must be rank 1")); + auto indices = ctx->Input(1); + DataType index_type = ctx->input_type(1); + + xla::XlaOp ta = resource->value(); + + // Look for the case where the gather takes a simple slice from the + // tensor array (0, 1, 2, 3, 4, ..., N) + std::vector const_indices; + absl::Status status = ctx->ConstantInputAsIntVector(1, &const_indices); + if (status.ok()) { + bool gather_is_dense_slice = true; + for (auto i = 0; i < const_indices.size(); i++) { + if (const_indices[i] != i) { + gather_is_dense_slice = false; + break; + } + } + + if (gather_is_dense_slice) { + std::vector begin(ta_shape.dims(), 0); + std::vector strides(ta_shape.dims(), 1); + std::vector end(ta_shape.dims(), 1); + end[0] = const_indices.size(); + for (auto i = 1; i < ta_shape.dims(); i++) { + end[i] = ta_shape.dim_size(i); + } + ctx->SetOutput(0, xla::Slice(ta, begin, end, strides)); + return; + } + } + + xla::XlaOp gather; + OP_REQUIRES_OK( + ctx, + XlaGather(ta, ta_shape, indices, indices_shape, /*axis=*/0, + /*indices_are_nd=*/false, dtype_, index_type, b, &gather)); + ctx->SetOutput(0, gather); + } + + private: + DataType dtype_; + + TensorArrayGatherOp(const TensorArrayGatherOp&) = delete; + void operator=(const TensorArrayGatherOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayGatherV3"), TensorArrayGatherOp); + +class TensorArrayScatterOp : public XlaOpKernel { + public: + explicit TensorArrayScatterOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + const TensorShape value_shape = ctx->InputShape(2); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + TensorShape elem_shape = value_shape; + elem_shape.RemoveDim(0); + OP_REQUIRES_OK(ctx, + MaybeInitializeTensorArray(b, resource, dtype_, elem_shape)); + + const TensorShape indices_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, indices_shape.dims() >= 1, + errors::InvalidArgument("indices must be rank 1")); + const int num_indices = indices_shape.dim_size(0); + const xla::XlaOp indices = ctx->Input(1); + + xla::XlaOp ta = resource->value(); + const xla::XlaOp value = ctx->Input(2); + const xla::XlaOp flow = ctx->Input(3); + + // Look for the case where the scatter is for each sub-tensor in order. The + // tensor array implementation allows for this to be a straight addition. + bool scatter_all_elements_in_order = false; + std::vector const_indices; + absl::Status status = ctx->ConstantInputAsIntVector(1, &const_indices); + if (status.ok() && num_indices == value_shape.dim_size(0)) { + scatter_all_elements_in_order = true; + for (auto i = 0; i < num_indices; i++) { + if (const_indices[i] != i) { + scatter_all_elements_in_order = false; + break; + } + } + } + + if (scatter_all_elements_in_order) { + if (dtype_ == DT_BOOL) { + ta = xla::Or(ta, value); + } else { + ta = xla::Add(ta, value); + } + } else { + auto slice_dims = value_shape.dim_sizes(); + slice_dims[0] = 1LL; + + std::vector value_starts(value_shape.dims(), 0); + auto value_ends = value_shape.dim_sizes(); + + std::vector value_strides(value_shape.dims(), 1); + + // For every (index, value) pair, update the corresponding TensorArray + // storage. + for (int i = 0; i < num_indices; ++i) { + // Slice out part of the value. + value_starts[0] = i; + value_ends[0] = i + 1; + auto slice = xla::Slice(value, value_starts, value_ends, value_strides); + + // start_indices of the DynamicUpdateSlice are [index, 0, 0, ..., 0]. + auto index = xla::Reshape(xla::Slice(indices, {i}, {i + 1}, {1}), {}); + std::vector start_indices(elem_shape.dims() + 1, + xla::ConstantR0(b, 0)); + start_indices[0] = index; + ta = DynamicAddSlice(b, ta, slice, slice_dims, start_indices, dtype_); + } + } + + OP_REQUIRES_OK(ctx, resource->SetValue(ta)); + ctx->SetOutput(0, flow); + } + + private: + DataType dtype_; + + TensorArrayScatterOp(const TensorArrayScatterOp&) = delete; + void operator=(const TensorArrayScatterOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayScatterV3"), TensorArrayScatterOp); + +class TensorArrayConcatOp : public XlaOpKernel { + public: + explicit TensorArrayConcatOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + + OP_REQUIRES_OK(ctx, + CheckTensorArrayIsInitialized(name(), resource, dtype_)); + TensorShape ta_shape; + OP_REQUIRES_OK(ctx, GetTensorArrayShape(resource, b, &ta_shape)); + + xla::XlaOp ta = resource->value(); + + auto ta_dims = ta_shape.dim_sizes(); + std::vector shape(ta_dims.begin() + 1, ta_dims.end()); + shape[0] *= ta_shape.dim_size(0); + ctx->SetOutput(0, xla::Reshape(ta, shape)); + + Tensor lengths(DT_INT64, {ta_dims[0]}); + auto lengths_vec = lengths.vec(); + for (int i = 0; i < ta_dims[0]; ++i) { + lengths_vec(i) = ta_dims[1]; + } + ctx->SetConstantOutput(1, lengths); + } + + private: + DataType dtype_; + + TensorArrayConcatOp(const TensorArrayConcatOp&) = delete; + void operator=(const TensorArrayConcatOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayConcatV3"), TensorArrayConcatOp); + +class TensorArraySplitOp : public XlaOpKernel { + public: + explicit TensorArraySplitOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + std::vector lengths; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(2, &lengths)); + + int64_t length = 0; + if (!lengths.empty()) { + length = lengths[0]; + for (int i = 1; i < lengths.size(); ++i) { + OP_REQUIRES(ctx, lengths[i] == length, + errors::InvalidArgument("lengths must be equal: ", length, + " vs. ", lengths[i])); + } + } + + TensorShape value_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, value_shape.dims() >= 1, + errors::InvalidArgument("value must have rank >= 1, got ", + value_shape.DebugString())); + TensorShape elem_shape = value_shape; + elem_shape.set_dim(0, length); + + xla::XlaBuilder* b = ctx->builder(); + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + OP_REQUIRES_OK(ctx, + MaybeInitializeTensorArray(b, resource, dtype_, elem_shape)); + xla::XlaOp ta = resource->value(); + + TensorShape ta_shape; + ta_shape.AddDim(resource->max_array_size()); + ta_shape.AppendShape(elem_shape); + + OP_REQUIRES(ctx, lengths.size() == resource->max_array_size(), + errors::InvalidArgument( + "TensorArray's size is not equal to the size of lengths (", + lengths.size(), " vs. ", resource->max_array_size(), ")")); + + const xla::XlaOp value = ctx->Input(1); + const xla::XlaOp flow = ctx->Input(3); + + OP_REQUIRES(ctx, value_shape.num_elements() == ta_shape.num_elements(), + errors::InvalidArgument("mismatched element count ", + value_shape.DebugString(), " vs. ", + ta_shape.DebugString())); + + const xla::XlaOp reshape = xla::Reshape(value, ta_shape.dim_sizes()); + if (dtype_ == DT_BOOL) { + ta = xla::Or(ta, reshape); + } else { + ta = xla::Add(ta, reshape); + } + OP_REQUIRES_OK(ctx, resource->SetValue(ta)); + + ctx->SetOutput(0, flow); + } + + private: + DataType dtype_; + + TensorArraySplitOp(const TensorArraySplitOp&) = delete; + void operator=(const TensorArraySplitOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArraySplitV3").CompileTimeConstantInput("lengths"), + TensorArraySplitOp); + +class TensorArraySizeOp : public XlaOpKernel { + public: + explicit TensorArraySizeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + XlaResource* var; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &var)); + Tensor size_tensor(DT_INT32, {}); + size_tensor.scalar()() = + static_cast(var->max_array_size()); + ctx->SetConstantOutput(0, size_tensor); + } + + private: + TensorArraySizeOp(const TensorArraySizeOp&) = delete; + void operator=(const TensorArraySizeOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArraySizeV3"), TensorArraySizeOp); + +class TensorArrayGradOp : public XlaOpKernel { + public: + explicit TensorArrayGradOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("source", &source_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaBuilder* b = ctx->builder(); + + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &resource)); + + OP_REQUIRES_OK( + ctx, CheckTensorArrayIsInitialized(name(), resource, resource->type())); + TensorShape ta_shape; + OP_REQUIRES_OK(ctx, GetTensorArrayShape(resource, b, &ta_shape)); + + // Finds or looks up the corresponding gradient TensorArray, which stores + // gradients computed during backpropagation. + XlaResource* gradient; + OP_REQUIRES_OK( + ctx, resource->GetOrCreateTensorArrayGradient(source_, b, &gradient)); + + ctx->SetResourceOutput(0, gradient); + ctx->SetConstantOutput(1, Tensor(DT_FLOAT)); + } + + private: + std::string source_; + + TensorArrayGradOp(const TensorArrayGradOp&) = delete; + void operator=(const TensorArrayGradOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayGradV3"), TensorArrayGradOp); + +class TensorArrayCloseOp : public XlaOpKernel { + public: + explicit TensorArrayCloseOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // Do nothing; XLA handles resource management. + } + + private: + TensorArrayCloseOp(const TensorArrayCloseOp&) = delete; + void operator=(const TensorArrayCloseOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorArrayCloseV3"), TensorArrayCloseOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..1a44c020f6fa4a5adf6cc819df689763afefc089 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_ops.cc @@ -0,0 +1,721 @@ +/* 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. +==============================================================================*/ + +// XLA TensorList operators. + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h" +#include "tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +namespace { + +// GetTensorListDynamicDims collects the dynamic dimensions that a tensorlist +// may carry and returns them in a 2D vector: XlaOp[ElementSize][DimSize]. If a +// dimension is static, a constant dimension is returned. If a dim is dynamic, a +// dynamic XlaOp representing the dynamic size is returned. +absl::StatusOr>> GetTensorListDynamicDims( + XlaOpKernelContext* ctx, const xla::Shape& element_shape, + const xla::Shape& list_shape, int64_t num_elements) { + std::vector dynamic_sizes; + // The multiplier can be a dynamic value. + TF_RETURN_IF_ERROR(ctx->ConstantInputAsIntVector(0, &dynamic_sizes)); + std::vector dims_are_dynamic; + TF_RETURN_IF_ERROR( + ctx->ResolveInputDynamismIntoPredVector(0, &dims_are_dynamic)); + bool leading_dim_is_dynamic; + TF_RETURN_IF_ERROR( + ctx->ResolveInputDynamismIntoPred(1, &leading_dim_is_dynamic)); + std::vector> list_dynamic_dims; + // Set dynamic dimension size to 0 for initialization value. + std::vector dynamic_dims; + dynamic_dims.reserve(1 + element_shape.dimensions().size()); + if (leading_dim_is_dynamic) { + dynamic_dims.push_back(ctx->Input(1)); + } else { + dynamic_dims.push_back( + xla::ConstantR0(ctx->builder(), num_elements)); + } + for (int64_t dim = 0; dim < element_shape.dimensions().size(); ++dim) { + if (dims_are_dynamic[dim]) { + auto dynamic_dim_size = xla::Slice(ctx->Input(0), {dim}, {dim + 1}, {1}); + dynamic_dim_size = xla::Reshape(dynamic_dim_size, {}); + dynamic_dim_size = xla::ConvertElementType(dynamic_dim_size, xla::S32); + dynamic_dims.push_back(dynamic_dim_size); + } else { + dynamic_dims.push_back( + xla::ConstantR0(ctx->builder(), dynamic_sizes[dim])); + } + } + list_dynamic_dims.push_back(std::move(dynamic_dims)); + return list_dynamic_dims; +} + +class TensorListLengthOp : public XlaOpKernel { + public: + explicit TensorListLengthOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + int64_t leading_dim; + xla::XlaOp leading_dim_size; + bool leading_dim_is_dynamic; + OP_REQUIRES_OK(ctx, GetLeadingDimForTensorList(ctx->Input(0), &leading_dim, + &leading_dim_is_dynamic, + &leading_dim_size)); + ctx->SetOutput(0, leading_dim_size); + } + + private: + TensorListLengthOp(const TensorListLengthOp&) = delete; + void operator=(const TensorListLengthOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListLength").IsMetadataOp(), TensorListLengthOp); + +// "input" is the shape input for EmptyTensorList/TensorListReserve ops. +// If "input" is a compile time constant and not "unknown rank" (-1), return +// its value in "*shape". +absl::Status TryGetElementShapeFromInput(XlaOpKernelContext* ctx, + xla::XlaOp input, + xla::PrimitiveType dtype, + bool* got_shape, xla::Shape* shape) { + auto is_compile_time_constant_or = input.builder()->IsConstant(input); + TF_RETURN_IF_ERROR(is_compile_time_constant_or.status()); + + bool is_compile_time_constant = is_compile_time_constant_or.value(); + if (!is_compile_time_constant) { + *got_shape = false; + return absl::OkStatus(); + } + + PartialTensorShape partial_shape; + TF_RETURN_IF_ERROR(ctx->ConstantInputAsPartialShape(0, &partial_shape)); + if (!partial_shape.IsFullyDefined()) { + *got_shape = false; + return absl::OkStatus(); + } + + *shape = xla::ShapeUtil::MakeShape(dtype, partial_shape.dim_sizes()); + *got_shape = true; + return absl::OkStatus(); +} + +class TensorListReserveOp : public XlaOpKernel { + public: + explicit TensorListReserveOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("element_dtype", &dtype_)); + // Only non-nested TensorList is supported for now. + OP_REQUIRES( + ctx, dtype_ != DT_VARIANT, + errors::Unimplemented( + "Only non-nested TensorList is supported for TensorListReserve.")); + } + + void Compile(XlaOpKernelContext* ctx) override { + int64_t num_elements; + OP_REQUIRES_OK(ctx, + ctx->ConstantInputAsIntScalar( + 1, &num_elements, xla::ValueInferenceMode::kUpperBound)); + bool num_element_is_dynamic; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPred(1, &num_element_is_dynamic)); + OP_REQUIRES( + ctx, num_elements >= 0, + errors::InvalidArgument( + "XLA compilation requires a fixed tensor list size. Set the number " + "of elements. This could also happen if you're using a TensorArray " + "in a while loop that does not have its maximum_iteration set, you " + "can fix this by setting maximum_iteration to a suitable value.")); + + // If element shape is compile time constant and it's not "unknown rank" + // shape (-1), create an initialized TensorList. Otherwise create an + // uninitialized TensorList. + xla::XlaOp element_shape_handle = ctx->Input(0); + xla::PrimitiveType type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype_, &type)); + bool got_shape; + xla::Shape element_shape; + OP_REQUIRES_OK(ctx, + TryGetElementShapeFromInput(ctx, element_shape_handle, type, + &got_shape, &element_shape)); + if (got_shape) { + xla::Shape list_shape; + OP_REQUIRES_OK(ctx, GetTensorListShapeFromElementShape( + element_shape, num_elements, + num_element_is_dynamic, &list_shape)); + // Set up dynamic dimension sizes to create the zero tensor. + auto list_dynamic_dims_or = GetTensorListDynamicDims( + ctx, element_shape, list_shape, num_elements); + OP_REQUIRES_OK(ctx, list_dynamic_dims_or.status()); + xla::XlaOp new_list; + OP_REQUIRES_OK(ctx, CreateZerosTensorListWithShape( + ctx->builder(), list_shape, + list_dynamic_dims_or.value(), &new_list)); + xla::XlaOp result; + OP_REQUIRES_OK( + ctx, + SetTensorListPushIndex( + new_list, xla::ConstantR0(ctx->builder(), num_elements), + &result)); + ctx->SetTensorListOutput(0, result); + return; + } + + xla::XlaOp result = BuildUninitializedTensorList( + ctx->builder(), num_elements, num_element_is_dynamic, ctx->Input(1)); + ctx->SetTensorListOutput(0, result); + } + + private: + DataType dtype_; + + TensorListReserveOp(const TensorListReserveOp&) = delete; + void operator=(const TensorListReserveOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListReserve") + .CompileTimeConstantInput("element_shape") + .CompileTimeConstantInput("num_elements"), + TensorListReserveOp); + +class EmptyTensorListOp : public XlaOpKernel { + public: + explicit EmptyTensorListOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("element_dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + int64_t max_num_elements; + OP_REQUIRES_OK( + ctx, ctx->ConstantInputAsIntScalar( + 1, &max_num_elements, xla::ValueInferenceMode::kUpperBound)); + bool num_element_is_dynamic; + OP_REQUIRES_OK( + ctx, ctx->ResolveInputDynamismIntoPred(1, &num_element_is_dynamic)); + OP_REQUIRES(ctx, max_num_elements >= 0, + errors::InvalidArgument( + "XLA compilation requires a fixed tensor list size. Set " + "the max number of elements. This could also happen if " + "you're using a TensorArray in a while loop that does not " + "have its maximum_iteration set, you can fix this by " + "setting maximum_iteration to a suitable value.")); + + if (dtype_ != DT_VARIANT) { + // We are creating a non-nested TensorList. + // If element shape is compile time constant and it's not "unknown + // rank" shape (-1), create an initialized TensorList. Otherwise + // create an uninitialized TensorList. + xla::XlaOp element_shape_handle = ctx->Input(0); + xla::PrimitiveType type; + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype_, &type)); + bool got_shape; + xla::Shape element_shape; + OP_REQUIRES_OK( + ctx, TryGetElementShapeFromInput(ctx, element_shape_handle, type, + &got_shape, &element_shape)); + if (got_shape) { + xla::Shape list_shape; + OP_REQUIRES_OK(ctx, GetTensorListShapeFromElementShape( + element_shape, max_num_elements, + num_element_is_dynamic, &list_shape)); + // Set up dynamic dimension sizes to create the zero tensor. + auto list_dynamic_dims_or = GetTensorListDynamicDims( + ctx, element_shape, list_shape, max_num_elements); + OP_REQUIRES_OK(ctx, list_dynamic_dims_or.status()); + + xla::XlaOp result; + OP_REQUIRES_OK(ctx, CreateZerosTensorListWithShape( + ctx->builder(), list_shape, + list_dynamic_dims_or.value(), &result)); + + ctx->SetTensorListOutput(0, result); + return; + } + } + + // We are creating a nested TensorList or a non-nested TensorList with + // unknown shape. Just create an uninitialized TensorList. + xla::XlaOp result = + BuildUninitializedTensorList(ctx->builder(), max_num_elements, + num_element_is_dynamic, ctx->Input(1)); + ctx->SetTensorListOutput(0, result); + } + + private: + DataType dtype_; + + EmptyTensorListOp(const EmptyTensorListOp&) = delete; + void operator=(const EmptyTensorListOp&) = delete; +}; + +REGISTER_XLA_OP(Name("EmptyTensorList") + .CompileTimeConstantInput("element_shape") + .CompileTimeConstantInput("max_num_elements") + .AllowVariantTypes(), + EmptyTensorListOp); + +class TensorListElementShapeOp : public XlaOpKernel { + public: + explicit TensorListElementShapeOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("shape_type", &shape_type_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + // Check that the TensorList is initialized. + bool is_initialized; + OP_REQUIRES_OK(ctx, + (IsTensorListInitialized(ctx->Input(0), &is_initialized))); + OP_REQUIRES(ctx, is_initialized, + errors::InvalidArgument("TensorList is not initialized")); + + // Only non-nested TensorList is supported for now. + bool is_nested; + OP_REQUIRES_OK(ctx, IsNestedTensorList(ctx->Input(0), &is_nested)); + OP_REQUIRES(ctx, !is_nested, + errors::Unimplemented("Only non-nested TensorList is supported " + "for TensorListElementShape.")); + + // For non-nested TensorList, element shape is the buffer shape without + // the first dimension. + xla::XlaBuilder* b = ctx->builder(); + xla::Shape list_shape; + OP_REQUIRES_OK(ctx, GetTensorListBufferShape(ctx->Input(0), &list_shape)); + list_shape.DeleteDimension(0); + + switch (shape_type_) { + case DT_INT64: + ctx->SetOutput(0, xla::ConstantR1(b, list_shape.dimensions())); + break; + case DT_INT32: { + std::vector size; + const auto& dimensions = list_shape.dimensions(); + size.reserve(dimensions.size()); + for (int64_t s : dimensions) { + size.push_back(s); + } + ctx->SetOutput(0, xla::ConstantR1(b, size)); + break; + } + default: + ctx->CtxFailure( + errors::InvalidArgument("Unsupported shape type requested")); + return; + } + } + + private: + DataType shape_type_; + + TensorListElementShapeOp(const TensorListElementShapeOp&) = delete; + void operator=(const TensorListElementShapeOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListElementShape").IsMetadataOp(), + TensorListElementShapeOp); + +class TensorListGetItemOp : public XlaOpKernel { + public: + explicit TensorListGetItemOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("element_dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + // Check that the TensorList is initialized. + bool is_initialized; + OP_REQUIRES_OK(ctx, + (IsTensorListInitialized(ctx->Input(0), &is_initialized))); + OP_REQUIRES(ctx, is_initialized, + errors::InvalidArgument("TensorList is not initialized")); + + // Only non-nested TensorList is supported for now. + bool is_nested; + OP_REQUIRES_OK(ctx, IsNestedTensorList(ctx->Input(0), &is_nested)); + OP_REQUIRES(ctx, !is_nested, + errors::Unimplemented("Only non-nested TensorList is supported " + "for TensorListGetItem.")); + + xla::XlaOp list = ctx->Input(0); + xla::XlaOp index = ctx->Input(1); + + xla::XlaOp result; + OP_REQUIRES_OK(ctx, ExecuteTensorListGetItem(list, index, &result)); + + ctx->SetOutput(0, result); + } + + private: + DataType dtype_; + + TensorListGetItemOp(const TensorListGetItemOp&) = delete; + void operator=(const TensorListGetItemOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListGetItem"), TensorListGetItemOp); + +class TensorListGatherOp : public XlaOpKernel { + public: + explicit TensorListGatherOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("element_dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + // Check that the TensorList is initialized. + bool is_initialized; + OP_REQUIRES_OK(ctx, + (IsTensorListInitialized(ctx->Input(0), &is_initialized))); + OP_REQUIRES(ctx, is_initialized, + errors::InvalidArgument("TensorList is not initialized")); + + // Only non-nested TensorList is supported for now. + bool is_nested; + OP_REQUIRES_OK(ctx, IsNestedTensorList(ctx->Input(0), &is_nested)); + OP_REQUIRES(ctx, !is_nested, + errors::Unimplemented("Only non-nested TensorList is supported " + "for TensorListGather.")); + + DataType indices_type = ctx->input_type(1); + + const TensorShape indices_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, indices_shape.dims() == 1, + errors::InvalidArgument("indices must be rank 1")); + + xla::XlaOp list = ctx->Input(0); + xla::XlaOp indices = ctx->Input(1); + + xla::XlaOp buffer; + OP_REQUIRES_OK(ctx, GetTensorListBuffer(list, &buffer)); + xla::Shape buffer_xla_shape; + OP_REQUIRES_OK(ctx, GetTensorListBufferShape(list, &buffer_xla_shape)); + TensorShape buffer_shape; + OP_REQUIRES_OK(ctx, XLAShapeToTensorShape(buffer_xla_shape, &buffer_shape)); + + xla::XlaOp result; + OP_REQUIRES_OK( + ctx, XlaGather(buffer, buffer_shape, indices, indices_shape, /*axis=*/0, + /*indices_are_nd=*/false, dtype_, indices_type, + ctx->builder(), &result)); + ctx->SetOutput(0, result); + } + + private: + DataType dtype_; + + TensorListGatherOp(const TensorListGatherOp&) = delete; + void operator=(const TensorListGatherOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListGather"), TensorListGatherOp); + +class TensorListStackOp : public XlaOpKernel { + public: + explicit TensorListStackOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // Check that the TensorList is initialized. + bool is_initialized; + OP_REQUIRES_OK(ctx, + (IsTensorListInitialized(ctx->Input(0), &is_initialized))); + OP_REQUIRES(ctx, is_initialized, + errors::InvalidArgument("TensorList is not initialized")); + + // Only non-nested TensorList is supported for now. + bool is_nested; + OP_REQUIRES_OK(ctx, IsNestedTensorList(ctx->Input(0), &is_nested)); + OP_REQUIRES(ctx, !is_nested, + errors::Unimplemented("Only non-nested TensorList is supported " + "for TensorListGetItem.")); + + xla::XlaOp buffer; + OP_REQUIRES_OK(ctx, GetTensorListBuffer(ctx->Input(0), &buffer)); + ctx->SetOutput(0, buffer); + } + + private: + TensorListStackOp(const TensorListStackOp&) = delete; + void operator=(const TensorListStackOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListStack"), TensorListStackOp); + +class TensorListConcatOp : public XlaOpKernel { + public: + explicit TensorListConcatOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input = ctx->Input(0); + + // Check that the TensorList is initialized. + bool is_initialized; + OP_REQUIRES_OK(ctx, (IsTensorListInitialized(input, &is_initialized))); + OP_REQUIRES(ctx, is_initialized, + errors::InvalidArgument("TensorList is not initialized")); + + // Only non-nested TensorList is supported for now. + bool is_nested; + OP_REQUIRES_OK(ctx, IsNestedTensorList(input, &is_nested)); + OP_REQUIRES(ctx, !is_nested, + errors::Unimplemented("Only non-nested TensorList is supported " + "for TensorListConcat.")); + + xla::XlaOp buffer; + OP_REQUIRES_OK(ctx, GetTensorListBuffer(input, &buffer)); + + xla::XlaBuilder* b = input.builder(); + auto shape_or = b->GetShape(buffer); + OP_REQUIRES_OK(ctx, shape_or.status()); + xla::Shape element_shape = std::move(shape_or).value(); + std::vector element_dims = + xla::SpanToVector(element_shape.dimensions()); + OP_REQUIRES( + ctx, element_dims.size() > 1, + errors::Unimplemented("TensorList of scalars is not supported")); + int64_t num_elements = element_dims[0]; + int64_t tensor_lengths = element_dims[1]; + + std::vector new_dims = {num_elements * tensor_lengths}; + + for (int i = 2; i < element_dims.size(); i++) { + new_dims.push_back(element_dims[i]); + } + + xla::XlaOp out = xla::Reshape(buffer, new_dims); + ctx->SetOutput(0, out); + + // Second output is a tensor of lengths of returned tensors. + xla::XlaOp lengths = xla::ConstantR1(b, num_elements, tensor_lengths); + ctx->SetOutput(1, lengths); + } + + private: + TensorListConcatOp(const TensorListConcatOp&) = delete; + void operator=(const TensorListConcatOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListConcatV2"), TensorListConcatOp); + +class TensorListSplitOp : public XlaOpKernel { + public: + explicit TensorListSplitOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("element_dtype", &dtype_)); + // Only non-nested TensorList is supported for now. + OP_REQUIRES( + ctx, dtype_ != DT_VARIANT, + errors::Unimplemented( + "Only non-nested TensorList is supported for TensorListReserve.")); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp input_tensor = ctx->Input(0); + + xla::XlaBuilder* b = input_tensor.builder(); + auto shape_or = b->GetShape(input_tensor); + OP_REQUIRES_OK(ctx, shape_or.status()); + xla::Shape element_shape = std::move(shape_or).value(); + std::vector element_dims = + xla::SpanToVector(element_shape.dimensions()); + OP_REQUIRES( + ctx, !element_dims.empty(), + errors::Unimplemented("Element dimensions have to be non-empty")); + + std::vector lengths; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(2, &lengths)); + OP_REQUIRES(ctx, !lengths.empty(), + errors::Unimplemented("Length has to be non-empty")); + int64_t length = lengths[0]; + for (int64_t len : lengths) { + OP_REQUIRES(ctx, len == length, + errors::Unimplemented("All lengths have to be the same")); + } + OP_REQUIRES(ctx, length > 0, + errors::Unimplemented("All lengths must be positive")); + OP_REQUIRES( + ctx, element_dims[0] % length == 0, + errors::Unimplemented("Buffer size has to be a multiple of length")); + std::vector new_dims = {element_dims[0] / length, length}; + for (int i = 1; i < element_dims.size(); i++) { + new_dims.push_back(element_dims[i]); + } + + xla::XlaOp reshaped = xla::Reshape(input_tensor, new_dims); + + xla::XlaOp result; + OP_REQUIRES_OK(ctx, ExecuteTensorListFromTensor(length, reshaped, &result)); + ctx->SetTensorListOutput(0, result); + } + + private: + DataType dtype_; + + TensorListSplitOp(const TensorListSplitOp&) = delete; + void operator=(const TensorListSplitOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListSplit") + .CompileTimeConstantInput("element_shape") + .CompileTimeConstantInput("lengths"), + TensorListSplitOp); + +class TensorListFromTensorOp : public XlaOpKernel { + public: + explicit TensorListFromTensorOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape& tensor_shape = ctx->InputShape(0); + int num_elements = tensor_shape.dim_size(0); + const xla::XlaOp tensor = ctx->Input(0); + xla::XlaOp result; + OP_REQUIRES_OK(ctx, + ExecuteTensorListFromTensor(num_elements, tensor, &result)); + auto list_shape_or = ctx->builder()->GetShape(result); + ctx->SetTensorListOutput(0, result); + } + + private: + TensorListFromTensorOp(const TensorListFromTensorOp&) = delete; + void operator=(const TensorListFromTensorOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("TensorListFromTensor").CompileTimeConstantInput("element_shape"), + TensorListFromTensorOp); + +class TensorListSetItemOp : public XlaOpKernel { + public: + explicit TensorListSetItemOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp list = ctx->Input(0); + xla::XlaOp index = ctx->Input(1); + xla::XlaOp element = ctx->Input(2); + xla::XlaOp initialized_list; + OP_REQUIRES_OK(ctx, GetInitializedTensorListForElement( + list, element, /*element_is_tensor_list=*/false, + &initialized_list)); + + // Only non-nested TensorList is supported for now. + bool is_nested; + OP_REQUIRES_OK(ctx, IsNestedTensorList(initialized_list, &is_nested)); + OP_REQUIRES(ctx, !is_nested, + errors::Unimplemented("Only non-nested TensorList is supported " + "for TensorListSetItem.")); + + xla::XlaOp result; + OP_REQUIRES_OK(ctx, ExecuteTensorListSetItem(initialized_list, index, + element, &result)); + + ctx->SetTensorListOutput(0, result); + } + + private: + TensorListSetItemOp(const TensorListSetItemOp&) = delete; + void operator=(const TensorListSetItemOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListSetItem"), TensorListSetItemOp); + +class TensorListPushBackOp : public XlaOpKernel { + public: + explicit TensorListPushBackOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp list = ctx->Input(0); + xla::XlaOp element = ctx->Input(1); + bool element_is_tensor_list = IsTensorListInput(ctx, 1); + xla::XlaOp initialized_list; + OP_REQUIRES_OK( + ctx, GetInitializedTensorListForElement( + list, element, element_is_tensor_list, &initialized_list)); + + xla::XlaOp result; + OP_REQUIRES_OK(ctx, + ExecuteTensorListPushBack(initialized_list, element, + element_is_tensor_list, &result)); + + ctx->SetTensorListOutput(0, result); + } + + private: + TensorListPushBackOp(const TensorListPushBackOp&) = delete; + void operator=(const TensorListPushBackOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListPushBack").AllowVariantTypes(), + TensorListPushBackOp); + +class TensorListPopBackOp : public XlaOpKernel { + public: + explicit TensorListPopBackOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + // Check that the TensorList is initialized. + bool is_initialized; + OP_REQUIRES_OK(ctx, + (IsTensorListInitialized(ctx->Input(0), &is_initialized))); + OP_REQUIRES(ctx, is_initialized, + errors::InvalidArgument("TensorList is not initialized")); + + xla::XlaOp list = ctx->Input(0); + xla::XlaOp list_result, element_result; + bool element_is_tensor_list; + OP_REQUIRES_OK(ctx, + ExecuteTensorListPopBack(list, &list_result, &element_result, + &element_is_tensor_list)); + + ctx->SetTensorListOutput(0, list_result); + if (element_is_tensor_list) { + ctx->SetTensorListOutput(1, element_result); + } else { + ctx->SetOutput(1, element_result); + } + } + + private: + DataType dtype_; + + TensorListPopBackOp(const TensorListPopBackOp&) = delete; + void operator=(const TensorListPopBackOp&) = delete; +}; + +REGISTER_XLA_OP(Name("TensorListPopBack").AllowVariantTypes(), + TensorListPopBackOp); + +} // anonymous namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..f603c1c517646ddbfda484c570af1e6929766afa --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.cc @@ -0,0 +1,593 @@ +/* Copyright 2019 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/kernels/tensor_list_utils.h" + +#include +#include + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +// TensorList is represented by a tuple. +// - The first part of the tuple is a buffer containing all the tensors, +// - The following parts are push indices for all nested levels of +// TensorLists. The last part is push index for the outermost TensorList. +// +// TensorList, as it name suggests, is conceptually a list of tensors. In actual +// representation of a non-nested TensorList, the buffer shape is +// [element_shape, tensor_list_size]. We will call tensor_list_size "leading +// dimension" below. Notice that the leading dimension must be a compile time +// constant, since it's part of the buffer shape. +// +// Example: consider a 3-level nested TensorList whose element type is scalar. +// Assume inner TensorList has leading dimension 4, middle TensorList has 3, +// and outer TensorList has 3. +// Assume that lower cased letter means there is data in that position, and "." +// means there is no data in that position. +// First element of outer TensorList: +// [ a . . . ] +// [ b c . . ] +// [ d e f . ] +// Second element of outer TensorList: +// [ g h i . ] +// [ j k . . ] +// [ . . . . ] +// Third element: not pushed yet. +// +// The first part of the tuple is an array of shape [3, 3, 4] containing data. +// The second part is an array of shape [3, 3], each element is push index +// for the inner TensorList. In this case, its values are: +// [ 1 2 3 ] +// [ 3 2 . ] +// [ . . . ] +// The third part is an array of shape [3], each element is push index for +// the middle TensorList. In this case, its values are: +// [ 3 ] +// [ 2 ] +// [ . ] +// The forth (and last) part is a scalar. It's the push index for the outer +// TensorList. In this case, its values is 2. +// +// Now imagine we need to push the following element to the outer TensorList: +// [ l . . . ] +// [ m n . . ] +// [ . . . . ] +// This element is represented by a tuple of 3 parts: +// First part is all data. +// Second part is push indices for the inner TensorList, which is [ 1 2 . ]. +// Third part is push index for the middle TensorList, which is 2. +// Now let's do the push. +// First, we append its data to outer TensorList's data. +// Then we start to deal with push indices. Similar to data, we append push +// indices for each level of TensorList. +// For the inner TensorList: append push indices for the pushed element. +// [ 1 2 3 ] [ 1 2 3 ] +// [ 3 2 . ] + = [ 3 2 . ] +// [ . . . ] [ 1 2 . ] [ 1 2 . ] +// For the middle TensorList: append push indices for the pushed element. +// [ 3 ] [ 3 ] +// [ 2 ] + = [ 2 ] +// [ . ] [ 2 ] [ 2 ] +// For the outer TensorList: just add 1. +// 2 + 1 = 3 +// +// Popping an element from the outer TensorList also follows a similar process. +// First part is data. We get data by slicing data with push index for outer +// TensorList (which is 3). +// Second part is push indices for inner TensorList. We get it by slicing +// push indices for inner TensorList with push index for outer TensorList (which +// is 3). +// [ 1 2 3 ] +// [ 3 2 . ] +// [ 1 2 . ] ===> This is what we want +// Third part is push index for middle TensorList. We get it by slicing +// push indices for middle TensorList with push index for outer TensorList +// (which is 3). +// [ 3 ] +// [ 2 ] +// [ 2 ] ===> This is what we want + +namespace tensorflow { + +bool IsTensorListInput(XlaOpKernelContext* ctx, int index) { + return ctx->InputExpression(index).kind() == XlaExpression::Kind::kTensorList; +} + +absl::Status IsTensorListInitialized(xla::XlaOp list, bool* is_initialized) { + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, list.builder()->GetShape(list)); + *is_initialized = list_shape.IsTuple(); + return absl::OkStatus(); +} + +absl::Status IsNestedTensorList(xla::XlaOp list, bool* is_nested_list) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, list.builder()->GetShape(list)); + *is_nested_list = (xla::ShapeUtil::TupleElementCount(list_shape) > 2); + return absl::OkStatus(); +} + +absl::Status BuildNonNestedTensorList(xla::XlaOp buffer, xla::XlaOp push_index, + xla::XlaOp* output_list) { + TF_RET_CHECK(buffer.builder()); + *output_list = xla::Tuple(buffer.builder(), {buffer, push_index}); + return absl::OkStatus(); +} + +absl::Status GetTensorListBufferShape(xla::XlaOp list, + xla::Shape* buffer_shape) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, list.builder()->GetShape(list)); + *buffer_shape = xla::ShapeUtil::GetTupleElementShape(list_shape, 0); + return absl::OkStatus(); +} + +absl::Status GetTensorListBuffer(xla::XlaOp list, xla::XlaOp* buffer) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + *buffer = xla::GetTupleElement(list, 0); + return absl::OkStatus(); +} + +absl::Status GetTensorListPushIndex(xla::XlaOp list, xla::XlaOp* push_index) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, list.builder()->GetShape(list)); + int tuple_size = xla::ShapeUtil::TupleElementCount(list_shape); + *push_index = xla::GetTupleElement(list, tuple_size - 1); + return absl::OkStatus(); +} + +absl::Status SetTensorListPushIndex(xla::XlaOp list, xla::XlaOp push_index, + xla::XlaOp* result) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, list.builder()->GetShape(list)); + int tuple_size = xla::ShapeUtil::TupleElementCount(list_shape); + std::vector result_parts; + result_parts.reserve(tuple_size); + for (int i = 0; i < tuple_size - 1; i++) { + result_parts.push_back(xla::GetTupleElement(list, i)); + } + result_parts.push_back(push_index); + *result = xla::Tuple(list.builder(), result_parts); + return absl::OkStatus(); +} + +xla::XlaOp BuildUninitializedTensorList(xla::XlaBuilder* b, + int64_t leading_dimension, + bool leading_size_is_dynamic, + xla::XlaOp leading_dim_size) { + auto zero = + xla::ConstantLiteral(b, xla::LiteralUtil::Zero(xla::PrimitiveType::S32)); + auto broadcast = + xla::Broadcast(zero, std::vector{leading_dimension}); + if (leading_size_is_dynamic) { + return xla::SetDimensionSize(broadcast, leading_dim_size, 0); + } else { + return broadcast; + } +} + +absl::Status GetLeadingDimForTensorList(xla::XlaOp list, int64_t* leading_dim, + bool* leading_dim_is_dynamic, + xla::XlaOp* leading_dim_dynamic_size) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, list.builder()->GetShape(list)); + if (is_initialized) { + auto buffer_shape = xla::ShapeUtil::GetTupleElementShape(list_shape, 0); + *leading_dim_is_dynamic = buffer_shape.is_dynamic_dimension(0); + auto buffer = xla::GetTupleElement(list, 0); + *leading_dim = buffer_shape.dimensions(0); + *leading_dim_dynamic_size = xla::GetDimensionSize(buffer, 0); + } else { + *leading_dim_is_dynamic = list_shape.is_dynamic_dimension(0); + *leading_dim = list_shape.dimensions(0); + *leading_dim_dynamic_size = xla::GetDimensionSize(list, 0); + } + return absl::OkStatus(); +} + +absl::Status GetTensorListShapeFromElementTensorListShape( + const xla::Shape& element_tensor_list_shape, int64_t leading_dim, + bool leading_dim_is_dynamic, xla::Shape* tensor_list_shape) { + std::vector shapes; + int tuple_size = xla::ShapeUtil::TupleElementCount(element_tensor_list_shape); + for (int i = 0; i < tuple_size; i++) { + const xla::Shape& shape = + xla::ShapeUtil::GetTupleElementShape(element_tensor_list_shape, i); + std::vector dimensions = xla::SpanToVector(shape.dimensions()); + dimensions.insert(dimensions.begin(), leading_dim); + shapes.push_back( + xla::ShapeUtil::MakeShape(shape.element_type(), dimensions)); + if (leading_dim_is_dynamic) { + shapes.back().set_dynamic_dimension(0, true); + } + } + shapes.push_back(xla::ShapeUtil::MakeShape(xla::PrimitiveType::S32, + std::vector{})); + *tensor_list_shape = xla::ShapeUtil::MakeTupleShape(shapes); + return absl::OkStatus(); +} + +absl::Status GetTensorListShapeFromElementShape(const xla::Shape& element_shape, + int64_t leading_dim, + bool leading_dim_is_dynamic, + xla::Shape* tensor_list_shape) { + if (!element_shape.IsArray()) { + return errors::InvalidArgument( + "GetTensorListShapeFromElementShape() only supports normal tensor " + "shape. But element shape is ", + element_shape.ToString()); + } + std::vector shapes; + std::vector dimensions = + xla::SpanToVector(element_shape.dimensions()); + dimensions.insert(dimensions.begin(), leading_dim); + shapes.push_back( + xla::ShapeUtil::MakeShape(element_shape.element_type(), dimensions)); + shapes.back().set_dynamic_dimension(0, leading_dim_is_dynamic); + shapes.push_back(xla::ShapeUtil::MakeShape(xla::PrimitiveType::S32, + std::vector{})); + *tensor_list_shape = xla::ShapeUtil::MakeTupleShape(shapes); + return absl::OkStatus(); +} + +absl::Status CreateZerosTensorListWithShape( + xla::XlaBuilder* b, const xla::Shape& list_shape, + const std::vector>& dynamic_dims, + xla::XlaOp* list) { + int tuple_size = xla::ShapeUtil::TupleElementCount(list_shape); + std::vector elements; + TF_RET_CHECK(dynamic_dims.size() == tuple_size - 1); + for (int i = 0; i < tuple_size - 1; i++) { + const xla::Shape& shape = + xla::ShapeUtil::GetTupleElementShape(list_shape, i); + xla::XlaOp zero = + xla::ConstantLiteral(b, xla::LiteralUtil::Zero(shape.element_type())); + xla::XlaOp zeros = xla::Broadcast(zero, shape.dimensions()); + TF_RET_CHECK(dynamic_dims[i].size() == shape.dimensions().size()); + for (int64_t dim = 0; dim < shape.dimensions().size(); ++dim) { + if (shape.is_dynamic_dimension(dim)) { + zeros = xla::SetDimensionSize(zeros, dynamic_dims[i][dim], dim); + } + } + elements.push_back(zeros); + } + // List size (last item) has to be S32. + TF_RET_CHECK(xla::ShapeUtil::GetTupleElementShape(list_shape, tuple_size - 1) + .element_type() == xla::S32); + elements.push_back(xla::ConstantLiteral(b, xla::LiteralUtil::Zero(xla::S32))); + *list = xla::Tuple(b, elements); + return absl::OkStatus(); +} + +absl::Status GetInitializedTensorListForElement(xla::XlaOp list, + xla::XlaOp element, + bool element_is_tensor_list, + xla::XlaOp* initialized_list) { + int64_t leading_dim; + xla::XlaOp leading_dim_dynamic_size; + bool leading_dim_is_dynamic; + TF_RETURN_IF_ERROR(GetLeadingDimForTensorList( + list, &leading_dim, &leading_dim_is_dynamic, &leading_dim_dynamic_size)); + + xla::XlaBuilder* b = list.builder(); + xla::Shape list_shape; + TF_ASSIGN_OR_RETURN(xla::Shape element_shape, b->GetShape(element)); + + if (element_is_tensor_list) { + TF_RETURN_IF_ERROR(GetTensorListShapeFromElementTensorListShape( + element_shape, leading_dim, leading_dim_is_dynamic, &list_shape)); + } else { + TF_RETURN_IF_ERROR(GetTensorListShapeFromElementShape( + element_shape, leading_dim, leading_dim_is_dynamic, &list_shape)); + } + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (is_initialized) { + // Check shape of initialized list is correct. + TF_ASSIGN_OR_RETURN(xla::Shape original_list_shape, b->GetShape(list)); + if (!xla::ShapeUtil::Compatible(original_list_shape, list_shape)) { + return errors::Internal( + "Invalid TensorList shape: ", original_list_shape.ToString(), + ", expected: ", list_shape.ToString()); + } + *initialized_list = list; + return absl::OkStatus(); + } else { + // Prepare dynamic dimension dimensions for zero tensor list. The dynamic + // sizes are created by reading the dynamic dimension size of sub-elements. + std::vector> list_dynamic_dims; + for (int i = 0; i < list_shape.tuple_shapes().size() - 1; ++i) { + std::vector dynamic_dims; + const xla::Shape& shape = list_shape.tuple_shapes(i); + dynamic_dims.push_back(leading_dim_dynamic_size); + xla::XlaOp sub_element; + if (element_is_tensor_list) { + sub_element = xla::GetTupleElement(element, i); + } else { + sub_element = element; + } + for (int64_t dim = 0; dim < shape.dimensions().size() - 1; ++dim) { + dynamic_dims.push_back(xla::GetDimensionSize(sub_element, dim)); + } + list_dynamic_dims.push_back(dynamic_dims); + } + return CreateZerosTensorListWithShape(b, list_shape, list_dynamic_dims, + initialized_list); + } +} + +absl::Status ExecuteTensorListPushBack(xla::XlaOp list, xla::XlaOp element, + bool element_is_tensor_list, + xla::XlaOp* result) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + + xla::XlaBuilder* b = list.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, b->GetShape(list)); + int list_tuple_size = xla::ShapeUtil::TupleElementCount(list_shape); + xla::XlaOp push_index = xla::GetTupleElement(list, list_tuple_size - 1); + + std::vector result_parts; + + if (element_is_tensor_list) { + TF_ASSIGN_OR_RETURN(xla::Shape element_shape, b->GetShape(element)); + int element_tuple_size = xla::ShapeUtil::TupleElementCount(element_shape); + for (int i = 0; i < element_tuple_size; i++) { + const xla::Shape& element_part_shape = + xla::ShapeUtil::GetTupleElementShape(element_shape, i); + xla::XlaOp element_part = xla::GetTupleElement(element, i); + std::vector element_part_dims = + xla::SpanToVector(element_part_shape.dimensions()); + element_part_dims.insert(element_part_dims.begin(), 1); + element_part = xla::Reshape(element_part, element_part_dims); + + std::vector start_indices( + element_part_shape.dimensions().size() + 1, + xla::ConstantR0(b, 0)); + start_indices[0] = push_index; + + xla::XlaOp list_part = xla::GetTupleElement(list, i); + xla::XlaOp updated_list_part = + xla::DynamicUpdateSlice(list_part, element_part, start_indices); + result_parts.push_back(updated_list_part); + } + } else { + TF_ASSIGN_OR_RETURN(xla::Shape element_shape, b->GetShape(element)); + std::vector element_dims = + xla::SpanToVector(element_shape.dimensions()); + element_dims.insert(element_dims.begin(), 1); + xla::XlaOp update = xla::Reshape(element, element_dims); + + std::vector start_indices(element_shape.dimensions().size() + 1, + xla::ConstantR0(b, 0)); + start_indices[0] = push_index; + + xla::XlaOp list_part = xla::GetTupleElement(list, 0); + xla::XlaOp updated_list_part = + xla::DynamicUpdateSlice(list_part, update, start_indices); + result_parts.push_back(updated_list_part); + } + + xla::XlaOp updated_push_index = push_index + xla::ConstantR0(b, 1); + result_parts.push_back(updated_push_index); + + *result = xla::Tuple(b, result_parts); + return absl::OkStatus(); +} + +absl::Status ExecuteTensorListPopBack(xla::XlaOp list, xla::XlaOp* list_result, + xla::XlaOp* element_result, + bool* element_is_tensor_list) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + + // If the TensorList is a nested TensorList, element will be TensorList. + TF_RETURN_IF_ERROR(IsNestedTensorList(list, element_is_tensor_list)); + + xla::XlaBuilder* b = list.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, b->GetShape(list)); + int list_tuple_size = xla::ShapeUtil::TupleElementCount(list_shape); + xla::XlaOp push_index = xla::GetTupleElement(list, list_tuple_size - 1); + push_index = push_index - xla::ConstantR0(b, 1); + + std::vector list_result_parts, element_result_parts; + for (int i = 0; i < list_tuple_size - 1; i++) { + const xla::Shape& list_part_shape = + xla::ShapeUtil::GetTupleElementShape(list_shape, i); + std::vector start_indices(list_part_shape.dimensions().size(), + xla::ConstantR0(b, 0)); + start_indices[0] = push_index; + + std::vector slice_shape = + xla::SpanToVector(list_part_shape.dimensions()); + slice_shape[0] = 1LL; + + xla::XlaOp list_part = xla::GetTupleElement(list, i); + xla::XlaOp read = xla::DynamicSlice(list_part, start_indices, slice_shape); + + slice_shape.erase(slice_shape.begin()); + element_result_parts.push_back(xla::Reshape(read, slice_shape)); + list_result_parts.push_back(list_part); + } + list_result_parts.push_back(push_index); + + *list_result = xla::Tuple(b, list_result_parts); + if (*element_is_tensor_list) { + *element_result = xla::Tuple(b, element_result_parts); + } else { + *element_result = element_result_parts[0]; + } + + return absl::OkStatus(); +} + +absl::Status ExecuteTensorListSetItem(xla::XlaOp list, xla::XlaOp index, + xla::XlaOp element, xla::XlaOp* result) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + bool is_nested; + TF_RETURN_IF_ERROR(IsNestedTensorList(list, &is_nested)); + if (is_nested) { + return errors::Unimplemented( + "ExecuteTensorListSetItem() only supports non-nested TensorList"); + } + + xla::XlaBuilder* b = list.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape element_shape, b->GetShape(element)); + std::vector element_dims = + xla::SpanToVector(element_shape.dimensions()); + element_dims.insert(element_dims.begin(), 1); + xla::XlaOp update = xla::Reshape(element, element_dims); + + std::vector start_indices(element_shape.dimensions().size() + 1, + xla::ConstantR0(b, 0)); + start_indices[0] = index; + + xla::XlaOp list_part = xla::GetTupleElement(list, 0); + { + TF_ASSIGN_OR_RETURN(const xla::Shape* list_part_shape, + b->GetShapePtr(list_part)); + TF_ASSIGN_OR_RETURN(const xla::Shape* update_shape, b->GetShapePtr(update)); + for (int i = 0; i < list_part_shape->dimensions().size(); ++i) { + auto list_part_dim_size = list_part_shape->dimensions(i); + auto update_dim_size = update_shape->dimensions(i); + // If the update is larger than the list part, the DynamicUpdateSlice will + // fail so just ignore this operation and return list as is. + if (update_dim_size > list_part_dim_size) { + LOG_FIRST_N(WARNING, 1) + << "Warning: TensorListSetItem: ignoring set item because the " + "update dim [" + << update_dim_size << "] is larger than the list dim [" + << list_part_dim_size << "] at dimension " << i << "."; + + *result = list; + return absl::OkStatus(); + } + } + } + xla::XlaOp updated_list_part = + xla::DynamicUpdateSlice(list_part, update, start_indices); + + std::vector result_parts; + result_parts.push_back(updated_list_part); + result_parts.push_back(xla::GetTupleElement(list, 1)); + *result = xla::Tuple(b, result_parts); + return absl::OkStatus(); +} + +absl::Status ExecuteTensorListGetItem(xla::XlaOp list, xla::XlaOp index, + xla::XlaOp* result) { + bool is_initialized; + TF_RETURN_IF_ERROR(IsTensorListInitialized(list, &is_initialized)); + if (!is_initialized) { + return errors::InvalidArgument("TensorList is not initialized"); + } + bool is_nested; + TF_RETURN_IF_ERROR(IsNestedTensorList(list, &is_nested)); + if (is_nested) { + return errors::Unimplemented( + "ExecuteTensorListGetItem() only supports non-nested TensorList"); + } + + xla::XlaBuilder* b = list.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape list_shape, b->GetShape(list)); + const xla::Shape& buffer_shape = + xla::ShapeUtil::GetTupleElementShape(list_shape, 0); + std::vector start_indices(buffer_shape.dimensions().size(), + xla::ConstantR0(b, 0)); + start_indices[0] = index; + + std::vector slice_shape = + xla::SpanToVector(buffer_shape.dimensions()); + slice_shape[0] = 1LL; + + xla::XlaOp list_part = xla::GetTupleElement(list, 0); + xla::XlaOp read = xla::DynamicSlice(list_part, start_indices, slice_shape); + // Propagate dynamic dimensions from buffer to the sliced buffer, except for + // leading dimension (which is always static 1). + for (int64_t i = 1; i < buffer_shape.dimensions().size(); ++i) { + if (buffer_shape.is_dynamic_dimension(i)) { + auto buffer = xla::GetTupleElement(list, 0); + auto gds = xla::GetDimensionSize(buffer, i); + read = xla::SetDimensionSize(read, gds, i); + } + } + slice_shape.erase(slice_shape.begin()); + *result = xla::Reshape(read, slice_shape); + return absl::OkStatus(); +} + +absl::Status ExecuteTensorListFromTensor(int push_index, xla::XlaOp tensor, + xla::XlaOp* result) { + xla::XlaBuilder* b = tensor.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape shape, b->GetShape(tensor)); + if (!shape.IsArray()) { + return errors::InvalidArgument( + "ExecuteTensorListFromTensor() only supports normal tensor. But input " + "shape is ", + shape.ToString()); + } + + std::vector result_parts{tensor, + xla::ConstantR0(b, push_index)}; + *result = xla::Tuple(b, result_parts); + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..6d5e3e71e69e5050b11e097869e9db3ad8c0168b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h @@ -0,0 +1,135 @@ +/* Copyright 2019 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_KERNELS_TENSOR_LIST_UTILS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_TENSOR_LIST_UTILS_H_ + +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +// Whether the input expression at `index` corresponds to a TensorList. +bool IsTensorListInput(XlaOpKernelContext* ctx, int index); + +// Whether the TensorList is initialized (has known data type and shape). +absl::Status IsTensorListInitialized(xla::XlaOp list, bool* is_initialized); + +// Whether the TensorList is a nested TensorList. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status IsNestedTensorList(xla::XlaOp list, bool* is_nested_list); + +// Builds a non-nested TensorList from `buffer` and `push_index`. +absl::Status BuildNonNestedTensorList(xla::XlaOp buffer, xla::XlaOp push_index, + xla::XlaOp* output_list); + +// Returns buffer shape for the TensorList. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status GetTensorListBufferShape(xla::XlaOp list, + xla::Shape* buffer_shape); + +// Returns buffer for the TensorList. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status GetTensorListBuffer(xla::XlaOp list, xla::XlaOp* buffer); + +// Returns push index for the TensorList. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status GetTensorListPushIndex(xla::XlaOp list, xla::XlaOp* push_index); + +// Returns a new TensorList with given push_index. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status SetTensorListPushIndex(xla::XlaOp list, xla::XlaOp push_index, + xla::XlaOp* result); + +// Returns an uninitialized TensorList. +xla::XlaOp BuildUninitializedTensorList(xla::XlaBuilder* b, + int64_t leading_dimension, + bool leading_size_is_dynamic, + xla::XlaOp leading_dim_size); + +// Returns leading dimension for the TensorList as well as a dynamic op +// representing the dynamic size. Input can be initialized or uninitialized +// TensorList. Non-nested and nested TensorLists are both supported. +absl::Status GetLeadingDimForTensorList(xla::XlaOp list, int64_t* leading_dim, + bool* leading_dim_is_dynamic, + xla::XlaOp* leading_dim_dynamic_size); + +// Returns TensorList shape for the element shape. +// Element shape must be a normal tensor shape. +absl::Status GetTensorListShapeFromElementShape(const xla::Shape& element_shape, + int64_t leading_dim, + bool leading_dim_is_dynamic, + xla::Shape* tensor_list_shape); + +// Returns a TensorList filled by zeros with the given shape. +absl::Status CreateZerosTensorListWithShape( + xla::XlaBuilder* b, const xla::Shape& list_shape, + const std::vector>& dynamic_dims, xla::XlaOp* list); + +// If the TensorList is initialized, check that its shape matches element shape; +// If the TensorList is uninitialized, initialize it with the element shape. +// Input can be initialized or uninitialized TensorList. +// "element" can be normal tensor or TensorList. +absl::Status GetInitializedTensorListForElement(xla::XlaOp list, + xla::XlaOp element, + bool element_is_tensor_list, + xla::XlaOp* initialized_list); + +// Executes TensorListPushBack with given TensorList and element. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status ExecuteTensorListPushBack(xla::XlaOp list, xla::XlaOp element, + bool element_is_tensor_list, + xla::XlaOp* result); + +// Executes TensorListPopBack with given TensorList. +// Input must be an initialized TensorList. +// Non-nested and nested TensorLists are both supported. +absl::Status ExecuteTensorListPopBack(xla::XlaOp list, xla::XlaOp* list_result, + xla::XlaOp* element_result, + bool* element_is_tensor_list); + +// Executes TensorListSetItem with given TensorList, index and element. +// Input must be an initialized TensorList. +// Only non-nested TensorList is supported. +absl::Status ExecuteTensorListSetItem(xla::XlaOp list, xla::XlaOp index, + xla::XlaOp element, xla::XlaOp* result); + +// Executes TensorListGetItem with given TensorList and index. +// Input must be an initialized TensorList. +// Only non-nested TensorList is supported. +absl::Status ExecuteTensorListGetItem(xla::XlaOp list, xla::XlaOp index, + xla::XlaOp* result); + +// Executes TensorListPushBack with given tensor and push index. +// "tensor" must be a normal tensor. +absl::Status ExecuteTensorListFromTensor(int push_index, xla::XlaOp tensor, + xla::XlaOp* result); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_TENSOR_LIST_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tile_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tile_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..d7a7b505b6b04569a55f92a30774ada55d9f2e0d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tile_ops.cc @@ -0,0 +1,126 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Tile Op. + +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/lib/broadcast.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +namespace { + +// -------------------------------------------------------------------------- +class TileOp : public XlaOpKernel { + public: + explicit TileOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + const TensorShape multiples_shape = ctx->InputShape("multiples"); + + OP_REQUIRES( + ctx, TensorShapeUtils::IsVector(multiples_shape), + errors::InvalidArgument("Expected multiples to be 1-D, but got shape ", + multiples_shape.DebugString())); + OP_REQUIRES(ctx, input_shape.dims() == multiples_shape.num_elements(), + errors::InvalidArgument( + "Expected multiples argument to be a vector of length ", + input_shape.dims(), " but got length ", + multiples_shape.dim_size(0))); + const int input_dims = input_shape.dims(); + auto input = ctx->Input(0); + // If input is a scalar then multiples has 0 elements and this is + // a NoOp. + if (input_dims == 0) { + ctx->SetOutput(0, input); + return; + } + + std::vector multiples_bounds; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector( + "multiples", &multiples_bounds, + xla::ValueInferenceMode::kUpperBound)); + + std::vector output_dims(input_shape.dims()); + for (int64_t i = 0; i < input_shape.dims(); ++i) { + OP_REQUIRES(ctx, multiples_bounds[i] >= 0, + errors::InvalidArgument("Expected multiples[", i, + "] >= 0, but got ", output_dims[i])); + output_dims[i] = input_shape.dim_size(i) * multiples_bounds[i]; + } + + std::vector multiples_are_dynamic; + + OP_REQUIRES_OK(ctx, ctx->ResolveInputDynamismIntoPredVector( + 1, &multiples_are_dynamic)); + + bool all_multiples_are_static = absl::c_all_of( + multiples_are_dynamic, [](bool dynamic) { return !dynamic; }); + // If a value is static, it means the upper bound is the value itself: + // constant_value = constant_upper_boudn = counstant_lower_bound + if (all_multiples_are_static) { + // If all multiples are 1, than the input is the same as the output. + if (absl::c_all_of(multiples_bounds, + [](int64_t multiple) { return multiple == 1; })) { + ctx->SetOutput(0, input); + return; + } + } + + auto result_or = BroadcastTo(ctx->Input("input"), output_dims); + + OP_REQUIRES_OK(ctx, result_or.status()); + auto result = result_or.value(); + if (!all_multiples_are_static) { + // Some values of multiples are unknown at compile time, this is a dynamic + // tile op. We need to call set dimension size. + for (int64_t i = 0; i < multiples_are_dynamic.size(); ++i) { + if (!multiples_are_dynamic[i]) { + continue; + } + // If a dimension is dynamic, call set-dimension-size on the output. + auto dynamic_dim_size = + xla::Slice(ctx->Input("multiples"), {i}, {i + 1}, {1}); + dynamic_dim_size = xla::Reshape(dynamic_dim_size, {}); + dynamic_dim_size = xla::ConvertElementType(dynamic_dim_size, xla::S32); + result = xla::SetDimensionSize(result, dynamic_dim_size, i); + } + } + + ctx->SetOutput(0, result); + } + + private: + TileOp(const TileOp&) = delete; + void operator=(const TileOp&) = delete; +}; + +REGISTER_XLA_OP(Name("Tile").CompileTimeConstantInput("multiples"), TileOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/to_bool_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/to_bool_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..fe24386cd5a6b1893dfacb949cad2097e70ba93e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/to_bool_op.cc @@ -0,0 +1,68 @@ +/* Copyright 2021 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 + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace { + +class ToBoolOp : public XlaOpKernel { + public: + explicit ToBoolOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES_OK(ctx, DoCompile(ctx)); + } + + private: + absl::Status DoCompile(XlaOpKernelContext* ctx) { + auto input = ctx->Input(0); + + // If the input is a scalar, then non-zero value returns True. + TF_ASSIGN_OR_RETURN(auto shape, ctx->InputXlaShape(0)); + if (shape.dimensions().empty()) { + auto result = xla::Ne(ctx->Input(0), xla::ZerosLike(input)); + ctx->SetOutput(0, result); + return absl::OkStatus(); + } + + // Otherwise, any input tensor with elements returns True. Input tensor + // dimensions might be dynamic with bounds so multiply all the dimensions. + xla::XlaOp num_elements = xla::One(ctx->builder(), xla::S32); + for (int64_t dim = 0; dim < shape.dimensions().size(); dim++) { + num_elements = xla::Mul(num_elements, xla::GetDimensionSize(input, dim)); + } + auto result = xla::Ne(num_elements, xla::ZerosLike(num_elements)); + ctx->SetOutput(0, result); + + return absl::OkStatus(); + } +}; + +REGISTER_XLA_OP(Name("ToBool"), ToBoolOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/topk_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/topk_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..765a7160a2848905212a3243207e8dfc7bd3f88b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/topk_op.cc @@ -0,0 +1,109 @@ +/* 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 + +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/sorting.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class TopKOp : public XlaOpKernel { + public: + explicit TopKOp(OpKernelConstruction* context) : XlaOpKernel(context) { + OP_REQUIRES_OK(context, context->GetAttr("sorted", &sorted_)); + DataType index_type; + OP_REQUIRES_OK(context, context->GetAttr("index_type", &index_type)); + OP_REQUIRES_OK(context, DataTypeToPrimitiveType(index_type, &index_type_)); + } + + void Compile(XlaOpKernelContext* context) override { + const absl::StatusOr input_shape_or = context->InputXlaShape(0); + OP_REQUIRES_OK(context, input_shape_or.status()); + const xla::Shape& input_shape = *input_shape_or; + int last_dim = input_shape.dimensions().size() - 1; + int last_dim_size = input_shape.dimensions(last_dim); + + int64_t k; + bool k_bound_inferrable = + context + ->ConstantInputAsIntScalar(1, &k, + xla::ValueInferenceMode::kUpperBound) + .ok(); + if (!k_bound_inferrable) { + // - If we can infer the bound of K, use the bound. + // - If not, use last dim's size. + k = last_dim_size; + } + OP_REQUIRES(context, k >= 0, + errors::InvalidArgument("Need k >= 0, got ", k)); + + OP_REQUIRES(context, input_shape.dimensions().size() >= 1, + errors::InvalidArgument("input must be >= 1-D, got shape ", + input_shape.ToString())); + + OP_REQUIRES( + context, last_dim_size >= k, + errors::InvalidArgument("input must have at least k columns. Had ", + last_dim_size, ", needed ", k)); + if (last_dim_size < k) { + k = last_dim_size; + } + + bool k_is_dynamic; + OP_REQUIRES_OK(context, + context->ResolveInputDynamismIntoPred(1, &k_is_dynamic)); + xla::XlaOp output_tuple = TopK(context->Input(0), k, index_type_); + auto values = xla::GetTupleElement(output_tuple, 0); + auto indices = xla::GetTupleElement(output_tuple, 1); + if (k_is_dynamic) { + xla::XlaOp dynamic_k = context->Input(1); + values = xla::SetDimensionSize(values, dynamic_k, last_dim); + indices = xla::SetDimensionSize(indices, dynamic_k, last_dim); + } + context->SetOutput(0, values); + context->SetOutput(1, indices); + } + + private: + bool sorted_; + xla::PrimitiveType index_type_; +}; + +REGISTER_XLA_OP(Name("TopKV2") + .CompileTimeConstantInput("k") + .TypeConstraint("T", + {DT_UINT32, DT_INT32, DT_UINT64, DT_INT64, + DT_FLOAT, DT_HALF, DT_DOUBLE, DT_BFLOAT16, + DT_UINT8, DT_INT8, DT_INT16}) + .TypeConstraint("Tk", {DT_INT16, DT_INT32, DT_INT64}) + .TypeConstraint("index_type", + {DT_INT16, DT_INT32, DT_INT64}), + TopKOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/training_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/training_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..620310d09ec9bf89efae373c879859823150e656 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/training_ops.cc @@ -0,0 +1,1080 @@ +/* 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/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class ResourceApplyGradientDescent : public XlaOpKernel { + public: + explicit ResourceApplyGradientDescent(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp handle; + DataType type = ctx->input_type(1); + TensorShape var_shape; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, type, &var_shape, &handle)); + + TensorShape alpha_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha_shape), + errors::InvalidArgument("alpha is not a scalar: ", + alpha_shape.DebugString())); + + TensorShape delta_shape = ctx->InputShape(2); + OP_REQUIRES( + ctx, var_shape.IsSameSize(delta_shape), + errors::InvalidArgument("var and delta do not have the same shape: ", + var_shape.DebugString(), " vs ", + delta_shape.DebugString())); + + handle = handle - ctx->Input(1) * ctx->Input(2); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, handle)); + } +}; +REGISTER_XLA_OP(Name("ResourceApplyGradientDescent") + .TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyGradientDescent); + +xla::XlaOp ProximalGradientDescentUpdate(xla::XlaOp var, xla::XlaOp lr, + xla::XlaOp l1, xla::XlaOp l2, + xla::XlaOp grad) { + xla::XlaOp one = xla::ScalarLike(lr, 1.0); + xla::XlaOp zero = xla::ScalarLike(lr, 0.0); + xla::XlaOp prox_var = var - grad * lr; + xla::XlaOp l1_gt_zero = + xla::Sign(prox_var) * xla::Max(xla::Abs(prox_var) - lr * l1, zero); + xla::XlaOp l1_le_zero = prox_var; + return xla::Select(xla::Gt(l1, zero), l1_gt_zero, l1_le_zero) / + (one + lr * l2); +} + +class ResourceApplyProximalGradientDescent : public XlaOpKernel { + public: + explicit ResourceApplyProximalGradientDescent(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp var; + TensorShape var_shape; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + + TensorShape alpha_shape = ctx->InputShape(1); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha_shape), + errors::InvalidArgument("alpha is not a scalar: ", + alpha_shape.DebugString())); + TensorShape l1_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha_shape), + errors::InvalidArgument("l1 is not a scalar: ", + l1_shape.DebugString())); + TensorShape l2_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha_shape), + errors::InvalidArgument("l2 is not a scalar: ", + l2_shape.DebugString())); + TensorShape delta_shape = ctx->InputShape(4); + OP_REQUIRES( + ctx, var_shape.IsSameSize(delta_shape), + errors::InvalidArgument("var and delta do not have the same shape: ", + var_shape.DebugString(), " vs ", + delta_shape.DebugString())); + xla::XlaOp alpha = ctx->Input(1); + xla::XlaOp l1 = ctx->Input(2); + xla::XlaOp l2 = ctx->Input(3); + xla::XlaOp delta = ctx->Input(4); + var = ProximalGradientDescentUpdate(var, alpha, l1, l2, delta); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + } + + private: + DataType dtype_; +}; +REGISTER_XLA_OP(Name("ResourceApplyProximalGradientDescent") + .TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyProximalGradientDescent); + +class ResourceApplyMomentum : public XlaOpKernel { + public: + explicit ResourceApplyMomentum(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("use_nesterov", &use_nesterov_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->input_type(2); + + TensorShape var_shape, accum_shape; + xla::XlaOp var, accum; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, type, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, type, &accum_shape, &accum)); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + TensorShape lr_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + + TensorShape grad_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + TensorShape momentum_shape = ctx->InputShape(4); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum_shape), + errors::InvalidArgument("momentum is not a scalar: ", + momentum_shape.DebugString())); + + xla::XlaOp lr = ctx->Input(2); + xla::XlaOp grad = ctx->Input(3); + xla::XlaOp momentum = ctx->Input(4); + + accum = accum * momentum + grad; + if (use_nesterov_) { + // See https://github.com/tensorflow/tensorflow/pull/2798 for an + // explanation of the reparameterization used here. + var = var - (grad * lr + accum * momentum * lr); + } else { + var = var - accum * lr; + } + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, type, accum)); + } + + private: + bool use_nesterov_; +}; +REGISTER_XLA_OP(Name("ResourceApplyMomentum").TypeConstraint("T", kFloatTypes), + ResourceApplyMomentum); + +class ResourceApplyKerasMomentum : public XlaOpKernel { + public: + explicit ResourceApplyKerasMomentum(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("use_nesterov", &use_nesterov_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->input_type(2); + + TensorShape var_shape, accum_shape; + xla::XlaOp var, accum; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, type, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, type, &accum_shape, &accum)); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + TensorShape lr_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + + TensorShape grad_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + TensorShape momentum_shape = ctx->InputShape(4); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum_shape), + errors::InvalidArgument("momentum is not a scalar: ", + momentum_shape.DebugString())); + + xla::XlaOp lr = ctx->Input(2); + xla::XlaOp grad = ctx->Input(3); + xla::XlaOp momentum = ctx->Input(4); + + accum = accum * momentum - grad * lr; + if (use_nesterov_) { + // See https://github.com/tensorflow/tensorflow/pull/2798 for an + // explanation of the reparameterization used here. + var = var + accum * momentum - grad * lr; + } else { + var = var + accum; + } + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, type, accum)); + } + + private: + bool use_nesterov_; +}; +REGISTER_XLA_OP(Name("ResourceApplyKerasMomentum") + .TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyKerasMomentum); + +class ResourceApplyAdagrad : public XlaOpKernel { + public: + explicit ResourceApplyAdagrad(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("update_slots", &update_slots_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->input_type(2); + + TensorShape var_shape, accum_shape; + xla::XlaOp var, accum; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, type, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, type, &accum_shape, &accum)); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + TensorShape lr_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + + TensorShape grad_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + xla::XlaOp lr = ctx->Input(2); + xla::XlaOp grad = ctx->Input(3); + + if (update_slots_) { + accum = accum + xla::Square(grad); + } + var = var - grad * lr * xla::Rsqrt(accum); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, type, accum)); + } + + private: + bool update_slots_; +}; +REGISTER_XLA_OP( + Name("ResourceApplyAdagrad").TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyAdagrad); + +class ResourceApplyAdagradV2 : public XlaOpKernel { + public: + explicit ResourceApplyAdagradV2(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("update_slots", &update_slots_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->input_type(2); + + TensorShape var_shape, accum_shape; + xla::XlaOp var, accum; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, type, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, type, &accum_shape, &accum)); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + TensorShape lr_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + + TensorShape epsilon_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon_shape), + errors::InvalidArgument("epsilon is not a scalar: ", + epsilon_shape.DebugString())); + + TensorShape grad_shape = ctx->InputShape(4); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + xla::XlaOp lr = ctx->Input(2); + xla::XlaOp epsilon = ctx->Input(3); + xla::XlaOp grad = ctx->Input(4); + + if (update_slots_) { + accum = accum + xla::Square(grad); + } + var = var - grad * lr / (xla::Sqrt(accum) + epsilon); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, type, accum)); + } + + private: + bool update_slots_; +}; +REGISTER_XLA_OP( + Name("ResourceApplyAdagradV2").TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyAdagradV2); + +class ResourceApplyProximalAdagrad : public XlaOpKernel { + public: + explicit ResourceApplyProximalAdagrad(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, accum_shape; + xla::XlaOp var, accum; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput(1, dtype_, &accum_shape, &accum)); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + TensorShape lr_shape = ctx->InputShape(2); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + TensorShape l1_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(l1_shape), + errors::InvalidArgument("l1 is not a scalar: ", + l1_shape.DebugString())); + TensorShape l2_shape = ctx->InputShape(4); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(l2_shape), + errors::InvalidArgument("l2 is not a scalar: ", + l2_shape.DebugString())); + TensorShape grad_shape = ctx->InputShape(5); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape: ", + var_shape.DebugString(), " vs ", grad_shape.DebugString())); + + xla::XlaOp lr = ctx->Input(2); + xla::XlaOp l1 = ctx->Input(3); + xla::XlaOp l2 = ctx->Input(4); + xla::XlaOp grad = ctx->Input(5); + accum = accum + xla::Square(grad); + // Adagrad learning rate. + xla::XlaOp adagrad_lr = lr * xla::Rsqrt(accum); + var = ProximalGradientDescentUpdate(var, adagrad_lr, l1, l2, grad); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype_, accum)); + } + + private: + DataType dtype_; +}; +REGISTER_XLA_OP(Name("ResourceApplyProximalAdagrad") + .TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyProximalAdagrad); + +class ResourceApplyAdagradDA : public XlaOpKernel { + public: + explicit ResourceApplyAdagradDA(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, accum_shape, squared_accum_shape; + xla::XlaOp var, accum, squared_accum; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput(1, dtype_, &accum_shape, &accum)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(2, dtype_, &squared_accum_shape, + &squared_accum)); + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + OP_REQUIRES( + ctx, var_shape.IsSameSize(squared_accum_shape), + errors::InvalidArgument( + "var and squared accum do not have the same shape", + var_shape.DebugString(), " ", squared_accum_shape.DebugString())); + + TensorShape grad_shape = ctx->InputShape(3); + TensorShape lr_shape = ctx->InputShape(4); + TensorShape l1_shape = ctx->InputShape(5); + TensorShape l2_shape = ctx->InputShape(6); + TensorShape global_step_shape = ctx->InputShape(7); + + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(l1_shape), + errors::InvalidArgument("l1 is not a scalar: ", + l1_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(l2_shape), + errors::InvalidArgument("l2 is not a scalar: ", + l2_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(global_step_shape), + errors::InvalidArgument("global step is not a scalar: ", + global_step_shape.DebugString())); + + xla::XlaOp grad = ctx->Input(3); + xla::XlaOp lr = ctx->Input(4); + xla::XlaOp l1 = ctx->Input(5); + xla::XlaOp l2 = ctx->Input(6); + xla::XlaOp global_step = + XlaHelpers::ConvertElementType(ctx->Input(7), dtype_); + + accum = accum + grad; + squared_accum = squared_accum + xla::Square(grad); + xla::XlaOp zero = xla::ScalarLike(lr, 0.0); + xla::XlaOp denominator = global_step * lr * l2 + xla::Sqrt(squared_accum); + xla::XlaOp l1_le_zero = -lr * accum / denominator; + xla::XlaOp l1_gt_zero = -lr * xla::Sign(accum) * + xla::Max(xla::Abs(accum) - global_step * l1, zero) / + denominator; + + var = xla::Select(xla::Gt(l1, zero), l1_gt_zero, l1_le_zero); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype_, accum)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(2, dtype_, squared_accum)); + } + + private: + DataType dtype_; +}; +REGISTER_XLA_OP(Name("ResourceApplyAdagradDA").TypeConstraint("T", kFloatTypes), + ResourceApplyAdagradDA); + +class ResourceApplyAdam : public XlaOpKernel { + public: + explicit ResourceApplyAdam(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("use_nesterov", &use_nesterov_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, m_shape, v_shape; + xla::XlaOp var, m, v; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, dtype_, &m_shape, &m)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(2, dtype_, &v_shape, &v)); + + TensorShape beta1_power_shape = ctx->InputShape(3); + TensorShape beta2_power_shape = ctx->InputShape(4); + TensorShape lr_shape = ctx->InputShape(5); + TensorShape beta1_shape = ctx->InputShape(6); + TensorShape beta2_shape = ctx->InputShape(7); + TensorShape epsilon_shape = ctx->InputShape(8); + TensorShape grad_shape = ctx->InputShape(9); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_power_shape), + errors::InvalidArgument("beta1_power is not a scalar: ", + beta1_power_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2_power_shape), + errors::InvalidArgument("beta2_power is not a scalar: ", + beta2_power_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar : ", + lr_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_shape), + errors::InvalidArgument("beta1 is not a scalar: ", + beta1_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2_shape), + errors::InvalidArgument("beta2 is not a scalar: ", + beta2_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon_shape), + errors::InvalidArgument("epsilon is not a scalar: ", + epsilon_shape.DebugString())); + + OP_REQUIRES(ctx, var_shape.IsSameSize(m_shape), + errors::InvalidArgument("var and m do not have the same shape", + var_shape.DebugString(), " ", + m_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(v_shape), + errors::InvalidArgument("var and v do not have the same shape", + var_shape.DebugString(), " ", + v_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + xla::XlaOp beta1_power = ctx->Input(3); + xla::XlaOp beta2_power = ctx->Input(4); + xla::XlaOp lr = ctx->Input(5); + xla::XlaOp beta1 = ctx->Input(6); + xla::XlaOp beta2 = ctx->Input(7); + xla::XlaOp epsilon = ctx->Input(8); + xla::XlaOp grad = ctx->Input(9); + + // alpha <- learning_rate * sqrt(1 - beta2^t) / (1 - beta1^t) + // m_t <- beta1 * m_{t-1} + (1 - beta1) * g_t + // v_t <- beta2 * v_{t-1} + (1 - beta2) * g_t * g_t + // if not use_nesterov: + // variable <- variable - alpha * m_t / (sqrt(v_t) + epsilon) + // if use_nesterov: + // variable <- variable - alpha * (m_t * beta1 + (1 - beta1) * g_t) / + // (sqrt(v_t) + epsilon) + + xla::XlaBuilder* b = ctx->builder(); + xla::XlaOp one = XlaHelpers::FloatLiteral(b, dtype_, 1.0); + + xla::XlaOp alpha = lr * xla::Sqrt(one - beta2_power) / (one - beta1_power); + auto m_t = m + (grad - m) * (one - beta1); + v = v + (xla::Square(grad) - v) * (one - beta2); + if (use_nesterov_) { + var = var - alpha * (m_t * beta1 + (one - beta1) * grad) / + (xla::Sqrt(v) + epsilon); + } else { + var = var - m_t * alpha / (xla::Sqrt(v) + epsilon); + } + + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype_, m_t)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(2, dtype_, v)); + } + + private: + DataType dtype_; + bool use_nesterov_; +}; +REGISTER_XLA_OP( + Name("ResourceApplyAdam").TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyAdam); + +class ResourceApplyAdaMax : public XlaOpKernel { + public: + explicit ResourceApplyAdaMax(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, m_shape, v_shape; + xla::XlaOp var, m, v; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, dtype_, &m_shape, &m)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(2, dtype_, &v_shape, &v)); + + TensorShape beta1_power_shape = ctx->InputShape(3); + TensorShape lr_shape = ctx->InputShape(4); + TensorShape beta1_shape = ctx->InputShape(5); + TensorShape beta2_shape = ctx->InputShape(6); + TensorShape epsilon_shape = ctx->InputShape(7); + TensorShape grad_shape = ctx->InputShape(8); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_power_shape), + errors::InvalidArgument("beta1_power is not a scalar: ", + beta1_power_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar : ", + lr_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta1_shape), + errors::InvalidArgument("beta1 is not a scalar: ", + beta1_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta2_shape), + errors::InvalidArgument("beta2 is not a scalar: ", + beta2_shape.DebugString())); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon_shape), + errors::InvalidArgument("epsilon is not a scalar: ", + epsilon_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(m_shape), + errors::InvalidArgument("var and m do not have the same shape", + var_shape.DebugString(), " ", + m_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(v_shape), + errors::InvalidArgument("var and v do not have the same shape", + var_shape.DebugString(), " ", + v_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + xla::XlaOp beta1_power = ctx->Input(3); + xla::XlaOp lr = ctx->Input(4); + xla::XlaOp beta1 = ctx->Input(5); + xla::XlaOp beta2 = ctx->Input(6); + xla::XlaOp epsilon = ctx->Input(7); + xla::XlaOp grad = ctx->Input(8); + + xla::XlaOp one = xla::ScalarLike(lr, 1.0); + m = beta1 * m + (one - beta1) * grad; + v = xla::Max(beta2 * v, xla::Abs(grad)); + var = var - lr / (one - beta1_power) * (m / (v + epsilon)); + + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype_, m)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(2, dtype_, v)); + } + + private: + DataType dtype_; +}; +REGISTER_XLA_OP(Name("ResourceApplyAdaMax").TypeConstraint("T", kFloatTypes), + ResourceApplyAdaMax); + +class ResourceApplyRMSProp : public XlaOpKernel { + public: + explicit ResourceApplyRMSProp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, ms_shape, mom_shape, mg_shape; + xla::XlaOp var, ms, mom, mg; + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput("var", dtype_, &var_shape, &var)); + if (centered_) { + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput("mg", dtype_, &mg_shape, &mg)); + } + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput("ms", dtype_, &ms_shape, &ms)); + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput("mom", dtype_, &mom_shape, &mom)); + + TensorShape lr_shape = ctx->InputShape("lr"); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + TensorShape rho_shape = ctx->InputShape("rho"); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(rho_shape), + errors::InvalidArgument("rho is not a scalar: ", + rho_shape.DebugString())); + TensorShape momentum_shape = ctx->InputShape("momentum"); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(momentum_shape), + errors::InvalidArgument("momentum is not a scalar: ", + momentum_shape.DebugString())); + TensorShape epsilon_shape = ctx->InputShape("epsilon"); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon_shape), + errors::InvalidArgument("epsilon is not a scalar: ", + epsilon_shape.DebugString())); + TensorShape grad_shape = ctx->InputShape("grad"); + + // var should be the same shape as mom and ms. + OP_REQUIRES(ctx, var_shape.IsSameSize(ms_shape), + errors::InvalidArgument("var and ms do not have the same shape", + var_shape.DebugString(), " ", + ms_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(mom_shape), + errors::InvalidArgument( + "var and mom do not have the same shape", + var_shape.DebugString(), " ", mom_shape.DebugString())); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + xla::XlaOp lr = ctx->Input("lr"); + xla::XlaOp rho = ctx->Input("rho"); + xla::XlaOp momentum = ctx->Input("momentum"); + xla::XlaOp epsilon = ctx->Input("epsilon"); + xla::XlaOp grad = ctx->Input("grad"); + + // ms <- rho * ms_{t-1} + (1-rho) * grad * grad + // mom <- momentum * mom_{t-1} + lr * grad / sqrt(ms + epsilon) + // var <- var - mom + // + // We use an alternate formulation of the ms equation: + // + // ms <- ms + (grad**2 - ms) * (1 - rho) + // + // Which expands to: + // + // ms <- ms + grad**2 - rho * grad ** 2 - ms + ms * rho + // + // Which simplifies to: + // + // ms <- grad**2 (1 - rho) + ms * rho + // + // Which is the equation listed above. + xla::XlaOp one = xla::ScalarLike(ms, 1.0); + xla::XlaOp new_ms = xla::Square(grad) * (one - rho) + ms * rho; + xla::XlaOp denominator; + if (centered_) { + mg = grad * (one - rho) + mg * rho; + denominator = new_ms - xla::Square(mg) + epsilon; + } else { + denominator = new_ms + epsilon; + } + xla::XlaOp new_mom = mom * momentum + grad * lr * xla::Rsqrt(denominator); + xla::XlaOp new_var = var - new_mom; + + OP_REQUIRES_OK(ctx, ctx->AssignVariable("var", dtype_, new_var)); + if (centered_) { + OP_REQUIRES_OK(ctx, ctx->AssignVariable("mg", dtype_, mg)); + } + OP_REQUIRES_OK(ctx, ctx->AssignVariable("ms", dtype_, new_ms)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable("mom", dtype_, new_mom)); + } + + protected: + bool centered_ = false; + + private: + DataType dtype_; +}; +REGISTER_XLA_OP( + Name("ResourceApplyRMSProp").TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyRMSProp); + +class ResourceApplyCenteredRMSProp : public ResourceApplyRMSProp { + public: + explicit ResourceApplyCenteredRMSProp(OpKernelConstruction* ctx) + : ResourceApplyRMSProp(ctx) { + centered_ = true; + } +}; +REGISTER_XLA_OP(Name("ResourceApplyCenteredRMSProp") + .TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyCenteredRMSProp); + +void CompileFtrl(XlaOpKernelContext* ctx, DataType dtype, bool has_l2_shrinkage, + bool multiply_linear_by_lr) { + xla::XlaBuilder* b = ctx->builder(); + + TensorShape var_shape, accum_shape, linear_shape; + xla::XlaOp var, accum, linear; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, dtype, &accum_shape, &accum)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(2, dtype, &linear_shape, &linear)); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + OP_REQUIRES(ctx, var_shape.IsSameSize(linear_shape), + errors::InvalidArgument( + "var and linear do not have the same shape", + var_shape.DebugString(), " ", linear_shape.DebugString())); + + TensorShape grad_shape = ctx->InputShape(3); + TensorShape lr_shape = ctx->InputShape(4); + TensorShape l1_shape = ctx->InputShape(5); + TensorShape l2_shape = ctx->InputShape(6); + TensorShape l2_shrinkage_shape; + TensorShape lr_power_shape; + if (has_l2_shrinkage) { + l2_shrinkage_shape = ctx->InputShape(7); + lr_power_shape = ctx->InputShape(8); + } else { + lr_power_shape = ctx->InputShape(7); + } + + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument("var and grad do not have the same shape", + var_shape.DebugString(), " ", + grad_shape.DebugString())); + + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", lr_shape.DebugString())); + + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(l1_shape), + errors::InvalidArgument("l1 is not a scalar: ", l1_shape.DebugString())); + + OP_REQUIRES( + ctx, TensorShapeUtils::IsScalar(l2_shape), + errors::InvalidArgument("l2 is not a scalar: ", l2_shape.DebugString())); + + if (has_l2_shrinkage) { + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(l2_shrinkage_shape), + errors::InvalidArgument("l2_shrinkage is not a scalar: ", + l2_shrinkage_shape.DebugString())); + } + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_power_shape), + errors::InvalidArgument("lr_power is not a scalar: ", + lr_power_shape.DebugString())); + + xla::XlaOp grad = ctx->Input(3); + xla::XlaOp lr = ctx->Input(4); + xla::XlaOp l1 = ctx->Input(5); + xla::XlaOp l2 = ctx->Input(6); + xla::XlaOp l2_shrinkage; + xla::XlaOp lr_power; + if (has_l2_shrinkage) { + l2_shrinkage = ctx->Input(7); + lr_power = ctx->Input(8); + } else { + lr_power = ctx->Input(7); + } + + // grad_to_use = grad + 2 * l2_shrinkage * var + // new_accum = accum + grad * grad + // linear += grad_to_use - + // (new_accum^(-lr_power) - accum^(-lr_power)) / lr * var + // quadratic = (new_accum^(-lr_power) / lr) + 2 * l2 + // linear_clipped = clamp linear in [-l1, l1] + // var = (linear_clipped - linear) / quadratic + // accum = new_accum + + xla::XlaOp two = XlaHelpers::FloatLiteral(b, dtype, 2.0); + xla::XlaOp grad_to_use; + if (has_l2_shrinkage) { + grad_to_use = grad + two * l2_shrinkage * var; + } else { + grad_to_use = grad; + } + + xla::XlaOp new_accum = accum + xla::Square(grad); + xla::XlaOp new_accum_lr_pow = xla::Pow(new_accum, -lr_power); + xla::XlaOp accum_lr_pow = xla::Pow(accum, -lr_power); + if (multiply_linear_by_lr) { + linear = + linear + grad_to_use * lr - (new_accum_lr_pow - accum_lr_pow) * var; + } else { + linear = + linear + grad_to_use - (new_accum_lr_pow - accum_lr_pow) / lr * var; + } + xla::XlaOp linear_clipped = + (multiply_linear_by_lr ? xla::Clamp(-l1 * lr, linear, l1 * lr) + : xla::Clamp(-l1, linear, l1)); + xla::XlaOp quadratic = + (multiply_linear_by_lr ? new_accum_lr_pow + two * l2 * lr + : new_accum_lr_pow / lr + two * l2); + var = (linear_clipped - linear) / quadratic; + accum = new_accum; + + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype, accum)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(2, dtype, linear)); +} + +class ResourceApplyFtrl : public XlaOpKernel { + public: + explicit ResourceApplyFtrl(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + OP_REQUIRES_OK( + ctx, ctx->GetAttr("multiply_linear_by_lr", &multiply_linear_by_lr_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + CompileFtrl(ctx, dtype_, /*has_l2_shrinkage=*/false, + /*multiply_linear_by_lr=*/multiply_linear_by_lr_); + } + + private: + DataType dtype_; + + // Whether to keep the "linear" slot variable multiplied by the learning rate. + bool multiply_linear_by_lr_; +}; +REGISTER_XLA_OP(Name("ResourceApplyFtrl").TypeConstraint("T", kFloatTypes), + ResourceApplyFtrl); + +class ResourceApplyFtrlV2 : public XlaOpKernel { + public: + explicit ResourceApplyFtrlV2(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + OP_REQUIRES_OK( + ctx, ctx->GetAttr("multiply_linear_by_lr", &multiply_linear_by_lr_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + CompileFtrl(ctx, dtype_, /*has_l2_shrinkage=*/true, + /*multiply_linear_by_lr=*/multiply_linear_by_lr_); + } + + private: + DataType dtype_; + + // Whether to keep the "linear" slot variable multiplied by the learning rate. + bool multiply_linear_by_lr_; +}; +REGISTER_XLA_OP(Name("ResourceApplyFtrlV2").TypeConstraint("T", kFloatTypes), + ResourceApplyFtrlV2); + +class ResourceApplyAdadelta : public XlaOpKernel { + public: + explicit ResourceApplyAdadelta(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, accum_shape, accum_update_shape; + xla::XlaOp var, accum, accum_update; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput(1, dtype_, &accum_shape, &accum)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(2, dtype_, &accum_update_shape, + &accum_update)); + + TensorShape lr_shape = ctx->InputShape(3); + TensorShape rho_shape = ctx->InputShape(4); + TensorShape epsilon_shape = ctx->InputShape(5); + TensorShape grad_shape = ctx->InputShape(6); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(rho_shape), + errors::InvalidArgument("rho is not a scalar: ", + rho_shape.DebugString())); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(epsilon_shape), + errors::InvalidArgument("epsilon is not a scalar: ", + epsilon_shape.DebugString())); + + OP_REQUIRES(ctx, var_shape.IsSameSize(accum_shape), + errors::InvalidArgument( + "var and accum do not have the same shape", + var_shape.DebugString(), " ", accum_shape.DebugString())); + + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + + xla::XlaOp lr = ctx->Input(3); + xla::XlaOp rho = ctx->Input(4); + xla::XlaOp epsilon = ctx->Input(5); + xla::XlaOp grad = ctx->Input(6); + + xla::XlaBuilder* b = ctx->builder(); + xla::XlaOp one = XlaHelpers::FloatLiteral(b, dtype_, 1.0); + + accum = rho * accum + (one - rho) * xla::Square(grad); + xla::XlaOp update = + xla::Sqrt(accum_update + epsilon) * xla::Rsqrt(accum + epsilon) * grad; + accum_update = rho * accum_update + (one - rho) * xla::Square(update); + var = var - update * lr; + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype_, accum)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(2, dtype_, accum_update)); + } + + private: + DataType dtype_; +}; +REGISTER_XLA_OP( + Name("ResourceApplyAdadelta").TypeConstraint("T", kFloatAndComplexTypes), + ResourceApplyAdadelta); + +class ResourceApplySignBase : public XlaOpKernel { + public: + explicit ResourceApplySignBase(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("T", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + TensorShape var_shape, m_shape; + xla::XlaOp var, m; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, dtype_, &var_shape, &var)); + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(1, dtype_, &m_shape, &m)); + OP_REQUIRES(ctx, var_shape.IsSameSize(m_shape), + errors::InvalidArgument("var and m do not have the same shape", + var_shape.DebugString(), " ", + m_shape.DebugString())); + TensorShape grad_shape = ctx->InputShape(6); + OP_REQUIRES(ctx, var_shape.IsSameSize(grad_shape), + errors::InvalidArgument( + "var and grad do not have the same shape", + var_shape.DebugString(), " ", grad_shape.DebugString())); + CheckScalarParams(ctx); + + xla::XlaOp lr = ctx->Input(2); + xla::XlaOp alpha = ctx->Input(3); + xla::XlaOp sign_decay = ctx->Input(4); + xla::XlaOp beta = ctx->Input(5); + xla::XlaOp grad = ctx->Input(6); + + m = m * beta + grad * (xla::ScalarLike(beta, 1.0) - beta); + xla::XlaOp decay = xla::Sign(grad) * xla::Sign(m) * sign_decay; + + xla::XlaOp grad_scale = ComputeGradientScale(alpha, decay); + var = var - lr * grad_scale * grad; + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, dtype_, var)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(1, dtype_, m)); + } + + virtual void CheckScalarParams(XlaOpKernelContext* ctx) { + TensorShape lr_shape = ctx->InputShape(2); + TensorShape sign_decay_shape = ctx->InputShape(4); + TensorShape beta_shape = ctx->InputShape(5); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(lr_shape), + errors::InvalidArgument("lr is not a scalar: ", + lr_shape.DebugString())); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(sign_decay_shape), + errors::InvalidArgument("sign_decay is not a scalar: ", + sign_decay_shape.DebugString())); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(beta_shape), + errors::InvalidArgument("beta is not a scalar: ", + beta_shape.DebugString())); + } + + virtual xla::XlaOp ComputeGradientScale(xla::XlaOp alpha, + xla::XlaOp decay) = 0; + + private: + DataType dtype_; +}; + +class ResourceApplyAddSign : public ResourceApplySignBase { + public: + explicit ResourceApplyAddSign(OpKernelConstruction* ctx) + : ResourceApplySignBase(ctx) {} + + void CheckScalarParams(XlaOpKernelContext* ctx) override { + ResourceApplySignBase::CheckScalarParams(ctx); + TensorShape alpha_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(alpha_shape), + errors::InvalidArgument("alpha is not a scalar: ", + alpha_shape.DebugString())); + } + + xla::XlaOp ComputeGradientScale(xla::XlaOp alpha, xla::XlaOp decay) override { + return alpha + decay; + } +}; +REGISTER_XLA_OP(Name("ResourceApplyAddSign").TypeConstraint("T", kFloatTypes), + ResourceApplyAddSign); + +class ResourceApplyPowerSign : public ResourceApplySignBase { + public: + explicit ResourceApplyPowerSign(OpKernelConstruction* ctx) + : ResourceApplySignBase(ctx) {} + + void CheckScalarParams(XlaOpKernelContext* ctx) override { + ResourceApplySignBase::CheckScalarParams(ctx); + TensorShape logbase_shape = ctx->InputShape(3); + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(logbase_shape), + errors::InvalidArgument("logbase is not a scalar: ", + logbase_shape.DebugString())); + } + + xla::XlaOp ComputeGradientScale(xla::XlaOp alpha, xla::XlaOp decay) override { + return xla::Exp(alpha * decay); + } +}; +REGISTER_XLA_OP(Name("ResourceApplyPowerSign").TypeConstraint("T", kFloatTypes), + ResourceApplyPowerSign); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/transpose_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/transpose_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..1d77466af8aa3592ff66e8ae57dd2b5526b0f3f2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/transpose_op.cc @@ -0,0 +1,211 @@ +/* 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. +==============================================================================*/ + +// XLA-specific Transpose Op. This is very different to the Eigen +// version in third_party/tensorflow because XLA's reshape neatly +// handles all transposes, while Eigen needs a restricted DoTranspose +// helper. + +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/lib/scatter.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/primitive_util.h" +#include "tensorflow/core/framework/bounds_check.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class TransposeOp : public XlaOpKernel { + public: + explicit TransposeOp(OpKernelConstruction* ctx, bool conjugate = false) + : XlaOpKernel(ctx), conjugate_(conjugate) {} + + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("x"); + const TensorShape perm_tensor_shape = ctx->InputShape("perm"); + + // Preliminary validation of sizes. + OP_REQUIRES(ctx, TensorShapeUtils::IsVector(perm_tensor_shape), + errors::InvalidArgument("perm must be a vector, not ", + perm_tensor_shape.DebugString())); + + const int dims = input_shape.dims(); + OP_REQUIRES(ctx, dims == perm_tensor_shape.num_elements(), + errors::InvalidArgument("transpose expects a vector of size ", + input_shape.dims(), + ". But input(1) is a vector of size ", + perm_tensor_shape.num_elements())); + + std::vector perm; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector("perm", &perm)); + + std::vector transposed_order; + // Check whether permutation is a permutation of integers of [0 .. dims). + absl::InlinedVector bits(dims); + bool is_identity = true; + for (int i = 0; i < dims; ++i) { + const int64_t d = perm[i]; + OP_REQUIRES( + ctx, 0 <= d && d < dims, + errors::InvalidArgument(d, " is out of range [0 .. ", dims, ")")); + bits[d] = true; + transposed_order.push_back(d); + if (d != i) { + is_identity = false; + } + } + for (int i = 0; i < dims; ++i) { + OP_REQUIRES( + ctx, bits[i], + errors::InvalidArgument(i, " is missing from 'perm' argument.")); + } + + xla::XlaOp transposed; + // 0-D, 1-D, and identity transposes do nothing. + if (dims <= 1 || is_identity) { + transposed = ctx->Input("x"); + } else { + transposed = xla::Transpose(ctx->Input("x"), transposed_order); + } + + // Conjugate the transposed result if this is ConjugateTransposeOp. + if (conjugate_) { + ctx->SetOutput(0, xla::Conj(transposed)); + } else { + ctx->SetOutput(0, transposed); + } + } + + private: + const bool conjugate_; +}; + +class ConjugateTransposeOp : public TransposeOp { + public: + explicit ConjugateTransposeOp(OpKernelConstruction* ctx) + : TransposeOp(ctx, /*conjugate=*/true) {} +}; + +REGISTER_XLA_OP(Name("Transpose").CompileTimeConstantInput("perm"), + TransposeOp); + +REGISTER_XLA_OP(Name("ConjugateTranspose").CompileTimeConstantInput("perm"), + ConjugateTransposeOp); + +// InvertPermutation frequently forms part of the gradient of Transpose. +// +// inv = InvertPermutationOp(p) takes a permutation of +// integers 0, 1, ..., n - 1 and returns the inverted +// permutation of p. I.e., inv[p[i]] == i, for i in [0 .. n). +// +// REQUIRES: input is a vector of int32 or int64. +// REQUIRES: input is a permutation of 0, 1, ..., n-1. + +class InvertPermutationOp : public XlaOpKernel { + public: + explicit InvertPermutationOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + DataType dtype = ctx->expected_output_dtype(0); + absl::Status status; + switch (dtype) { + case DT_INT32: + InvertPermutation(ctx); + break; + case DT_INT64: + InvertPermutation(ctx); + break; + default: + // This should never happen since we restrict this kernel to only match + // inputs with supported Tensor datatype. + OP_REQUIRES_OK(ctx, errors::InvalidArgument( + "InvertPermutation expects x as either ", + "int32 or int64, not ", DataTypeString(dtype))); + } + } + + template + void InvertPermutation(XlaOpKernelContext* ctx) { + OP_REQUIRES(ctx, + FastBoundsCheck(ctx->InputShape(0).num_elements(), + std::numeric_limits::max()), + errors::InvalidArgument( + "permutation of nonnegative integers must have <= ", + std::numeric_limits::max(), " elements")); + + auto e = ctx->InputExpression(0); + auto* client = ctx->compiler() ? ctx->compiler()->client() : nullptr; + auto tensor_or_status = e.ResolveConstant(client); + OP_REQUIRES_OK(ctx, tensor_or_status.status()); + // If the input is a constant, we also want the output to be a constant. + // Some models rely on the result of InvertPermutation being a constant. + // TODO(b/32495713): Remove this when we can check whether Scatter is + // constant. Right now, we always assume it is non-constant because we don't + // check the embedded computation. + if (tensor_or_status.value().has_value()) { + std::vector perm; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(0, &perm)); + + int size = perm.size(); + + std::vector output(size); + std::fill_n(output.data(), size, -1); + for (int i = 0; i < size; ++i) { + const int64_t d = perm[i]; + OP_REQUIRES(ctx, FastBoundsCheck(d, size), + errors::InvalidArgument(d, " is not between 0 and ", size)); + OP_REQUIRES(ctx, output[d] == -1, + errors::InvalidArgument(d, " is duplicated in the input.")); + output[d] = i; + } + + ctx->SetOutput(0, xla::ConstantR1(ctx->builder(), output)); + } else { + auto indices = ctx->Input(0); + T size = ctx->InputShape(0).num_elements(); + auto iota = + xla::Iota(ctx->builder(), + xla::primitive_util::NativeToPrimitiveType(), size); + auto result = XlaScatter(iota, iota, indices, + /*indices_are_vectors=*/false, + /*indices_are_sorted=*/false, + /*combiner=*/{}, ctx->builder()); + OP_REQUIRES_OK(ctx, result.status()); + ctx->SetOutput(0, result.value()); + } + } +}; + +REGISTER_XLA_OP( + Name("InvertPermutation").TypeConstraint("T", {DT_INT32, DT_INT64}), + InvertPermutationOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tridiagonal_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tridiagonal_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..e3410bf965d3aae3101b953014bae47946883746 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/tridiagonal_ops.cc @@ -0,0 +1,80 @@ +/* Copyright 2019 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/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/slicing.h" +#include "xla/hlo/builder/lib/tridiagonal.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class TridiagonalSolveOp : public XlaOpKernel { + public: + explicit TridiagonalSolveOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + auto diagonals = ctx->Input(0); + auto rhs = ctx->Input(1); + bool partial_pivoting = false; + OP_REQUIRES_OK(ctx, + GetNodeAttr(def(), "partial_pivoting", &partial_pivoting)); + if (partial_pivoting) { + ctx->SetStatus(errors::Unimplemented( + "Current implementation does not yet support pivoting.")); + return; + } + + auto result = xla::tridiagonal::TridiagonalSolver(xla::tridiagonal::kThomas, + diagonals, rhs); + if (!result.ok()) { + ctx->SetStatus(result.status()); + return; + } + ctx->SetOutput(0, result.value()); + } +}; + +class TridiagonalMatMulOp : public XlaOpKernel { + public: + explicit TridiagonalMatMulOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + auto upper_diagonal = ctx->Input(0); + auto main_diagonal = ctx->Input(1); + auto lower_diagonal = ctx->Input(2); + auto rhs = ctx->Input(3); + + auto result = xla::tridiagonal::TridiagonalMatMul( + upper_diagonal, main_diagonal, lower_diagonal, rhs); + if (!result.ok()) { + ctx->SetStatus(result.status()); + return; + } + ctx->SetOutput(0, result.value()); + } +}; + +REGISTER_XLA_OP(Name("TridiagonalSolve").TypeConstraint("T", kFloatTypes), + TridiagonalSolveOp); + +REGISTER_XLA_OP(Name("TridiagonalMatMul").TypeConstraint("T", kFloatTypes), + TridiagonalMatMulOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unary_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unary_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..9dad102cd8e8ca9ce19830409bc4207618217759 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unary_ops.cc @@ -0,0 +1,136 @@ +/* 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. +==============================================================================*/ + +// Native XLA implementations of simple unary Ops + +#include + +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { +namespace { + +#define XLAJIT_MAKE_UNARY(NAME, COMPUTATION) \ + class NAME##Op : public XlaOpKernel { \ + public: \ + explicit NAME##Op(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} \ + void Compile(XlaOpKernelContext* ctx) { \ + xla::XlaBuilder* b = ctx->builder(); \ + (void)b; \ + xla::XlaOp x = ctx->Input(0); \ + xla::XlaOp y = COMPUTATION; \ + ctx->SetOutput(0, y); \ + } \ + }; \ + REGISTER_XLA_OP(Name(#NAME), NAME##Op); + +XLAJIT_MAKE_UNARY(ComplexAbs, xla::Abs(x)); + +XLAJIT_MAKE_UNARY(Angle, xla::Atan2(xla::Imag(x), xla::Real(x))); + +XLAJIT_MAKE_UNARY(Conj, xla::Conj(x)); + +// Return x if x>0, otherwise -x. +REGISTER_XLA_OP(Name("Abs"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Acos"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Acosh"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Asin"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Asinh"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Atan"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Atanh"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Ceil"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Cos"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Cosh"), MlirXlaOpKernel); +XLAJIT_MAKE_UNARY(Sin, xla::Sin(x)); +XLAJIT_MAKE_UNARY(Tan, xla::Tan(x)); +REGISTER_XLA_OP(Name("Exp"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Expm1"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Floor"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("IsFinite"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("IsInf"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("IsNan"), MlirXlaOpKernel); +// Return 1/x +XLAJIT_MAKE_UNARY(Inv, xla::ScalarLike(x, 1.0) / x); +REGISTER_XLA_OP(Name("Reciprocal"), MlirXlaOpKernel); +XLAJIT_MAKE_UNARY(Log, xla::Log(x)); +REGISTER_XLA_OP(Name("Log1p"), MlirXlaOpKernel); + +XLAJIT_MAKE_UNARY(Invert, xla::Not(x)); +XLAJIT_MAKE_UNARY(LogicalNot, xla::Not(x)); +XLAJIT_MAKE_UNARY(PopulationCount, + xla::ConvertElementType(xla::PopulationCount(x), xla::U8)); +XLAJIT_MAKE_UNARY(Neg, -x); + +XLAJIT_MAKE_UNARY(Rint, xla::RoundToEven(x)); +XLAJIT_MAKE_UNARY(Round, xla::RoundToEven(x)); + +REGISTER_XLA_OP(Name("Rsqrt"), MlirXlaOpKernel); + +REGISTER_XLA_OP(Name("Sigmoid"), MlirXlaOpKernel); + +// Returns NaN if x is NaN, 0 if x is 0, -1 if x < 0 and 1 if x > 0. +REGISTER_XLA_OP(Name("Sign"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Sinh"), MlirXlaOpKernel); + +static xla::XlaOp Softplus(xla::XlaBuilder* b, xla::XlaOp features) { + return b->ReportErrorOrReturn([&]() -> absl::StatusOr { + TF_ASSIGN_OR_RETURN(auto shape, b->GetShape(features)); + xla::XlaOp threshold = + Log(xla::Epsilon(b, shape.element_type())) + ScalarLike(features, 2.0); + // Value above which exp(x) may overflow, but softplus(x) == x + // is within machine epsilon. + xla::XlaOp too_large = Gt(features, -threshold); + // Value below which exp(x) may underflow, but softplus(x) == exp(x) + // is within machine epsilon. + xla::XlaOp too_small = Lt(features, threshold); + xla::XlaOp features_exp = Exp(features); + xla::XlaOp output = + Select(too_large, features, + Select(too_small, features_exp, Log1p(features_exp))); + return output; + }); +} +XLAJIT_MAKE_UNARY(Softplus, Softplus(b, x)); + +// softsign(x) = x / (abs(x) + 1) +XLAJIT_MAKE_UNARY(Softsign, x / (xla::Abs(x) + xla::ScalarLike(x, 1.0))); +REGISTER_XLA_OP(Name("Sqrt"), MlirXlaOpKernel); +XLAJIT_MAKE_UNARY(Square, x* x); +REGISTER_XLA_OP(Name("Tanh"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Real"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("Imag"), MlirXlaOpKernel); +XLAJIT_MAKE_UNARY(Erf, xla::Erf(x)); +XLAJIT_MAKE_UNARY(Erfc, xla::Erfc(x)); +XLAJIT_MAKE_UNARY(Erfinv, xla::ErfInv(x)); +// ndtri = sqrt(2) * erfinv(2 * x - 1) +XLAJIT_MAKE_UNARY(Ndtri, xla::ScalarLike(x, std::sqrt(2.0)) * + xla::ErfInv(xla::ScalarLike(x, 2.0) * x - + xla::ScalarLike(x, 1.0))); +REGISTER_XLA_OP(Name("Lgamma"), MlirXlaOpKernel); +XLAJIT_MAKE_UNARY(Digamma, xla::Digamma(x)); +XLAJIT_MAKE_UNARY(BesselI0e, xla::BesselI0e(x)); +XLAJIT_MAKE_UNARY(BesselI1e, xla::BesselI1e(x)); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unary_ops_composition.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unary_ops_composition.cc new file mode 100644 index 0000000000000000000000000000000000000000..bbe5c715b882b41063d5e96d865f58ebe421f4ee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unary_ops_composition.cc @@ -0,0 +1,129 @@ +/* Copyright 2019 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 +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/log/check.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/kernels/elu_op.h" +#include "tensorflow/compiler/tf2xla/kernels/relu_op.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +using XlaUnaryOpGenerator = std::function; +using XlaOpGeneratorMap = absl::flat_hash_map; + +void PopulateXlaOpGeneratorMap(XlaOpGeneratorMap* op_generator_map) { + auto add_xla_op_generator = [&](std::string name, + XlaUnaryOpGenerator xla_op_generator) { + CHECK(op_generator_map->insert({name, xla_op_generator}).second); + }; + +#define ADD_XLA_OP_GENERATOR(Name) \ + add_xla_op_generator(#Name, \ + [](xla::XlaOp operand) { return xla::Name(operand); }); + + ADD_XLA_OP_GENERATOR(Abs); + ADD_XLA_OP_GENERATOR(Acos); + ADD_XLA_OP_GENERATOR(Acosh); + ADD_XLA_OP_GENERATOR(Asin); + ADD_XLA_OP_GENERATOR(Asinh); + ADD_XLA_OP_GENERATOR(Atan); + ADD_XLA_OP_GENERATOR(Atanh); + ADD_XLA_OP_GENERATOR(Ceil); + ADD_XLA_OP_GENERATOR(Cos); + ADD_XLA_OP_GENERATOR(Cosh); + ADD_XLA_OP_GENERATOR(Expm1); + ADD_XLA_OP_GENERATOR(Exp); + ADD_XLA_OP_GENERATOR(Floor); + add_xla_op_generator( + "Inv", [](xla::XlaOp x) { return xla::ScalarLike(x, 1.0) / x; }); + ADD_XLA_OP_GENERATOR(Log); + ADD_XLA_OP_GENERATOR(Log1p); + ADD_XLA_OP_GENERATOR(Neg); + ADD_XLA_OP_GENERATOR(Reciprocal); + add_xla_op_generator("Rint", xla::RoundToEven); + ADD_XLA_OP_GENERATOR(Round); + ADD_XLA_OP_GENERATOR(Rsqrt); + add_xla_op_generator("Sigmoid", + [](xla::XlaOp x) { return xla::Logistic(x); }); + ADD_XLA_OP_GENERATOR(Sin); + ADD_XLA_OP_GENERATOR(Sinh); + ADD_XLA_OP_GENERATOR(Sqrt); + ADD_XLA_OP_GENERATOR(Square); + ADD_XLA_OP_GENERATOR(Tan); + ADD_XLA_OP_GENERATOR(Tanh); + + ADD_XLA_OP_GENERATOR(Elu); + ADD_XLA_OP_GENERATOR(Relu); + ADD_XLA_OP_GENERATOR(Relu6); + ADD_XLA_OP_GENERATOR(Selu); + +#undef ADD_XLA_OP_GENERATOR +} + +const XlaOpGeneratorMap& GetXlaOpGeneratorMap() { + static XlaOpGeneratorMap* result = []() { + auto* result = new XlaOpGeneratorMap; + PopulateXlaOpGeneratorMap(result); + return result; + }(); + + return *result; +} + +class UnaryOpsCompositionOp : public XlaOpKernel { + public: + explicit UnaryOpsCompositionOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("op_names", &op_names_)); + + const XlaOpGeneratorMap& op_generator_map = GetXlaOpGeneratorMap(); + for (absl::string_view op_name : op_names_) { + OP_REQUIRES(ctx, op_generator_map.contains(op_name), + errors::Unimplemented( + op_name, " not supported in _UnaryOpsComposition")); + } + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp x = ctx->Input(0); + const XlaOpGeneratorMap& op_generator_map = GetXlaOpGeneratorMap(); + for (absl::string_view op_name : op_names_) { + x = op_generator_map.find(op_name)->second(x); + } + ctx->SetOutput(0, x); + } + + private: + std::vector op_names_; +}; + +REGISTER_XLA_OP(Name("_UnaryOpsComposition"), UnaryOpsCompositionOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/uniform_quantized_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/uniform_quantized_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..138a501f62a070dc59f984dd9b1b5476568e4010 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/uniform_quantized_ops.cc @@ -0,0 +1,70 @@ +/* Copyright 2023 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/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +// Declare MlirXlaOpKernel for TF UniformQuantized ops. +// The lowering passes for these ops are located at: +// tensorflow/compiler/mlir/quantization/stablehlo/passes/bridge + +REGISTER_XLA_OP(Name("UniformQuantize") + .CompileTimeConstantInput("scales") + .CompileTimeConstantInput("zero_points"), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("UniformDequantize") + .CompileTimeConstantInput("scales") + .CompileTimeConstantInput("zero_points"), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("UniformRequantize") + .CompileTimeConstantInput("input_scales") + .CompileTimeConstantInput("input_zero_points") + .CompileTimeConstantInput("output_scales") + .CompileTimeConstantInput("output_zero_points"), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("UniformQuantizedAdd") + .CompileTimeConstantInput("lhs_scales") + .CompileTimeConstantInput("lhs_zero_points") + .CompileTimeConstantInput("rhs_scales") + .CompileTimeConstantInput("rhs_zero_points") + .CompileTimeConstantInput("output_scales") + .CompileTimeConstantInput("output_zero_points"), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("UniformQuantizedClipByValue") + .CompileTimeConstantInput("scales") + .CompileTimeConstantInput("zero_points"), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("UniformQuantizedConvolution") + .CompileTimeConstantInput("lhs_scales") + .CompileTimeConstantInput("lhs_zero_points") + .CompileTimeConstantInput("rhs_scales") + .CompileTimeConstantInput("rhs_zero_points") + .CompileTimeConstantInput("output_scales") + .CompileTimeConstantInput("output_zero_points"), + MlirXlaOpKernel); +REGISTER_XLA_OP(Name("UniformQuantizedDot") + .CompileTimeConstantInput("lhs_scales") + .CompileTimeConstantInput("lhs_zero_points") + .CompileTimeConstantInput("rhs_scales") + .CompileTimeConstantInput("rhs_zero_points") + .CompileTimeConstantInput("output_scales") + .CompileTimeConstantInput("output_zero_points"), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unique_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unique_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..525b42f54efebe20e5b3ca43a7322f9a36b739e1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unique_op.cc @@ -0,0 +1,288 @@ +/* Copyright 2020 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 + +#include +#include +#include +#include +#include + +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/comparison_util.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/comparators.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class UniqueOpBase : public XlaOpKernel { + public: + explicit UniqueOpBase(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + DataType dtype; + OP_REQUIRES_OK(ctx, ctx->GetAttr("out_idx", &dtype)); + OP_REQUIRES_OK(ctx, DataTypeToPrimitiveType(dtype, &idx_type_)); + } + + // Transpose a tensor by moving axis `from` into `to`. + xla::XlaOp MoveAxis(xla::XlaOp a, int64_t from, int64_t to, + const xla::Shape& input_shape) { + std::vector permutation; + permutation.reserve(input_shape.dimensions().size()); + for (int64_t i = 0; i < input_shape.dimensions().size(); ++i) { + permutation.push_back(i); + } + std::swap(permutation[from], permutation[to]); + return xla::Transpose(a, permutation); + } + + xla::XlaOp CumSumR1(XlaOpKernelContext* ctx, xla::XlaOp input, int64_t size) { + auto init = xla::Zero(ctx->builder(), xla::S32); + auto reducer = xla::CreateScalarAddComputation(xla::S32, ctx->builder()); + + return xla::ReduceWindowWithGeneralPadding( + input, init, reducer, {size}, {1}, + /*base_dilations=*/{}, /*window_dilations=*/{}, {{size - 1, 0}}); + } + + // RollingSelectR1 takes two arrays: `data` and `mask`. It scans this two + // arrays in parallel and accumulates outputs into `accum`. + // + // For each position i, accum[i] = data[i] + // if mask[i] = 1 or accum[i - 1] if mask[i] = 0. + // + // Requires mask[0] = 1, meaning that accum[i - 1] will never be accessed. + // + // This is implemented as an hlo while loop. + xla::XlaOp RollingSelectR1(XlaOpKernelContext* ctx, xla::XlaOp data, + xla::XlaOp mask, int64_t size) { + xla::XlaComputation cond, body; + const xla::Shape r1_shape = xla::ShapeUtil::MakeShape(xla::S32, {size}); + const xla::Shape counter_shape = xla::ShapeUtil::MakeScalarShape(xla::S32); + const xla::Shape& single_element_shape = counter_shape; + + auto loop_shape = xla::ShapeUtil::MakeTupleShape( + {counter_shape, r1_shape, r1_shape, r1_shape}); + { + std::unique_ptr builder = + ctx->builder()->CreateSubBuilder("loop_cond"); + auto param = xla::Parameter(builder.get(), 0, loop_shape, "param"); + auto counter = xla::GetTupleElement(param, 0); + auto limit = xla::ConstantR0(builder.get(), size); + xla::Lt(counter, limit); + + cond = builder->Build().value(); + } + + { + std::unique_ptr builder = + ctx->builder()->CreateSubBuilder("loop_body"); + auto param = xla::Parameter(builder.get(), 0, loop_shape, "param"); + auto counter = xla::GetTupleElement(param, 0); + + auto data_stack = xla::GetTupleElement(param, 1); + auto data = xla::DynamicSlice(data_stack, {counter}, {1}); + data = xla::Reshape(single_element_shape, data); + + auto mask_stack = xla::GetTupleElement(param, 2); + auto mask = xla::DynamicSlice(mask_stack, {counter}, {1}); + mask = xla::Reshape(single_element_shape, mask); + + auto counter_minus = counter - xla::One(builder.get(), xla::S32); + // If counter = 0, then counter_minus = 0. + auto zero = xla::Zero(builder.get(), xla::S32); + counter_minus = xla::Select(xla::Eq(counter, zero), zero, counter_minus); + + auto accum_stack = xla::GetTupleElement(param, 3); + auto accum_minus = xla::DynamicSlice(accum_stack, {counter_minus}, {1}); + accum_minus = xla::Reshape(single_element_shape, accum_minus); + + auto accum = xla::Select(xla::ConvertElementType(mask, xla::PRED), data, + accum_minus); + accum_stack = xla::DynamicUpdateSlice( + accum_stack, xla::Reshape(accum, {1}), {counter}); + counter = counter + xla::One(builder.get(), xla::S32); + + xla::Tuple(builder.get(), {counter, data_stack, mask_stack, accum_stack}); + body = builder->Build().value(); + } + + auto zero = xla::Zero(ctx->builder(), xla::S32); + auto zero_broadcast = xla::Broadcast(zero, {size}); + auto init = xla::Tuple(ctx->builder(), {zero, data, mask, zero_broadcast}); + return xla::GetTupleElement(xla::While(cond, body, init), 3); + } + + void CompileWithAxis(XlaOpKernelContext* ctx, int64_t axis) { + xla::XlaOp input = ctx->Input(0); + absl::StatusOr input_shape_or = ctx->builder()->GetShape(input); + OP_REQUIRES_OK(ctx, input_shape_or.status()); + auto input_shape = input_shape_or.value(); + axis = axis < 0 ? axis + input_shape.dimensions().size() : axis; + OP_REQUIRES(ctx, 0 <= axis && axis < input_shape.dimensions().size(), + errors::InvalidArgument("axis has to be between [0, ", + input_shape.dimensions().size(), ")")); + auto aux = MoveAxis(input, axis, 0, input_shape); + auto aux_shape = ctx->builder()->GetShape(aux).value(); + int64_t leading_size = aux_shape.dimensions(0); + int64_t product = 1; + for (int64_t i = 1; i < aux_shape.dimensions().size(); ++i) { + product *= aux_shape.dimensions(i); + } + aux = xla::Reshape(aux, {leading_size, product}); + if (leading_size == 0) { + auto result_data = xla::Reshape(aux, aux_shape.dimensions()); + result_data = MoveAxis(result_data, 0, axis, aux_shape); + ctx->SetOutput(0, result_data); + ctx->SetOutput(1, xla::Iota(ctx->builder(), xla::S32, leading_size)); + return; + } + std::vector sort_keys; + sort_keys.reserve(product + 1); + std::vector sort_types; + sort_types.reserve(product + 1); + for (int64_t i = 0; i < product; ++i) { + xla::XlaOp slice = xla::SliceInDim(aux, i, i + 1, 1, 1); + sort_keys.push_back(xla::Reshape(slice, {leading_size})); + sort_types.push_back(input_shape.element_type()); + } + auto iota = xla::Iota(ctx->builder(), xla::S32, leading_size); + sort_keys.push_back(iota); + sort_types.push_back(xla::S32); + + std::vector)>> + generators(sort_types.size(), xla::LtTotalOrder); + auto lt_chain = xla::CreateScalarComparisonComputation( + "UniqueV2Lt", sort_types, generators, ctx->builder()); + + auto sorted = xla::Sort(sort_keys, lt_chain, 0, /*is_stable=*/true); + // Last element is permutation. + xla::XlaOp perm; + if (sort_keys.size() == 1) { + perm = sorted; + } else { + perm = xla::GetTupleElement(sorted, sort_keys.size() - 1); + } + + // Use gather to rearrange minor dimension. + xla::GatherDimensionNumbers gather_dim_numbers; + gather_dim_numbers.add_offset_dims(1); + // The dimension to rewrite is the index dim. + gather_dim_numbers.add_start_index_map(0); + gather_dim_numbers.set_index_vector_dim(1); + gather_dim_numbers.add_collapsed_slice_dims(0); + auto permuted = xla::Gather(aux, perm, gather_dim_numbers, {1, product}); + // Tail is everything except for first element. + auto tail = xla::SliceInDim(permuted, 1, leading_size, 1, 0); + // Init is everything except for last element. + auto init = xla::SliceInDim(permuted, 0, leading_size - 1, 1, 0); + auto ne = xla::Compare(tail, init, xla::ComparisonDirection::kNe); + auto reduce = + xla::Reduce(ne, xla::ConstantR0(ctx->builder(), false), + CreateScalarOrComputation(xla::PRED, ctx->builder()), {1}); + auto mask = xla::ConvertElementType(reduce, xla::S32); + mask = xla::PadInDim(mask, xla::One(ctx->builder(), xla::S32), 0, 1, 0); + auto iperm = RollingSelectR1(ctx, perm, mask, leading_size); + + auto sort_by_iperm = + xla::Sort({iperm, mask, perm}, + xla::CreateScalarLtComputation({xla::S32, xla::S32, xla::S32}, + ctx->builder()), + 0, + /*is_stable=*/true); + mask = xla::GetTupleElement(sort_by_iperm, 1); + // perm_sort is used later to revert the indices back to input order. + auto perm_sort = xla::GetTupleElement(sort_by_iperm, 2); + + auto dynamic_size = xla::ReduceAll( + mask, xla::Zero(ctx->builder(), xla::S32), + xla::CreateScalarAddComputation(xla::S32, ctx->builder())); + auto mask_sort = xla::Sort( + {mask, perm_sort}, + xla::CreateScalarGtComputation({xla::S32, xla::S32}, ctx->builder()), 0, + /*is_stable=*/true); + auto mask_permute = xla::GetTupleElement(mask_sort, 1); + permuted = xla::Gather(aux, mask_permute, gather_dim_numbers, {1, product}); + auto result_data = xla::Reshape(permuted, aux_shape.dimensions()); + result_data = MoveAxis(result_data, 0, axis, aux_shape); + result_data = xla::SetDimensionSize(result_data, dynamic_size, axis); + ctx->SetOutput(0, result_data); + auto imask = CumSumR1(ctx, mask, leading_size); + imask = xla::Sub(imask, xla::One(ctx->builder(), xla::S32), {}); + auto idx = xla::GetTupleElement( + xla::Sort({perm_sort, imask}, + xla::CreateScalarLtComputation({xla::S32, xla::S32}, + ctx->builder())), + 1); + idx = xla::ConvertElementType(idx, idx_type_); + ctx->SetOutput(1, idx); + } + + private: + xla::PrimitiveType idx_type_; +}; + +class UniqueOp : public UniqueOpBase { + public: + explicit UniqueOp(OpKernelConstruction* ctx) : UniqueOpBase(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + CompileWithAxis(ctx, /*axis=*/0); + } +}; + +REGISTER_XLA_OP(Name("Unique"), UniqueOp); + +class UniqueV2Op : public UniqueOpBase { + public: + explicit UniqueV2Op(OpKernelConstruction* ctx) : UniqueOpBase(ctx) {} + + void Compile(XlaOpKernelContext* ctx) override { + std::vector axises; + OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntVector(1, &axises)); + OP_REQUIRES( + ctx, axises.size() <= 1, + xla::InvalidArgument("Only single axis unique op is supported")); + int64_t axis; + if (axises.empty()) { + axis = 0; + } else { + axis = axises.front(); + } + CompileWithAxis(ctx, /*axis=*/axis); + } +}; + +REGISTER_XLA_OP(Name("UniqueV2").CompileTimeConstantInput("axis"), UniqueV2Op); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unpack_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unpack_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..95fba76569a086117ef55c9b4111b5ee91ecc11a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/unpack_op.cc @@ -0,0 +1,84 @@ +/* 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. +==============================================================================*/ + +// XLA Unpack operator. + +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class UnpackOp : public XlaOpKernel { + public: + explicit UnpackOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("axis", &axis_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + const int num = num_outputs(); + const TensorShape input_shape = ctx->InputShape(0); + + int axis = axis_; + if (axis < 0) axis += input_shape.dims(); + + OP_REQUIRES(ctx, 0 <= axis && axis < input_shape.dims(), + errors::InvalidArgument("axis = ", axis_, " not in [", + -input_shape.dims(), ", ", + input_shape.dims(), ")")); + + OP_REQUIRES( + ctx, input_shape.dims() > 0 && input_shape.dim_size(axis) == num, + errors::InvalidArgument("Input shape axis ", axis, " must equal ", num, + ", got shape ", input_shape.DebugString())); + + auto output_shape = input_shape; + output_shape.RemoveDim(axis); + + auto input = ctx->Input(0); + + std::vector start_indices(input_shape.dims(), 0); + std::vector limit_indices(input_shape.dims()); + std::vector strides(input_shape.dims(), 1); + for (int i = 0; i < input_shape.dims(); ++i) { + limit_indices[i] = input_shape.dim_size(i); + } + + for (int i = 0; i < num; ++i) { + start_indices[axis] = i; + limit_indices[axis] = i + 1; + auto slice = xla::Slice(input, start_indices, limit_indices, strides); + // Reshape to drop the 'axis' dimension. + auto result = xla::Reshape(slice, output_shape.dim_sizes()); + ctx->SetOutput(i, result); + } + } + + private: + int axis_; +}; + +REGISTER_XLA_OP(Name("Unpack"), UnpackOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/variable_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/variable_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..c2df3167b9762533a277aaa0e4aa1dfa2f2475af --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/variable_ops.cc @@ -0,0 +1,338 @@ +/* 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 +#include +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/kernels/gather_op_helpers.h" +#include "tensorflow/compiler/tf2xla/kernels/shape_util.h" +#include "tensorflow/compiler/tf2xla/lib/scatter.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/hlo/builder/lib/slicing.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/kernels/resource_variable_util.h" +#include "tensorflow/core/kernels/scatter_nd_util.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +absl::Status ValidateAssignUpdateVariableOpShapes(XlaOpKernelContext* ctx) { + DataType variable_dtype; + TensorShape variable_shape; + TensorShape value_shape = ctx->InputShape(1); + TF_RETURN_IF_ERROR( + ctx->GetVariableTypeAndShape(0, &variable_dtype, &variable_shape)); + TF_RETURN_IF_ERROR( + ValidateAssignUpdateVariableOpShapes(variable_shape, value_shape)); + return absl::OkStatus(); +} + +class VarIsInitializedOp : public XlaOpKernel { + public: + explicit VarIsInitializedOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + XlaResource* variable; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(0, &variable)); + ctx->SetOutput( + 0, xla::ConstantR0(ctx->builder(), variable->initialized())); + } +}; +REGISTER_XLA_OP(Name("VarIsInitializedOp"), VarIsInitializedOp); + +class VariableShapeOp : public XlaOpKernel { + public: + explicit VariableShapeOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("out_type", &out_dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + DataType variable_dtype; + TensorShape shape; + OP_REQUIRES_OK(ctx, + ctx->GetVariableTypeAndShape(0, &variable_dtype, &shape)); + Tensor shape_constant(out_dtype_, TensorShape({shape.dims()})); + OP_REQUIRES_OK(ctx, TensorShapeToConstant(shape, &shape_constant)); + ctx->SetConstantOutput(0, shape_constant); + } + + private: + DataType out_dtype_; +}; +REGISTER_XLA_OP(Name("VariableShape").CompilationOnly().IsMetadataOp(), + VariableShapeOp); + +class ReadVariableOp : public XlaOpKernel { + public: + explicit ReadVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &dtype_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + xla::XlaOp handle; + OP_REQUIRES_OK( + ctx, ctx->ReadVariableInput(0, dtype_, /*shape=*/nullptr, &handle)); + ctx->SetOutput(0, handle); + } + + private: + DataType dtype_; +}; +REGISTER_XLA_OP(Name("ReadVariableOp").CompilationOnly(), ReadVariableOp); + +class AssignVariableOp : public XlaOpKernel { + public: + explicit AssignVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES_OK(ctx, + ctx->AssignVariable(0, ctx->input_type(1), ctx->Input(1))); + } +}; +REGISTER_XLA_OP(Name("AssignVariableOp").CompilationOnly(), AssignVariableOp); + +class AssignAddVariableOp : public XlaOpKernel { + public: + explicit AssignAddVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->input_type(1); + xla::XlaOp handle; + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput(0, type, /*shape=*/nullptr, &handle)); + OP_REQUIRES_OK(ctx, ValidateAssignUpdateVariableOpShapes(ctx)); + handle = xla::Add(handle, ctx->Input(1)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, handle)); + } +}; +REGISTER_XLA_OP( + Name("AssignAddVariableOp").TypeConstraint("dtype", kNumericTypes), + AssignAddVariableOp); + +class AssignSubVariableOp : public XlaOpKernel { + public: + explicit AssignSubVariableOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->input_type(1); + xla::XlaOp handle; + OP_REQUIRES_OK(ctx, + ctx->ReadVariableInput(0, type, /*shape=*/nullptr, &handle)); + OP_REQUIRES_OK(ctx, ValidateAssignUpdateVariableOpShapes(ctx)); + handle = xla::Sub(handle, ctx->Input(1)); + OP_REQUIRES_OK(ctx, ctx->AssignVariable(0, type, handle)); + } +}; +REGISTER_XLA_OP( + Name("AssignSubVariableOp").TypeConstraint("dtype", kNumericTypes), + AssignSubVariableOp); + +class ResourceGatherOp : public XlaOpKernel { + public: + explicit ResourceGatherOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("batch_dims", &batch_dims_)); + } + void Compile(XlaOpKernelContext* ctx) override { + DataType type = ctx->expected_output_dtype(0); + + TensorShape input_shape; + xla::XlaOp input; + OP_REQUIRES_OK(ctx, ctx->ReadVariableInput(0, type, &input_shape, &input)); + + xla::XlaOp gather; + OP_REQUIRES_OK(ctx, XlaGatherWithBatchDimsOpImpl(ctx, input, input_shape, + batch_dims_, &gather)); + ctx->SetOutput(0, gather); + } + + private: + int32_t batch_dims_; +}; +REGISTER_XLA_OP(Name("ResourceGather"), ResourceGatherOp); + +class ResourceScatterOp : public XlaOpKernel { + public: + explicit ResourceScatterOp( + OpKernelConstruction* context, bool indices_are_vectors, + std::function + combiner) + : XlaOpKernel(context), + indices_are_vectors_(indices_are_vectors), + combiner_(std::move(combiner)) {} + + void Compile(XlaOpKernelContext* context) override { + xla::XlaBuilder* builder = context->builder(); + + DataType dtype = context->input_type(2); + TensorShape var_shape; + xla::XlaOp var_value; + OP_REQUIRES_OK( + context, context->ReadVariableInput(0, dtype, &var_shape, &var_value)); + // This check is only required for ScatterNdOps. + if (indices_are_vectors_) { + OP_REQUIRES_OK(context, ValidateScatterNdUpdateShape( + var_shape, context->InputShape(1), + context->InputShape(2))); + } + + const xla::XlaOp indices = context->Input(1); + const xla::XlaOp updates = context->Input(2); + + auto result = XlaScatter(var_value, updates, indices, indices_are_vectors_, + /*indices_are_sorted=*/false, combiner_, builder); + OP_REQUIRES_OK(context, result.status()); + OP_REQUIRES_OK(context, context->AssignVariable(0, dtype, result.value())); + } + + private: + const bool indices_are_vectors_; + const std::function + combiner_; +}; + +class ResourceScatterAddOp : public ResourceScatterOp { + public: + explicit ResourceScatterAddOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Add(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterAdd"), ResourceScatterAddOp); + +class ResourceScatterSubOp : public ResourceScatterOp { + public: + explicit ResourceScatterSubOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Sub(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterSub"), ResourceScatterSubOp); + +class ResourceScatterMulOp : public ResourceScatterOp { + public: + explicit ResourceScatterMulOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Mul(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterMul"), ResourceScatterMulOp); + +class ResourceScatterDivOp : public ResourceScatterOp { + public: + explicit ResourceScatterDivOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Div(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterDiv"), ResourceScatterDivOp); + +class ResourceScatterMinOp : public ResourceScatterOp { + public: + explicit ResourceScatterMinOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Min(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterMin"), ResourceScatterMinOp); + +class ResourceScatterMaxOp : public ResourceScatterOp { + public: + explicit ResourceScatterMaxOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Max(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterMax"), ResourceScatterMaxOp); + +class ResourceScatterUpdateOp : public ResourceScatterOp { + public: + explicit ResourceScatterUpdateOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/false, + /*combiner=*/{}) {} +}; +REGISTER_XLA_OP(Name("ResourceScatterUpdate"), ResourceScatterUpdateOp); + +class ResourceScatterNdUpdateOp : public ResourceScatterOp { + public: + explicit ResourceScatterNdUpdateOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/true, + /*combiner=*/{}) {} +}; +REGISTER_XLA_OP(Name("ResourceScatterNdUpdate"), ResourceScatterNdUpdateOp); + +class ResourceScatterNdAddOp : public ResourceScatterOp { + public: + explicit ResourceScatterNdAddOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/true, + /*combiner=*/Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Add(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterNdAdd"), ResourceScatterNdAddOp); + +class ResourceScatterNdSubOp : public ResourceScatterOp { + public: + explicit ResourceScatterNdSubOp(OpKernelConstruction* context) + : ResourceScatterOp(context, /*indices_are_vectors=*/true, + /*combiner=*/Combine) {} + + private: + static xla::XlaOp Combine(const xla::XlaOp x, const xla::XlaOp y, + xla::XlaBuilder* builder) { + return xla::Sub(x, y); + } +}; +REGISTER_XLA_OP(Name("ResourceScatterNdSub"), ResourceScatterNdSubOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/where_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/where_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..c44303b06797244aaa1385340e3143e876e4f92f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/where_op.cc @@ -0,0 +1,353 @@ +/* Copyright 2020 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 +#include +#include +#include + +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/arithmetic.h" +#include "xla/hlo/builder/lib/comparators.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/dynamic_shaped_ops.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/bits.h" + +namespace tensorflow { +namespace { + +using xla::S32; +using xla::XlaOp; + +// "Shifts" a rank-1 array one element to the right, inserting a 0 at the +// beginning and cutting off the last element of the array. +// +// That is, transforms [x0, x1, ..., xn] into [0, x0, ..., xn-1]. +absl::StatusOr ShiftElemsRight(XlaOp x) { + xla::XlaBuilder* b = x.builder(); + absl::StatusOr shape = b->GetShape(x); + TF_RETURN_IF_ERROR(shape.status()); + TF_RET_CHECK(shape->dimensions().size() == 1); + int64_t n = shape->dimensions(0); + + XlaOp padded = xla::PadInDim(x, xla::Zero(b, shape->element_type()), + /*dimno=*/0, /*pad_lo=*/1, /*pad_hi=*/0); + return xla::SliceInDim(padded, /*start_index=*/0, /*limit_index=*/n, + /*stride=*/1, /*dimno=*/0); +} + +// Recursive prefix-sum algorithm. +// +// - Let the input be an array x. +// - Let evens be [x0, x2, ...]. +// - Let odds be [x1, x3, ...]. +// - Let combined be evens + odds. +// - Let psum = prefix-sum(combined), recursively. +// +// Then the prefix-sum of x is the interleaving of psum - odds and psum. +// Written out, this is: +// +// [psum[0] - odds[0], psum[0], psum[1] - odds[1], psum[1], ...]. +// +// Requires: `arr` is a 1D S32 array whose length is padded to a power of 2. +// +// Optimization: Rather than split the input into two slices (evens/odds), we +// split it into kNumSlices pieces. The basic algorithm is the same, but this +// reduces the number of GPU kernels we have to launch. +// +// There are much more efficient algorithms to be had! In particular, on GPU +// this launches O(log4 n) kernels, but there are efficient algorithms that use +// just one kernel, see +// https://research.nvidia.com/publication/single-pass-parallel-prefix-scan-decoupled-look-back +// +// Nonetheless, this is much simpler than the algorithm in the paper above, but +// also much faster than implementing tf.where by sorting the input. +absl::StatusOr PrefixSum(XlaOp arr) { + xla::XlaBuilder* b = arr.builder(); + absl::StatusOr input_shape = b->GetShape(arr); + TF_RETURN_IF_ERROR(input_shape.status()); + + TF_RET_CHECK(input_shape->dimensions().size() == 1); + int64_t n = input_shape->dimensions(0); + + // The original input length must be a power of 2, but we recursively divide + // it into kNumSlices chunks. Assuming kNumSlices == 4, this means our + // base-case needs to handle n == 1 (original length was a power of 4) or + // n == 2 (original size was a power of 2). + constexpr int kNumSlices = 4; + if (n <= 1) { + return arr; + } + if (n == 2) { + TF_ASSIGN_OR_RETURN(XlaOp shifted, ShiftElemsRight(arr)); + return arr + shifted; + } + TF_RET_CHECK(n % kNumSlices == 0); + + std::array slices; + for (int i = 0; i < slices.size(); i++) { + slices[i] = xla::Slice(arr, /*start_indices=*/{i}, /*limit_indices=*/{n}, + /*strides=*/{kNumSlices}); + } + + XlaOp combined = slices[0]; + for (int i = 1; i < kNumSlices; ++i) { + combined = combined + slices[i]; + } + + TF_ASSIGN_OR_RETURN(XlaOp psum, PrefixSum(combined)); + + std::array slices_psummed; + slices_psummed[kNumSlices - 1] = psum; + for (int i = kNumSlices - 2; i >= 0; --i) { + slices_psummed[i] = slices_psummed[i + 1] - slices[i + 1]; + } + + // Interleave the slices. + std::array slices_padded; + for (int i = 0; i < kNumSlices; ++i) { + xla::PaddingConfig padding_config; + auto* dim = padding_config.add_dimensions(); + dim->set_edge_padding_low(i); + dim->set_edge_padding_high(kNumSlices - i - 1); + dim->set_interior_padding(kNumSlices - 1); + slices_padded[i] = + xla::Pad(slices_psummed[i], xla::Zero(b, S32), padding_config); + } + + XlaOp ret = slices_padded[0]; + for (int i = 1; i < kNumSlices; ++i) { + ret = ret + slices_padded[i]; + } + + return ret; +} + +// prefix-sum works better on CPU/GPU, whereas sort works better on TPU. +bool ShouldUsePrefixSumImpl(const DeviceType& dt) { + absl::string_view t = dt.type_string(); + return t == DEVICE_CPU_XLA_JIT || t == DEVICE_GPU_XLA_JIT || + t == DEVICE_XLA_CPU || t == DEVICE_XLA_GPU; +} + +absl::StatusOr CompileWhereWithSort(XlaOpKernelContext* ctx) { + XlaOp condition = ctx->Input(0); + TF_ASSIGN_OR_RETURN(xla::Shape input_shape, + ctx->builder()->GetShape(condition)); + auto iota_shape = + xla::ShapeUtil::MakeShape(xla::S32, input_shape.dimensions()); + + int64_t flattened_size = xla::Product(iota_shape.dimensions()); + XlaOp reshaped_condition = xla::Reshape(condition, {flattened_size}); + XlaOp zeros = xla::ZerosLike(reshaped_condition); + XlaOp compared = xla::Ne(reshaped_condition, zeros); + + std::vector to_sort = {compared}; + std::vector types_to_sort = {xla::PRED}; + // Generate iota for each dimension, which after combining becomes + // indices of each element. + for (int64_t axis = 0; axis < iota_shape.dimensions().size(); ++axis) { + XlaOp iota = xla::Iota(ctx->builder(), iota_shape, axis); + XlaOp reshaped = xla::Reshape(iota, {flattened_size}); + to_sort.push_back(reshaped); + types_to_sort.push_back(xla::S32); + } + + XlaOp sorted = xla::Sort( + to_sort, xla::CreateScalarGtComputation(types_to_sort, ctx->builder()), + /*dimension=*/0, /*is_stable=*/true); + std::vector to_concat; + for (int64_t i = 0; i < iota_shape.dimensions().size(); ++i) { + XlaOp index_single_dim = xla::GetTupleElement(sorted, i + 1); + to_concat.push_back(xla::Reshape(index_single_dim, {flattened_size, 1})); + } + + XlaOp result = xla::ConcatInDim(ctx->builder(), to_concat, 1); + result = xla::ConvertElementType(result, ctx->output_xla_type(0)); + + // Dynamic padder will handle the dynamic dimension. + XlaOp compared_int = xla::ConvertElementType(compared, xla::S32); + XlaOp length = + xla::ReduceAll(compared_int, xla::Zero(ctx->builder(), xla::S32), + xla::CreateScalarAddComputation(xla::S32, ctx->builder())); + absl::StatusOr rebounded_result = xla::SetDimensionSizeWithRebound( + &ctx->value_inference(), result, length, 0); + if (rebounded_result.ok()) { + return rebounded_result; + } + // TODO(b/207187072): Remove special handling once dynamic reshape can also + // be handled. + return xla::SetDimensionSize(result, length, 0); +} + +absl::StatusOr CompileWhereWithPrefixSum(XlaOpKernelContext* ctx) { + xla::XlaBuilder* b = ctx->builder(); + XlaOp condition = ctx->Input(0); + + TF_ASSIGN_OR_RETURN(xla::Shape input_shape, b->GetShape(condition)); + + int64_t flattened_size = xla::Product(input_shape.dimensions()); + XlaOp reshaped_condition = xla::Reshape(condition, {flattened_size}); + XlaOp zeros = xla::ZerosLike(reshaped_condition); + XlaOp preds = + xla::ConvertElementType(xla::Ne(reshaped_condition, zeros), S32); + + // Given preds, we compute prefix_sum and out_idx as in the following + // example. + // + // preds = [T, F, F, T, F, T], therefore + // prefix_sum = [1, 1, 1, 2, 2, 3], and + // out_idxs = [0, ⊥, ⊥, 1, ⊥, 2], where ⊥ is an OOB index. + // + // We then scatter out_idxs into the result. + TF_ASSIGN_OR_RETURN( + XlaOp padded_prefix_sum, + PrefixSum(xla::PadInDim( + preds, xla::Zero(b, S32), /*dimno=*/0, /*pad_lo=*/0, + /*pad_hi=*/NextPowerOfTwo(flattened_size) - flattened_size))); + XlaOp prefix_sum = xla::SliceInDim(padded_prefix_sum, /*start_index=*/0, + /*limit_index=*/flattened_size, + /*stride=*/1, /*dimno=*/0); + + // We could compute out_idxs as + // + // out_idxs[i] = preds[i] ? prefix_sum[i] - 1 : ⊥, + // + // but it's faster to compute it as + // + // let ps = prefix_sum in + // out_idxs[i] = + // if i == 0: ps[i] != 0 ? ps[i] - 1 : ⊥ + // else: ps[i] != ps[i-1] ? ps[i] - 1 : ⊥ + // + // because we read less memory. + XlaOp oob_idx = xla::ConstantR0WithType(b, S32, flattened_size); // ⊥ + TF_ASSIGN_OR_RETURN(XlaOp prefix_sum_shifted, ShiftElemsRight(prefix_sum)); + XlaOp out_idxs = xla::Select(xla::Ne(prefix_sum, prefix_sum_shifted), + /*on_true=*/prefix_sum - xla::One(b, S32), + /*on_false=*/oob_idx); + out_idxs = xla::Reshape(out_idxs, {flattened_size, 1}); + + // tf.where returns an array of multidimensional indices where the condition + // is true. For example: + // + // input = [ + // [F, T], + // [T, F], + // [F, F], + // ] + // + // results in + // + // output = [ + // [0,0], [1,0], + // ] + // + // Generate the list + // + // iotas = [[0,...,0], [0,...,1], ..., [limit_0,...,limit_n]], + // + // and then scatter iotas[out_idxs] into the output. + std::vector iotas_to_concat; + auto iota_shape = xla::ShapeUtil::MakeShape(S32, input_shape.dimensions()); + iotas_to_concat.reserve(iota_shape.dimensions().size()); + for (int64_t axis = 0; axis < iota_shape.dimensions().size(); ++axis) { + iotas_to_concat.push_back( + xla::Reshape(xla::Iota(b, iota_shape, axis), {flattened_size, 1})); + } + XlaOp iotas = xla::ConcatInDim(b, iotas_to_concat, /*dimension=*/1); + + // Scatter subcomputation. Instead of the usual `return p0 + p1`, simply + // does `return p1`, because we just want to overwrite whatever was in the + // scatter dest. + xla::XlaComputation assn_computation = [&] { + std::unique_ptr subb = + b->CreateSubBuilder("where_op_scatter_assn"); + xla::Shape param_shape = xla::ShapeUtil::MakeShape(S32, {}); + xla::Parameter(subb.get(), 0, param_shape, "p0"); + xla::Parameter(subb.get(), 1, param_shape, "p1"); + // Simply return p1, the last op we created. + return subb->BuildAndNoteError(); + }(); + + xla::ScatterDimensionNumbers scatter_dnums; + scatter_dnums.set_index_vector_dim(1); + scatter_dnums.add_inserted_window_dims(0); + scatter_dnums.add_scatter_dims_to_operand_dims(0); + scatter_dnums.add_update_window_dims(1); + XlaOp scattered = xla::Scatter( + /*input=*/xla::Zeros( + b, /*shape=*/xla::ShapeUtil::MakeShape( + S32, {flattened_size, iota_shape.dimensions_size()})), + /*scatter_indices=*/out_idxs, /*updates=*/iotas, + /*update_computation=*/assn_computation, scatter_dnums, + /*indices_are_sorted=*/true, /*unique_indices=*/true); + scattered = xla::ConvertElementType(scattered, ctx->output_xla_type(0)); + + // Now count how many valid elements there are and slice off the tail of + // `scattered`. + XlaOp num_valid = + xla::ReduceAll(xla::ConvertElementType(preds, S32), xla::Zero(b, S32), + xla::CreateScalarAddComputation(S32, b)); + absl::StatusOr rebounded_result = xla::SetDimensionSizeWithRebound( + &ctx->value_inference(), scattered, num_valid, 0); + if (rebounded_result.ok()) { + return *rebounded_result; + } + // TODO(b/207187072): Remove special handling once dynamic reshape can also + // be handled. + return xla::SetDimensionSize(scattered, num_valid, 0); +} + +class WhereOp : public XlaOpKernel { + public: + explicit WhereOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx), + use_prefix_sum_(ShouldUsePrefixSumImpl(ctx->device_type())) {} + + void Compile(XlaOpKernelContext* ctx) override { + absl::StatusOr ret; + if (use_prefix_sum_) { + ret = CompileWhereWithPrefixSum(ctx); + } else { + ret = CompileWhereWithSort(ctx); + } + OP_REQUIRES_OK(ctx, ret.status()); + ctx->SetOutput(0, *ret); + } + + private: + bool use_prefix_sum_; +}; + +REGISTER_XLA_OP(Name("Where"), WhereOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/while_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/while_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..e2bf4db24e54956dfaf95abd9b6cd8aa2bd064de --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/while_op.cc @@ -0,0 +1,705 @@ +/* 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/kernels/while_op.h" + +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/kernels/if_while_utils.h" +#include "tensorflow/compiler/tf2xla/kernels/tensor_list_utils.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/client/client.h" +#include "xla/hlo/builder/lib/tuple.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/shape_tree.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +namespace { + +// Verify that input resources are grouped in the end. +absl::Status VerifyResourceArgsGroupedAtEnd( + XlaOpKernelContext* ctx, const NameAttrList& body_name_attr) { + const FunctionBody* body; + TF_RETURN_IF_ERROR(ctx->compiler()->FindFunctionBody(body_name_attr, &body)); + bool has_seen_resource = false; + for (int i = 0; i < body->arg_types.size(); i++) { + DataType arg_type = body->arg_types[i]; + if (has_seen_resource) { + if (arg_type != DT_RESOURCE) { + return errors::InvalidArgument( + "Expect input resources are grouped in the end of while body ", + body_name_attr.name(), ", but the ", i, "-th argument ", + body->arg_nodes[i]->name(), " is not a resource."); + } + } else { + if (arg_type == DT_RESOURCE) { + has_seen_resource = true; + } + } + } + return absl::OkStatus(); +} + +// Builds XlaCompiler argument descriptions `args` from `ctx`. +absl::Status MakeXlaCompilerArgumentsFromInputs( + XlaOpKernelContext* ctx, std::vector* args, + bool* has_uninitialized_vars, bool* has_tensor_arrays, + bool* has_uninitialized_tensor_lists) { + VLOG(2) << "Num inputs " << ctx->num_inputs(); + args->resize(ctx->num_inputs()); + *has_uninitialized_vars = false; + *has_tensor_arrays = false; + *has_uninitialized_tensor_lists = false; + for (int i = 0; i < ctx->num_inputs(); ++i) { + VLOG(2) << " Input " << i << " type: " << DataTypeString(ctx->input_type(i)) + << " shape: " << ctx->InputShape(i).DebugString(); + XlaCompiler::Argument& arg = (*args)[i]; + DataType type = ctx->input_type(i); + // When reading a resource input, use the type and shape of the resource's + // current value. + if (type == DT_RESOURCE) { + XlaResource* resource; + TF_RETURN_IF_ERROR(ctx->GetResourceInput(i, &resource)); + XlaCompiler::PopulateArgumentFromResource(*resource, &arg); + if (arg.resource_kind == XlaResource::kTensorArray) { + *has_tensor_arrays = true; + } + if (!arg.initialized) { + *has_uninitialized_vars = true; + } + VLOG(2) << " resource " << resource->name() + << " type: " << DataTypeString(arg.type) + << " shape: " << arg.ShapeHumanString() + << " initialized: " << arg.initialized; + } else { + arg.kind = XlaCompiler::Argument::kParameter; + arg.type = type; + TF_ASSIGN_OR_RETURN(arg.shape, ctx->builder()->GetShape(ctx->Input(i))); + if (IsTensorListInput(ctx, i)) { + // arg.initialized == false means that the element_shape of the list + // was not available at the time of building the list so an empty list + // was created instead. If so, the body function of While is run once + // to infer the shape of the list before actually building the While op. + TF_RETURN_IF_ERROR( + IsTensorListInitialized(ctx->Input(i), &arg.initialized)); + if (!arg.initialized) { + *has_uninitialized_tensor_lists = true; + } + } + } + } + return absl::OkStatus(); +} + +// Populates loop invariant indices to true in `loop_invariants`. +void GetLoopInvariants(XlaOpKernelContext* ctx, + const NameAttrList& body_name_attr, + std::vector* const loop_invariants) { + const FunctionBody* body; + OP_REQUIRES_OK(ctx, ctx->compiler()->FindFunctionBody(body_name_attr, &body)); + const tensorflow::FunctionLibraryDefinition* fld = + ctx->compiler()->flib_runtime()->GetFunctionLibraryDefinition(); + for (int i = 0; i < body->ret_nodes.size(); i++) { + absl::StatusOr is_loop_invariant = IsLoopInvariant(body, i, fld); + OP_REQUIRES_OK(ctx, is_loop_invariant.status()); + (*loop_invariants)[i] = *is_loop_invariant; + VLOG(2) << "Arg " << i << " of " << body_name_attr.name() << " is " + << ((*loop_invariants)[i] ? "" : "not ") << "loop invariant"; + } +} + +// Converts entries in `args` which are loop invariants and have compile time +// constant inputs and need to be constants in order to be compilable to +// constants so that they can be propagated in the loop body. +absl::Status ConvertLoopInvariantsToConst( + XlaOpKernelContext* ctx, const NameAttrList& body_name_attr, + const NameAttrList& cond_name_attr, + std::vector* args, + std::vector* compile_time_const_arg_indices, + int* num_compile_time_const_args, xla::Client* client) { + std::vector loop_invariants(ctx->num_inputs()); + GetLoopInvariants(ctx, body_name_attr, &loop_invariants); + + std::vector body_must_be_const_nodes; + const FunctionBody* body; + std::vector cond_must_be_const_nodes; + const FunctionBody* cond; + TF_RETURN_IF_ERROR(FindMustBeConstNodes(ctx, body_name_attr, + &body_must_be_const_nodes, &body)); + TF_RETURN_IF_ERROR(FindMustBeConstNodes(ctx, cond_name_attr, + &cond_must_be_const_nodes, &cond)); + + auto should_convert_to_const = [&](int arg_idx) { + XlaCompiler::Argument& arg = (*args)[arg_idx]; + return arg.kind != XlaCompiler::Argument::kResource && + loop_invariants[arg_idx] && + (body_must_be_const_nodes[body->arg_nodes[arg_idx]->id()] || + cond_must_be_const_nodes[cond->arg_nodes[arg_idx]->id()]); + }; + absl::InlinedVector converted_constants = + ConvertCompileTimeConstArgumentsToConst(ctx, args, + /*xla_expression_offset=*/0, + should_convert_to_const); + VLOG(2) << "Converted args to constants: {" + << absl::StrJoin(converted_constants, ",") << "}"; + for (int arg_idx : converted_constants) { + compile_time_const_arg_indices->at(arg_idx) = true; + (*num_compile_time_const_args)++; + } + return absl::OkStatus(); +} + +absl::Status VerifyBodyInputAndOutputShapeMatch( + XlaOpKernelContext* ctx, + const std::vector& compile_time_const_arg_indices, + const XlaCompiler::CompilationResult& body, bool has_token_input_output) { + xla::Shape body_input_shape = body.xla_input_shapes[0]; + xla::Shape body_output_shape; + body_output_shape.set_element_type(xla::TUPLE); + for (int i = 0; i < ctx->num_outputs(); i++) { + if (!compile_time_const_arg_indices[i]) { + *(body_output_shape.add_tuple_shapes()) = + body.xla_output_shape.tuple_shapes(i); + } + } + // If `body` has a token output, append its shape to `body_output_shape`. + if (has_token_input_output) { + *(body_output_shape.add_tuple_shapes()) = + body.xla_output_shape.tuple_shapes(ctx->num_inputs()); + } + if (!xla::ShapeUtil::Compatible(body_input_shape, body_output_shape)) { + return errors::InvalidArgument( + "Input and output shapes of loop body do not match: ", + xla::ShapeUtil::HumanString(body_input_shape), " vs. ", + xla::ShapeUtil::HumanString(body_output_shape)); + } + return absl::OkStatus(); +} + +absl::StatusOr BuildWrappedCond( + XlaOpKernelContext* ctx, const XlaCompiler::CompilationResult& cond) { + xla::Shape cond_input_shape = cond.xla_input_shapes[0]; + std::unique_ptr cb = + ctx->builder()->CreateSubBuilder("cond_wrapper"); + auto inputs = xla::Parameter(cb.get(), 0, cond_input_shape, "inputs"); + auto outputs = xla::Call(cb.get(), *cond.computation, {inputs}); + xla::GetTupleElement(outputs, 0); + return cb->Build(); +} + +absl::StatusOr BuildWrappedBody( + XlaOpKernelContext* ctx, const XlaCompiler::CompilationResult& body, + const std::vector& compile_time_const_arg_indices, + int num_compile_time_const_args, bool has_token_input_output) { + if (num_compile_time_const_args <= 0 && + body.xla_input_shapes[0] == body.xla_output_shape) { + return xla::XlaComputation(body.computation->proto()); + } + xla::XlaComputation body_wrapper; + std::unique_ptr cb = + ctx->builder()->CreateSubBuilder("body_wrapper"); + xla::Shape body_input_shape = body.xla_input_shapes[0]; + auto inputs = xla::Parameter(cb.get(), 0, body_input_shape, "inputs"); + // Call the original body function which has mismatched inputs and outputs + // and strip the compile time consts from the list of outputs. While requires + // the inputs and outputs of its body function to match. + auto outputs = xla::Call(cb.get(), *body.computation, {inputs}); + std::vector non_compile_time_const_outputs; + int input_num = 0; + for (int i = 0; i < compile_time_const_arg_indices.size(); i++) { + if (!compile_time_const_arg_indices[i]) { + xla::XlaOp output = xla::GetTupleElement(outputs, i); + const xla::Shape& input_shape = body_input_shape.tuple_shapes(input_num); + const xla::Shape& output_shape = body.xla_output_shape.tuple_shapes(i); + TF_RET_CHECK(xla::ShapeUtil::Compatible(input_shape, output_shape)); + if (input_shape != output_shape) { + TF_ASSIGN_OR_RETURN(xla::ShapeTree disassembled_tuple, + xla::DisassembleTuple(output)); + disassembled_tuple.ForEachMutableElement( + [&](const xla::ShapeIndex& index, xla::XlaOp* element) { + const xla::Shape& output_subshape = + xla::ShapeUtil::GetSubshape(output_shape, index); + if (output_subshape.IsArray()) { + const xla::Shape& input_subshape = + xla::ShapeUtil::GetSubshape(input_shape, index); + for (int d = 0; d < output_subshape.dimensions().size(); ++d) { + if (input_subshape.is_dynamic_dimension(d) && + !output_subshape.is_dynamic_dimension(d)) { + *element = xla::SetDimensionSize( + *element, + xla::ConstantR0( + cb.get(), + static_cast(output_shape.dimensions()[d])), + d); + } + } + } + }); + output = + xla::AssembleTuple(output.builder(), std::move(disassembled_tuple)); + } + non_compile_time_const_outputs.push_back(output); + ++input_num; + } + } + // If `body` has a token output, append it to + // `non_compile_time_const_outputs`. + if (has_token_input_output) { + non_compile_time_const_outputs.push_back( + xla::GetTupleElement(outputs, ctx->num_outputs())); + } + xla::Tuple(cb.get(), non_compile_time_const_outputs); + return cb->Build(); +} + +xla::XlaOp BuildWhile(XlaOpKernelContext* ctx, + const xla::XlaComputation& wrapped_cond, + const xla::XlaComputation& wrapped_body, + const xla::XlaOp initial_values, + const std::vector& input_mapping, + const std::vector& compile_time_const_arg_indices, + int num_compile_time_const_args, + bool has_token_input_output) { + xla::XlaOp while_result = + xla::While(wrapped_cond, wrapped_body, initial_values); + std::vector padded_while_outputs(ctx->num_outputs()); + int while_result_index = 0; + for (int i = 0; i < ctx->num_inputs(); i++) { + if (!compile_time_const_arg_indices[i]) { + padded_while_outputs[input_mapping[while_result_index]] = + xla::GetTupleElement(while_result, while_result_index); + while_result_index++; + } else { + padded_while_outputs[i] = ctx->Input(i); + } + } + // If `body` has a token output, append it to `padded_while_outputs`. + if (has_token_input_output) { + padded_while_outputs.push_back(xla::GetTupleElement( + while_result, ctx->num_inputs() - num_compile_time_const_args)); + } + return xla::Tuple(ctx->builder(), padded_while_outputs); +} + +} // anonymous namespace + +XlaWhileOp::XlaWhileOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + const NameAttrList* name_attr; + OP_REQUIRES_OK(ctx, ctx->GetAttr("cond", &name_attr)); + cond_name_attr_ = *name_attr; + OP_REQUIRES_OK(ctx, ctx->GetAttr("body", &name_attr)); + body_name_attr_ = *name_attr; + if (!ctx->GetAttr(kXlaTokenInputNodesAttrName, &token_input_nodes_).ok()) { + has_token_input_output_ = false; + } else { + has_token_input_output_ = !token_input_nodes_.empty(); + } + if (ctx->HasAttr(kPropagateCompileTimeConsts)) { + OP_REQUIRES_OK(ctx, ctx->GetAttr(kPropagateCompileTimeConsts, + &propagate_compile_time_consts_)); + } + if (!ctx->GetAttr(kXlaOriginalOutsideCompilationNodeName, + &original_node_name_) + .ok()) + original_node_name_ = name(); +} + +void XlaWhileOp::Compile(XlaOpKernelContext* ctx) { + VLOG(1) << "WhileOp::Compile"; + + // Input resources need to be grouped in the end of the body function + // according to the convention of the XLA bridge. + OP_REQUIRES_OK(ctx, VerifyResourceArgsGroupedAtEnd(ctx, body_name_attr_)); + + std::vector arguments; + bool has_uninitialized_vars; + bool has_tensor_arrays; + bool has_uninitialized_tensor_lists; + OP_REQUIRES_OK(ctx, MakeXlaCompilerArgumentsFromInputs( + ctx, &arguments, &has_uninitialized_vars, + &has_tensor_arrays, &has_uninitialized_tensor_lists)); + + xla::XlaBuilder* builder = ctx->builder(); + XlaCompiler* compiler = ctx->compiler(); + + // Indices of loop vars which satisfy the following conditions: + // 1. They are loop invariants. + // 2. The op inputs at these indices are compile time constants. + // + // These compile time consts do not appear as _Args in the cond/body functions + // and are replaced by kConstant nodes instead. As a result, the compiled + // body function does not have matching input and output shape. We fix this + // by rewriting the body computation (see body_wrapper below) to output + // just the non compile-time-const values and later pad up the while output + // with the const args. + std::vector compile_time_const_arg_indices(ctx->num_inputs()); + int num_compile_time_const_args = 0; + if (propagate_compile_time_consts_) { + OP_REQUIRES_OK(ctx, ConvertLoopInvariantsToConst( + ctx, body_name_attr_, cond_name_attr_, &arguments, + &compile_time_const_arg_indices, + &num_compile_time_const_args, compiler->client())); + } + + VLOG(1) << "Compiling body"; + + // All resource that are inputs to the loop's body must also be + // present as loop body outputs; the signature of the loop's input and + // output must match. We ensure this by asking the compiler to include the + // current values of all resources, even if they haven't been updated by the + // computation. We must also ask the compiler to keep compile-time constant + // outputs as part of the generated computation, for the same reason. + // TODO(phawkins): consider adding loop-invariant inputs to XLA's While() + // operator. + XlaCompiler::CompileOptions body_options; + body_options.use_tuple_arg = true; + body_options.return_updated_values_for_all_resources = true; + body_options.is_entry_computation = false; + body_options.add_token_input_output = has_token_input_output_; + auto body = std::make_unique(); + OP_REQUIRES_OK(ctx, compiler->CompileFunction(body_options, body_name_attr_, + arguments, body.get())); + OP_REQUIRES_OK( + ctx, ctx->xla_context()->RecordCollectiveInfoFromNestedCompilationResult( + *body.get())); + + // We must use a static shape for parameters to an XLA compilation. However, + // we may not know the shape of a resource if it is first + // written inside the loop. Furthermore, we do not know ahead of time which + // gradient TensorArrays will be created by the TensorArrayGradV3 operator. + // + // Ideally we would change TensorFlow to provide static shape always, but + // but this is not easy to do. So if uninitialized resources or TensorArrays + // are used by the loop body, we compile the body function twice: + // 1) once with uninitialized resource inputs and no TensorArray gradient + // inputs. We then discard the computation but we assume resource shapes + // and the set of gradients read or written will reach a fixpoint after one + // iteration. + // Hence we can use the output shapes and TensorArray gradients of each + // resource as the "true" shapes. + // 2) again with the "correct" resource information determined by (1). + if (has_uninitialized_vars || has_tensor_arrays || + has_uninitialized_tensor_lists) { + VLOG(2) << "Recompiling loop body: has_uninitialized_vars: " + << has_uninitialized_vars + << " has_tensor_arrays: " << has_tensor_arrays + << " has_uninitialized_tensor_lists: " + << has_uninitialized_tensor_lists; + // Initializes any uninitialized resource with zero values of the + // shape determined by the first compilation. + for (int i = 0; i < body->resource_updates.size(); ++i) { + const XlaCompiler::ResourceUpdate& update = body->resource_updates[i]; + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(update.input_index, &resource)); + + XlaCompiler::Argument& arg = arguments[update.input_index]; + if (!arg.initialized) { + VLOG(2) << "Update shape for argument " << update.input_index << " " + << update.shape.DebugString(); + arg.initialized = true; + + arg.shape = update.shape; + OP_REQUIRES_OK(ctx, + resource->SetTypeAndShape(update.type, update.shape)); + + OP_REQUIRES_OK(ctx, resource->SetZeroValue(builder)); + } + + // Add any TensorArray gradients touched by the body to the enclosing + // graph. + for (const std::string& grad_source : + update.tensor_array_gradients_accessed) { + VLOG(4) << "TensorArray " << resource->name() << " accessed gradient " + << grad_source; + XlaResource* gradient; + OP_REQUIRES_OK(ctx, resource->GetOrCreateTensorArrayGradient( + grad_source, builder, &gradient)); + } + + // Add all of the TensorArray gradients to the argument. For simplicity, + // we always pass all known gradients. + for (const auto& gradient : resource->tensor_array_gradients()) { + arg.tensor_array_gradients.insert(gradient.first); + } + } + + // Set the shape of any uninitialized TensorLists to the shape determined by + // the first compilation. Note that, unlike resources, we do not initialize + // the input list with zeros here, that is done later. + xla::Shape body_output_shape = body->xla_output_shape; + OP_REQUIRES(ctx, body_output_shape.IsTuple(), + errors::FailedPrecondition( + "xla_output_shape of while body must be a tuple.")); + for (int i = 0; i < arguments.size(); i++) { + XlaCompiler::Argument& arg = arguments[i]; + if (arg.initialized || !IsTensorListInput(ctx, i)) { + continue; + } + arg.shape = body_output_shape.tuple_shapes(i); + arg.initialized = true; + } + + // Recompile the body with the "correct" resource shapes. + VLOG(1) << "Recompiling body with corrected resource shapes"; + *body = {}; + OP_REQUIRES_OK(ctx, compiler->CompileFunction(body_options, body_name_attr_, + arguments, body.get())); + } + + VLOG(1) << "Compiling condition"; + + XlaCompiler::CompileOptions cond_options; + cond_options.use_tuple_arg = true; + cond_options.is_entry_computation = false; + cond_options.add_token_input_output = has_token_input_output_; + XlaCompiler::CompilationResult cond; + OP_REQUIRES_OK(ctx, compiler->CompileFunction(cond_options, cond_name_attr_, + arguments, &cond)); + + OP_REQUIRES(ctx, body->xla_input_shapes.size() == 1, + errors::FailedPrecondition("Expected one input shape")); + xla::Shape body_input_shape = body->xla_input_shapes[0]; + OP_REQUIRES(ctx, body_input_shape.IsTuple(), + errors::FailedPrecondition("Expected tuple shape")); + OP_REQUIRES(ctx, cond.xla_input_shapes.size() == 1, + errors::FailedPrecondition("Expected one input shape")); + xla::Shape cond_input_shape = cond.xla_input_shapes[0]; + OP_REQUIRES(ctx, cond_input_shape.IsTuple(), + errors::FailedPrecondition("Expected tuple shape")); + + VLOG(2) << "Body shape: " << xla::ShapeUtil::HumanString(body_input_shape) + << " -> " << xla::ShapeUtil::HumanString(body->xla_output_shape); + VLOG(2) << "Cond shape: " << xla::ShapeUtil::HumanString(cond_input_shape) + << " -> " << xla::ShapeUtil::HumanString(cond.xla_output_shape); + + OP_REQUIRES(ctx, + xla::ShapeUtil::Compatible(body_input_shape, cond_input_shape), + errors::InvalidArgument( + "Input shapes of loop body and condition do not match: ", + xla::ShapeUtil::HumanString(body_input_shape), " vs. ", + xla::ShapeUtil::HumanString(cond_input_shape))); + + // Check that the shape of the body outputs excluding the compile time const + // args (which are pruned from the body outputs in body_wapper) matches the + // shape of the inputs. + OP_REQUIRES_OK(ctx, VerifyBodyInputAndOutputShapeMatch( + ctx, compile_time_const_arg_indices, *body.get(), + has_token_input_output_)); + + xla::Shape expected_cond_output_shape_without_side_effect = + xla::ShapeUtil::MakeTupleShape( + {xla::ShapeUtil::MakeShape(xla::PRED, {})}); + xla::Shape expected_cond_output_shape_with_side_effect = + xla::ShapeUtil::MakeTupleShape({xla::ShapeUtil::MakeShape(xla::PRED, {}), + xla::ShapeUtil::MakeTokenShape()}); + OP_REQUIRES(ctx, + xla::ShapeUtil::Compatible( + cond.xla_output_shape, + expected_cond_output_shape_without_side_effect) || + xla::ShapeUtil::Compatible( + cond.xla_output_shape, + expected_cond_output_shape_with_side_effect), + errors::InvalidArgument( + "Output shape of loop condition should be (pred[]) or " + "(pred[], token[]), got: ", + xla::ShapeUtil::HumanString(cond.xla_output_shape))); + + int num_inputs = body->input_mapping.size(); + std::vector inputs(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + int input_num = body->input_mapping[i]; + if (has_token_input_output_ && i == num_inputs - 1) { + // Set token input for this "while" op. + std::vector token_inputs; + token_inputs.reserve(token_input_nodes_.size()); + for (const std::string& node_name : token_input_nodes_) { + auto token_or = compiler->GetNodeToken(node_name); + OP_REQUIRES_OK(ctx, token_or.status()); + token_inputs.push_back(token_or.value()); + } + inputs[i] = xla::AfterAll(builder, token_inputs); + } else if (ctx->input_type(input_num) == DT_RESOURCE) { + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(input_num, &resource)); + OP_REQUIRES_OK(ctx, resource->Pack(&inputs[i], builder)); + } else if (IsTensorListInput(ctx, input_num)) { + xla::XlaOp input = ctx->Input(input_num); + auto input_shape_or = ctx->builder()->GetShape(input); + OP_REQUIRES_OK(ctx, input_shape_or.status()); + xla::Shape input_shape = input_shape_or.value(); + const xla::Shape& list_shape = body_input_shape.tuple_shapes(i); + // Shape/datatype of the input list may differ from shape/datatype of the + // body/cond input if the list's shape/datatype was inferred after the + // first compilation and the body/cond was recompiled with the updated + // shape/datatype of the list. + if (input_shape != list_shape) { + // Prepare dynamic dimensions for element shapes. + std::vector> list_dynamic_dims; + for (int i = 0; i < list_shape.tuple_shapes().size() - 1; ++i) { + std::vector dynamic_dims; + + const xla::Shape& shape = list_shape.tuple_shapes(i); + + // We already have the dynamic size of leading dimension outside of + // the while loop without initializing the TensorList inside the while + // loop. + if (shape.is_dynamic_dimension(0)) { + xla::XlaOp leading_dim_size = xla::GetDimensionSize(input, 0); + dynamic_dims.push_back(leading_dim_size); + } else { + int32_t dim_size = shape.dimensions(0); + dynamic_dims.push_back( + xla::ConstantR0(ctx->builder(), dim_size)); + } + + // Set dynamic dimension size to 0 for element value. Inside the while + // loop, TensorlistSetItem will properly set the element shape's + // dynamic dimension. + for (int64_t dim = 1; dim < shape.dimensions().size(); ++dim) { + int32_t dim_size = shape.dimensions(dim); + if (shape.is_dynamic_dimension(dim)) { + dim_size = 0; + } + dynamic_dims.push_back( + xla::ConstantR0(ctx->builder(), dim_size)); + } + list_dynamic_dims.push_back(dynamic_dims); + } + OP_REQUIRES_OK( + ctx, CreateZerosTensorListWithShape(ctx->builder(), list_shape, + list_dynamic_dims, &inputs[i])); + } else { + inputs[i] = ctx->Input(input_num); + } + } else { + inputs[i] = ctx->Input(input_num); + } + } + + xla::XlaOp init = xla::Tuple(builder, inputs); + + VLOG(1) << "Building while loop"; + + // Wraps the condition in a computation that unpacks the output tuple. + absl::StatusOr cond_result = BuildWrappedCond(ctx, cond); + OP_REQUIRES_OK(ctx, cond_result.status()); + xla::XlaComputation wrapped_cond = std::move(cond_result.value()); + + // Remove compile time const args from the list of body outputs. + absl::StatusOr body_result = + BuildWrappedBody(ctx, *body.get(), compile_time_const_arg_indices, + num_compile_time_const_args, has_token_input_output_); + OP_REQUIRES_OK(ctx, body_result.status()); + xla::XlaComputation wrapped_body = std::move(body_result.value()); + + // Builds the While op and pads its output with the compile time const args. + xla::XlaOp while_result = + BuildWhile(ctx, wrapped_cond, wrapped_body, init, body->input_mapping, + compile_time_const_arg_indices, num_compile_time_const_args, + has_token_input_output_); + + // Sets non-variable outputs and determine when resource variables start. + int resource_index = 0; + for (int i = 0; i < ctx->num_outputs(); ++i) { + if (ctx->input_type(i) != DT_RESOURCE) { + if (IsTensorListInput(ctx, i)) { + ctx->SetTensorListOutput(i, xla::GetTupleElement(while_result, i)); + } else { + ctx->SetOutput(i, xla::GetTupleElement(while_result, i)); + } + ++resource_index; + } else { + break; + } + } + if (has_token_input_output_) { + // Set token output for this "while" op. + xla::XlaOp token_output = + xla::GetTupleElement(while_result, ctx->num_outputs()); + auto shape_or = builder->GetShape(token_output); + OP_REQUIRES_OK(ctx, shape_or.status()); + OP_REQUIRES(ctx, shape_or.value().IsToken(), + errors::FailedPrecondition( + "Token output is not token type: ", + xla::ShapeUtil::HumanString(shape_or.value()))); + OP_REQUIRES_OK(ctx, + compiler->SetNodeToken(original_node_name_, token_output)); + } + + // Updates the values of any resource variables modified by the loop. + for (int i = 0; i < body->resource_updates.size(); ++i) { + const XlaCompiler::ResourceUpdate& update = body->resource_updates[i]; + XlaResource* resource; + OP_REQUIRES_OK(ctx, ctx->GetResourceInput(update.input_index, &resource)); + if (update.modified) { + int pos = resource_index + i; + OP_REQUIRES_OK(ctx, + resource->SetFromPack( + arguments[update.input_index].tensor_array_gradients, + xla::GetTupleElement(while_result, pos), builder)); + } + VLOG(2) << "Loop-carried variable: pos: " << update.input_index + << " name: " << resource->name() << " modified: " << update.modified + << " type: " << DataTypeString(update.type) + << " shape: " << update.shape.DebugString(); + // Copies the identity of the resource variable from input to output + // unchanged, even if the variable was not modified. + ctx->op_kernel_context()->set_output( + update.input_index, + ctx->op_kernel_context()->input(update.input_index)); + } + + VLOG(1) << "Done building while loop"; +} + +REGISTER_XLA_OP(Name("While").AllowResourceTypes().AllowVariantTypes(), + XlaWhileOp); +REGISTER_XLA_OP(Name("StatelessWhile").AllowResourceTypes().AllowVariantTypes(), + XlaWhileOp); +REGISTER_XLA_OP(Name("XlaWhile").AllowResourceTypes().AllowVariantTypes(), + XlaWhileOp); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/while_op.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/while_op.h new file mode 100644 index 0000000000000000000000000000000000000000..2dedf13a2dc63ae7c92e80dd439101615300f47a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/while_op.h @@ -0,0 +1,77 @@ +/* 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_KERNELS_WHILE_OP_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_WHILE_OP_H_ + +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// This TensorFlow op provides a functional iteration primitive. +// +// The inputs and outputs of the loop body must agree on the number, types, and +// shapes of the Tensors carried around the loop body. +// +// Computations in while loops may read from and write to resource variables. +// Resource variables may be passed as arguments to a function's body and +// condition functions. The XlaCompiler converts resource variable arguments +// into parameters to the XLA computation and moves them to the end of the +// parameter list, and by using the `return_updated_values_for_all_variables` +// we ensure that all variables that appear in the input also appear at the +// end of the body's output. This ensures the loop body's input and output +// signatures match. +// +// It is the user's responsibility to ensure that each non-variable _Arg matches +// the corresponding _Retval. +// +// For example, suppose we have a loop body with arguments: +// DT_INT32, DT_RESOURCE (pointing to a DT_BOOL var), DT_FLOAT +// and return values +// DT_INT32, DT_FLOAT +// It is an error for the body to return DT_RESOURCE values. +// +// The body will be lowered into an XLA computation that takes and returns a +// tuple with XLA type (I32, F32, PRED). Note the resource variable appears at +// the end of both the loop body's input and output argument lists. +class XlaWhileOp : public XlaOpKernel { + public: + explicit XlaWhileOp(OpKernelConstruction* ctx); + + void Compile(XlaOpKernelContext* ctx) override; + + private: + NameAttrList cond_name_attr_; + NameAttrList body_name_attr_; + bool has_token_input_output_; + std::vector token_input_nodes_; + std::string original_node_name_; + // Whether to propagate compile time consts into the loop body. + // This is not supported by default now since it may cause HBM memory + // overheads. + bool propagate_compile_time_consts_ = false; + + XlaWhileOp(const XlaWhileOp&) = delete; + void operator=(const XlaWhileOp&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_WHILE_OP_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_broadcast_helper_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_broadcast_helper_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..b28701039656c5551671ecf96f569cb51038459e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_broadcast_helper_op.cc @@ -0,0 +1,117 @@ +/* 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 +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +namespace { + +class XlaBroadcastHelperOp : public XlaOpKernel { + public: + explicit XlaBroadcastHelperOp(OpKernelConstruction* context) + : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + xla::XlaOp lhs = context->Input(0); + xla::XlaOp rhs = context->Input(1); + const TensorShape lhs_shape = context->InputShape(0); + const TensorShape rhs_shape = context->InputShape(1); + + const bool broadcast_lhs = lhs_shape.dims() < rhs_shape.dims(); + const TensorShape* min_rank_shape = broadcast_lhs ? &lhs_shape : &rhs_shape; + const TensorShape* max_rank_shape = broadcast_lhs ? &rhs_shape : &lhs_shape; + + std::vector broadcast_dims; + OP_REQUIRES_OK(context, context->ConstantInputAsIntVector("broadcast_dims", + &broadcast_dims)); + if (broadcast_dims.empty()) { + OP_REQUIRES( + context, + lhs_shape.dims() == rhs_shape.dims() || lhs_shape.dims() == 0 || + rhs_shape.dims() == 0, + errors::InvalidArgument( + "If broadcast_dims is empty, both " + "arguments must have equal rank; " + "argument shapes, or at least one argument must be a scalar: ", + lhs_shape.DebugString(), " and ", rhs_shape.DebugString())); + context->SetOutput(0, lhs); + context->SetOutput(1, rhs); + return; + } + + OP_REQUIRES( + context, broadcast_dims.size() == min_rank_shape->dims(), + errors::InvalidArgument( + "broadcast_dims must have size equal to the smaller argument rank; " + "broadcast_dims: [", + absl::StrJoin(broadcast_dims, ","), "]; argument shapes: ", + lhs_shape.DebugString(), " and ", rhs_shape.DebugString())); + std::vector sorted_broadcast_dims = broadcast_dims; + absl::c_sort(sorted_broadcast_dims); + std::set dims_set(broadcast_dims.begin(), broadcast_dims.end()); + OP_REQUIRES(context, + dims_set.size() == broadcast_dims.size() && + broadcast_dims == sorted_broadcast_dims, + errors::InvalidArgument( + "Duplicate or nonmonotonic dimension in broadcast_dims; " + "broadcast_dims: [", + absl::StrJoin(broadcast_dims, ","), "]")); + + std::vector broadcast_shape(max_rank_shape->dims(), 1LL); + for (int i = 0; i < broadcast_dims.size(); ++i) { + const int dim = broadcast_dims[i]; + OP_REQUIRES( + context, dim >= 0 && dim < broadcast_shape.size(), + errors::InvalidArgument( + "Invalid broadcast dimension (", dim, "); broadcast_dims: [", + absl::StrJoin(broadcast_dims, ","), "]; argument shapes: ", + lhs_shape.DebugString(), " and ", rhs_shape.DebugString())); + broadcast_shape[dim] = min_rank_shape->dim_size(i); + } + if (broadcast_lhs) { + lhs = xla::BroadcastInDim(lhs, broadcast_shape, broadcast_dims); + } else { + rhs = xla::BroadcastInDim(rhs, broadcast_shape, broadcast_dims); + } + context->SetOutput(0, lhs); + context->SetOutput(1, rhs); + } + + private: + xla::DotDimensionNumbers dnums_; + + XlaBroadcastHelperOp(const XlaBroadcastHelperOp&) = delete; + void operator=(const XlaBroadcastHelperOp&) = delete; +}; + +REGISTER_XLA_OP( + Name("XlaBroadcastHelper").CompileTimeConstantInput("broadcast_dims"), + XlaBroadcastHelperOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.cc new file mode 100644 index 0000000000000000000000000000000000000000..a9d8eeb88ade45629acc6457d64e25dbcd86054e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.cc @@ -0,0 +1,557 @@ +/* Copyright 2023 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/kernels/xla_call_module_loader.h" + +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/log/vlog_is_on.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/LogicalResult.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Block.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinDialect.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/OperationSupport.h" // from @llvm-project +#include "mlir/IR/TypeRange.h" // from @llvm-project +#include "mlir/IR/TypeUtilities.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/IR/Value.h" // from @llvm-project +#include "mlir/IR/Verifier.h" // from @llvm-project +#include "mlir/IR/Visitors.h" // from @llvm-project +#include "mlir/Parser/Parser.h" // from @llvm-project +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Support/DebugStringHelper.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "mlir/Support/LogicalResult.h" // from @llvm-project +#include "mlir/Transforms/Passes.h" // from @llvm-project +#include "shardy/dialect/sdy/ir/dialect.h" // from @shardy +#include "shardy/dialect/sdy/transforms/import/passes.h" // from @shardy +#include "stablehlo/dialect/ChloOps.h" // from @stablehlo +#include "stablehlo/dialect/Serialization.h" // from @stablehlo +#include "stablehlo/dialect/StablehloOps.h" // from @stablehlo +#include "stablehlo/dialect/VhloOps.h" // from @stablehlo +#include "stablehlo/transforms/StablehloRefineShapes.h" // from @stablehlo +#include "stablehlo/transforms/optimization/Passes.h" // from @stablehlo +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/error_util.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/hlo/translate/stablehlo.h" +#include "xla/mlir/utils/type_util.h" +#include "xla/python/refine_polymorphic_shapes.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/spmd/shardy/sdy_round_trip/pipelines.h" +#include "xla/shape.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" + +namespace tensorflow { + +namespace { + +// When adding a new version, write when it was added. Also change the default +// version in the constructor in xla.py. +// See +// https://github.com/google/jax/blob/main/jax/experimental/jax2tf/README.md#native-serialization-versions +// for a description of the different versions. + +constexpr int kVersionStartStableHloCompatibility = 4; +constexpr int kVersionStartSupportCallTFGraph = 5; +constexpr int kVersionStartSupportDisabledChecks = 6; +constexpr int kVersionStartSupportShapeAssertions = 7; +constexpr int kVersionStartSupportUsesShapePolymorphismAttr = 8; +constexpr int kVersionStartSupportEffects = 9; +constexpr int kVersionStartSupportShardyPartitioner = 10; +constexpr int kVersionMinimumSupported = kVersionStartStableHloCompatibility; + +// This should match xla.py:call_module_maximum_supported_version +constexpr int kVersionMaximumSupported = kVersionStartSupportShardyPartitioner; + +constexpr llvm::StringRef kDisabledCheckPlatform = "platform"; + +bool IsPlatformCheckDisabled(absl::Span disabled_checks) { + return llvm::is_contained(disabled_checks, kDisabledCheckPlatform); +} + +constexpr llvm::StringRef kDisabledCheckShapeAssertions = "shape_assertions"; + +bool IsShapeAssertionsCheckDisabled( + absl::Span loading_disabled_checks) { + return llvm::is_contained(loading_disabled_checks, + kDisabledCheckShapeAssertions); +} + +constexpr llvm::StringRef kUsesShapePolymorphismAttr = + "jax.uses_shape_polymorphism"; + +} // namespace + +bool IsTokenType(mlir::Type type) { + return mlir::isa(type); +} + +absl::StatusOr> +XlaCallModuleLoader::Create(mlir::MLIRContext* context, int version, + mlir::StringRef module_str, + std::vector disabled_checks, + std::vector platforms, + int num_invocation_args, + bool main_has_token_input_output, + bool use_shardy_partitioner) { + std::unique_ptr loader(new XlaCallModuleLoader); + TF_RETURN_IF_ERROR(loader->LoadModule( + context, version, module_str, std::move(disabled_checks), + std::move(platforms), num_invocation_args, main_has_token_input_output, + use_shardy_partitioner)); + return loader; +} + +absl::Status XlaCallModuleLoader::SetPlatformIndex( + absl::string_view compilation_platform) { + int platform_index = -1; + if (!platforms_.empty()) { + auto found_platform = + std::find(platforms_.begin(), platforms_.end(), compilation_platform); + if (found_platform == platforms_.end()) { + if (!IsPlatformCheckDisabled(loading_disabled_checks_)) { + return absl::NotFoundError(absl::StrCat( + "The current platform ", compilation_platform, + " is not among the platforms required by the module: [", + absl::StrJoin(platforms_, ", "), "]")); + } else { + if (platforms_.size() > 1) { + platform_index = 0; + } + } + } else { + // We only use a platform index argument if we support at least 2 + // platforms. + if (platforms_.size() > 1) { + platform_index = found_platform - platforms_.begin(); + } + } + } + + if (platform_index < 0) return absl::OkStatus(); + VLOG(3) << "XlaCallModule setting the platform_index to " << platform_index + << " for platform " << compilation_platform << "."; + mlir::Block& main_body = main_.front(); + + if (main_.getNumArguments() < 1) { + return absl::InvalidArgumentError(absl::StrCat( + "The module should have a platform index argument but it has no ", + "arguments")); + } + mlir::OpBuilder op_builder(main_); + op_builder.setInsertionPointToStart(&main_body); + mlir::BlockArgument platform_index_arg = main_body.getArgument(0); + mlir::RankedTensorType arg_ranked_type = + mlir::dyn_cast(platform_index_arg.getType()); + if (!arg_ranked_type || arg_ranked_type.getRank() != 0 || + !(arg_ranked_type.getElementType().isSignlessInteger(32) || + arg_ranked_type.getElementType().isSignlessInteger(64))) { + return absl::InvalidArgumentError( + absl::StrCat("Module argument at index 0 should be a 0-dimensional " + "32-bit or 64-bit integer-tensor platform index argument " + "but has type ", + mlir::debugString(platform_index_arg.getType()))); + } + bool is_32_bit = arg_ranked_type.getElementType().isSignlessInteger(32); + auto const_attr = is_32_bit ? op_builder.getI32IntegerAttr(platform_index) + : op_builder.getI64IntegerAttr(platform_index); + auto platform_index_op = mlir::stablehlo::ConstantOp::create( + op_builder, platform_index_arg.getLoc(), const_attr); + platform_index_arg.replaceAllUsesWith(platform_index_op); + + CHECK(llvm::succeeded(main_.eraseArgument(0))); + platform_index_arg_set_ = true; + return absl::OkStatus(); +} + +absl::Status XlaCallModuleLoader::RefineDynamicShapes( + llvm::ArrayRef input_shapes) { + // Skip shape refinement for new versions if USES_SHAPE_POLYMORPHISM_ATTR=1 + if (version_ >= kVersionStartSupportUsesShapePolymorphismAttr) { + if (mlir::Attribute uses_shape_poly_attr = + (*module_)->getAttr(kUsesShapePolymorphismAttr)) { + mlir::BoolAttr uses_shape_poly_bool_attr = + llvm::dyn_cast(uses_shape_poly_attr); + + if (!uses_shape_poly_bool_attr) { + return absl::InvalidArgumentError(absl::StrCat( + "jax.uses_shape_polymorphism is not a boolean attribute: ", + mlir::debugString(uses_shape_poly_attr))); + } + if (!uses_shape_poly_bool_attr.getValue()) { + VLOG(3) << "XlaCallModule skipping shape refinement due to module " + << " attribute " << kUsesShapePolymorphismAttr.str() << "=" + << mlir::debugString(uses_shape_poly_attr); + return absl::OkStatus(); + } + } else { + VLOG(3) << "XlaCallModule skipping shape refinement due to module " + << " attribute " << kUsesShapePolymorphismAttr.str() + << " missing"; + return absl::OkStatus(); + } + } + // Add the tokens to the input_shapes. Starting with version 9, the main + // function may take token arguments that do not correspond with op inputs. + int nr_inputs = NrInputs(); + int nr_expected_tokens = llvm::count_if(InputTypes(), IsTokenType); + bool has_platform_index_arg = + platforms_.size() > 1 && !platform_index_arg_set_; + int nr_expected_platform_index_args = has_platform_index_arg ? 1 : 0; + if (input_shapes.size() != + nr_inputs - nr_expected_tokens - nr_expected_platform_index_args) { + return absl::InvalidArgumentError(absl::StrCat( + "XlaCallModule RefineDynamicShapes called with ", input_shapes.size(), + " input shapes, but the main function takes ", + nr_inputs - nr_expected_tokens - nr_expected_platform_index_args, + " non-token and non-platform-index arguments. The input ", + "shapes are (", + absl::StrJoin(input_shapes, ", ", + [](std::string* out, const xla::Shape& s) { + absl::StrAppend(out, s.ToString()); + }), + ") and the main function argument types are ", + absl::StrJoin(InputTypes(), ", ", + [](std::string* out, const mlir::Type& t) { + absl::StrAppend(out, mlir::debugString(t)); + }), + ")")); + } + + // Derive static input types to use for main. + mlir::Block& main_body = main_.front(); + mlir::Builder builder(module_->getContext()); + std::vector static_array_input_types(nr_inputs); + int next_actual_input = 0; + for (int i = 0, end = nr_inputs; i < end; ++i) { + mlir::Type arg_type = main_body.getArgument(i).getType(); + if (i == 0 && has_platform_index_arg) { + static_array_input_types[i] = arg_type; + continue; + } + if (IsTokenType(arg_type)) { + static_array_input_types[i] = arg_type; + VLOG(3) << "XlaCallModule static array input type #" << i << ": " + << mlir::debugString(static_array_input_types[i]) + << " for argument type " << mlir::debugString(arg_type); + continue; + } + + // Get static MLIR Type from xla Shape. + const xla::Shape& xla_shape = input_shapes[next_actual_input++]; + std::vector xla_dimensions; + if (xla_shape.IsArray()) { + xla_dimensions = std::vector(xla_shape.dimensions().begin(), + xla_shape.dimensions().end()); + } + TF_ASSIGN_OR_RETURN( + mlir::Type element_type, + ConvertPrimitiveTypeToMlirType(xla_shape.element_type(), builder)); + mlir::RankedTensorType type = + mlir::RankedTensorType::get(xla_dimensions, element_type); + + VLOG(3) << "XlaCallModule static array input type #" << i << ": " + << mlir::debugString(type) << " for argument type " + << mlir::debugString(arg_type); + static_array_input_types[i] = type; + } + + // Insert custom_call ops as shims to maintain the validity of the module when + // main's input types are changed later. This is a workaround to allow shape + // refinement to be applied; the custom_calls are removed before returning. + // Arguments to main may occur as return values, or as inputs to called + // functions, and changing their types may invalidate the module due to type + // mismatches. To prevent this, for each argument that is a dynamically-shaped + // tensor, we insert a custom_call op that takes the argument as an input and + // replace uses of the argument with the custom_call's result. custom_call + // is used as it allows its inputs and outputs to be unranked. + // + // Example: + // + // The below main function returns its argument directly: + // + // func.func @main(%arg0: tensor<*xf32>) -> tensor<*xf32> { + // return %arg0 : tensor<*xf32> + // } + // + // Changing the argument's type invalidates the IR (type mismatch): + // + // func.func @main(%arg0: tensor<2x3xf32>) -> tensor<*xf32> { + // return %arg0 : tensor<*xf32> + // } + // + // Inserting a custom_call allows the IR to remain valid: + // + // func.func @main(%arg0: tensor<2x3xf32>) -> tensor<*xf32> { + // %0 = stablehlo.constant dense<[2, 3]> : tensor<2xi64> + // %1 = stablehlo.custom_call + // @stablehlo.shape_refinement_operand_wrapper(%arg0, %0) + // {indices_of_shape_operands = dense<1> : tensor<1xi64>} : + // (tensor<2x3xf32>, tensor<2xi64>) -> tensor<*xf32> + // return %1 : tensor<*xf32> + // } + // + // After shapes are refined and the custom_calls are removed, we get: + // + // func.func @main(%arg0: tensor<2x3xf32>) -> tensor<2x3xf32> { + // return %arg0 : tensor<2x3xf32> + // } + // + { + mlir::StatusScopedDiagnosticHandler diag_handler(module_->getContext()); + if (failed(mlir::stablehlo::refineArguments(main_, + static_array_input_types))) { + return absl::InvalidArgumentError( + absl::StrCat("Error refining argument shapes: ", + diag_handler.ConsumeStatus().ToString())); + } + } + + if (VLOG_IS_ON(5)) { + DumpMlirOpToFile("xla_call_module.after_refined_input_types", *module_); + } + bool enable_shape_assertions = + (version_ >= kVersionStartSupportShapeAssertions && + !IsShapeAssertionsCheckDisabled(loading_disabled_checks_)); + + // Store the original output types before shape refinement. + mlir::TypeRange original_output_types = OutputTypes(); + + // RefinePolymorphicShapes will refine using the new static types and clean up + // the shape_refinement_operand_wrapper custom calls. + TF_RETURN_IF_ERROR( + xla::RefinePolymorphicShapes(*module_, enable_shape_assertions)); + + if (VLOG_IS_ON(3)) { + DumpMlirOpToFile("xla_call_module.after_shape_refinement", *module_); + } + + // Mark the output types as refined if they are different from the original + // output types. + if (OutputTypes() != original_output_types) { + output_types_refined_ = true; + } + + return absl::OkStatus(); +} + +absl::Status XlaCallModuleLoader::LoadModule( + mlir::MLIRContext* context, int version, mlir::StringRef module_str, + std::vector disabled_checks, + std::vector platforms, int num_invocation_args, + bool main_has_token_input_output, bool use_shardy_partitioner) { + context_ = context; + version_ = version; + platforms_ = platforms; + loading_disabled_checks_ = disabled_checks; + use_shardy_partitioner_ = use_shardy_partitioner; + loading_disabled_checks_.insert( + loading_disabled_checks_.end(), + GetXlaCallModuleFlags()->disabled_checks.begin(), + GetXlaCallModuleFlags()->disabled_checks.end()); + + // Load a superset of dialects; we should check at serialization time that + // we only include allowable dialects. + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + context_->loadDialect(); + + if (version < kVersionMinimumSupported) { + return absl::InvalidArgumentError(absl::StrCat( + "XlaCallModuleOp with version ", version, + " is not supported anymore. Must be >= ", kVersionMinimumSupported)); + } + if (version > kVersionMaximumSupported) { + return absl::InvalidArgumentError( + absl::StrCat("XlaCallModuleOp with version ", version, + " is not supported by this build. Must be <= ", + kVersionMaximumSupported)); + } + if (version >= kVersionStartSupportDisabledChecks && platforms.empty()) { + return absl::InvalidArgumentError( + absl::StrCat("XlaCallModuleOp with version ", version, + " must have non-empty platforms.")); + } + + // Parse the StableHLO/VHLO bytecode + { + mlir::StatusScopedDiagnosticHandler diag_handler(context_); + module_ = + mlir::stablehlo::deserializePortableArtifact(module_str, context_); + if (!module_) { + return absl::InvalidArgumentError( + absl::StrCat("Cannot deserialize computation: ", + diag_handler.ConsumeStatus().ToString())); + } + } + VLOG(3) << "Parsed serialized module (version = " << version + << ", platforms = [" << absl::StrJoin(platforms, ", ") + << "], main_has_token_input_output = " << main_has_token_input_output + << ", disabled_checks = [" << absl::StrJoin(disabled_checks, ", ") + << "], loading_disabled_checks = [" + << absl::StrJoin(loading_disabled_checks_, ", ") << "]), module = " + << DumpMlirOpToFile("xla_call_module.parsed", *module_); + + if (use_shardy_partitioner) { + // We need to inline `sdy.mesh` symbols because otherwise they are going + // to be discarded or their names might collide with `sdy.mesh` symbols in + // another XlaCallModuleOp. + mlir::StatusScopedDiagnosticHandler diag_handler(context_); + mlir::PassManager pm(module_->getContext()); + pm.addPass(mlir::sdy::createInlineMeshesPass()); + if (failed(pm.run(*module_))) { + return absl::InternalError( + absl::StrCat("Shardy inline meshes pass failed: ", + diag_handler.ConsumeStatus().ToString())); + } + } + + { + mlir::StatusScopedDiagnosticHandler diag_handler(module_->getContext()); + if (mlir::failed(mlir::verify(*module_))) { + return absl::InvalidArgumentError(absl::StrCat( + "Error verifying module: ", diag_handler.ConsumeStatus().ToString())); + } + } + main_ = module_->lookupSymbol("main"); + if (!main_) { + return absl::InvalidArgumentError("Cannot find 'main' in module"); + } + + mlir::Block& main_body = main_.front(); + + int nr_token_arguments = llvm::count_if(InputTypes(), IsTokenType); + if (version < kVersionStartSupportEffects) { + bool has_token_at_start = (nr_token_arguments == 1 && + IsTokenType(main_.getArgument(0).getType())); + if (main_has_token_input_output != has_token_at_start) { + return absl::InvalidArgumentError(absl::StrCat( + "Expected a token at start iff main_has_token_input_output. ", + "Found main function type ", + mlir::debugString(main_.getFunctionType()), + " and main_has_token_input_output = ", main_has_token_input_output)); + } + } + int nr_platform_args = (platforms.size() > 1 ? 1 : 0); + if (num_invocation_args != + main_body.getNumArguments() - nr_platform_args - nr_token_arguments) { + return absl::InvalidArgumentError(absl::StrCat( + "Incorrect number of arguments passed to XlaCallModule = ", + num_invocation_args, ". It must be called with ", + main_body.getNumArguments() - nr_platform_args - nr_token_arguments, + " because the module main function takes ", main_body.getNumArguments(), + " arguments of which ", nr_platform_args, " platform index arguments, ", + "and ", nr_token_arguments, " token arguments.")); + } + return absl::OkStatus(); +} + +absl::Status XlaCallModuleLoader::ValidateXlaCallModuleInvariants() { + mlir::StatusScopedDiagnosticHandler diag_handler(module_->getContext()); + bool moduleValidationFailed = false; + + module_->walk([&](mlir::Operation* op) { + // StableHLO programs created by jax2tf only contain operations + // from Builtin, Func, StableHLO, Shardy dialects. + if (!llvm::isa(op->getDialect())) { + op->emitOpError() << "is an op from an unsupported dialect"; + moduleValidationFailed = true; + } + // `shape_assertion` custom calls must have side effects. We check this here + // because a pure `shape_assertion` is likely to be removed by MLIR's + // dead-code elimination, preventing us from detecting the issue later. + if (auto customCallOp = llvm::dyn_cast(op)) { + if (!customCallOp.getHasSideEffect() && + customCallOp.getCallTargetName() == "shape_assertion") { + op->emitOpError() << "`shape_assertion` custom calls must set " + "`has_side_effect = true`."; + moduleValidationFailed = true; + } + } + }); + + if (moduleValidationFailed) { + return absl::InvalidArgumentError( + absl::StrCat("XlaCallModule failed validation: ", + diag_handler.ConsumeStatus().ToString())); + } + return absl::OkStatus(); +} + +absl::Status XlaCallModuleLoader::ValidateStaticShapes() { + return xla::ValidateStaticShapes(*module_); +} + +absl::Status XlaCallModuleLoader::PrepareStablehloForLowering() { + mlir::StatusScopedDiagnosticHandler diag_handler(module_->getContext()); + + mlir::PassManager pm(module_->getContext()); + pm.addNestedPass( + mlir::stablehlo::createStablehloTargetIndependentOptimizationPass()); + if (use_shardy_partitioner_) { + // We need to export shardings because the lowering path go directly to + // HLO but not the MLIR to HLO path that invokes SdyRoundTripExport. + // We keep meshes inlined to avoid naming collisions when multiple + // XlaCallModules are combined. + xla::sdy::addSdyRoundTripExportPipeline(pm, /*keepMeshesInlined=*/true); + } + + if (failed(pm.run(*module_))) { + return absl::InternalError( + absl::StrCat("StableHLO->HLO lowering passes failed: ", + diag_handler.ConsumeStatus().ToString())); + } + + if (VLOG_IS_ON(5)) { + DumpMlirOpToFile("xla_call_module.after_canonicalization", *module_); + } + + return absl::OkStatus(); +} + +absl::StatusOr XlaCallModuleLoader::ToXlaComputation() { + xla::HloProto proto; + TF_RETURN_IF_ERROR(xla::ConvertStablehloToHloProto(*module_, &proto)); + return xla::XlaComputation(std::move(*proto.mutable_hlo_module())); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.h new file mode 100644 index 0000000000000000000000000000000000000000..66a7d83767d656418b982408bf28e72f36b26613 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.h @@ -0,0 +1,141 @@ +/* Copyright 2023 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_KERNELS_XLA_CALL_MODULE_LOADER_H_ +#define TENSORFLOW_COMPILER_TF2XLA_KERNELS_XLA_CALL_MODULE_LOADER_H_ + +#include + +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "llvm/ADT/ArrayRef.h" +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/IR/TypeRange.h" // from @llvm-project +#include "mlir/IR/Types.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/tsl/platform/statusor.h" + +namespace tensorflow { + +bool IsTokenType(mlir::Type type); + +class XlaCallModuleLoader { + public: + static absl::StatusOr> Create( + mlir::MLIRContext* context, int version, mlir::StringRef module_str, + std::vector disabled_checks, + std::vector platforms, int num_invocation_args, + bool main_has_token_input_output, bool use_shardy_partitioner); + + int NrInputs() { return main_.getNumArguments(); } + mlir::TypeRange InputTypes() { return main_.getArgumentTypes(); } + + int NrOutputs() { return main_.getNumResults(); } + mlir::TypeRange OutputTypes() { return main_.getResultTypes(); } + + // Sets the platform index argument, if the module is compiled for multiple + // platforms, and then erases the argument. + absl::Status SetPlatformIndex(absl::string_view compilation_platform); + + // Refines the dynamic module arguments based on the static argument shapes. + // This assumes that the module has a "main" function without dimension args, + // but possibly with dynamic shapes. We read the static shapes of the inputs, + // then set them as the types of the function parameters, and run StableHLO + // shape refinement to specialize all dynamic shapes in the StableHLO program + // to static shapes. + // Starting with version 9, the "main" function may accept token arguments. + // + // If the module uses multi-platform lowering, and you called SetPlatformIndex + // then the refinement will also remove the dead platform code. + // + // This method accepts a list of `llvm::ArrayRef` instead of `mlir::Type`. + // This is to prevent callers from accidentally passing `mlir::Type` owned by + // a context that's different from the one passed to `Create`, which could + // cause lifetime issues. + // The input_shapes includes only the non-token and the non-platform-index + // arguments. + absl::Status RefineDynamicShapes(llvm::ArrayRef input_shapes); + + // Returns true iff the output types are refined by RefineDynamicShapes. + bool IsOutputTypeRefined() { return output_types_refined_; }; + + // Validates that the module only contains ops from valid dialects and that + // any `shape_assertion` custom calls have side effects as expected. + absl::Status ValidateXlaCallModuleInvariants(); + + // Validates that the module represents a statically-shaped StableHLO program, + // otherwise all sorts of weirdness might happen in the HLO exporter which is + // much easier to detect here. + absl::Status ValidateStaticShapes(); + + // Runs some passes on the StableHLO module to prepare it for lowering to + // HLO and TF call lowering. + absl::Status PrepareStablehloForLowering(); + + // Lowers the StableHLO module to XlaComputation and returns it. + absl::StatusOr ToXlaComputation(); + + // Returns the deserialized stablehlo module. + mlir::ModuleOp module() & { return *module_; } + mlir::OwningOpRef module() && { return std::move(module_); } + + private: + XlaCallModuleLoader() = default; + + // Initializes the loader with the given serialized module string. + absl::Status LoadModule(mlir::MLIRContext* context, int version, + mlir::StringRef module_str, + std::vector disabled_checks, + std::vector platforms, + int num_invocation_args, + bool main_has_token_input_output, + bool use_shardy_partitioner); + + // Adds a wrapper for the "main" function to compute the platform index and + // the dimension arguments. + absl::Status AddMainWrapper(); + + mlir::MLIRContext* context_; + int version_; + mlir::OwningOpRef module_; + std::vector platforms_; + bool platform_index_arg_set_ = false; + // The disabled checks at loading time, including those from the + // disabled_checks attribute and the TF_XLA_FLAGS environment variable. + std::vector loading_disabled_checks_; + mlir::func::FuncOp main_; + // Keeps track of whether the output types are refined by RefineDynamicShapes. + bool output_types_refined_ = false; + // Whether the module is using the shardy partitioner. When Shardy partitioner + // is used, we need to inline meshes represented as module attributes to each + // individual sharding representation to preserve mesh information. See + // https://openxla.org/shardy/overview for more details. + bool use_shardy_partitioner_ = false; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_KERNELS_XLA_CALL_MODULE_LOADER_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..d1f3eeaaee4908c582a2ec08f831c7d6ab98a376 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_call_module_op.cc @@ -0,0 +1,611 @@ +/* Copyright 2022 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 +#include +#include +#include +#include + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/strings/string_view.h" +#include "llvm/ADT/ArrayRef.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/STLExtras.h" +#include "llvm/ADT/SmallVector.h" +#include "llvm/Support/Casting.h" +#include "llvm/Support/LogicalResult.h" +#include "mlir/Dialect/Func/Extensions/AllExtensions.h" // from @llvm-project +#include "mlir/Dialect/Func/IR/FuncOps.h" // from @llvm-project +#include "mlir/IR/Attributes.h" // from @llvm-project +#include "mlir/IR/Builders.h" // from @llvm-project +#include "mlir/IR/BuiltinAttributes.h" // from @llvm-project +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/BuiltinTypes.h" // from @llvm-project +#include "mlir/IR/DialectRegistry.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "mlir/IR/SymbolTable.h" // from @llvm-project +#include "mlir/IR/TypeRange.h" // from @llvm-project +#include "mlir/IR/TypeUtilities.h" // from @llvm-project +#include "mlir/IR/ValueRange.h" // from @llvm-project +#include "mlir/IR/Visitors.h" // from @llvm-project +#include "mlir/Pass/Pass.h" // from @llvm-project // IWYU pragma: keep +#include "mlir/Pass/PassManager.h" // from @llvm-project +#include "mlir/Support/DebugStringHelper.h" // from @llvm-project +#include "mlir/Support/LLVM.h" // from @llvm-project +#include "stablehlo/dialect/StablehloOps.h" // from @stablehlo +#include "tensorflow/compiler/mlir/tensorflow/utils/convert_type.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/dump_mlir_util.h" +#include "tensorflow/compiler/tf2xla/kernels/xla_call_module_loader.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/debug_options_flags.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/hlo/ir/hlo_instruction.h" +#include "xla/hlo/translate/mhlo_to_hlo/type_to_shape.h" +#include "xla/hlo/translate/stablehlo.h" +#include "xla/service/hlo_module_config.h" +#include "xla/service/spmd/shardy/stablehlo_round_trip/stablehlo_import.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/framework/mlir/status_scoped_diagnostic_handler.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/tpu/tpu_defs.h" + +namespace tensorflow { +namespace { + +absl::Status ImportShardingsAndInlineMeshes(mlir::ModuleOp module) { + mlir::PassManager sdy_roundtrip(module->getContext()); + sdy_roundtrip.addPass(xla::sdy::createImportShardingsPass( + /*allowPropagationToArgs=*/{}, /*allowPropagationToResults=*/{}, + /*inlineMesh=*/true)); + + tsl::StatusScopedDiagnosticHandler diagnosticHandler(module->getContext()); + absl::Status status = + diagnosticHandler.consumeStatus(sdy_roundtrip.run(module)); + if (status.ok() && VLOG_IS_ON(5)) { + DumpMlirOpToFile("xla_call_module.imported_tf_func_after_shardy_import", + module); + } + return status; +} + +// Imports the given `XlaComputation` into StableHLO functions the MLIR module. +// Returns the MLIR function in the imported module that represents the entry +// function of the imported computation. +absl::StatusOr ImportXlaComputation( + mlir::SymbolTableCollection& symbol_table_collection, mlir::ModuleOp module, + const xla::XlaComputation& computation, bool use_shardy_partitioner) { + mlir::MLIRContext *context = module.getContext(); + mlir::SymbolTable &symbol_table = + symbol_table_collection.getSymbolTable(module); + + TF_ASSIGN_OR_RETURN( + mlir::OwningOpRef imported, + xla::ConvertHloToStablehlo(*context, &computation.proto())); + if (VLOG_IS_ON(5)) { + DumpMlirOpToFile("xla_call_module.imported_tf_func", *imported); + } + + if (use_shardy_partitioner) { + // Shardings for the tf function calls are not added in + // XlaCompiler::CompileGraph. Therefore we need to add shardy shardings + // separately here. + TF_RETURN_IF_ERROR(ImportShardingsAndInlineMeshes(imported.get())); + } + + // Rename all functions beforehand in order to avoid conflicts. + mlir::StringAttr main_func_name; + for (auto func : imported->getOps()) { + mlir::StringAttr name = func.getSymNameAttr(); + mlir::StringAttr new_name = name; + for (int i = 0; symbol_table.lookup(new_name) != nullptr; ++i) { + new_name = mlir::StringAttr::get( + context, absl::StrCat(absl::string_view(name.getValue()), i)); + } + if (new_name != name) { + if (failed(mlir::SymbolTable::replaceAllSymbolUses(func, new_name, + *imported))) { + return absl::InternalError( + absl::StrCat("Failed to replace all symbol uses of function '", + absl::string_view(func.getName()), "'")); + } + func.setSymNameAttr(new_name); + } + if (name.getValue() == "main") { + main_func_name = new_name; + } + } + if (!main_func_name) { + return absl::InternalError( + "HLO module lowered from TF function is missing a main function"); + } + + mlir::func::FuncOp main_func; + for (auto func : imported->getOps()) { + auto cloned = func.clone(); + cloned.setPrivate(); + symbol_table.insert(cloned); + if (func.getSymNameAttr() == main_func_name) { + main_func = cloned; + } + } + + return main_func; +} + +class XlaCallModuleOp : public XlaOpKernel { + public: + explicit XlaCallModuleOp(OpKernelConstruction *ctx) : XlaOpKernel(ctx) { + int version; + OP_REQUIRES_OK(ctx, ctx->GetAttr("version", &version)); + std::string module_str; + OP_REQUIRES_OK(ctx, ctx->GetAttr("module", &module_str)); + std::vector expected_output_shapes; + OP_REQUIRES_OK(ctx, ctx->GetAttr("Sout", &expected_output_shapes)); + std::vector expected_output_dtypes; + OP_REQUIRES_OK(ctx, ctx->GetAttr("Tout", &expected_output_dtypes)); + std::vector dim_args_spec; + OP_REQUIRES_OK(ctx, ctx->GetAttr("dim_args_spec", &dim_args_spec)); + OP_REQUIRES(ctx, dim_args_spec.empty(), + absl::UnimplementedError( + "dim_args_spec attribute is no longer supported")); + OP_REQUIRES(ctx, + expected_output_shapes.size() == expected_output_dtypes.size(), + absl::InvalidArgumentError(absl::StrCat( + "The size of Sout (", expected_output_shapes.size(), + ") must match the size of Tout (", + expected_output_dtypes.size(), ")"))); + std::vector disabled_checks; + OP_REQUIRES_OK(ctx, ctx->GetAttr("disabled_checks", &disabled_checks)); + std::vector platforms; + OP_REQUIRES_OK(ctx, ctx->GetAttr("platforms", &platforms)); + // TODO(necula): change this to OP_REQUIRES_OK when 6 months have passed + // since we added the function_list and has_token_input_output + // attributes (May 25, 2023). + bool main_has_token_input_output = false; + if (!ctx->GetAttr("has_token_input_output", &main_has_token_input_output) + .ok()) { + // Whether the StableHLO module's main function has token input/output as + // the first argument and the first result. + // This is used only prior to version 9; afterwards, we just look for + // tokens among the types of the arguments and results, and we support + // multiple tokens, not necessarily at the start. + main_has_token_input_output = false; + } + if (!ctx->GetAttr("function_list", &function_list_).ok()) { + function_list_.clear(); + } + + bool use_shardy_partitioner = false; + if (!ctx->GetAttr("use_shardy_partitioner", &use_shardy_partitioner).ok()) { + use_shardy_partitioner = false; + } + if (VLOG_IS_ON(3)) { + VLOG(3) << "Initializing XlaCallModuleOp (version = " << version + << ", platforms = [" << absl::StrJoin(platforms, ", ") + << "], has_token_input_output = " << main_has_token_input_output + << ", use_shardy_partitioner = " << use_shardy_partitioner + << ", disabled_checks = [" << absl::StrJoin(disabled_checks, ", ") + << "], " + << "function_list = [" + << absl::StrJoin(function_list_, ",", + [](std::string *out, NameAttrList x) { + absl::StrAppend(out, x.name()); + }) + << "])"; + } + std::string compilation_device_type = ctx->device_type().type_string(); + compilation_platform_ = ""; + if (compilation_device_type == DEVICE_CPU_XLA_JIT) { + compilation_platform_ = "CPU"; + } else if (compilation_device_type == DEVICE_GPU_XLA_JIT) { +#if GOOGLE_CUDA + compilation_platform_ = "CUDA"; +#elif TENSORFLOW_USE_ROCM + compilation_platform_ = "ROCM"; +#else + OP_REQUIRES(ctx, false, + absl::UnimplementedError("CUDA or ROCM build required")); +#endif + } else if (compilation_device_type == DEVICE_TPU_XLA_JIT) { + compilation_platform_ = "TPU"; + } else { + OP_REQUIRES(ctx, false, + absl::UnimplementedError(absl::StrCat( + "Unexpected device type ", compilation_device_type))); + } + VLOG(3) << "Initializing XlaCallModuleOp on " << compilation_platform_; + { + auto loader = XlaCallModuleLoader::Create( + &context_, version, module_str, std::move(disabled_checks), + std::move(platforms), + /*num_invocation_args=*/ctx->num_inputs(), + main_has_token_input_output, use_shardy_partitioner); + OP_REQUIRES_OK(ctx, loader.status()); + loader_ = *std::move(loader); + } + OP_REQUIRES_OK(ctx, loader_->ValidateXlaCallModuleInvariants()); + + if (!ctx->GetAttr(kXlaTokenInputNodesAttrName, &op_token_input_nodes_) + .ok()) { + op_token_input_nodes_.clear(); + } + if (!ctx->GetAttr(kXlaOriginalOutsideCompilationNodeName, + &original_node_name_) + .ok()) { + original_node_name_ = name(); + } + + mlir::DialectRegistry registry; + mlir::func::registerAllExtensions(registry); + context_.appendDialectRegistry(registry); + } + + void Compile(XlaOpKernelContext *ctx) override { + XlaCompiler *const compiler = ctx->compiler(); + xla::XlaBuilder *const b = ctx->builder(); + + std::vector input_shapes; + for (int i = 0; i < ctx->num_inputs(); ++i) { + auto shape = ctx->InputXlaShape(i); + OP_REQUIRES_OK(ctx, shape.status()); + input_shapes.push_back(*std::move(shape)); + } + OP_REQUIRES_OK(ctx, loader_->SetPlatformIndex(compilation_platform_)); + OP_REQUIRES_OK(ctx, loader_->RefineDynamicShapes(input_shapes)); + OP_REQUIRES_OK(ctx, loader_->ValidateStaticShapes()); + // Lowering tf function calls before SdyRoundTripExport which is a part of + // PrepareStablehloForLowering, as we run ImportShardy pass while lowering + // tf function calls. + if (!function_list_.empty()) { + OP_REQUIRES_OK(ctx, LowerTfFunctionCalls(ctx)); + } + OP_REQUIRES_OK(ctx, loader_->PrepareStablehloForLowering()); + + xla::XlaOp token_input; + if (!op_token_input_nodes_.empty()) { + std::vector token_inputs; + for (const std::string& node_name : op_token_input_nodes_) { + auto token = compiler->GetNodeToken(node_name); + OP_REQUIRES_OK(ctx, token.status()); + token_inputs.push_back(token.value()); + } + token_input = xla::AfterAll(b, token_inputs); + } + + // Set input and output types after removing platform args, but before + // lowering the XLA computation since that will mutate the module in place + // to use MHLO types. + auto input_types = loader_->InputTypes(); + auto output_types = loader_->OutputTypes(); + + std::vector inputs; + int next_actual_input = 0; + for (mlir::Type inputType : input_types) { + if (IsTokenType(inputType)) { + if (token_input.IsUninitialized()) { + // Generate a dummy token if the XlaCallModule doesn't take one. + token_input = xla::CreateToken(b); + } + inputs.push_back(token_input); + } else { + inputs.push_back(ctx->Input(next_actual_input++)); + } + } + auto xla_computation = loader_->ToXlaComputation(); + OP_REQUIRES_OK(ctx, xla_computation.status()); + + if (VLOG_IS_ON(3)) { + OP_REQUIRES_VALUE( + const xla::HloModuleConfig module_config, ctx, + xla::HloModule::CreateModuleConfigFromProto( + xla_computation->proto(), xla::GetDebugOptionsFromFlags())); + OP_REQUIRES_VALUE(std::unique_ptr hlo_module, ctx, + xla::HloModule::CreateFromProto( + xla_computation->proto(), module_config)); + xla::HloPrintOptions options; + options = xla::HloPrintOptions::ShortParsable(); + XLA_VLOG_LINES(3, absl::StrCat("XlaCallModule converted to HLO module ", + hlo_module->ToString(options))); + } + + xla::XlaOp computation_output = xla::Call(b, *xla_computation, inputs); + + // Check that the resulting computation returns the expected shape + OP_REQUIRES_VALUE(xla::Shape found_output_shape, ctx, + b->GetShape(computation_output)); + VLOG(3) << "XlaCallModule compiled output shape : " + << xla::ShapeUtil::HumanString(found_output_shape); + std::vector computation_outputs; + if (loader_->NrOutputs() == 1) { + computation_outputs.push_back(computation_output); + } else { + for (int i = 0; i < loader_->NrOutputs(); ++i) { + computation_outputs.push_back( + xla::GetTupleElement(computation_output, i)); + } + } + + // Collect the token outputs and set the non-token outputs + std::vector token_outputs; + int next_actual_output = 0; + for (auto it : llvm::enumerate(output_types)) { + int i = it.index(); + mlir::Type output_type = it.value(); + auto shape = b->GetShape(computation_outputs[i]); + OP_REQUIRES_OK(ctx, shape.status()); + if (IsTokenType(output_type)) { + OP_REQUIRES(ctx, shape->IsToken(), + absl::FailedPreconditionError(absl::StrCat( + "Token output at index ", i, " (", + mlir::debugString(output_type), ") is not token type: ", + xla::ShapeUtil::HumanString(*shape)))); + token_outputs.push_back(computation_outputs[i]); + } else { + OP_REQUIRES(ctx, !shape->IsToken(), + absl::FailedPreconditionError(absl::StrCat( + "Non-token output at index ", i, " (", + mlir::debugString(output_type), ") is not token type: ", + xla::ShapeUtil::HumanString(*shape)))); + ctx->SetOutput(next_actual_output++, computation_outputs[i]); + } + } + + if (!op_token_input_nodes_.empty()) { + xla::XlaOp token_output = token_input; + if (!token_outputs.empty()) { + token_output = xla::AfterAll(b, token_outputs); + } else { + if (token_output.IsUninitialized()) { + token_output = xla::CreateToken(b); + } + } + OP_REQUIRES_OK(ctx, + compiler->SetNodeToken(original_node_name_, token_output)); + } + } + + private: + // Lowers `stablehlo.CustomCall` ops representing TF function calls into + // nested XLA computation. The called TF functions are lowered into StableHLO + // and inserted as function calls in the main module. + // + // This is implemented here instead of in xla_call_module_loader.cc in order + // to prevent cyclic dependency with TF MLIR passes. + absl::Status LowerTfFunctionCalls(XlaOpKernelContext *ctx) { + mlir::ModuleOp module = loader_->module(); + mlir::SymbolTableCollection symbol_table_collection; + + llvm::SmallDenseSet updated_funcs; + + auto lower = + [&](mlir::stablehlo::CustomCallOp custom_call) -> absl::Status { + if (custom_call.getCallTargetName() != "tf.call_tf_function") { + return absl::OkStatus(); + } + + NameAttrList f; + bool custom_call_has_token_input_output = false; + { + auto backend_config = custom_call->getAttrOfType( + "tf.backend_config"); + if (!backend_config) { + return absl::InternalError( + "TF function custom call must have 'tf.backend_config' " + "attribute"); + } + + auto called_index = + backend_config.getAs("called_index"); + if (!called_index) { + return absl::InternalError( + "TF function custom call must have 'called_index' in the " + "'tf.backend_config' attribute"); + } + + int index = called_index.getInt(); + if (index < 0 || index >= function_list_.size()) { + return absl::OutOfRangeError(absl::StrCat( + "XlaCallModule has function_list of size ", function_list_.size(), + " but TF function custom call references function #", index)); + } + f = function_list_[index]; + + // Whether the custom call takes a token argument and returns another + // token. Used to model side effects. + if (auto attr = + backend_config.getAs("has_token_input_output"); + attr != nullptr) { + custom_call_has_token_input_output = attr.getValue(); + } + } + + // Lower the called TF function into an HLO module. + std::vector arguments; + { + mlir::TypeRange input_types(custom_call->getOperandTypes()); + if (custom_call_has_token_input_output) { + if (input_types.empty() || !IsTokenType(input_types.front())) { + return absl::InvalidArgumentError(absl::StrCat( + "stablehlo.custom_call with has_token_input_output = true is " + "expected to take !stablehlo.token as the first argument, but " + "got ", + mlir::debugString(custom_call))); + } + input_types = input_types.drop_front(); + } + for (mlir::Type input_type : input_types) { + XlaCompiler::Argument &argument = arguments.emplace_back(); + argument.kind = XlaCompiler::Argument::kParameter; + TF_RETURN_IF_ERROR(ConvertToDataType(input_type, &argument.type)); + argument.shape = xla::TypeToShape(input_type); + } + + mlir::TypeRange result_types(custom_call->getResultTypes()); + if (custom_call_has_token_input_output) { + if (result_types.empty() || !IsTokenType(result_types.front())) { + return absl::InvalidArgumentError(absl::StrCat( + "stablehlo.custom_call with has_token_input_output = true is " + "expected to return !stablehlo.token as the first result, but " + "got ", + mlir::debugString(custom_call))); + } + } + } + + // There are times when TPU prefers tuple arguments, i.e. when there are + // 2k+ input arguments, but for the most part we want to avoid tuples. + XlaCompiler::CompileOptions options; + options.use_tuple_arg = false; + options.always_return_tuple = false; + options.is_entry_computation = false; + // Propagate tokens from XlaCallModule to inner computation. + options.add_token_input_output = !op_token_input_nodes_.empty(); + + XlaCompiler::CompilationResult result; + TF_RETURN_IF_ERROR( + ctx->compiler()->CompileFunction(options, f, arguments, &result)); + + // Import the lowered HLO module into StableHLO functions in `module`. + // The main function accepts variadic arguments and returns variadic + // results. + TF_ASSIGN_OR_RETURN( + mlir::func::FuncOp main_func, + ImportXlaComputation( + symbol_table_collection, module, *result.computation, + ctx->compiler()->options().use_shardy_partitioner)); + + // Replace the custom call with ops that call the imported main function. + mlir::OpBuilder builder(custom_call); + auto loc = custom_call.getLoc(); + + // If `has_tuple_input_output` is true, the first argument is a token type + llvm::SmallVector input_args; + { + llvm::SmallVector args(custom_call->getOperands()); + if (custom_call_has_token_input_output) { + // Adjust the indexes since custom calls with `has_token_input_output` + // takes a token as the first argument, but TF2XLA'ed computation + // expects the token to be the last argument. + std::rotate(args.begin(), args.begin() + 1, args.end()); + } else if (options.add_token_input_output) { + // Add a dummy token if the inner computation takes a token but the + // custom call doesn't have a token argument. + args.push_back(mlir::stablehlo::CreateTokenOp::create(builder, loc)); + } + + input_args.reserve(result.input_mapping.size()); + for (int index : result.input_mapping) { + input_args.push_back(args[index]); + } + } + + // Call the lowered function. + auto call = + mlir::func::CallOp::create(builder, loc, main_func, input_args); + + // Unpack the result tuple (`options.always_return_tuple` is true). If + // `has_tuple_input_output` is true, the first result is a token type. + { + llvm::SmallVector results(custom_call->getResults()); + if (custom_call_has_token_input_output) { + // Adjust the indexes since custom calls with `has_token_input_output` + // returns a token as the first result, but TF2XLA'ed computation + // returns the token as the last result. + std::rotate(results.begin(), results.begin() + 1, results.end()); + + if (!options.add_token_input_output) { + // If the custom call returns a token but the inner computation + // doesn't, replace the token result with a dummy token. + mlir::Value token = results.back(); + if (!token.use_empty()) { + token.replaceAllUsesWith( + mlir::stablehlo::CreateTokenOp::create(builder, loc)); + } + results.pop_back(); + } + } + + for (const auto &it : llvm::enumerate(results)) { + if (!it.value().use_empty()) { + it.value().replaceAllUsesWith(call.getResult(it.index())); + } + } + } + + updated_funcs.insert(call->getParentOfType()); + custom_call->erase(); + + return absl::OkStatus(); + }; + + absl::Status status; + mlir::WalkResult result = + module->walk([&](mlir::stablehlo::CustomCallOp op) { + status.Update(lower(op)); + if (!status.ok()) { + return mlir::WalkResult::interrupt(); + } + return mlir::WalkResult::advance(); + }); + if (result.wasInterrupted()) { + return status; + } + + // If the call results are used by `func.return`, then we may need to update + // function result types. + for (auto func : updated_funcs) { + auto ret = llvm::cast( + func.getFunctionBody().front().getTerminator()); + func.setFunctionType(mlir::FunctionType::get( + &context_, func.getArgumentTypes(), ret.getOperandTypes())); + } + + if (VLOG_IS_ON(5)) { + DumpMlirOpToFile("xla_call_module.after_tf_func_call_import", module); + } + return absl::OkStatus(); + } + + mlir::MLIRContext context_{mlir::MLIRContext::Threading::DISABLED}; + std::unique_ptr loader_; + std::vector function_list_; + std::string compilation_platform_; + + // Whether the XlaCallModule op has token input/output. + std::vector op_token_input_nodes_; + std::string original_node_name_; +}; + +REGISTER_XLA_OP(Name("XlaCallModule"), XlaCallModuleOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_conv_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_conv_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..331d9f3084fd22b3da19dfcf9d302c6d8ace2d18 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_conv_op.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/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/xla_data.pb.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaConv") + .CompileTimeConstantInput("window_strides") + .CompileTimeConstantInput("lhs_dilation") + .CompileTimeConstantInput("rhs_dilation") + .CompileTimeConstantInput("feature_group_count") + .CompileTimeConstantInput("padding"), + MlirXlaOpKernel); + +REGISTER_XLA_OP(Name("XlaConvV2") + .CompileTimeConstantInput("window_strides") + .CompileTimeConstantInput("lhs_dilation") + .CompileTimeConstantInput("rhs_dilation") + .CompileTimeConstantInput("feature_group_count") + .CompileTimeConstantInput("padding"), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_custom_call_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_custom_call_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..5fbdb81019585b2c03580669158836d56901a0cd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_custom_call_op.cc @@ -0,0 +1,65 @@ +/* Copyright 2022 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 +#include + +#include "absl/log/check.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" + +namespace tensorflow { +namespace { + +class XlaCustomCallOp : public XlaOpKernel { + public: + explicit XlaCustomCallOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("target_name", &target_name_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("backend_config", &backend_config_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("dtype", &output_type_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("shape", &output_shape_)); + } + + void Compile(XlaOpKernelContext* ctx) override { + std::vector inputs(ctx->num_inputs()); + for (int i = 0, end = ctx->num_inputs(); i < end; ++i) { + inputs[i] = ctx->Input(i); + } + + xla::Shape output_shape; + CHECK_OK(TensorShapeToXLAShape(output_type_, output_shape_, &output_shape)); + xla::XlaOp output = xla::CustomCall(ctx->builder(), target_name_, inputs, + output_shape, backend_config_); + ctx->SetOutput(0, output); + } + + private: + std::string target_name_; + std::string backend_config_; + DataType output_type_; + TensorShape output_shape_; +}; + +REGISTER_XLA_OP(Name("XlaCustomCall"), XlaCustomCallOp); +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_custom_call_v2_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_custom_call_v2_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..ea957d57a76fd3e78861d42922c9baf19ef0eeb4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_custom_call_v2_op.cc @@ -0,0 +1,114 @@ +/* Copyright 2022 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 +#include + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/layout_util.h" +#include "xla/service/hlo.pb.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace { + +class XlaCustomCallV2Op : public XlaOpKernel { + public: + explicit XlaCustomCallV2Op(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("call_target_name", &call_target_name_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("has_side_effect", &has_side_effect_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("backend_config", &backend_config_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("result_dtypes", &result_dtypes_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("result_shapes", &result_shapes_)); + OP_REQUIRES(ctx, result_shapes_.size() == result_dtypes_.size(), + errors::InvalidArgument("Unexpected number of result shapes: ", + result_shapes_.size(), + " != ", result_dtypes_.size())); + } + + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES_OK(ctx, CompileImpl(*ctx)); + } + + private: + absl::Status CompileImpl(XlaOpKernelContext& ctx) const { + std::vector operands(ctx.num_inputs()); + std::vector operand_shapes(ctx.num_inputs()); + for (int i = 0; i < ctx.num_inputs(); ++i) { + operands[i] = ctx.Input(i); + TF_ASSIGN_OR_RETURN(operand_shapes[i], ctx.InputXlaShape(i)); + xla::LayoutUtil::SetToDefaultLayout(&operand_shapes[i]); + } + + std::vector result_shapes(ctx.num_outputs()); + for (int i = 0; i < ctx.num_outputs(); ++i) { + const DataType dt = result_dtypes_[i]; + const TensorShape& shape = result_shapes_[i]; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &result_shapes[i])); + } + + TF_ASSIGN_OR_RETURN( + auto result_shape, + xla::ShapeUtil::MakeValidatedMaybeTupleShape(result_shapes)); + xla::XlaOp results = xla::CustomCallWithLayout( // + ctx.builder(), // + call_target_name_, // + operands, // + result_shape, // + operand_shapes, // + backend_config_, // + has_side_effect_, // + /*output_operand_aliasing=*/{}, // + /*literal=*/nullptr, // + /*schedule=*/xla::CustomCallSchedule::SCHEDULE_NONE, // + xla::CustomCallApiVersion::API_VERSION_STATUS_RETURNING_UNIFIED // + ); + + if (ctx.num_outputs() == 1) { + ctx.SetOutput(0, results); + } else { + for (int i = 0; i < ctx.num_outputs(); ++i) { + ctx.SetOutput(i, xla::GetTupleElement(results, i)); + } + } + + return absl::OkStatus(); + } + + std::string call_target_name_; + std::string backend_config_; + bool has_side_effect_; + std::vector result_dtypes_; + std::vector result_shapes_; +}; + +REGISTER_XLA_OP(Name("XlaCustomCallV2"), XlaCustomCallV2Op); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_dequantize_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_dequantize_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..748538cff2818bece078d0dfb2c557ad5f3bd68e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_dequantize_op.cc @@ -0,0 +1,64 @@ +/* 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 +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/quantize.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class XlaDequantizeOp : public XlaOpKernel { + public: + explicit XlaDequantizeOp(OpKernelConstruction* context) + : XlaOpKernel(context) { + OP_REQUIRES_OK(context, context->GetAttr("min_range", &min_range_)); + OP_REQUIRES_OK(context, context->GetAttr("max_range", &max_range_)); + OP_REQUIRES_OK(context, context->GetAttr("mode", &mode_)); + OP_REQUIRES_OK(context, + context->GetAttr("transpose_output", &transpose_output_)); + } + + void Compile(XlaOpKernelContext* context) override { + const xla::XlaOp& input = context->Input(0); + + xla::QuantizedRange range(min_range_, max_range_); + + xla::XlaOp output = + xla::Dequantize(input, range, mode_, transpose_output_); + context->SetOutput(0, output); + } + + private: + float min_range_; + float max_range_; + bool transpose_output_; + std::string mode_; + XlaDequantizeOp(const XlaDequantizeOp&) = delete; + void operator=(const XlaDequantizeOp&) = delete; +}; + +REGISTER_XLA_OP(Name("XlaDequantize"), XlaDequantizeOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_dot_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_dot_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..bf20083d99cb5b204cbf648acba4b52618b31538 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_dot_op.cc @@ -0,0 +1,97 @@ +/* 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 +#include + +#include "tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class XlaDotOp : public XlaOpKernel { + public: + explicit XlaDotOp(OpKernelConstruction* context) : XlaOpKernel(context) { + std::string dnums_attr; + OP_REQUIRES_OK(context, context->GetAttr("dimension_numbers", &dnums_attr)); + OP_REQUIRES( + context, dnums_.ParsePartialFromString(dnums_attr), + errors::InvalidArgument("Error parsing convolution dimension numbers")); + std::string precision_config_attr; + OP_REQUIRES_OK( + context, context->GetAttr("precision_config", &precision_config_attr)); + OP_REQUIRES( + context, + precision_config_.ParsePartialFromString(precision_config_attr), + errors::InvalidArgument("Error parsing convolution dimension numbers")); + preferred_element_type_ = std::nullopt; + } + + void Compile(XlaOpKernelContext* context) override { + const TensorShape lhs_shape = context->InputShape(0); + const TensorShape rhs_shape = context->InputShape(1); + + // We do only minimal checking, relying on XLA to check the shape + // invariants. + xla::XlaOp output = + xla::DotGeneral(context->Input(0), context->Input(1), dnums_, + &precision_config_, preferred_element_type_); + context->SetOutput(0, output); + } + + protected: + std::optional preferred_element_type_; + + private: + xla::DotDimensionNumbers dnums_; + xla::PrecisionConfig precision_config_; + XlaDotOp(const XlaDotOp&) = delete; + void operator=(const XlaDotOp&) = delete; +}; + +REGISTER_XLA_OP(Name("XlaDot"), MlirXlaOpKernel); + +class XlaDotV2Op : public XlaDotOp { + public: + explicit XlaDotV2Op(OpKernelConstruction* context) : XlaDotOp(context) { + DataType preferred_element_dtype; + OP_REQUIRES_OK(context, context->GetAttr("preferred_element_type", + &preferred_element_dtype)); + xla::PrimitiveType preferred_element_type; + OP_REQUIRES_OK(context, DataTypeToPrimitiveType(preferred_element_dtype, + &preferred_element_type)); + preferred_element_type_ = preferred_element_type; + } + + private: + XlaDotV2Op(const XlaDotV2Op&) = delete; + void operator=(const XlaDotV2Op&) = delete; +}; + +REGISTER_XLA_OP(Name("XlaDotV2"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_optimization_barrier_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_optimization_barrier_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..698b609178ad5be59d9db994e807ce6e846b8522 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_optimization_barrier_op.cc @@ -0,0 +1,25 @@ +/* Copyright 2022 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/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaOptimizationBarrier"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_pad_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_pad_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..35d6a1bead1181985dfa9685ef62d7e3ae61a083 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_pad_op.cc @@ -0,0 +1,103 @@ +/* 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 +#include + +#include "absl/algorithm/container.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { +namespace { + +class XlaPadOp : public XlaOpKernel { + public: + explicit XlaPadOp(OpKernelConstruction* context) : XlaOpKernel(context) {} + + void Compile(XlaOpKernelContext* context) override { + const TensorShape input_shape = context->InputShape("input"); + const TensorShape padding_value_shape = + context->InputShape("padding_value"); + + std::vector padding_low; + std::vector padding_high; + std::vector padding_interior; + OP_REQUIRES_OK(context, context->ConstantInputAsIntVector("padding_low", + &padding_low)); + OP_REQUIRES_OK(context, context->ConstantInputAsIntVector("padding_high", + &padding_high)); + OP_REQUIRES_OK(context, context->ConstantInputAsIntVector( + "padding_interior", &padding_interior)); + + OP_REQUIRES(context, TensorShapeUtils::IsScalar(padding_value_shape), + errors::InvalidArgument("padding_value must be a scalar")); + const int rank = input_shape.dims(); + OP_REQUIRES(context, rank == padding_low.size(), + errors::InvalidArgument( + "The size of padding_low must be equal to the input " + "rank (", + padding_low.size(), " vs. ", rank, ")")); + OP_REQUIRES(context, rank == padding_high.size(), + errors::InvalidArgument( + "The size of padding_high must be equal to the input " + "rank (", + padding_high.size(), " vs. ", rank, ")")); + OP_REQUIRES(context, rank == padding_interior.size(), + errors::InvalidArgument( + "The size of padding_interior must be equal to the input " + "rank (", + padding_interior.size(), " vs. ", rank, ")")); + + auto non_negative = [](int64_t x) { return x >= 0; }; + OP_REQUIRES( + context, absl::c_all_of(padding_interior, non_negative), + errors::InvalidArgument("padding_interior must be non-negative, got [", + absl::StrJoin(padding_interior, ","), "]")); + + xla::PaddingConfig padding_config; + for (int i = 0; i < rank; ++i) { + auto* dim = padding_config.add_dimensions(); + dim->set_edge_padding_low(padding_low[i]); + dim->set_edge_padding_high(padding_high[i]); + dim->set_interior_padding(padding_interior[i]); + } + + xla::XlaOp output = + xla::Pad(context->Input("input"), context->Input("padding_value"), + padding_config); + context->SetOutput(0, output); + } + + private: + XlaPadOp(const XlaPadOp&) = delete; + void operator=(const XlaPadOp&) = delete; +}; + +REGISTER_XLA_OP(Name("XlaPad") + .CompileTimeConstantInput("padding_low") + .CompileTimeConstantInput("padding_high") + .CompileTimeConstantInput("padding_interior"), + XlaPadOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_reduce_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_reduce_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..446bcd275a3c7a0c7e8bac815ad74a7ff58ab23d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_reduce_op.cc @@ -0,0 +1,27 @@ +/* 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/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaReduce"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("XlaVariadicReduce"), MlirXlaOpKernel); +REGISTER_XLA_OP(Name("XlaVariadicReduceV2"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_reduce_precision_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_reduce_precision_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..99acc6269cf44cf62566b73d045ccb2c0f17a278 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_reduce_precision_op.cc @@ -0,0 +1,25 @@ +/* Copyright 2022 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/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaReducePrecision"), MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_select_and_scatter_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_select_and_scatter_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..21bfc990bce6ece7d89682d9a5aae22b7008109c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_select_and_scatter_op.cc @@ -0,0 +1,29 @@ +/* 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/tf2xla/mlir_xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" + +namespace tensorflow { +namespace { + +REGISTER_XLA_OP(Name("XlaSelectAndScatter") + .CompileTimeConstantInput("window_dimensions") + .CompileTimeConstantInput("window_strides") + .CompileTimeConstantInput("padding"), + MlirXlaOpKernel); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_self_adjoint_eig_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_self_adjoint_eig_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..bc7cd269e4a3dd6de7a4e028f94ca8ba2950834f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_self_adjoint_eig_op.cc @@ -0,0 +1,70 @@ +/* Copyright 2019 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 + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/self_adjoint_eig.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/bits.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class XlaSelfAdjointEigOp : public XlaOpKernel { + public: + explicit XlaSelfAdjointEigOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("lower", &lower_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("max_iter", &max_iter_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("epsilon", &epsilon_)); + } + void Compile(XlaOpKernelContext* ctx) override { + auto result = + xla::SelfAdjointEig(ctx->Input(0), lower_, max_iter_, epsilon_); + ctx->SetOutput(0, result.w); + ctx->SetOutput(1, result.v); + } + + private: + bool lower_; + int32_t max_iter_; + float epsilon_; +}; + +class SelfAdjointEigV2Op : public XlaOpKernel { + public: + explicit SelfAdjointEigV2Op(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + int n = input_shape.dim_size(input_shape.dims() - 1); + // This is based on heuristics that approx log(n) sweep updates are needed. + // Note: the heuristics provides no theoretical guarantee, max_iter=100 and + // epsilon should be used to determine exit condition. + int max_iter = 2 * tensorflow::Log2Ceiling(n); + auto result = xla::SelfAdjointEig(ctx->Input(0), true, max_iter, 1e-6); + ctx->SetOutput(0, result.w); + ctx->SetOutput(1, result.v); + } +}; + +REGISTER_XLA_OP(Name("XlaSelfAdjointEig"), XlaSelfAdjointEigOp); +REGISTER_XLA_OP(Name("SelfAdjointEigV2"), SelfAdjointEigV2Op); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_svd_op.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_svd_op.cc new file mode 100644 index 0000000000000000000000000000000000000000..51a7ea660577f1b483f0ee46eda0071aa971b77a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/kernels/xla_svd_op.cc @@ -0,0 +1,112 @@ +/* Copyright 2019 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 +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/slicing.h" +#include "xla/hlo/builder/lib/svd.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/lib/core/bits.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +class XlaSvdOp : public XlaOpKernel { + public: + explicit XlaSvdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("max_iter", &max_iter_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("epsilon", &epsilon_)); + std::string precision_config_attr; + OP_REQUIRES_OK(ctx, + ctx->GetAttr("precision_config", &precision_config_attr)); + OP_REQUIRES(ctx, + precision_config_.ParsePartialFromString(precision_config_attr), + errors::InvalidArgument("Error parsing precision config.")); + if (precision_config_.operand_precision_size() == 0) { + precision_config_.mutable_operand_precision()->Add( + xla::PrecisionConfig::HIGHEST); + } + } + void Compile(XlaOpKernelContext* ctx) override { + auto result = xla::SVD(ctx->Input(0), max_iter_, epsilon_, + precision_config_.operand_precision(0)); + ctx->SetOutput(0, result.d); + ctx->SetOutput(1, result.u); + ctx->SetOutput(2, result.v); + } + + private: + int32_t max_iter_; + float epsilon_; + xla::PrecisionConfig precision_config_; +}; + +class SvdOp : public XlaOpKernel { + public: + explicit SvdOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("compute_uv", &compute_uv_)); + OP_REQUIRES_OK(ctx, ctx->GetAttr("full_matrices", &full_matrices_)); + } + void Compile(XlaOpKernelContext* ctx) override { + const TensorShape input_shape = ctx->InputShape("input"); + int m = input_shape.dim_size(input_shape.dims() - 2); + int n = input_shape.dim_size(input_shape.dims() - 1); + // This is based on heuristics that approx log(n) sweep updates are needed. + // Note: the heuristics provides no theoretical guarantee, max_iter=100 and + // epsilon should be used to determine exit condition. + int max_iter = 2 * tensorflow::Log2Ceiling(std::max(m, n)); + auto result = xla::SVD(ctx->Input(0), max_iter, 1e-6); + ctx->SetOutput(0, result.d); + if (compute_uv_) { + int p = std::min(m, n); + if (!full_matrices_) { + if (p < m) { + result.u = xla::SliceInMinorDims(result.u, {0, 0}, {m, p}); + } + if (p < n) { + result.v = xla::SliceInMinorDims(result.v, {0, 0}, {n, p}); + } + } + ctx->SetOutput(1, result.u); + ctx->SetOutput(2, result.v); + } else { + auto shape = + xla::ShapeUtil::MakeShape(ctx->input_xla_type(0), /*dimensions=*/{0}); + ctx->SetOutput(1, xla::Zeros(ctx->builder(), shape)); + ctx->SetOutput(2, xla::Zeros(ctx->builder(), shape)); + } + } + + private: + bool compute_uv_; + bool full_matrices_; +}; + +REGISTER_XLA_OP(Name("XlaSvd").TypeConstraint("T", kFloatTypes), XlaSvdOp); +REGISTER_XLA_OP(Name("Svd").TypeConstraint("T", kFloatTypes), SvdOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/layout_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/layout_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..cf86b3b6b27e97b271e819efbe6f1f52b278a0a9 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/layout_util.cc @@ -0,0 +1,132 @@ +/* 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/layout_util.h" + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_argument.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { + +XlaShapeLayoutHelpers::ShapeDeterminationFns::ShapeDeterminationFns() { + layout_preference_fn = UseNoPreferenceLayoutFn(); + shape_representation_fn = IdentityShapeRepresentationFn(); +} + +XlaShapeLayoutHelpers::LayoutPreferenceFn UseNoPreferenceLayoutFn() { + return [](const TensorShape& shape, DataType dtype, + std::optional) -> XlaLayoutPreference { + return XlaLayoutPreference::kNoPreference; + }; +} + +// Rewrites the layout of xla_shape if there is tiled sharding. +absl::Status RewriteLayoutWithShardedShape( + const std::optional& sharding, bool use_fast_memory, + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns, + xla::Shape* xla_shape) { + if (sharding && !sharding->IsReplicatedOrSingleDevice() && + !sharding->IsManual()) { + // After sharding, per core shape might have different layout. For example, + // before sharding, a shape [128, 128] will be assigned default + // minor-to-major {1, 0}. But after we shard this shape to [128, 64] * 2, + // the sharded shapes will have minor-to-major {0, 1}. + // + // As a result, for sharded shapes, we set their layout to per core shape's + // layout. + // + // TODO(endlessroad): for variable input & update, we might have + // different layouts which will prevent input output aliasing and + // increase memory usage. Investigate such cases. + xla::Shape per_device_xla_shape = sharding->TileShape(*xla_shape); + TensorShape per_device_tensor_shape; + TF_RETURN_IF_ERROR( + XLAShapeToTensorShape(per_device_xla_shape, &per_device_tensor_shape)); + TF_ASSIGN_OR_RETURN(DataType dtype, EncodePrimitiveTypeAsDataType( + xla_shape->element_type())); + auto layout_preference = shape_determination_fns.layout_preference_fn( + per_device_tensor_shape, dtype, std::nullopt); + TF_ASSIGN_OR_RETURN(per_device_xla_shape, + shape_determination_fns.shape_representation_fn( + per_device_tensor_shape, dtype, use_fast_memory, + layout_preference)); + *xla_shape->mutable_layout() = per_device_xla_shape.layout(); + } + return absl::OkStatus(); +} + +// There is a shape_representation_fn or sharding for an output, this function +// uses a reshape to fix the layout. +absl::StatusOr ReshapeWithCorrectRepresentationAndSharding( + xla::XlaBuilder* builder, xla::XlaOp original, xla::Shape original_shape, + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns, + std::optional sharding, bool fast_mem) { + if (original_shape.IsTuple()) { + std::vector elements; + for (int i = 0; i < original_shape.tuple_shapes().size(); ++i) { + auto subsharding = sharding ? sharding->tuple_shardings(i) : sharding; + TF_ASSIGN_OR_RETURN(auto element, + ReshapeWithCorrectRepresentationAndSharding( + builder, xla::GetTupleElement(original, i), + original_shape.tuple_shapes(i), + shape_determination_fns, subsharding, fast_mem)); + elements.push_back(element); + } + return xla::Tuple(builder, elements); + } + if (!original_shape.IsArray()) return original; + TensorShape shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(original_shape, &shape)); + TF_ASSIGN_OR_RETURN(DataType dtype, EncodePrimitiveTypeAsDataType( + original_shape.element_type())); + auto layout_preference = + shape_determination_fns.layout_preference_fn(shape, dtype, std::nullopt); + TF_ASSIGN_OR_RETURN(auto to_shape, + shape_determination_fns.shape_representation_fn( + shape, dtype, fast_mem, layout_preference)); + if (sharding) { + TF_ASSIGN_OR_RETURN(auto hlo_sharding, + xla::HloSharding::FromProto(*sharding)); + + TF_RETURN_IF_ERROR(RewriteLayoutWithShardedShape( + hlo_sharding, fast_mem, shape_determination_fns, &to_shape)); + } + if (xla::ShapeUtil::Compatible(original_shape, to_shape)) { + for (int64_t i = 0; i < original_shape.dimensions().size(); ++i) { + to_shape.set_dynamic_dimension(i, original_shape.is_dynamic_dimension(i)); + } + } + return xla::Reshape(to_shape, original); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/layout_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/layout_util.h new file mode 100644 index 0000000000000000000000000000000000000000..fcb9f6656cdfbe1d398d605f95931d03936f3d51 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/layout_util.h @@ -0,0 +1,84 @@ +/* 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. +==============================================================================*/ + +// Utilities for working with XLA layout and shapes. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_LAYOUT_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LAYOUT_UTIL_H_ + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/xla_argument.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +class XlaShapeLayoutHelpers { + public: + // The following defines the layout preference of an xla tensor. + // The return value of LayoutPreferenceFn can be used in + // XlaHelper::ShapeRepresentationFn. + typedef std::function)> + LayoutPreferenceFn; + + // A bundle of LayoutPreferenceFn and ShapeRepresentationFn. + struct ShapeDeterminationFns { + // Use no preference function, and identity shape representation function, + // as default value. + ShapeDeterminationFns(); + + ShapeDeterminationFns( + LayoutPreferenceFn layout_preference_fn, + XlaHelpers::ShapeRepresentationFn shape_representation_fn) + : layout_preference_fn(layout_preference_fn), + shape_representation_fn(shape_representation_fn) {} + + LayoutPreferenceFn layout_preference_fn; + XlaHelpers::ShapeRepresentationFn shape_representation_fn; + }; +}; + +// Return a LayoutPreferenceFn that always uses kNoPreference layout. +XlaShapeLayoutHelpers::LayoutPreferenceFn UseNoPreferenceLayoutFn(); + +// Rewrites the layout of xla_shape if there is tiled sharding. +absl::Status RewriteLayoutWithShardedShape( + const std::optional& sharding, bool use_fast_memory, + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns, + xla::Shape* xla_shape); + +// Adds reshapes to fix the layout of an output, if a shape_representation_fn or +// sharding is present. +absl::StatusOr ReshapeWithCorrectRepresentationAndSharding( + xla::XlaBuilder* builder, xla::XlaOp original, xla::Shape original_shape, + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns, + std::optional sharding, bool fast_mem); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_SHAPE_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..18aa5b9bfc11f923b1916bb368ac642f8ac96b82 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/BUILD @@ -0,0 +1,107 @@ +# Utilities for building XLA computations. + +load("//tensorflow:tensorflow.default.bzl", "filegroup") +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//tensorflow/compiler/tf2xla:friends"], + licenses = ["notice"], +) + +# Filegroup used to collect source files for dependency checking. +filegroup( + name = "c_srcs", + data = glob([ + "**/*.cc", + "**/*.h", + ]), +) + +cc_library( + name = "broadcast", + srcs = ["broadcast.cc"], + hdrs = ["broadcast.h"], + deps = [ + "//tensorflow/compiler/tf2xla:common", + "//tensorflow/core:framework", + "//tensorflow/core/platform:errors", + "//tensorflow/core/platform:status", + "//tensorflow/core/platform:statusor", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/types:span", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:broadcast", + "@xla//xla/tsl/platform:errors", + "@xla//xla/tsl/platform:statusor", + ], +) + +cc_library( + name = "random", + srcs = ["random.cc"], + hdrs = ["random.h"], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compiler", + "//tensorflow/compiler/tf2xla:xla_helpers", + "//tensorflow/core:protos_all_cc", + "//tensorflow/core/platform:statusor", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder/lib:constants", + "@xla//xla/hlo/builder/lib:math", + ], +) + +cc_library( + name = "scatter", + srcs = ["scatter.cc"], + hdrs = ["scatter.h"], + deps = [ + "//tensorflow/core:lib", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@com_google_absl//absl/types:span", + "@xla//xla:shape_util", + "@xla//xla:status_macros", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + ], +) + +cc_library( + name = "util", + srcs = ["util.cc"], + hdrs = ["util.h"], + deps = [ + "//tensorflow/core:lib", + "@com_google_absl//absl/log", + "@com_google_absl//absl/types:span", + "@xla//xla:literal", + "@xla//xla:literal_util", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/hlo/builder:xla_builder", + "@xla//xla/hlo/builder:xla_computation", + ], +) + +cc_library( + name = "data_format", + srcs = ["data_format.cc"], + hdrs = ["data_format.h"], + deps = [ + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "@com_google_absl//absl/status", + "@com_google_absl//absl/status:statusor", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:util", + "@xla//xla/hlo/builder:xla_builder", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.cc new file mode 100644 index 0000000000000000000000000000000000000000..a730072c7c5837b3e45c125bc8f41e47cadd097f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.cc @@ -0,0 +1,60 @@ +/* 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/tf2xla/lib/broadcast.h" + +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "xla/hlo/builder/lib/broadcast.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/util/bcast.h" + +namespace tensorflow { + +absl::StatusOr BroadcastTo(xla::XlaOp input, + absl::Span output_dims) { + return xla::BroadcastTo(input, output_dims); +} + +absl::Status BroadcastOpsToSame(xla::XlaOp* lhs, xla::XlaOp* rhs) { + TF_ASSIGN_OR_RETURN(auto lhs_xla_shape, lhs->builder()->GetShape(*lhs)); + TF_ASSIGN_OR_RETURN(auto rhs_xla_shape, rhs->builder()->GetShape(*rhs)); + tensorflow::TensorShape lhs_tf_shape; + tensorflow::TensorShape rhs_tf_shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(lhs_xla_shape, &lhs_tf_shape)); + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(rhs_xla_shape, &rhs_tf_shape)); + if (!lhs_tf_shape.IsSameSize(rhs_tf_shape)) { + tensorflow::BCast bcast(tensorflow::BCast::FromShape(lhs_tf_shape), + tensorflow::BCast::FromShape(rhs_tf_shape)); + if (!bcast.IsValid()) { + return absl::InvalidArgumentError( + "Dimensions cannot be made to match through broadcasting"); + } + TF_ASSIGN_OR_RETURN(*lhs, xla::BroadcastTo(*lhs, bcast.output_shape())); + TF_ASSIGN_OR_RETURN(*rhs, xla::BroadcastTo(*rhs, bcast.output_shape())); + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.h new file mode 100644 index 0000000000000000000000000000000000000000..1766de3834c5287a88dfb909598931de3b840493 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.h @@ -0,0 +1,39 @@ +/* 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_TF2XLA_LIB_BROADCAST_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LIB_BROADCAST_H_ + +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Forwards to xla::BroadcastTo. +// TODO(cheshire): Call the underlying function directly. +absl::StatusOr BroadcastTo(xla::XlaOp input, + absl::Span output_dims); + +// Forwards to xla::BroadcastOpsToSame. +absl::Status BroadcastOpsToSame(xla::XlaOp* lhs, xla::XlaOp* rhs); +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_LIB_BROADCAST_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/data_format.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/data_format.cc new file mode 100644 index 0000000000000000000000000000000000000000..ed81f8756a7ebdc7f661cf04a8a636058817e784 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/data_format.cc @@ -0,0 +1,104 @@ +/* Copyright 2019 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/lib/data_format.h" + +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +namespace { + +absl::StatusOr Contract(xla::XlaOp input, int64_t dim) { + xla::XlaBuilder* builder = input.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape input_shape, builder->GetShape(input)); + + if (input_shape.dimensions().back() != 4) { + return absl::InvalidArgumentError( + absl::StrCat("Expected last dimension to be 4; got ", + input_shape.dimensions().back())); + } + + // Transpose the input so C is directly followed by VECT_C. + std::vector permutation; + const int64_t rank = input_shape.dimensions().size(); + permutation.reserve(rank); + for (int64_t i = 0; i != rank - 1; ++i) { + permutation.push_back(i); + if (i == dim) { + permutation.push_back(rank - 1); + } + } + + // Now merge the adjacent dimensions with a reshape. + std::vector contracted_shape(input_shape.dimensions().begin(), + input_shape.dimensions().end() - 1); + contracted_shape[dim] *= 4; + + return xla::Reshape(xla::Transpose(input, permutation), contracted_shape); +} + +absl::StatusOr Expand(xla::XlaOp input, int64_t dim) { + xla::XlaBuilder* builder = input.builder(); + TF_ASSIGN_OR_RETURN(xla::Shape input_shape, builder->GetShape(input)); + + if (input_shape.dimensions(dim) % 4 != 0) { + return absl::InvalidArgumentError(absl::StrCat( + "Expected vectorized dimension to be evenly divisible by 4; got ", + input_shape.dimensions(dim))); + } + + // Split the `dim` into two dimensions with a reshape. The size of the new + // dimension is always 4. + std::vector expanded_shape = + xla::SpanToVector(input_shape.dimensions()); + expanded_shape[dim] /= 4; + expanded_shape.insert(expanded_shape.begin() + dim + 1, 4); + + // Move the newly created dimension to the end with a transpose. + std::vector permutation; + const int64_t expanded_shape_size = expanded_shape.size(); + permutation.reserve(expanded_shape_size); + for (int64_t i = 0; i != expanded_shape_size; ++i) { + permutation.push_back(i); + if (i == dim) { + ++i; + } + } + permutation.push_back(dim + 1); + + return xla::Transpose(xla::Reshape(input, expanded_shape), permutation); +} + +} // namespace + +absl::StatusOr NCHW_VECT_CToNCHW(xla::XlaOp input) { + return Contract(input, 1); +} + +absl::StatusOr NCHWToNCHW_VECT_C(xla::XlaOp input) { + return Expand(input, 1); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/data_format.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/data_format.h new file mode 100644 index 0000000000000000000000000000000000000000..18bd6937508c716b00ab4baa07316cdb70f65623 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/data_format.h @@ -0,0 +1,38 @@ +/* Copyright 2019 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_LIB_DATA_FORMAT_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LIB_DATA_FORMAT_H_ + +#include "absl/status/statusor.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/platform/statusor.h" +#include "tensorflow/core/util/tensor_format.h" + +namespace tensorflow { + +// Reformat from NCHW_VECT_C to NCHW. +// +// Prerequisites: the last dimension of the input must be of size 4. +absl::StatusOr NCHW_VECT_CToNCHW(xla::XlaOp input); + +// Reformat from NCHW to NCHW_VECT_C. +// +// Prerequisites: the vectorized dimension `C` must be a multiple of 4. +absl::StatusOr NCHWToNCHW_VECT_C(xla::XlaOp input); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_LIB_DATA_FORMAT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/random.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/random.cc new file mode 100644 index 0000000000000000000000000000000000000000..66958b5754484ff0d107abe55ec6ae37c18f8f3a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/random.cc @@ -0,0 +1,82 @@ +/* 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/tf2xla/lib/random.h" + +#include + +#include "xla/hlo/builder/lib/constants.h" +#include "xla/hlo/builder/lib/math.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/xla_data.pb.h" + +namespace tensorflow { + +xla::XlaOp TruncatedNormal(xla::XlaOp uniform) { + const double kA = -2.0; + const double kB = 2.0; + const double kMu = 0.0; + const double kSigma = 1.0; + return ParameterizedTruncatedNormal( + uniform, xla::ScalarLike(uniform, kMu), xla::ScalarLike(uniform, kSigma), + xla::ScalarLike(uniform, kA), xla::ScalarLike(uniform, kB)); +} + +// Implements the sampling of truncated normal distribution using the +// inversed cumulative distribution function (CDF) method as described in +// https://people.sc.fsu.edu/~jburkardt/presentations/truncated_normal.pdf. +xla::XlaOp ParameterizedTruncatedNormal(xla::XlaOp uniform, xla::XlaOp mu, + xla::XlaOp sigma, xla::XlaOp a, + xla::XlaOp b) { + xla::XlaOp one = xla::ScalarLike(uniform, 1.0); + xla::XlaOp two = xla::ScalarLike(uniform, 2.0); + xla::XlaOp sqrt_2 = xla::ScalarLike(uniform, std::sqrt(2.0)); + + auto normal_cdf = [&](xla::XlaOp x) { + return (one + xla::Erf(x / sqrt_2)) / two; + }; + + // Calculate the cumulative probabilities for the lower and upper bound, a and + // b. + xla::XlaOp alpha = (a - mu) / sigma; + xla::XlaOp beta = (b - mu) / sigma; + xla::XlaOp alpha_normal_cdf = normal_cdf(alpha); + xla::XlaOp beta_normal_cdf = normal_cdf(beta); + + // Convert the random uniform value in range (0, 1) (uniform) to a value in + // range (alpha_normal_cdf, beta_normal_cdf) that represents the cumulative + // probability (p) of a value (x) in the truncated normal distribution. + xla::XlaOp p = + alpha_normal_cdf + (beta_normal_cdf - alpha_normal_cdf) * uniform; + + // Calculate x using the inversed cumulative distribution function: + // x = inversed_cdf(mu, sigma; p) = mu + sigma * sqrt(2) * erfinv(2*p-1) + // Clamp the input of erfinv to (-1, 1) because 2*p-1 may produce +/-1 due to + // computation precision. + xla::XlaOp v = two * p - one; + xla::PrimitiveType primitive_type = + uniform.builder()->GetShape(uniform).value().element_type(); + xla::XlaOp epsilon = xla::Epsilon(uniform.builder(), primitive_type); + v = xla::Clamp(-one + epsilon, v, one - epsilon); + xla::XlaOp x = mu + sigma * sqrt_2 * xla::ErfInv(v); + + // The value of x may be out of the range of (a, b), this typically happens + // when the region of the truncated normal has a very small probability. + x = xla::Clamp(a, x, b); + + return x; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/random.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/random.h new file mode 100644 index 0000000000000000000000000000000000000000..67c7a2317b9edbe47b81f3a3ca23dddb8fc473b3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/random.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_TF2XLA_LIB_RANDOM_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LIB_RANDOM_H_ + +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Builds an array of values sampled from a truncated normal distribution: +// +// uniform: an array of random numbers in uniform distribution (0, 1). +// mu: the mean of the normal distribution. +// sigma: the standard deviation of the normal distribution. +// a: the lower bound of the generated values. +// b: the upper bound of the generated values. +xla::XlaOp ParameterizedTruncatedNormal(xla::XlaOp uniform, xla::XlaOp mu, + xla::XlaOp sigma, xla::XlaOp a, + xla::XlaOp b); + +// A specialized version of ParameterizedTruncatedNormal, with mu=0, sigma=1, +// a=-2 and b=2. +xla::XlaOp TruncatedNormal(xla::XlaOp uniform); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_LIB_RANDOM_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/scatter.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/scatter.cc new file mode 100644 index 0000000000000000000000000000000000000000..177669b4b815255cc532ab1f392a5bf76fc10912 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/scatter.cc @@ -0,0 +1,211 @@ +/* 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/tf2xla/lib/scatter.h" + +#include +#include +#include + +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/types/span.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +absl::StatusOr XlaScatter( + const xla::XlaOp buffer, const xla::XlaOp updates, const xla::XlaOp indices, + bool indices_are_vectors, bool indices_are_sorted, + const std::function& + combiner, + xla::XlaBuilder* builder) { + TF_ASSIGN_OR_RETURN(xla::Shape buffer_shape, builder->GetShape(buffer)); + TF_ASSIGN_OR_RETURN(xla::Shape updates_shape, builder->GetShape(updates)); + TF_ASSIGN_OR_RETURN(xla::Shape indices_shape, builder->GetShape(indices)); + absl::Span indices_dims = indices_shape.dimensions(); + + // If the indices are N-dimensional, the minor dimension of indices contains + // the indices to update. Otherwise the indices are all scalars. + int64_t num_index_dims = 1; + if (indices_are_vectors) { + TF_RET_CHECK(!indices_dims.empty()); + num_index_dims = indices_dims.back(); + if (num_index_dims > buffer_shape.dimensions().size()) { + return absl::InvalidArgumentError(absl::StrCat( + "The size of the minor dimension of the indices (shape: ", + xla::ShapeUtil::HumanString(indices_shape), + ") must be <= the rank of the buffer (shape: ", + xla::ShapeUtil::HumanString(buffer_shape), ")")); + } + indices_dims.remove_suffix(1); + } + + int64_t num_indices = 1; + for (int64_t dim : indices_dims) { + num_indices *= dim; + } + + // Degenerate case: nothing to update. Return the buffer unchanged. + if (num_indices == 0) { + return buffer; + } + + // If any of the indexed dimensions are zero in the buffer, the update cannot + // succeed since it updates a slice of size 1. + for (int64_t i = 0; i < num_index_dims; ++i) { + if (xla::ShapeUtil::GetDimension(buffer_shape, i) == 0) { + return absl::InvalidArgumentError(absl::StrCat( + "Scatter dimension ", i, " is of size zero in tensor with shape ", + xla::ShapeUtil::HumanString(buffer_shape))); + } + } + + // Example of a 1-D scatter that updates two [3,1] tensors in a tensor of + // shape [3,3]: + // NOTE: ***This case will not be generated by any of the tf.scatter ops.*** + // + // operand = s32[3,3] parameter(0) + // indices = s32[2] parameter(1) + // updates = s32[3,2] parameter(2) + // scatter = s32[3,3] scatter(operand, indices, updates), + // to_apply=update_computation, + // update_window_dims={0}, + // inserted_window_dims={1}, + // scatter_dims_to_operand_dims={1}, + // index_vector_dim=1 + // + // + // Example of a 1-D scatter that updates two [1,3] tensors in a tensor of + // shape [3,3]: + // + // operand = s32[3,3] parameter(0) + // indices = s32[2] parameter(1) + // updates = s32[2,3] parameter(2) + // scatter = s32[3,3] scatter(operand, indices, updates), + // to_apply=update_computation, + // update_window_dims={1}, + // inserted_window_dims={0}, + // scatter_dims_to_operand_dims={0}, + // index_vector_dim=1 + // + // + // Example of an N-D scatter updating slices of shape [1,1,2] in a tensor of + // shape [3,3,2] + // + // operand = s32[3,3,2] parameter(0) + // indices = s32[2,2] parameter(1) + // updates = s32[2,2] parameter(2) + // scatter = s32[3,3,2] scatter(operand, indices, updates), + // to_apply=update_computation, + // update_window_dims={1}, + // inserted_window_dims={0,1}, + // scatter_dims_to_operand_dims={0,1}, + // index_vector_dim=1 + // + // + // Example of a scatter updating slices of shape [] in a tensor of shape [1,1] + // + // operand = s32[1,1] parameter(0) + // indices = s32[1] parameter(1) + // updates = s32[1] parameter(2) + // scatter = s32[1,1] scatter(operand, indices, updates), + // to_apply=update_computation, + // update_window_dims={}, + // inserted_window_dims={0,1}, + // scatter_dims_to_operand_dims={0}, + // index_vector_dim=1 + // Note that updates operand would be broadcasted into [1] in this case. + // + + xla::ScatterDimensionNumbers dim_numbers; + dim_numbers.set_index_vector_dim(indices_are_vectors + ? indices_shape.dimensions().size() - 1 + : indices_shape.dimensions().size()); + + int64_t updates_rank = updates_shape.dimensions().size(); + int64_t buffer_rank = buffer_shape.dimensions().size(); + int64_t num_window_dims_in_updates = buffer_rank - num_index_dims; + + // If the rank of `updates` is 0 and does not match the expected rank of + // updates, broadcast `updates` to the expected shape of updates. + auto new_updates = updates; + std::vector expected_updates_dims(indices_dims.begin(), + indices_dims.end()); + for (int64_t dim = num_index_dims; dim < buffer_rank; ++dim) { + expected_updates_dims.push_back(buffer_shape.dimensions(dim)); + } + int64_t expected_updates_rank = expected_updates_dims.size(); + if (updates_rank == 0 && expected_updates_rank != 0) { + new_updates = xla::Broadcast(updates, expected_updates_dims); + TF_ASSIGN_OR_RETURN(updates_shape, builder->GetShape(new_updates)); + updates_rank = updates_shape.dimensions().size(); + } + + if (updates_rank > 0) { + for (int64_t i = (updates_rank - num_window_dims_in_updates); + i < updates_rank; ++i) { + dim_numbers.add_update_window_dims(i); + } + } + + for (int64_t i = 0; i < num_index_dims; ++i) { + dim_numbers.add_inserted_window_dims(i); + dim_numbers.add_scatter_dims_to_operand_dims(i); + } + + // Build the combiner computation. + xla::XlaComputation combiner_computation; + { + xla::XlaBuilder cb("scatter-combiner"); + auto xla_scalar_shape = + xla::ShapeUtil::MakeShape(buffer_shape.element_type(), {}); + auto p0 = xla::Parameter(&cb, 0, xla_scalar_shape, "p0"); + auto p1 = xla::Parameter(&cb, 1, xla_scalar_shape, "p1"); + if (combiner) { + combiner(p0, p1, &cb); + } + combiner_computation = cb.Build().value(); + } + + VLOG(3) << "Scatter op:"; + VLOG(3) << " Input: " << xla::ShapeUtil::HumanString(buffer_shape); + VLOG(3) << " Indices: " << xla::ShapeUtil::HumanString(indices_shape); + VLOG(3) << " Updates: " << xla::ShapeUtil::HumanString(updates_shape); + VLOG(3) << " Scatter Dimension Numbers: "; + VLOG(3) << " index_vector_dim: " << dim_numbers.index_vector_dim(); + VLOG(3) << " update_window_dims: [" + << absl::StrJoin(dim_numbers.update_window_dims(), ",") << "]"; + VLOG(3) << " inserted_window_dims: [" + << absl::StrJoin(dim_numbers.inserted_window_dims(), ",") << "]"; + VLOG(3) << " scatter_dims_to_operand_dims: [" + << absl::StrJoin(dim_numbers.scatter_dims_to_operand_dims(), ",") + << "]"; + + return xla::Scatter(buffer, indices, new_updates, combiner_computation, + dim_numbers, indices_are_sorted); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/scatter.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/scatter.h new file mode 100644 index 0000000000000000000000000000000000000000..d47b5049fa95807e33db25be53479a70f9583fd5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/scatter.h @@ -0,0 +1,56 @@ +/* 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_TF2XLA_LIB_SCATTER_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LIB_SCATTER_H_ + +#include + +#include "absl/status/statusor.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Builds an XLA computation that performs a scatter operation on `buffer`, +// returning an updated buffer. +// For each i0, i1, ..., sets +// buffer[indices[i0, i1, ...], ...] := updates[i0, i1, ...] +// +// If `indices_are_vectors` is false, then each index in indices is a scalar, +// and the shape of `indices` must be a prefix of the shape of updates. +// Otherwise, `indices_are_vectors`, then indices are multidimensional and the +// minor dimension of `indices` represents a vector of indices. +// +// If `updates` is a scalar, then it will be broadcasted into the expected shape +// of updates. +// +// If any part of the update region is out-of-bounds, the corresponding update +// is discarded. +// +// If a `combiner` is provided, updates are combined with the existing values in +// the buffer using the combiner function. Otherwise, the updates replace the +// existing values. The order of updates is implementation-defined. +absl::StatusOr XlaScatter( + xla::XlaOp buffer, xla::XlaOp updates, xla::XlaOp indices, + bool indices_are_vectors, bool indices_are_sorted, + const std::function& + combiner, + xla::XlaBuilder* builder); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_LIB_SCATTER_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/util.cc new file mode 100644 index 0000000000000000000000000000000000000000..0ac54701c161bb1e1dc0d1d013528f390c07c9e7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/util.cc @@ -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. +==============================================================================*/ + +#include "tensorflow/compiler/tf2xla/lib/util.h" + +#include + +#include "absl/log/log.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/primitive_util.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" + +namespace tensorflow { + +xla::XlaOp Zeros(xla::XlaBuilder* builder, const xla::Shape& shape) { + return xla::Broadcast( + xla::ConstantLiteral(builder, + xla::LiteralUtil::Zero(shape.element_type())), + shape.dimensions()); +} + +xla::XlaOp FloatLiteral(xla::XlaBuilder* builder, xla::PrimitiveType type, + double value) { + return xla::primitive_util::PrimitiveTypeSwitch( + [&](auto primitive_type_constant) -> xla::XlaOp { + if constexpr (xla::primitive_util::IsFloatingPointType( + primitive_type_constant) || + xla::primitive_util::IsComplexType( + primitive_type_constant)) { + using NativeT = + xla::primitive_util::NativeTypeOf; + return xla::ConstantR0(builder, static_cast(value)); + } + LOG(FATAL) << "unhandled element type " << type; + }, + type); +} + +xla::XlaOp IntegerLiteral(xla::XlaBuilder* builder, xla::PrimitiveType type, + int64_t value) { + xla::Literal literal = xla::primitive_util::PrimitiveTypeSwitch( + [&](auto primitive_type_constant) -> xla::Literal { + if constexpr (xla::primitive_util::IsArrayType( + primitive_type_constant)) { + using NativeT = + xla::primitive_util::NativeTypeOf; + return xla::LiteralUtil::CreateR0( + static_cast(value)); + } + LOG(FATAL) << "unhandled element type " << type; + }, + type); + return xla::ConstantLiteral(builder, literal); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/util.h new file mode 100644 index 0000000000000000000000000000000000000000..969866891661c7b6fb6a1a54c835aed9f771fc76 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/lib/util.h @@ -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. +==============================================================================*/ + +#ifndef TENSORFLOW_COMPILER_TF2XLA_LIB_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LIB_UTIL_H_ + +#include + +#include "absl/types/span.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Returns a floating point scalar constant of 'type' with 'value'. +// If 'type' is complex, returns a real value with zero imaginary component. +xla::XlaOp FloatLiteral(xla::XlaBuilder* builder, xla::PrimitiveType type, + double value); + +// Makes a 1D tensor [0, ..., x, y] from two tensors x and y with zeros +// prepended until the array is length n_dims. +xla::XlaOp PrependZerosInMajorDims(xla::XlaOp x, + absl::Span starts); + +// Returns a integer scalar constant of 'type' with 'value'. +// If 'type' is complex, returns a real value with zero imaginary component. +xla::XlaOp IntegerLiteral(xla::XlaBuilder* builder, xla::PrimitiveType type, + int64_t value); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_LIB_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/light_outside_compilation_kernels_for_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/light_outside_compilation_kernels_for_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..1c0602bfb67336ea380047494cc0c9c5fc21f3b2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/light_outside_compilation_kernels_for_test.cc @@ -0,0 +1,403 @@ +/* Copyright 2022 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 +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/kernels/light_outside_compilation.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/stream_executor/device_memory.h" +#include "xla/stream_executor/stream.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/allocator.h" +#include "tensorflow/core/framework/node_def.pb.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/op_requires.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/types.h" + +// Sample kernels for the light outside compilation test. + +namespace tensorflow { +namespace { + +// Just copy the input. +REGISTER_OP("TestStaticTf") + .Input("input: float") + .Output("output: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->input(0)); + return absl::OkStatus(); + }); + +class TestStaticTfOp : public OpKernel { + public: + explicit TestStaticTfOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} + void Compute(OpKernelContext* ctx) override { + Tensor* out_tensor = nullptr; + const Tensor& input = ctx->input(0); + OP_REQUIRES_OK(ctx, ctx->allocate_output("output", ctx->input(0).shape(), + &out_tensor)); + + // Just pass the value through. + uint64_t size = input.AllocatedBytes(); + stream_executor::DeviceAddressBase gpu_dst{out_tensor->data(), size}; + se::Stream* stream = ctx->op_device_context()->stream(); + + OP_REQUIRES_OK( + ctx, + stream->MemcpyD2D( + /*gpu_dst=*/&gpu_dst, + /*gpu_src=*/stream_executor::DeviceAddressBase{input.data(), size}, + /*size=*/input.AllocatedBytes())); + } +}; + +REGISTER_KERNEL_BUILDER(Name("TestStaticTf").Device(DEVICE_GPU), + TestStaticTfOp); +REGISTER_XLA_OP(Name("TestStaticTf").Device(DEVICE_GPU_XLA_JIT), + LightOutsideCompilationOp) + +REGISTER_OP("TestStaticMultipleOutputTf") + .Input("input: float") + .Output("output1: float") + .Output("output2: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->input(0)); + c->set_output(1, c->input(0)); + return absl::OkStatus(); + }); + +class TestStaticMultipleOutputTfOp : public OpKernel { + public: + explicit TestStaticMultipleOutputTfOp(OpKernelConstruction* ctx) + : OpKernel(ctx) {} + void Compute(OpKernelContext* ctx) override { + Tensor* out_tensor1 = nullptr; + Tensor* out_tensor2 = nullptr; + const Tensor& input = ctx->input(0); + OP_REQUIRES_OK(ctx, ctx->allocate_output("output1", ctx->input(0).shape(), + &out_tensor1)); + OP_REQUIRES_OK(ctx, ctx->allocate_output("output2", ctx->input(0).shape(), + &out_tensor2)); + + // Just pass the value through. + uint64_t size = input.AllocatedBytes(); + stream_executor::DeviceAddressBase gpu_dst1{out_tensor1->data(), size}; + stream_executor::DeviceAddressBase gpu_dst2{out_tensor2->data(), size}; + se::Stream* stream = + ctx->device()->tensorflow_accelerator_device_info()->stream; + + OP_REQUIRES_OK( + ctx, + stream->MemcpyD2D( + /*gpu_dst=*/&gpu_dst1, + /*gpu_src=*/stream_executor::DeviceAddressBase{input.data(), size}, + /*size=*/input.AllocatedBytes())); + OP_REQUIRES_OK( + ctx, + stream->MemcpyD2D( + /*gpu_dst=*/&gpu_dst2, + /*gpu_src=*/stream_executor::DeviceAddressBase{input.data(), size}, + /*size=*/input.AllocatedBytes())); + } +}; + +REGISTER_KERNEL_BUILDER(Name("TestStaticMultipleOutputTf").Device(DEVICE_GPU), + TestStaticMultipleOutputTfOp); +REGISTER_XLA_OP(Name("TestStaticMultipleOutputTf").Device(DEVICE_GPU_XLA_JIT), + LightOutsideCompilationOp) + +// Copy the input up to `max_size`. +REGISTER_OP("TestDynamicTf") + .Input("input: float") + .Attr("max_size: int") + .Output("output: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->UnknownShapeOfRank(c->Rank(c->input(0)))); + return absl::OkStatus(); + }); + +// Same as TestStaticTfOp, but only copies up to `max_size` attribute. +class TestDynamicTfOp : public OpKernel { + public: + explicit TestDynamicTfOp(OpKernelConstruction* ctx) : OpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("max_size", &max_size_)); + } + void Compute(OpKernelContext* ctx) override { + const Tensor& input = ctx->input(0); + + // Pass through the part of the value specified by the `max_size` attribute. + int64_t size = input.AllocatedBytes(); + CHECK_LE(max_size_, size); + uint64_t size_to_cpy = std::min(size, max_size_) / 2; + + TensorShape allocated_shape; + OP_REQUIRES_OK(ctx, + TensorShapeUtils::MakeShape( + absl::Span{static_cast(size_to_cpy)}, + &allocated_shape)); + + Tensor* out_tensor = nullptr; + OP_REQUIRES_OK( + ctx, ctx->allocate_output("output", allocated_shape, &out_tensor)); + + se::Stream* stream = + ctx->device()->tensorflow_accelerator_device_info()->stream; + + stream_executor::DeviceAddressBase gpu_dst{out_tensor->data(), size_to_cpy}; + OP_REQUIRES_OK(ctx, stream->MemcpyD2D( + /*gpu_dst=*/&gpu_dst, + /*gpu_src=*/ + stream_executor::DeviceAddressBase{ + input.data(), static_cast(size)}, + /*size=*/size_to_cpy)); + } + + private: + int64_t max_size_; +}; +REGISTER_KERNEL_BUILDER(Name("TestDynamicTf").Device(DEVICE_GPU), + TestDynamicTfOp); + +class TestDynamicTfXlaOp : public LightOutsideCompilationOp { + public: + explicit TestDynamicTfXlaOp(OpKernelConstruction* context) + : LightOutsideCompilationOp(context) {} + absl::StatusOr DynamicOutputDimensions( + const NodeDef& ndef, XlaOpKernelContext* ctx) const override { + OutputDimensionBoundsMap out; + TF_ASSIGN_OR_RETURN(auto max_bound, GetNodeAttr(ndef, "max_size")); + out[0][0] = max_bound; + return out; + } +}; + +REGISTER_XLA_OP(Name("TestDynamicTf").Device(DEVICE_GPU_XLA_JIT), + TestDynamicTfXlaOp); + +REGISTER_OP("DynamicMultidim") + .Input("output_shape: int32") + .Output("output: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->UnknownShapeOfRank(5)); + return absl::OkStatus(); + }); + +// Just fill in the data with ones for a given shape. +class DynamicMultidimOp : public OpKernel { + public: + explicit DynamicMultidimOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} + + void Compute(OpKernelContext* ctx) override { + TensorShape output_shape; + auto vec = ctx->input(0).flat(); + for (int i = 0; i < vec.size(); i++) { + OP_REQUIRES_OK(ctx, output_shape.AddDimWithStatus(vec(i))); + } + Tensor* out_tensor = nullptr; + OP_REQUIRES_OK(ctx, + ctx->allocate_output("output", output_shape, &out_tensor)); + + // Fill in the value with ones. + int32_t num_elements = output_shape.num_elements(); + std::vector host_data(num_elements); + for (int i = 0; i < output_shape.num_elements(); i++) { + host_data[i] = 1.0; + } + stream_executor::DeviceAddressBase gpu_dst{ + out_tensor->data(), static_cast(num_elements)}; + + se::Stream* stream = + ctx->device()->tensorflow_accelerator_device_info()->stream; + OP_REQUIRES_OK(ctx, stream->Memcpy( + /*gpu_dst=*/&gpu_dst, /*host_src=*/host_data.data(), + /*size=*/num_elements * sizeof(float))); + } +}; + +REGISTER_KERNEL_BUILDER( + Name("DynamicMultidim").Device(DEVICE_GPU).HostMemory("output_shape"), + DynamicMultidimOp); + +class DynamicMultidimXlaOp : public LightOutsideCompilationOp { + public: + explicit DynamicMultidimXlaOp(OpKernelConstruction* context) + : LightOutsideCompilationOp(context) {} + absl::StatusOr DynamicOutputDimensions( + const NodeDef& ndef, XlaOpKernelContext* ctx) const override { + OutputDimensionBoundsMap out; + for (int i = 0; i < 5; i++) { + out[0][i] = 20; + } + return out; + } +}; + +REGISTER_XLA_OP(Name("DynamicMultidim") + .Device(DEVICE_GPU_XLA_JIT) + .CompileTimeConstantInput("output_shape"), + DynamicMultidimXlaOp); + +REGISTER_OP("DynamicUnranked") + .Output("output: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->UnknownShape()); + return absl::OkStatus(); + }); + +REGISTER_XLA_OP(Name("DynamicUnranked").Device(DEVICE_GPU_XLA_JIT), + LightOutsideCompilationOp); + +// Copies up to `to_copy_bytes` from the input: tests constant storage. +REGISTER_OP("TestTfMustBeConstant") + .Input("input: float") + .Input("constant_to_add: int32") + .Output("output: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->input(0)); + return absl::OkStatus(); + }); + +class TestTfMustBeConstantOp : public OpKernel { + public: + explicit TestTfMustBeConstantOp(OpKernelConstruction* ctx) : OpKernel(ctx) {} + void Compute(OpKernelContext* ctx) override { + const Tensor& input = ctx->input(0); + + OP_REQUIRES(ctx, TensorShapeUtils::IsScalar(ctx->input(1).shape()), + absl::InvalidArgumentError( + absl::StrCat("Expected argument 0 to be a scalar. Received", + ctx->input(1).DebugString()))); + int constant_to_add = ctx->input(1).scalar()(); + size_t allocated_size = input.AllocatedBytes(); + + se::Stream* stream = + ctx->device()->tensorflow_accelerator_device_info()->stream; + + Tensor tmp; + AllocatorAttributes pinned_alloc_attrs; + pinned_alloc_attrs.set_on_host(true); + pinned_alloc_attrs.set_gpu_compatible(true); + CHECK_OK(ctx->allocate_temp(input.dtype(), input.shape(), &tmp, + pinned_alloc_attrs)); + + OP_REQUIRES_OK(ctx, stream->Memcpy(tmp.data(), + stream_executor::DeviceAddressBase{ + input.data(), allocated_size}, + allocated_size)); + + OP_REQUIRES_OK(ctx, stream->BlockHostUntilDone()); + + for (int i = 0; i < input.NumElements(); i++) { + tmp.flat().data()[i] += constant_to_add; + } + + Tensor* out_tensor = nullptr; + OP_REQUIRES_OK(ctx, ctx->allocate_output("output", ctx->input(0).shape(), + &out_tensor)); + stream_executor::DeviceAddressBase gpu_dst{ + out_tensor->data(), static_cast(allocated_size)}; + OP_REQUIRES_OK(ctx, stream->Memcpy(&gpu_dst, tmp.data(), allocated_size)); + } +}; + +REGISTER_KERNEL_BUILDER(Name("TestTfMustBeConstant").Device(DEVICE_GPU), + TestTfMustBeConstantOp); + +REGISTER_XLA_OP(Name("TestTfMustBeConstant") + .Device(DEVICE_GPU_XLA_JIT) + .CompileTimeConstantInput("constant_to_add"), + LightOutsideCompilationOp) + +REGISTER_OP("TestDynamicTfWithBound") + .Input("input: float") + .Attr("max_size: int") + .Output("output: float") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->input(0)); + return absl::OkStatus(); + }); + +class TestDynamicTfWithBoundOp : public OpKernel { + public: + explicit TestDynamicTfWithBoundOp(OpKernelConstruction* ctx) : OpKernel(ctx) { + OP_REQUIRES_OK(ctx, ctx->GetAttr("max_size", &max_size_)); + } + void Compute(OpKernelContext* ctx) override { + const Tensor& input = ctx->input(0); + uint64_t size_to_cpy = + std::min(input.AllocatedBytes(), static_cast(max_size_)); + + TensorShape allocated_shape; + OP_REQUIRES_OK(ctx, + TensorShapeUtils::MakeShape( + absl::Span{static_cast(size_to_cpy)}, + &allocated_shape)); + + Tensor* out_tensor = nullptr; + OP_REQUIRES_OK( + ctx, ctx->allocate_output("output", allocated_shape, &out_tensor)); + + se::Stream* stream = + ctx->device()->tensorflow_accelerator_device_info()->stream; + stream_executor::DeviceAddressBase gpu_dst{out_tensor->data(), size_to_cpy}; + OP_REQUIRES_OK( + ctx, stream->MemcpyD2D( + /*gpu_dst=*/&gpu_dst, + /*gpu_src=*/ + stream_executor::DeviceAddressBase{input.data(), size_to_cpy}, + /*size=*/size_to_cpy)); + } + + private: + int64_t max_size_; +}; + +REGISTER_KERNEL_BUILDER(Name("TestDynamicTfWithBound").Device(DEVICE_GPU), + TestDynamicTfWithBoundOp); + +class TestDynamicTfWithBoundXlaOp : public LightOutsideCompilationOp { + public: + explicit TestDynamicTfWithBoundXlaOp(OpKernelConstruction* context) + : LightOutsideCompilationOp(context) {} + + absl::StatusOr DynamicOutputDimensions( + const NodeDef& ndef, XlaOpKernelContext* ctx) const override { + OutputDimensionBoundsMap out; + TF_ASSIGN_OR_RETURN(auto max_bound, GetNodeAttr(ndef, "max_size")); + out[0][0] = max_bound; + return out; + } +}; + +REGISTER_XLA_OP(Name("TestDynamicTfWithBound").Device(DEVICE_GPU_XLA_JIT), + TestDynamicTfWithBoundXlaOp); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/light_outside_compilation_test.py b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/light_outside_compilation_test.py new file mode 100644 index 0000000000000000000000000000000000000000..0c040735354a2aaa4354d993f70841c23e2963b1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/light_outside_compilation_test.py @@ -0,0 +1,229 @@ +# Copyright 2022 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 tensorflow.compiler.mlir.python.mlir_wrapper import filecheck_wrapper as fw +from tensorflow.compiler.tf2xla import test_ops_for_light_outside_compilation +from tensorflow.python.eager import context +from tensorflow.python.eager import def_function +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 nn_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.platform import googletest +from tensorflow.python.platform import test + + +class LightOutsideCompilationTest(test_util.TensorFlowTestCase): + + def setUp(self): + super().setUp() + if not test_util.is_gpu_available(): + self.skipTest('Light outside compilation only works for GPUs now') + + def assertFilecheck(self, actual, expected): + """Assert that FileCheck runs successfully.""" + if not fw.check(actual, expected): + self.fail(f'Got output:\n{actual}\nExpected:\n{expected}') + + def test_static_tf_op(self): + """Test operations with static shapes.""" + + @def_function.function(jit_compile=True) + def compiled_f(x): + return test_ops_for_light_outside_compilation.test_static_tf(x) + + with context.device('/gpu:0'): + z = random_ops.random_normal([2, 2]) + + self.assertFilecheck( + compiled_f.experimental_get_compiler_ir(z)('hlo'), r""" + CHECK: f32[2,2]{1,0} custom-call(f32[2,2]{1,0} [[v:.*]]), custom_call_target="GenericTfCallbackGPU" + CHECK: TestStaticTf + """) + + self.assertAllClose(compiled_f(z), z) + + def test_run_op_multiple_times(self): + """Call the op multiple times with different output buffers.""" + + @def_function.function(jit_compile=True) + def compiled_f(): + x = random_ops.random_normal([2, 2]) + y = test_ops_for_light_outside_compilation.test_static_tf(x) + return (x, y) + + with context.device('/gpu:0'): + x, y = compiled_f() + self.assertAllClose(x, y) + + x1, y1 = compiled_f() + self.assertAllClose(x1, y1) + + def test_unranked_output_error(self): + """Test that we error out for unranked dynamic shape.""" + + @def_function.function(jit_compile=True) + def compiled_f(): + return test_ops_for_light_outside_compilation.dynamic_unranked() + + with context.device('/gpu:0'): + + with self.assertRaisesRegex(ValueError, 'Output 0 has unknown rank'): + compiled_f.experimental_get_compiler_ir()() + + def test_dynamic_output_multidim(self): + """Test that we correctly handle multi-dimensional dynamic output.""" + + @def_function.function(jit_compile=True) + def compiled_f(shape): + return test_ops_for_light_outside_compilation.dynamic_multidim(shape) + + with context.device('/gpu:0'): + + # Rank is hardcoded to 5. + shape = [3, 4, 5, 4, 3] + hlo = compiled_f.experimental_get_compiler_ir(shape)('hlo_no_metadata') + out = compiled_f(shape) + + self.assertFilecheck( + hlo, r""" + CHECK: f32[<=20,<=20,<=20,<=20,<=20]{4,3,2,1,0} custom-call(), custom_call_target="GenericTfCallbackGPU" + CHECK: DynamicMultidim + """) + self.assertAllClose(out, array_ops.ones(shape)) + + def test_dynamic_output_tf_op(self): + """Test that dynamic output is sliced properly to the size known at runtime.""" + + @def_function.function(jit_compile=True) + def compiled_f(x): + return test_ops_for_light_outside_compilation.test_dynamic_tf( + x, max_size=5) + + with context.device('/gpu:0'): + z = random_ops.random_normal([10]) + out = compiled_f(z) + hlo = compiled_f.experimental_get_compiler_ir(z)('hlo_no_metadata') + + self.assertFilecheck( + hlo, r""" + CHECK: f32[<=5]{0} custom-call(f32[10]{0} [[v:.*]]), custom_call_target="GenericTfCallbackGPU" + CHECK: TestDynamicTf + """) + self.assertAllClose(out, z[:2]) + self.assertEqual(len(out), 2) + + def test_dynamic_input(self): + """Test dynamic input => returns bad status at runtime.""" + + @def_function.function(jit_compile=True) + def compiled_f(x): + x = array_ops.unique(x).y + return test_ops_for_light_outside_compilation.test_dynamic_tf( + x, max_size=5) + + with context.device('/gpu:0'): + z = random_ops.random_normal([10]) + + with self.assertRaisesRegex(ValueError, + 'Input dynamic dimensions are not supported'): + compiled_f.experimental_get_compiler_ir(z)() + + def test_multi_output_tf_op(self): + """Test light outside compilation for mulitple outputs.""" + + @def_function.function(jit_compile=True) + def compiled_f(x): + return test_ops_for_light_outside_compilation.test_static_multiple_output_tf( + x) + + with context.device('/gpu:0'): + z = random_ops.random_normal([2, 2]) + hlo = compiled_f.experimental_get_compiler_ir(z)('hlo_no_metadata') + + self.assertFilecheck( + hlo, r""" + CHECK: custom_call_target="GenericTfCallbackGPU" + CHECK: TestStaticMultipleOutputTf + """) + self.assertAllClose(compiled_f(z)[0], z) + self.assertAllClose(compiled_f(z)[1], z) + + def test_must_be_constant_tf_op(self): + """Test operations with must-be-constant input.""" + + @def_function.function(jit_compile=True) + def compiled_f(x, y): + return test_ops_for_light_outside_compilation.test_tf_must_be_constant( + x, constant_to_add=y) + + with context.device('/gpu:0'): + + z = random_ops.random_normal([10]) + hlo = compiled_f.experimental_get_compiler_ir(z, 5)('hlo_no_metadata') + + self.assertFilecheck( + hlo, r""" + CHECK: custom-call(f32[10]{0} [[v:.*]]), custom_call_target="GenericTfCallbackGPU" + CHECK: TestTfMustBeConstant + """) + + expected_output = [j + 5 for j in z] + self.assertAllClose(compiled_f(z, 5), expected_output) + + def testTighterProvidedBounds(self): + """Dynamic bounds are tighter than those deduced by shape inference.""" + + @def_function.function(jit_compile=True) + def compiled_f(x): + return test_ops_for_light_outside_compilation.test_dynamic_tf_with_bound( + x, max_size=5) + + with context.device('/gpu:0'): + z = random_ops.random_normal([10]) + hlo = compiled_f.experimental_get_compiler_ir(z)() + self.assertFilecheck( + hlo, r""" + CHECK: f32[5]{0} custom-call(f32[10]{0} [[v:.*]]), custom_call_target="GenericTfCallbackGPU" + """) + + def testFixedLayout(self): + """Test correct operand layout is fixed by the lowering.""" + + @def_function.function(jit_compile=True) + def compiled_f(conv_input): + filters = random_ops.random_uniform([2, 3, 3, 2]) + conv = nn_ops.conv2d( + conv_input, + filters, + strides=[1, 1, 2, 1], + dilations=[1, 1, 1, 1], + padding='SAME', + data_format='NHWC') + return test_ops_for_light_outside_compilation.test_static_tf(conv) + + with context.device('/gpu:0'): + hlo = compiled_f.experimental_get_compiler_ir( + random_ops.random_uniform([1, 3, 4, 3]))() + self.assertFilecheck( + hlo, r""" + CHECK: operand_layout_constraints={f32[1,3,2,2]{3,2,1,0}} + """) + + +if __name__ == '__main__': + ops.enable_eager_execution() + googletest.main() diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..e2d06a863f0320dc8fb56775aa38812957628c29 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util.cc @@ -0,0 +1,139 @@ +/* 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/literal_util.h" + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/common_runtime/dma_helper.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tsl/platform/errors.h" + +namespace tensorflow { + +absl::Status HostTensorToBorrowingLiteral(const Tensor& host_tensor, + xla::BorrowingLiteral* literal) { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor.dtype(), + host_tensor.shape(), &xla_shape)); + return HostTensorToBorrowingLiteral(xla_shape, host_tensor, literal); +} + +absl::Status HostTensorToBorrowingLiteral(const xla::Shape& xla_shape, + const Tensor& host_tensor, + xla::BorrowingLiteral* literal) { + const auto& tshape = host_tensor.shape(); + TF_RET_CHECK(tshape.IsFullyDefined() && + tshape.dims() == xla_shape.dimensions().size() && + tshape.dim_sizes() == xla_shape.dimensions()) + << "Provided xla::Shape must have the same dims as the Tensor shape."; + *literal = xla::BorrowingLiteral( + static_cast(DMAHelper::base(&host_tensor)), xla_shape); + return absl::OkStatus(); +} + +absl::StatusOr HostTensorToLiteral(const Tensor& host_tensor) { + xla::BorrowingLiteral literal; + TF_RETURN_IF_ERROR(HostTensorToBorrowingLiteral(host_tensor, &literal)); + return literal.Clone(); +} + +absl::Status HostTensorToMutableBorrowingLiteral( + Tensor* host_tensor, xla::MutableBorrowingLiteral* literal) { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(host_tensor->dtype(), + host_tensor->shape(), &xla_shape)); + return HostTensorToMutableBorrowingLiteral(xla_shape, host_tensor, literal); +} + +absl::Status HostTensorToMutableBorrowingLiteral( + const xla::Shape& xla_shape, Tensor* host_tensor, + xla::MutableBorrowingLiteral* literal) { + *literal = xla::MutableBorrowingLiteral( + static_cast(DMAHelper::base(host_tensor)), xla_shape); + + return absl::OkStatus(); +} + +absl::Status HostTensorsToBorrowingLiteralTuple( + absl::Span host_tensors, xla::BorrowingLiteral* literal) { + std::vector buf_ptrs; + buf_ptrs.reserve(host_tensors.size()); + std::vector tensor_shapes(host_tensors.size()); + + for (int i = 0, end = host_tensors.size(); i < end; i++) { + // Validate runtime shapes and fail if it doesn't match the contract. + const Tensor* tensor = &host_tensors[i]; + buf_ptrs.emplace_back(static_cast(DMAHelper::base(tensor))); + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(tensor->dtype(), tensor->shape(), + &tensor_shapes[i])); + } + + *literal = xla::BorrowingLiteral( + buf_ptrs, xla::ShapeUtil::MakeTupleShape(tensor_shapes)); + + return absl::OkStatus(); +} + +absl::Status CopyLiteralToHostTensor(const xla::LiteralSlice& literal, + Tensor* host_tensor) { + TF_RET_CHECK(literal.shape().IsArray() && + xla::ShapeUtil::ElementsIn(literal.shape()) == + host_tensor->NumElements()); + xla::PrimitiveType primitive_type; + TF_RETURN_IF_ERROR( + DataTypeToPrimitiveType(host_tensor->dtype(), &primitive_type)); + if (literal.shape().element_type() != primitive_type) { + return absl::InvalidArgumentError(absl::StrCat( + "Cannot convert literal of type ", + xla::PrimitiveType_Name(literal.shape().element_type()), + " to tensor of type ", DataTypeString(host_tensor->dtype()))); + } + size_t total_bytes = host_tensor->TotalBytes(); + if (total_bytes > 0) { + const void* src_ptr = literal.untyped_data(); + void* dst_ptr = DMAHelper::base(host_tensor); + memcpy(dst_ptr, src_ptr, total_bytes); + } + return absl::OkStatus(); +} + +absl::Status LiteralToHostTensor(const xla::LiteralSlice& literal, + DataType target_type, Tensor* host_tensor) { + TensorShape shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(literal.shape(), &shape)); + *host_tensor = Tensor(target_type, shape); + return CopyLiteralToHostTensor(literal, host_tensor); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util.h new file mode 100644 index 0000000000000000000000000000000000000000..7b82e45e986c9a2a88cc4a0965e84aeab7a2c29b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util.h @@ -0,0 +1,82 @@ +/* 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. +==============================================================================*/ + +// Utilities for working with XLA Literals. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_LITERAL_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_LITERAL_UTIL_H_ + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Returns a BorrowingLiteral that utilizes the same underlying buffer owned by +// 'host_tensor'. +absl::Status HostTensorToBorrowingLiteral(const Tensor& host_tensor, + xla::BorrowingLiteral* literal); +// Similar as above, except the literal shape is explicitly provided and used +// instead of obtaining it from the 'host_tensor'. The provided literal shape +// 'xla_shape' must be compatible with the shape of 'host_tensor'. +absl::Status HostTensorToBorrowingLiteral(const xla::Shape& xla_shape, + const Tensor& host_tensor, + xla::BorrowingLiteral* literal); + +// Returns a Literal with the contents of 'host_tensor', backed by its own +// storage (i.e., not reusing 'host_tensor's buffers.) +absl::StatusOr HostTensorToLiteral(const Tensor& host_tensor); + +// Returns a MutableBorrowingLiteral that utilizes the same underlying buffer +// owned by 'host_tensor', but is mutable via the xla::Literal methods. +absl::Status HostTensorToMutableBorrowingLiteral( + Tensor* host_tensor, xla::MutableBorrowingLiteral* literal); +// Similar as above, except the literal shape is explicitly provided and used +// instead of obtaining it from the 'host_tensor'. The provided literal shape +// 'xla_shape' must be compatible with the shape of 'host_tensor'. +absl::Status HostTensorToMutableBorrowingLiteral( + const xla::Shape& xla_shape, Tensor* host_tensor, + xla::MutableBorrowingLiteral* literal); + +// Returns a BorrowingLiteral tuple that utilizes the same underlying buffers +// owned by 'host_tensors'. +absl::Status HostTensorsToBorrowingLiteralTuple( + absl::Span host_tensors, xla::BorrowingLiteral* literal); + +// Copies 'literal' to freshly allocated 'host_tensor', which is allocated of +// type . +// Fails if the literal's primitive type != +// DataTypeToPrimitiveType(target_type). Note that is not +// derivable from the type of , because multiple tensorflow types map +// to the same XLA type (e.g. INT32 and QINT32 both map to INT32 in +// XLA). +absl::Status LiteralToHostTensor(const xla::LiteralSlice& literal, + DataType target_type, Tensor* host_tensor); + +// Copies the contents of 'literal' to a previously allocated tensor +// 'host_tensor'. The tensor and the literal must have the same number of +// elements and the same type. +absl::Status CopyLiteralToHostTensor(const xla::LiteralSlice& literal, + Tensor* host_tensor); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_LITERAL_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..193dfa79edd9d98976cea05ffccbaa4c893cbb69 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/literal_util_test.cc @@ -0,0 +1,93 @@ +/* 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/literal_util.h" + +#include +#include +#include + +#include +#include "absl/types/span.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/tsl/protobuf/error_codes.pb.h" +#include "tensorflow/core/framework/numeric_types.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/platform/test.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +TEST(LiteralUtil, LiteralToHostTensor) { + // int64 literal can only be converted to an int64 host tensor. + std::vector int64_values = {1, 2, 3}; + xla::Literal int64_values_literal = + xla::LiteralUtil::CreateR1(absl::Span(int64_values)); + Tensor host_tensor; + EXPECT_EQ("Cannot convert literal of type S64 to tensor of type int32", + LiteralToHostTensor(int64_values_literal, DT_INT32, &host_tensor) + .message()); + EXPECT_EQ("Cannot convert literal of type S64 to tensor of type qint32", + LiteralToHostTensor(int64_values_literal, DT_QINT32, &host_tensor) + .message()); + EXPECT_TRUE( + LiteralToHostTensor(int64_values_literal, DT_INT64, &host_tensor).ok()); + test::ExpectTensorEqual(host_tensor, + test::AsTensor(int64_values)); +} + +template +using LiteralUtilTest = ::testing::Test; +using Types = + ::testing::Types, std::pair, + std::pair, std::pair, + std::pair>; + +TYPED_TEST_SUITE(LiteralUtilTest, Types); + +TYPED_TEST(LiteralUtilTest, LiteralToQuantizedHostTensor) { + using int_type = typename TypeParam::first_type; + using qint_type = typename TypeParam::second_type; + + Tensor host_tensor; + std::vector int_values = {10, 11}; + xla::Literal int_values_literal = + xla::LiteralUtil::CreateR1(absl::Span(int_values)); + EXPECT_TRUE(LiteralToHostTensor(int_values_literal, + DataTypeToEnum::value, &host_tensor) + .ok()); + test::ExpectTensorEqual(host_tensor, + test::AsTensor(int_values)); + + EXPECT_TRUE(LiteralToHostTensor(int_values_literal, + DataTypeToEnum::value, + &host_tensor) + .ok()); + std::vector qint_values = {10, 11}; + test::ExpectTensorEqual(host_tensor, + test::AsTensor(qint_values)); + + EXPECT_EQ( + error::INVALID_ARGUMENT, + LiteralToHostTensor(int_values_literal, DT_INT64, &host_tensor).code()); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass.cc new file mode 100644 index 0000000000000000000000000000000000000000..15b52af087ae20cb22ac1b856f208d56326a1645 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass.cc @@ -0,0 +1,418 @@ +/* Copyright 2019 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/mlir_bridge_pass.h" + +#include +#include + +#include "tensorflow/compiler/mlir/tf2xla/mlir_bridge_rollout_policy.h" +#include "absl/algorithm/container.h" +#include "absl/base/call_once.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "llvm/Support/LogicalResult.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/Support/WalkResult.h" // from @llvm-project +#include "tensorflow/compiler/mlir/mlir_graph_optimization_pass.h" +#include "tensorflow/compiler/mlir/tensorflow/ir/tf_structs.h" +#include "tensorflow/compiler/mlir/tensorflow/transforms/host_runtime/lower_cluster_to_runtime_ops.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/cluster_tf.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/tf_dialect_to_executor.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v2/cluster_tf.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v2/tf_dialect_to_executor.h" +#include "tensorflow/compiler/mlir/tf2xla/internal/mlir_bridge_pass_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla_defs.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/tsl/framework/device_type.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/logging.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/optimization_registry.h" +#include "tensorflow/core/framework/device.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/metrics.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/monitoring/gauge.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/public/session_options.h" +#include "tensorflow/core/tpu/tpu_defs.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace tensorflow { + +auto* mlir_bridge_gauge_v1 = monitoring::Gauge::New( + "/tensorflow/config/experimental/enable_mlir_bridge_gauge_v1", + "Tracks usage of the MLIR-based TF2XLA bridge among TF1 models"); +auto* mlir_bridge_gauge_v2 = monitoring::Gauge::New( + "/tensorflow/config/experimental/enable_mlir_bridge_gauge_v2", + "Tracks usage of the MLIR-based TF2XLA bridge among TF2 models"); + +namespace { + +using ::mlir::ModuleOp; + +bool HasTPUDevice(const DeviceSet& device_set) { + for (const Device* device : device_set.devices()) { + if (!device) continue; + const DeviceNameUtils::ParsedName& name = device->parsed_name(); + if (name.has_type && name.type == "TPU") return true; + } + return false; +} + +bool HasTPUDevice(mlir::ModuleOp module) { + mlir::TF::RuntimeDevices devices; + if (failed(GetDevicesFromOp(module.getOperation(), &devices))) return false; + return absl::c_any_of( + devices.device_names(), + [](const tensorflow::DeviceNameUtils::ParsedName& device) { + return device.has_type && device.type == kTpuDevice; + }); +} + +bool HasDevice(mlir::ModuleOp module) { + mlir::TF::RuntimeDevices devices; + if (failed(GetDevicesFromOp(module.getOperation(), &devices))) return false; + return !devices.device_names().empty(); +} + +// V1 Compat Bridge extracts out a program into a submodule and runs clustering +// only on the submodule. +absl::Status RunLowerToRuntimeOpsOnSubmodule(ModuleOp parent_module, + bool is_in_fallback_enabled_mode) { + int num_submodules = 0; + absl::Status runtime_lowering_status; + parent_module.walk([&](ModuleOp submodule) { + if (submodule == parent_module) return mlir::WalkResult::advance(); + num_submodules++; + runtime_lowering_status = + tensorflow::tfrt_compiler::RunLowerClusterToRuntimeOpsPassPipeline( + submodule, tsl::DeviceType(DEVICE_TPU_XLA_JIT)); + if (num_submodules > 1) { + return mlir::WalkResult::interrupt(); + } + + return mlir::WalkResult::advance(); + }); + + if (num_submodules > 1) { + return absl::InternalError( + "Lower to runtime has more than one submodule. Erroring out."); + } + + return runtime_lowering_status; +} + +} // namespace + +// Analyzes the user requested policy as well as the contents of the graph and +// function_library_definition to determine whether the MLIR Bridge should be +// run. +// +// If the user explicitly requests the bridge be enabled or disabled, this +// function will respect the request. If the user does not explicitly request +// enabled or disabled, it will decide whether or not to run the bridge. +// +// The config_proto param is a required input for all TF1 graphs but it is +// redundant for TF2 graphs. +MlirOptimizationPassState GetPassStateImpl( + bool is_supported_by_replicated_brige, const ConfigProto& config_proto, + const Graph& graph, const FunctionLibraryDefinition& function_library) { + // Skip MLIR TF/XLA Bridge if no XLA-compilable ops are found. + if (!is_supported_by_replicated_brige && + !IsSupportedByNonReplicatedBridge(graph, &function_library)) { + VLOG(3) << "Skipping MLIR Bridge, graph is not qualified to run the bridge"; + return MlirOptimizationPassState::Disabled; + } + + // GetMlirBridgeRolloutPolicy will analyze a TPU graph if users have not + // explicltly requested a policy. + MlirBridgeRolloutPolicy policy = GetMlirBridgeRolloutPolicy( + graph, &function_library, config_proto, is_supported_by_replicated_brige, + /*is_v1_compat=*/false, /*record_stats=*/false); + // GetPassState is called once before MlirBridgePass starts, and the pass + // gets skipped if it is disabled. Log such cases in this function. The cases + // where the pass is enabled will only be logged during their execution to + // prevent them from being counted twice. + switch (policy) { + case MlirBridgeRolloutPolicy::kEnabledByUser: + return MlirOptimizationPassState::Enabled; + case MlirBridgeRolloutPolicy::kEnabledAfterGraphAnalysis: + return MlirOptimizationPassState::FallbackEnabled; + case MlirBridgeRolloutPolicy::kDisabledByUser: { + VLOG(1) << "Skipping MLIR " + << (is_supported_by_replicated_brige ? "Replicated" + : "Non-replicated") + << " Bridge, disabled by user. " + "The fallback will evaluate."; + metrics::UpdateTfMlirBridgeFirstPhaseCounter( + /*bridge_type*/ is_supported_by_replicated_brige + ? mlir::TF::kMlirPh1BridgeCounterReplicated + : mlir::TF::kMlirPh1BridgeCounterNonReplicated, + /*bridge_version*/ mlir::TF::kMlirPh1BridgeCounterV2, + /*device_type*/ + is_supported_by_replicated_brige + ? mlir::TF::kMlirPh1BridgeCounterTpu + : mlir::TF::kMlirPh1BridgeCounterNonTpu, + /*fallback_enabled*/ true, + /*result*/ "disabled_by_user"); + return MlirOptimizationPassState::Disabled; + } + case MlirBridgeRolloutPolicy::kDisabledAfterGraphAnalysis: + // Graph analysis only runs on TPU graph. + VLOG(1) << "Skipping MLIR TPU Bridge, disabled because the " + "graph has unsupported features. The fallback will evaluate."; + metrics::UpdateTfMlirBridgeFirstPhaseCounter( + /*bridge_type*/ mlir::TF::kMlirPh1BridgeCounterReplicated, + /*bridge_version*/ mlir::TF::kMlirPh1BridgeCounterV2, + /*device_type*/ mlir::TF::kMlirPh1BridgeCounterTpu, + /*fallback_enabled*/ true, + /*result*/ "invalid_graph"); + // For Invalid Graph Analysis we need to log here because Run will not + // be called. + LogGraphFeatures(graph, &function_library, config_proto, + /*is_v1_compat=*/false); + return MlirOptimizationPassState::Disabled; + } +} + +MlirOptimizationPassState MlirBridgePass::GetPassState( + const DeviceSet* device_set, const ConfigProto& config_proto, + const Graph& graph, + const FunctionLibraryDefinition& function_library) const { + // While we do not use device type information to choose which pass pipeline + // to execute, it's needed for successful execution. + if (!device_set) { + // This is not expected in practice. + VLOG(1) << "Device set is empty!"; + return MlirOptimizationPassState::Disabled; + } + + // TODO(b/328084279): when MlirBridgePass::GetPassState() returns + // MlirOptimizationPassState::FallbackEnabled or + // MlirOptimizationPassState::Enabled, Tensorflow imports a Graph to an + // MLIR module, calls MlirBridgePass::Run(), and exports the MLIR module to a + // Graph. The Graph->MLIR module->Graph round trip will not happen if + // MlirOptimizationPassState::Disabled is returned. Some input graphs with a + // TPU device in device_set yet without replication depends on the round + // trip, which does not always produce the same Graph. Call + // HasTPUDevice(*device_set) to ensure such graps work. Note + // MlirBridgePass::Run() will still reject such graphs that they do not go + // through the Phase 1 Bridge. + return GetPassStateImpl( + /*is_supported_by_replicated_brige*/ IsSupportedByReplicatedBridge( + graph, &function_library) || + HasTPUDevice(*device_set), + config_proto, graph, function_library); +} + +// This runs the first phase of the "bridge", transforming the graph in a form +// that can be executed with delegation of some computations to an accelerator. +// This builds on the model of XLA where a subset of the graph is encapsulated +// and attached to a "compile" operation, whose result is fed to an "execute" +// operation. The kernel for these operations is responsible to lower the +// encapsulated graph to a particular device. +absl::Status MlirBridgePass::Run( + const std::string& function_name, const ConfigProto& config_proto, + mlir::ModuleOp module, const Graph& graph, + const FunctionLibraryDefinition& function_library) { + static absl::once_flag flag; + absl::call_once(flag, tsl::UpdateLogVerbosityIfDefined, + "TF_DEBUG_LOG_VERBOSITY"); + + if (!HasDevice(module)) { + LOG(INFO) << "No devices in " << function_name << "\n"; + return absl::OkStatus(); + } + + if (HasTPUPartitionedCallOpInModule(module)) { + VLOG(1) << "Skipping MLIR TF2XLA Bridge. This is an inference graph, " + "Session V1 Bridge should be used during execution of " + "TPUPartitionedCall."; + return absl::OkStatus(); + } + + // TODO(b/241853328): Add caching of pass state and call logging/metrics + // related to graph analysis from here. + bool is_supported_by_replicated_brige = IsSupportedByReplicatedBridge(module); + auto pass_state = GetPassStateImpl(is_supported_by_replicated_brige, + config_proto, graph, function_library); + + if (pass_state == MlirOptimizationPassState::Disabled) { + // GetPassState is called before run() and run() will only be called if the + // pass is not disabled. However, the graph may have been updated between + // when the pass state was originally calculated and now, so this check is + // required to reflect any possible changes. + VLOG(1) << "MlirBridgePass is disabled and will not run."; + return absl::OkStatus(); + } + + bool fallback_enabled = false; + if (is_supported_by_replicated_brige) { + if (pass_state == MlirOptimizationPassState::FallbackEnabled) { + // TODO (b/241853328) Consider moving logging if caching for graph + // analysis or GetPassState is added + LogGraphFeatures(graph, &function_library, config_proto, + /*is_v1_compat=*/false); + fallback_enabled = true; + } + VLOG(1) << "Running MLIR Replicated Bridge"; + mlir_bridge_gauge_v2->GetCell()->Set(true); + + TF_RETURN_IF_ERROR( + tensorflow::tf2xla::v2::RunFunctionTf2xlaClusteringBridge( + module, /*is_supported_by_replicated_brige*/ true, fallback_enabled, + function_name)); + + TF_RETURN_IF_ERROR( + tensorflow::tfrt_compiler::RunLowerClusterToRuntimeOpsPassPipeline( + module, tsl::DeviceType(DEVICE_TPU_XLA_JIT), function_name)); + } else { + VLOG(1) << "Running MLIR Non-replicated Bridge"; + TF_RETURN_IF_ERROR( + tensorflow::tf2xla::v2::RunFunctionTf2xlaClusteringBridge( + module, /*is_supported_by_replicated_brige*/ false, + fallback_enabled, function_name)); + + TF_RETURN_IF_ERROR( + tensorflow::tfrt_compiler::RunLowerClusterToRuntimeOpsPassPipeline( + module, tsl::DeviceType(DEVICE_GPU_XLA_JIT), function_name)); + } + + return tensorflow::tf2xla::v2::ExportFromTensorflowDialectToExecutor( + module, function_name); +} + +MlirOptimizationPassState MlirBridgeV1CompatPass::GetPassState( + const DeviceSet* device_set, const ConfigProto& config_proto, + const Graph& graph, + const FunctionLibraryDefinition& function_library) const { + // Skip MLIR Bridge if no potential XLA clusters are found. + if (!IsSupportedByReplicatedBridge(graph, &function_library)) + return MlirOptimizationPassState::Disabled; + MlirBridgeRolloutPolicy policy = GetMlirBridgeRolloutPolicy( + graph, /*function_library=*/&function_library, config_proto, + /*is_supported_by_replicated_brige*/ true, + /*is_v1_compat=*/true, + /*record_stats=*/false); + switch (policy) { + case MlirBridgeRolloutPolicy::kEnabledByUser: + return MlirOptimizationPassState::Enabled; + case MlirBridgeRolloutPolicy::kEnabledAfterGraphAnalysis: + return MlirOptimizationPassState::FallbackEnabled; + case MlirBridgeRolloutPolicy::kDisabledByUser: + VLOG(1) << "Skipping MLIR Replicated Bridge V1 Compat, MLIR Replicated " + "bridge disabled " + "by user. Fallback will evaluate."; + metrics::UpdateTfMlirBridgeFirstPhaseCounter( + /*bridge_type*/ mlir::TF::kMlirPh1BridgeCounterReplicated, + /*bridge_version*/ mlir::TF::kMlirPh1BridgeCounterV1, + /*device_type*/ mlir::TF::kMlirPh1BridgeCounterTpu, + /*fallback_enabled*/ true, + /*result*/ "disabled_by_user"); + return MlirOptimizationPassState::Disabled; + case MlirBridgeRolloutPolicy::kDisabledAfterGraphAnalysis: + VLOG(1) << "Skipping MLIR Replicated Bridge V1 Compat, MLIR Replicated " + "bridge disabled " + "because graph has unsupported features. Old bridge will " + "evaluate."; + metrics::UpdateTfMlirBridgeFirstPhaseCounter( + /*bridge_type*/ mlir::TF::kMlirPh1BridgeCounterReplicated, + /*bridge_version*/ mlir::TF::kMlirPh1BridgeCounterV1, + /*device_type*/ mlir::TF::kMlirPh1BridgeCounterTpu, + /*fallback_enabled*/ true, + /*result*/ "invalid_graph"); + // For Invalid Graph Analysis we need to log here because Run will not be + // called. + LogGraphFeatures(graph, &function_library, config_proto, + /*is_v1_compat=*/true); + return MlirOptimizationPassState::Disabled; + } +} + +absl::Status MlirBridgeV1CompatPass::Run( + const GraphOptimizationPassOptions& options, mlir::ModuleOp module) { + static absl::once_flag flag; + absl::call_once(flag, tsl::UpdateLogVerbosityIfDefined, + "TF_DEBUG_LOG_VERBOSITY"); + + // Skip function graphs as MlirBridgePass will be used instead. + if (options.is_function_graph) return absl::OkStatus(); + + // Skip MLIR Replicated Bridge if no eligible ops found. + if (!IsSupportedByReplicatedBridge(module)) { + VLOG(1) << "Skipping MLIR Replicated Bridge V1 Compat, no eligible ops " + "found"; + return absl::OkStatus(); + } + + MlirOptimizationPassState pass_state = + GetPassState(/*device_set=*/nullptr, options.session_options->config, + **options.graph, *options.flib_def); + + // Set device_set to nullptr here as the device specific checks are performed + // based on the devices in the module. + if (pass_state == MlirOptimizationPassState::Disabled) { + // GetPassState is called before run() and run() will only be called if the + // pass is not disabled. However, the graph may have been updated between + // when the pass state was originally calculated and now, so this check is + // required to reflect any possible changes. + VLOG(1) << "Skipping MLIR Replicated Bridge V1 Compat, session flag not " + "enabled"; + mlir_bridge_gauge_v1->GetCell()->Set(false); + return absl::OkStatus(); + } + + // 1) If the MLIR module contains a TPUPartitionedCall, we skip here + // 2) When TPUPartitionedCall starts executing, it calls MLIR bridge as a + // part of PRE_PLACEMENT optimization + // 3) This MLIR bridge version is V1 Compat + if (HasTPUPartitionedCallOpInModule(module)) { + VLOG(1) << "Skipping MLIR Replicated Bridge V1 Compat. This is an " + "inference graph, V1 " + "Compat should be used during execution of TPUPartitionedCall."; + return absl::OkStatus(); + } + + bool fallback_enabled = false; + if (pass_state == MlirOptimizationPassState::FallbackEnabled) { + // TODO (b/241853328) Consider moving logging if caching for graph analysis + // or GetPassState is added + LogGraphFeatures(**options.graph, options.flib_def, + options.session_options->config, + /*is_v1_compat=*/true); + fallback_enabled = true; + } + + VLOG(1) << "Running MLIR Replicated Bridge V1 Compat"; + mlir_bridge_gauge_v1->GetCell()->Set(true); + TF_RETURN_IF_ERROR(tensorflow::tf2xla::v1::RunSessionTf2xlaClusteringBridge( + module, fallback_enabled)); + + auto lower_cluster_to_runtime_ops_pass_pipeline = + RunLowerToRuntimeOpsOnSubmodule(module, fallback_enabled); + if (!lower_cluster_to_runtime_ops_pass_pipeline.ok()) { + VLOG(1) << "Error while lowering cluster to runtime ops: " + << lower_cluster_to_runtime_ops_pass_pipeline; + return lower_cluster_to_runtime_ops_pass_pipeline; + } + + return tensorflow::tf2xla::v1::ExportFromTensorflowDialectToExecutor(module); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass.h new file mode 100644 index 0000000000000000000000000000000000000000..04efaa7e908236f98f9e0024f95acd971aa37f00 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass.h @@ -0,0 +1,76 @@ +/* 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_MLIR_BRIDGE_PASS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_MLIR_BRIDGE_PASS_H_ + +#include + +#include "tensorflow/compiler/mlir/tf2xla/mlir_bridge_rollout_policy.h" +#include "absl/status/status.h" +#include "llvm/ADT/StringRef.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/compiler/mlir/mlir_graph_optimization_pass.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/optimization_registry.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/protobuf/config.pb.h" + +namespace tensorflow { + +// This pass uses MLIR to implement all the conversion steps to target XLA from +// a TensorFlow Function Graph. It is meant to expose a very limited set of +// functionalities during the bring-up of MLIR-based bridge. +class MlirBridgePass : public MlirOptimizationPass { + public: + llvm::StringRef name() const override { return "bridge"; } + + MlirOptimizationPassState GetPassState( + const DeviceSet* device_set, const ConfigProto& config_proto, + const Graph& graph, + const FunctionLibraryDefinition& function_library) const override; + + // This should be used as a thin mapper around mlir::ModulePass::runOnModule + // API integrated with the Tensorflow runtime. + absl::Status Run(const std::string& function_name, + const ConfigProto& config_proto, mlir::ModuleOp module, + const Graph& graph, + const FunctionLibraryDefinition& function_library) override; +}; + +// This pass uses MLIR to implement all the conversion steps to target XLA from +// a TensorFlow V1 Graph. It is meant to expose a very limited set of +// functionalities during the bring-up of MLIR-based bridge. +class MlirBridgeV1CompatPass : public MlirV1CompatOptimizationPass { + public: + llvm::StringRef name() const override { return "bridge"; } + + MlirOptimizationPassState GetPassState( + const DeviceSet* device_set, const ConfigProto& config_proto, + const Graph& graph, + const FunctionLibraryDefinition& function_library) const override; + + // This should be used as a thin mapper around mlir::ModulePass::runOnModule + // API integrated with the Tensorflow runtime. + absl::Status Run(const GraphOptimizationPassOptions& options, + mlir::ModuleOp module) override; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_MLIR_BRIDGE_PASS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass_registration.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass_registration.cc new file mode 100644 index 0000000000000000000000000000000000000000..b2b981701fa4d1e5033d825d2a9a055b6c089b8d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_bridge_pass_registration.cc @@ -0,0 +1,34 @@ +/* Copyright 2019 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 + +#include "tensorflow/compiler/mlir/mlir_graph_optimization_pass.h" +#include "tensorflow/compiler/tf2xla/mlir_bridge_pass.h" + +namespace tensorflow { +namespace { +constexpr int kMlirBridgePriority = 10; +} + +static mlir_pass_registration::MlirOptimizationPassRegistration + register_mlir_bridge_pass(kMlirBridgePriority, + std::make_unique()); + +static mlir_pass_registration::MlirV1CompatOptimizationPassRegistration + register_v1_compat_mlir_bridge_pass( + std::make_unique()); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_tf2xla.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_tf2xla.cc new file mode 100644 index 0000000000000000000000000000000000000000..fd7c52cf4a11731544d8a0a2e247fa2b1fbcedc7 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_tf2xla.cc @@ -0,0 +1,200 @@ +/* Copyright 2019 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 +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/log/log.h" +#include "absl/log/vlog_is_on.h" +#include "absl/status/status.h" +#include "absl/strings/string_view.h" +#include "mlir/IR/BuiltinOps.h" // from @llvm-project +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "mlir/IR/OwningOpRef.h" // from @llvm-project +#include "tensorflow/compiler/mlir/tensorflow/transforms/bridge.h" +#include "tensorflow/compiler/mlir/tensorflow/translate/mlir_roundtrip_flags.h" +#include "tensorflow/compiler/mlir/tensorflow/translate/tools/parsers.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/device_util.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/import_utils.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/compile_mlir_util.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v2/graph_to_tf_executor.h" +#include "tensorflow/compiler/tf2xla/tf2xla.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/common_runtime/device_set.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/framework/device.h" +#include "tensorflow/core/framework/device_attributes.pb.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/graph_debug_info.pb.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { + +namespace { + +// A fake device to simulate the presence of a CPU. +class FakeDevice : public Device { + public: + explicit FakeDevice(const DeviceAttributes& device_attributes) + : Device(nullptr, device_attributes) {} + + absl::Status Sync() override { + return absl::UnimplementedError("FakeDevice::Sync()"); + } +}; + +// Translates the graph input information from tf2xla:::Config to +// GraphImportConfig. +absl::Status ConvertInputInfo( + const tf2xla::Config& config, + const std::unordered_map& feed_name_remap, + GraphImportConfig* specs) { + std::vector array_names; + std::vector data_types; + std::vector>> shapes; + for (const tf2xla::Feed& feed : config.feed()) { + std::string place_holder_name = + feed_name_remap.at(TensorIdToString(feed.id())); + array_names.push_back(place_holder_name); + data_types.push_back( + feed.type() == DT_INVALID ? "" : DataType_Name(feed.type())); + if (feed.shape().unknown_rank()) { + shapes.push_back(std::nullopt); + continue; + } + std::vector dims; + dims.reserve(feed.shape().dim_size()); + absl::c_for_each(feed.shape().dim(), [&](const TensorShapeProto::Dim d) { + dims.push_back(d.size()); + }); + shapes.push_back(dims); + } + + return ParseInputArrayInfo(array_names, data_types, shapes, &specs->inputs); +} + +// Translates the graph output information from tf2xla:::Config to +// GraphImportConfig. +absl::Status ConvertOutputInfo(const tf2xla::Config& config, + GraphImportConfig* specs) { + std::vector array_names; + for (const tf2xla::Fetch& fetch : config.fetch()) { + array_names.push_back(fetch.id().node_name()); + } + + return ParseOutputArrayInfo(array_names, &specs->outputs); +} + +} // namespace + +absl::Status ConvertGraphDefToXlaViaMlir( + GraphDef graph_def, const tf2xla::Config& config, + xla::XlaComputation* computation, absl::string_view debug_info_filename, + absl::string_view debug_info_path_begin_marker) { + // AddPlaceholdersForFeeds prepares for PruneGraphDefInto and serves two + // purposes: (1) It creates a placeholder node for each feed, so that + // PruneGraphDefInfo can prune away the node containing the feed. (2) It + // is also a workaround for b/149029125. It replaces a feed representation + // with a placeholder node that contains a single output. + FunctionLibraryDefinition flib_def(OpRegistry::Global(), graph_def.library()); + std::unique_ptr graph(new Graph(flib_def)); + std::unordered_map feed_name_remap; + TF_RETURN_IF_ERROR(AddPlaceholdersForFeeds(config, graph->op_registry(), + &feed_name_remap, &graph_def)); + + // TODO(b/149024678): remove this workaround after the ticket is fixed. + // Prune the GraphDef because MLIR importer doesn't allow unknown ops in + // graph nodes even the nodes are not needed for computing the outputs. + GraphDef pruned_graph_def; + TF_RETURN_IF_ERROR(PruneGraphDefInto(config, graph_def, &pruned_graph_def)); + + GraphImportConfig specs; + specs.prune_unused_nodes = false; + specs.convert_legacy_fed_inputs = false; + specs.graph_as_function = false; + specs.upgrade_legacy = true; + TF_RETURN_IF_ERROR(ConvertInputInfo(config, feed_name_remap, &specs)); + TF_RETURN_IF_ERROR(ConvertOutputInfo(config, &specs)); + + GraphDebugInfo debug_info; + if (!debug_info_filename.empty()) { + TF_RETURN_IF_ERROR(LoadProtoFromFile(debug_info_filename, &debug_info)); + + if (!debug_info_path_begin_marker.empty()) { + for (size_t i = 0, e = debug_info.files_size(); i < e; ++i) { + std::string* file_name = debug_info.mutable_files(i); + size_t location = + file_name->rfind(std::string(debug_info_path_begin_marker)); + if (location != std::string::npos) { + *file_name = file_name->substr(location + + debug_info_path_begin_marker.length()); + } + } + } + } + + mlir::MLIRContext context; + GraphConstructorOptions options; + options.allow_internal_ops = true; + options.add_default_attributes = true; + options.upgrade_legacy = specs.upgrade_legacy; + Graph final_graph(OpRegistry::Global()); + TF_RETURN_IF_ERROR( + ConvertGraphDefToGraph(options, pruned_graph_def, &final_graph)); + TF_ASSIGN_OR_RETURN( + mlir::OwningOpRef module, + tf2xla::v2::ConvertGraphToTfExecutor( + final_graph, debug_info, final_graph.flib_def(), specs, &context)); + + // Construct a CPU device and add the device to the operations. + DeviceSet device_set; + DeviceAttributes attr; + attr.set_name("/job:localhost/replica:0/task:0/device:CPU:0"); + attr.set_device_type(DeviceType("CPU").type()); + FakeDevice device(attr); + device_set.AddDevice(&device); + AddDevicesToOp(*module, &device_set); + + TF_RETURN_IF_ERROR(mlir::TF::RunBridgeWithStandardPipeline( + *module, /*enable_logging=*/VLOG_IS_ON(1), /*enable_inliner=*/true)); + + // Convert the MLIR module to XLA computation. If the input graph can't be + // lowered down to a single graph node with a single island by the previous + // step, this step will return an error. + return ConvertMLIRToXlaComputation( + *module, /*device_type=*/"XLA_CPU_JIT", computation, + /*use_tuple_args=*/false, /*prefer_tf2xla=*/false, + /*return_tuple=*/true); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.cc new file mode 100644 index 0000000000000000000000000000000000000000..fd9324dd094b3d0ac7d3ea29a78c6a5cc282424f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.cc @@ -0,0 +1,193 @@ +/* Copyright 2021 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/mlir_xla_op_kernel.h" + +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "llvm/ADT/DenseSet.h" +#include "llvm/ADT/SmallVector.h" +#include "mlir/IR/MLIRContext.h" // from @llvm-project +#include "tensorflow/compiler/jit/xla_compile_util.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/compile_mlir_util.h" +#include "tensorflow/compiler/mlir/utils/array_container_utils.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/device.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/op_requires.h" +#include "tensorflow/core/framework/resource_base.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/refcount.h" +#include "tensorflow/core/platform/status.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { + +namespace { + +class MLIRContextResource : public ResourceBase { + public: + static constexpr const char* kDefaultResourceName = + "mlir-xla-op-cached-context"; + + static absl::Status Create(MLIRContextResource** resource) { + *resource = new MLIRContextResource(); + return absl::OkStatus(); + } + mlir::MLIRContext* GetContext() { return &mlir_ctx_; } + std::string DebugString() const override { + return "MlirXlaOpKernel MLIRContext resource"; + } + + private: + // Since this kernel implements lowering for a single TF operation, we + // disable MLIR threading for efficiency purpose (avoid starting a large + // number of threads eagerly). + MLIRContextResource() : mlir_ctx_(mlir::MLIRContext::Threading::DISABLED) {} + mlir::MLIRContext mlir_ctx_; +}; + +} // namespace + +absl::Status MlirXlaOpKernel::ContextToXlaArgs( + XlaOpKernelContext* ctx, std::vector& xla_args) { + // Collect arguments that are registered as CompileTimeConstantInput. + std::vector registered_consts_vec; + TF_RETURN_IF_ERROR(tensorflow::XlaOpRegistry::CompileTimeConstantInputs( + *this, ®istered_consts_vec)); + llvm::SmallDenseSet registered_consts; + registered_consts.insert(registered_consts_vec.begin(), + registered_consts_vec.end()); + + int num_inputs = ctx->num_inputs(); + xla_args.reserve(num_inputs); + for (int i = 0; i < num_inputs; ++i) { + // TODO(b/180448774): Handle kResource and kTensorList. + XlaExpression::Kind ctx_kind_i = ctx->InputExpression(i).kind(); + if (ctx_kind_i != XlaExpression::Kind::kXlaOp && + ctx_kind_i != XlaExpression::Kind::kConstant) + return absl::InvalidArgumentError( + absl::StrCat("Input ", i, " to an MlirXlaOpKernel is invalid: ", + ctx->InputExpression(i).HumanString())); + XlaCompiler::Argument arg; + arg.type = ctx->input_type(i); + arg.shape = ctx->InputXlaShape(i).value(); + arg.name = absl::StrCat("_arg", i); + if (registered_consts.count(i)) { + arg.kind = XlaCompiler::Argument::kConstant; + TF_ASSIGN_OR_RETURN(arg.constant_value, ctx->ConstantInputTensor(i)); + } else { + arg.kind = XlaCompiler::Argument::kParameter; + } + xla_args.push_back(arg); + } + return absl::OkStatus(); +} + +MlirXlaOpKernel::MlirXlaOpKernel(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + +absl::Status MlirXlaOpKernel::ConstructXlaOp(XlaOpKernelContext* ctx) { + // Create input XlaArguments. + std::vector xla_args; + TF_RETURN_IF_ERROR(ContextToXlaArgs(ctx, xla_args)); + + // Create input XlaOps. + llvm::SmallVector xla_params(ctx->num_inputs()); + for (int i = 0, end = ctx->num_inputs(); i < end; ++i) { + xla_params[i] = ctx->Input(i); + } + + // Create outputs. + std::vector result_dtypes(ctx->num_outputs()); + for (int i = 0, end = result_dtypes.size(); i < end; ++i) { + result_dtypes[i] = ctx->expected_output_dtype(i); + } + + // When there are no data-flow outputs from the node, the node is used as a + // control output by the graph to TensorflowDialect importer. + std::vector control_rets; + if (result_dtypes.empty()) { + control_rets.push_back(def().name()); + } + + // Get the context's device. + auto device = dynamic_cast(ctx->op_kernel_context()->device()); + if (!device) { + return absl::InvalidArgumentError( + "Expected the XlaOpKernelContext argument's device to have type " + "Device."); + } + + // Create a graph that wraps the kernel. + TF_ASSIGN_OR_RETURN(auto graph, + CreateSingleOpGraph(def(), xla_args, result_dtypes)); + + ResourceMgr* res_manager = ctx->op_kernel_context()->resource_manager(); + MLIRContextResource* ctx_res; + TF_RETURN_IF_ERROR(res_manager->LookupOrCreate( + res_manager->default_container(), + MLIRContextResource::kDefaultResourceName, &ctx_res, + MLIRContextResource::Create)); + core::ScopedUnref unref_ctx(ctx_res); + + // Compile the graph to HLO. + std::vector returns(1); + auto build_hlo = [&](bool unconditionally_use_output_shapes) { + return BuildHloFromGraph( + *graph, *ctx->builder(), *ctx_res->GetContext(), xla_params, returns, + unconditionally_use_output_shapes, + mlir::SpanToArrayRef(xla_args), control_rets, + device->device_type(), + *ctx->function_library()->GetFunctionLibraryDefinition()); + }; + + // Some of the operations that come through here do not know how to set their + // own output shapes (e.g. _XlaHostComputeMlir') so we may need to use the + // unconditional output shapes option. However, many graphs fail if we do it + // unconditionally so try both. + if (!build_hlo(/*unconditionally_use_output_shapes=*/false).ok()) { + // If that failed, then try again with the unconditional set true + TF_RETURN_IF_ERROR(build_hlo(/*unconditionally_use_output_shapes=*/true)); + } + + // Set context outputs. + for (int i = 0, end = returns.size(); i < end; ++i) { + ctx->SetOutput(i, returns[i]); + } + + return absl::OkStatus(); +} + +void MlirXlaOpKernel::Compile(XlaOpKernelContext* ctx) { + auto status = ConstructXlaOp(ctx); + if (!status.ok()) { + errors::AppendToMessage(&status, "Failure to legalize ", def().name(), + " using MlirXlaOpKernel in the tf2xla bridge."); + } + OP_REQUIRES_OK(ctx, status); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..322b0a898dde32c8ff4eac1744058ad16ce1b90a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/mlir_xla_op_kernel.h @@ -0,0 +1,42 @@ +/* Copyright 2021 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_MLIR_XLA_OP_KERNEL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_MLIR_XLA_OP_KERNEL_H_ + +#include "absl/status/status.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +// An XlaOpKernel that's implemented by lowering using MLIR TensorFlow to HLO +// legalization. +class MlirXlaOpKernel : public XlaOpKernel { + public: + explicit MlirXlaOpKernel(OpKernelConstruction* ctx); + + private: + absl::Status ContextToXlaArgs(XlaOpKernelContext* ctx, + std::vector& xla_args); + void Compile(XlaOpKernelContext* ctx) override; + absl::Status ConstructXlaOp(XlaOpKernelContext* ctx); +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_MLIR_XLA_OP_KERNEL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/ops/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/ops/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..97d5c8398a222d6ec2c9d04993e83cbf0e473cf4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/ops/BUILD @@ -0,0 +1,60 @@ +load("@xla//third_party/rules_python/python:py_library.bzl", "py_library") +load( + "//tensorflow:tensorflow.bzl", + "tf_custom_op_library", + "tf_gen_op_wrapper_py", +) +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//tensorflow:internal"], + licenses = ["notice"], +) + +cc_library( + name = "xla_ops", + srcs = ["xla_ops.cc"], + deps = [ + "//tensorflow/core:framework", + "//tensorflow/core:lib", + "//tensorflow/core:protos_all_cc", + "@com_google_absl//absl/algorithm:container", + "@com_google_absl//absl/container:inlined_vector", + "@com_google_absl//absl/log", + "@com_google_absl//absl/status", + "@com_google_absl//absl/strings", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/service:shape_inference", + ], + alwayslink = 1, +) + +tf_gen_op_wrapper_py( + name = "gen_xla_ops", + out = "gen_xla_ops.py", + extra_py_deps = [ + "//tensorflow/python:pywrap_tfe", + "//tensorflow/python/util:dispatch", + "//tensorflow/python/util:deprecation", + "//tensorflow/python/util:tf_export", + ], + py_lib_rule = py_library, + deps = [ + ":xla_ops", + ], +) + +tf_custom_op_library( + name = "_xla_ops.so", + srcs = [ + "xla_ops.cc", + ], + deps = [ + "@com_google_absl//absl/algorithm:container", + "@xla//xla:shape_util", + "@xla//xla:xla_data_proto_cc", + "@xla//xla/service:shape_inference", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/ops/xla_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/ops/xla_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..08255155dac09ac47901ab2066830350595cc877 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/ops/xla_ops.cc @@ -0,0 +1,1500 @@ +/* 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 +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/container/inlined_vector.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/match.h" +#include "absl/strings/str_join.h" +#include "xla/service/shape_inference.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/common_shape_fns.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/shape_inference.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" + +// Note: Most of the operators defined in this module are used by the jax2tf +// converter (see go/jax2tf for details) and are used in SavedModel produced +// by jax2tf. Hence, we need to maintain backwards compatibility for these +// operators. Please reach out to the JAX team if you want to make changes. + +namespace tensorflow { +namespace { + +// Helper shape function for operators that return an output with the same rank +// as their first input. +absl::Status UnchangedRank(shape_inference::InferenceContext* c) { + if (c->RankKnown(c->input(0))) { + c->set_output(0, c->UnknownShapeOfRank(c->Rank(c->input(0)))); + } else { + c->set_output(0, c->input(0)); + } + return absl::OkStatus(); +} + +REGISTER_OP("XlaBroadcastHelper") + .Input("lhs: T") + .Input("rhs: T") + .Input("broadcast_dims: Tindices") + .Attr("T: numbertype") + .Attr("Tindices: {int32, int64}") + .Output("lhs_output: T") + .Output("rhs_output: T") + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +Helper operator for performing XLA-style broadcasts + +Broadcasts `lhs` and `rhs` to the same rank, by adding size 1 dimensions to +whichever of `lhs` and `rhs` has the lower rank, using XLA's broadcasting rules +for binary operators. + +lhs: the LHS input tensor +rhs: the RHS input tensor +broadcast_dims: an XLA-style broadcast dimension specification +lhs_output: the broadcasted LHS tensor +rhs_output: the broadcasted RHS tensor +)doc"); + +REGISTER_OP("XlaSelfAdjointEig") + .Input("a: T") + .Attr("lower: bool") + .Attr("max_iter: int") + .Attr("epsilon: float") + .Output("w: T") + .Output("v: T") + .SetShapeFn(shape_inference::UnknownShape) + .Attr("T: numbertype") + .Doc(R"doc( +Computes the eigen decomposition of a batch of self-adjoint matrices +(Note: Only real inputs are supported). + +Computes the eigenvalues and eigenvectors of the innermost N-by-N matrices in +tensor such that tensor[...,:,:] * v[..., :,i] = e[..., i] * v[...,:,i], for +i=0...N-1. + +a: the input tensor. + +lower: a boolean specifies whether the calculation is done with the lower + triangular part or the upper triangular part. + +max_iter: maximum number of sweep update, i.e., the whole lower triangular + part or upper triangular part based on parameter lower. Heuristically, it has + been argued that approximately logN sweeps are needed in practice (Ref: Golub & + van Loan "Matrix Computation"). + +epsilon: the tolerance ratio. + +w: The eigenvalues in ascending order, each repeated according to its + multiplicity. +v: The column v[..., :, i] is the normalized eigenvector corresponding to the + eigenvalue w[..., i]. +)doc"); + +REGISTER_OP("XlaSvd") + .Input("a: T") + .Attr("max_iter: int") + .Attr("epsilon: float") + .Attr("precision_config: string") + .Output("s: T") + .Output("u: T") + .Output("v: T") + .SetShapeFn(shape_inference::UnknownShape) + .Attr("T: numbertype") + .Doc(R"doc( +Computes the eigen decomposition of a batch of self-adjoint matrices +(Note: Only real inputs are supported). + +Computes the eigenvalues and eigenvectors of the innermost M-by-N matrices in +tensor such that tensor[...,:,:] = u[..., :, :] * Diag(s[..., :]) * Transpose(v[...,:,:]). + +a: the input tensor. + +max_iter: maximum number of sweep update, i.e., the whole lower triangular + part or upper triangular part based on parameter lower. Heuristically, it has + been argued that approximately log(min (M, N)) sweeps are needed in practice + (Ref: Golub & van Loan "Matrix Computation"). + +epsilon: the tolerance ratio. + +precision_config: a serialized xla::PrecisionConfig proto. + +s: Singular values. The values are sorted in reverse order of magnitude, so + s[..., 0] is the largest value, s[..., 1] is the second largest, etc. +u: Left singular vectors. +v: Right singular vectors. +)doc"); + +REGISTER_OP("XlaConv") + .Input("lhs: T") + .Input("rhs: T") + .Input("window_strides: Tindices") + .Input("padding: Tindices") + .Input("lhs_dilation: Tindices") + .Input("rhs_dilation: Tindices") + .Input("feature_group_count: Tindices") + .Attr("T: numbertype") + .Attr("Tindices: {int32, int64}") + .Attr("dimension_numbers: string") + .Attr("precision_config: string") + .Output("output: T") + .SetShapeFn(UnchangedRank) + .Doc(R"doc( +Wraps the XLA ConvGeneralDilated operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution +. + +lhs: the input tensor +rhs: the kernel tensor +window_strides: the inter-window strides +padding: the padding to apply at the start and end of each input dimensions +lhs_dilation: dilation to apply between input elements +rhs_dilation: dilation to apply between kernel elements +feature_group_count: number of feature groups for grouped convolution. +dimension_numbers: a serialized xla::ConvolutionDimensionNumbers proto. +precision_config: a serialized xla::PrecisionConfig proto. +)doc"); + +REGISTER_OP("XlaConvV2") + .Input("lhs: LhsT") + .Input("rhs: RhsT") + .Input("window_strides: Tindices") + .Input("padding: Tindices") + .Input("lhs_dilation: Tindices") + .Input("rhs_dilation: Tindices") + .Input("feature_group_count: Tindices") + .Attr("LhsT: numbertype") + .Attr("RhsT: numbertype") + .Attr("Tindices: {int32, int64}") + .Attr("dimension_numbers: string") + .Attr("precision_config: string") + .Attr("preferred_element_type: numbertype") + .Attr("batch_group_count: int = 1") + .Output("output: preferred_element_type") + .SetShapeFn(UnchangedRank) + .Doc(R"doc( +Wraps the XLA ConvGeneralDilated operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution +. + +lhs: input tensor +rhs: kernel tensor +window_strides: inter-window strides +padding: padding to apply at the start and end of each input dimensions +lhs_dilation: dilation to apply between input elements +rhs_dilation: dilation to apply between kernel elements +feature_group_count: number of feature groups for grouped convolution. +dimension_numbers: serialized xla::ConvolutionDimensionNumbers proto. +precision_config: serialized xla::PrecisionConfig proto. +preferred_element_type: type of the tensor. +batch_group_count: number of batch groups or grouped filters. +)doc"); + +static absl::Status XlaDotShapeFunction(shape_inference::InferenceContext* c) { + shape_inference::ShapeHandle lhs_shape_handle = c->input(0); + shape_inference::ShapeHandle rhs_shape_handle = c->input(1); + if (!c->RankKnown(lhs_shape_handle) || !c->RankKnown(rhs_shape_handle)) { + return shape_inference::UnknownShape(c); + } + + std::string dimension_numbers_string; + TF_RETURN_IF_ERROR( + c->GetAttr("dimension_numbers", &dimension_numbers_string)); + + xla::DotDimensionNumbers dimension_numbers; + dimension_numbers.ParseFromString(dimension_numbers_string); + + // Check that number of contracting dimensions match. + if (dimension_numbers.lhs_contracting_dimensions_size() != + dimension_numbers.rhs_contracting_dimensions_size()) + return absl::InvalidArgumentError(absl::StrCat( + "Must specify the same number of contracting dimensions for lhs " + "and rhs. Got: ", + dimension_numbers.lhs_contracting_dimensions_size(), " and ", + dimension_numbers.rhs_contracting_dimensions_size())); + + // Check that contracting dimension sizes match. + for (int64_t i = 0; i < dimension_numbers.lhs_contracting_dimensions_size(); + ++i) { + const int64_t lhs_contracting_dimension = + dimension_numbers.lhs_contracting_dimensions(i); + const int64_t rhs_contracting_dimension = + dimension_numbers.rhs_contracting_dimensions(i); + shape_inference::DimensionHandle unused; + TF_RETURN_WITH_CONTEXT_IF_ERROR( + c->Merge(c->DimKnownRank(lhs_shape_handle, lhs_contracting_dimension), + c->DimKnownRank(rhs_shape_handle, rhs_contracting_dimension), + &unused), + "For contracting dimension ", i, " which is lhs dimension ", + lhs_contracting_dimension, " and rhs dimension ", + rhs_contracting_dimension); + } + + // Check that number of batch dimensions match. + if (dimension_numbers.lhs_batch_dimensions_size() != + dimension_numbers.rhs_batch_dimensions_size()) + return absl::InvalidArgumentError( + absl::StrCat("Must specify the same number of batch dimensions for lhs " + "and rhs. Got: ", + dimension_numbers.lhs_batch_dimensions_size(), " and ", + dimension_numbers.rhs_batch_dimensions_size())); + + // The ranks of lhs and rhs are decremented by the number of contractions, + // and added for the rank of the result. When an input tensor + // is a scalar, its contribution to the rank of the result is 0. Generate + // the result dimensions in order, batch dimensions, then the + // non-contracted and non-batch lhs and rhs dimensions. + std::vector output_dims; + + // Check that batch dimension sizes match, and add them to output_dims. + for (int64_t i = 0; i < dimension_numbers.lhs_batch_dimensions_size(); ++i) { + const int64_t lhs_batch_dimension = + dimension_numbers.lhs_batch_dimensions(i); + const int64_t rhs_batch_dimension = + dimension_numbers.rhs_batch_dimensions(i); + shape_inference::DimensionHandle out; + TF_RETURN_WITH_CONTEXT_IF_ERROR( + c->Merge(c->DimKnownRank(lhs_shape_handle, lhs_batch_dimension), + c->DimKnownRank(rhs_shape_handle, rhs_batch_dimension), &out), + "For batch dimension ", i, " which is lhs dimension ", + lhs_batch_dimension, " and rhs dimension ", rhs_batch_dimension); + output_dims.emplace_back(out); + } + + const int32_t lhs_rank = c->Rank(lhs_shape_handle); + for (int64_t i = 0; i < lhs_rank; ++i) { + if (absl::c_linear_search(dimension_numbers.lhs_contracting_dimensions(), + i) || + absl::c_linear_search(dimension_numbers.lhs_batch_dimensions(), i)) { + continue; + } + output_dims.emplace_back(c->Dim(lhs_shape_handle, i)); + } + + const int32_t rhs_rank = c->Rank(rhs_shape_handle); + for (int64_t i = 0; i < rhs_rank; ++i) { + if (absl::c_linear_search(dimension_numbers.rhs_contracting_dimensions(), + i) || + absl::c_linear_search(dimension_numbers.rhs_batch_dimensions(), i)) { + continue; + } + output_dims.emplace_back(c->Dim(rhs_shape_handle, i)); + } + + c->set_output(0, c->MakeShape(output_dims)); + return absl::OkStatus(); +} + +REGISTER_OP("XlaDot") + .Input("lhs: T") + .Input("rhs: T") + .Attr("T: numbertype") + .Attr("dimension_numbers: string") + .Attr("precision_config: string") + .Output("output: T") + .SetShapeFn(XlaDotShapeFunction) + .Doc(R"doc( +Wraps the XLA DotGeneral operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#dotgeneral +. + +lhs: the LHS tensor +rhs: the RHS tensor +dimension_numbers: a serialized xla::DotDimensionNumbers proto. +precision_config: a serialized xla::PrecisionConfig proto. +)doc"); + +REGISTER_OP("XlaDotV2") + .Input("lhs: LhsT") + .Input("rhs: RhsT") + .Attr("LhsT: numbertype") + .Attr("RhsT: numbertype") + .Attr("dimension_numbers: string") + .Attr("precision_config: string") + .Attr("preferred_element_type: numbertype") + .Output("output: preferred_element_type") + .SetShapeFn(XlaDotShapeFunction) + .Doc(R"doc( +Wraps the XLA DotGeneral operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#dotgeneral +. + +lhs: the LHS tensor +rhs: the RHS tensor +dimension_numbers: a serialized xla::DotDimensionNumbers proto. +precision_config: a serialized xla::PrecisionConfig proto. +preferred_element_type: The type of the tensor. +)doc"); + +REGISTER_OP("XlaSetBound") + .Input("input: int32") + .Input("bound: int32") + .Output("output: int32") + .SetShapeFn(shape_inference::UnknownShape) + .Doc( + R"doc(Set a bound for the given input value as a hint to Xla compiler, + returns the same value. +)doc"); + +REGISTER_OP("XlaSetDynamicDimensionSize") + .Input("input: T") + .Input("dim_index: int32") + .Input("size: int32") + .Output("output: T") + .Attr("T: type") + // Use unknown shape to prevent constant folding. + .SetShapeFn(shape_inference::UnknownShape) + .Doc( + R"doc(Make a static dimension into a xla bounded dynamic dimension. + The current static dimension size will become the bound and the second + operand becomes the dynamic size of the dimension.)doc"); + +REGISTER_OP("XlaRemoveDynamicDimensionSize") + .Input("input: T") + .Input("dim_index: int32") + .Output("output: T") + .Attr("T: type") + // Use unknown shape to prevent constant folding. + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +Inverse of XlaSetDynamicDimensionSize. + +Make an xla bounded dynamic dimension into a static dimension. The bound of the +size of dimension `dim_index` becomes the static dimension size. +)doc"); + +REGISTER_OP("XlaDynamicSlice") + .Input("input: T") + .Input("start_indices: Tindices") + .Input("size_indices: Tindices") + .Output("output: T") + .Attr("T: type") + .Attr("Tindices: {int32, int64}") + .SetShapeFn([](shape_inference::InferenceContext* c) -> absl::Status { + shape_inference::ShapeHandle size_indices_shape = c->input(2); + if (!c->RankKnown(size_indices_shape)) { + return UnchangedRank(c); + } + if (c->Rank(size_indices_shape) != 1) { + return absl::InvalidArgumentError("size_indices must be a 1D tensor"); + } + shape_inference::ShapeHandle size_indices_value; + TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(2, &size_indices_value)); + if (!c->RankKnown(size_indices_value)) { + // If we cannot tell the rank of the output from the value of + // size_indices, perhaps we can find it from the rank of first operand. + return UnchangedRank(c); + } + c->set_output(0, size_indices_value); + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA DynamicSlice operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#dynamicslice +. + +DynamicSlice extracts a sub-array from the input array at dynamic +start_indices. The size of the slice in each dimension is passed in +size_indices, which specify the end point of exclusive slice intervals in each +dimension -- [start, start + size). The shape of start_indices must have rank 1, +with dimension size equal to the rank of operand. + +input: A `Tensor` of type T. + +start_indices: Rank 1 tensor of N integers containing the starting indices of + the slice for each dimension. Value must be greater than or equal to zero. + +start_indices: List of N integers containing the slice size for each + dimension. Each value must be strictly greater than zero, and start + size + must be less than or equal to the size of the dimension to avoid + implementation defined behavior. +)doc"); + +REGISTER_OP("XlaDynamicUpdateSlice") + .Input("input: T") + .Input("update: T") + .Input("indices: Tindices") + .Output("output: T") + .Attr("T: type") + .Attr("Tindices: {int32, int64}") + .SetShapeFn(shape_inference::UnchangedShape) + .Doc(R"doc( +Wraps the XLA DynamicUpdateSlice operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#dynamicupdateslice +. + +XlaDynamicUpdateSlice generates a result which is the value of the `input` +operand, with a slice update overwritten at `indices`. The shape of `update` +determines the shape of the sub-array of the result which is updated. The shape +of indices must be rank == 1, with dimension size equal to the rank of `input`. + +Handling of out-of-bounds slice indices is implementation-defined. + +input: A `Tensor` of type T. +indices: A vector of indices into `input`. Must have length equal to the rank of + `input`. +update: A `Tensor` of type T. Same rank as `input`. +output: A `Tensor` of type T. +)doc"); + +// TODO(b/37549631) setting the If Op to always be stateful is too +// conservative. +REGISTER_OP("XlaIf") + .Input("cond: Tcond") + .Input("inputs: Tin") + .Output("output: Tout") + .Attr("Tcond: type") + .Attr("then_branch: func") + .Attr("else_branch: func") + .Attr("Tin: list(type) >= 0") + .Attr("Tout: list(type) >= 0") + .SetIsStateful() + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +output = cond ? then_branch(inputs) : else_branch(inputs). + +cond: A boolean scalar. +inputs: A list of input tensors. +output: A list of tensors returned by either then_branch(inputs) or + else_branch(inputs). The input shapes of the then_branch and + else_branch must match. +then_branch: A function takes 'inputs' and returns a list of tensors, + whose types are the same as what else_branch returns. +else_branch: A function takes 'inputs' and returns a list of tensors. + whose types are the same as what then_branch returns. +)doc"); + +REGISTER_OP("XlaPad") + .Input("input: T") + .Input("padding_value: T") + .Input("padding_low: Tindices") + .Input("padding_high: Tindices") + .Input("padding_interior: Tindices") + .Output("output: T") + .Attr("T: type") + .Attr("Tindices: {int32, int64}") + .SetShapeFn([](shape_inference::InferenceContext* c) { + shape_inference::ShapeHandle input_shape_handle = c->input(0); + if (!c->RankKnown(input_shape_handle)) { + return UnchangedRank(c); + } + const int32_t op_rank = c->Rank(input_shape_handle); + + shape_inference::ShapeHandle padding_shape_handle = c->input(1); + if (c->RankKnown(padding_shape_handle) && + c->Rank(padding_shape_handle) != 0) { + return absl::InvalidArgumentError( + absl::StrCat("padding_value input must be scalar, found rank ", + c->Rank(padding_shape_handle))); + } + const Tensor* padding_low_tensor = c->input_tensor(2); + const Tensor* padding_high_tensor = c->input_tensor(3); + const Tensor* padding_interior_tensor = c->input_tensor(4); + if (padding_low_tensor == nullptr || padding_high_tensor == nullptr || + padding_interior_tensor == nullptr) { + return UnchangedRank(c); + } + + if (padding_low_tensor->shape().dims() != 1 || + padding_low_tensor->shape().dim_size(0) != op_rank) { + return absl::InvalidArgumentError( + absl::StrCat("padding_low must be a 1D tensor of size ", op_rank)); + } + if (padding_high_tensor->shape().dims() != 1 || + padding_high_tensor->shape().dim_size(0) != op_rank) { + return absl::InvalidArgumentError( + absl::StrCat("padding_high must be a 1D tensor of size ", op_rank)); + } + if (padding_interior_tensor->shape().dims() != 1 || + padding_interior_tensor->shape().dim_size(0) != op_rank) { + return absl::InvalidArgumentError(absl::StrCat( + "padding_interior must be a 1D tensor of size ", op_rank)); + } + std::vector output_dims; + output_dims.reserve(op_rank); + for (int64_t i = 0; i < op_rank; ++i) { + int64_t low, high, interior; + TF_RETURN_IF_ERROR(c->GetScalarFromTensor(padding_low_tensor, i, &low)); + TF_RETURN_IF_ERROR( + c->GetScalarFromTensor(padding_high_tensor, i, &high)); + TF_RETURN_IF_ERROR( + c->GetScalarFromTensor(padding_interior_tensor, i, &interior)); + if (interior < 0) { + return absl::InvalidArgumentError(absl::StrCat( + "padding_interior must contain only non-negative values, found ", + interior)); + } + + shape_inference::DimensionHandle orig_size_handle = + c->Dim(input_shape_handle, i); + if (c->ValueKnown(orig_size_handle)) { + auto orig_dim = c->Value(orig_size_handle); + int64_t new_dim = orig_dim + low + high; + if (orig_dim > 0) { + new_dim += interior * (orig_dim - 1); + } + if (new_dim < 0) { + return absl::InvalidArgumentError(absl::StrCat( + "resulting padded dimension has negative size ", new_dim)); + } + output_dims.emplace_back(c->MakeDim(new_dim)); + } else { + output_dims.emplace_back(c->UnknownDim()); + } + } + + c->set_output(0, c->MakeShape(output_dims)); + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA Pad operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#pad +. + +input: A `Tensor` of type T. +padding_value: A scalar `Tensor` of type T. +padding_low: the padding to apply at the start of each input dimensions. Must + be a compile-time constant 1D tensor of length equal to rank of input. +padding_high: the padding to apply at the end of each input dimension. Must + be a compile-time constant 1D tensor of length equal to rank of input. +padding_interior: the padding to apply between each input element. Must + be a compile-time constant 1D tensor of length equal to rank of input, + containing only non-negative values. +output: A `Tensor` of type T. +)doc"); + +REGISTER_OP("XlaRecv") + .Output("tensor: dtype") + .Attr("dtype: type") + .Attr("tensor_name: string") + .Attr("shape: shape") + .SetIsStateful() + .SetShapeFn([](shape_inference::InferenceContext* c) { + TensorShape shape_attr; + TF_RETURN_IF_ERROR(c->GetAttr("shape", &shape_attr)); + shape_inference::ShapeHandle s; + TF_RETURN_IF_ERROR(c->MakeShapeFromTensorShape(shape_attr, &s)); + c->set_output(0, s); + return absl::OkStatus(); + }) + .Doc(R"doc( +Receives the named tensor from another XLA computation. Wraps the XLA Recv +operator documented at + https://www.tensorflow.org/performance/xla/operation_semantics#recv . + +tensor: The tensor to receive. +dtype: The type of the tensor. +tensor_name: A string key that identifies the channel. +shape: The shape of the tensor. +)doc"); + +REGISTER_OP("XlaReduce") + .Input("input: T") + .Input("init_value: T") + .Attr("T: {numbertype, bool}") + .Attr("dimensions_to_reduce: list(int)") + .Attr("reducer: func") + .Output("output: T") + .SetShapeFn([](shape_inference::InferenceContext* c) { + if (c->RankKnown(c->input(0))) { + int rank = c->Rank(c->input(0)); + std::vector dimensions_to_reduce; + TF_RETURN_IF_ERROR( + c->GetAttr("dimensions_to_reduce", &dimensions_to_reduce)); + std::set dims_set(dimensions_to_reduce.begin(), + dimensions_to_reduce.end()); + auto dim_in_range = [rank](int64_t dim) { + return dim >= 0 && dim < rank; + }; + const int dimensions_to_reduce_size = dimensions_to_reduce.size(); + if (rank < dimensions_to_reduce_size || + dims_set.size() != dimensions_to_reduce.size() || + !absl::c_all_of(dimensions_to_reduce, dim_in_range)) { + return absl::InvalidArgumentError( + "Invalid dimensions_to_reduce argument to XlaReduce"); + } + c->set_output( + 0, c->UnknownShapeOfRank(rank - dimensions_to_reduce.size())); + } else { + c->set_output(0, c->input(0)); + } + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA Reduce operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#reduce . + +input: the input tensor +init_value: a scalar representing the initial value for the reduction +reducer: a reducer function to apply +dimensions_to_reduce: dimension numbers over which to reduce +)doc"); + +REGISTER_OP("XlaVariadicReduce") + .Input("input: N * T") + .Input("init_value: N * T") + .Attr("N: int >= 1") + .Attr("T: {numbertype, bool}") + .Attr("dimensions_to_reduce: list(int)") + .Attr("reducer: func") + .Output("output: N * T") + .SetShapeFn([](shape_inference::InferenceContext* c) { + int n; + TF_RETURN_IF_ERROR(c->GetAttr("N", &n)); + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + c->MergeInput(i, c->input(j)); + } + } + if (c->RankKnown(c->input(0))) { + int rank = c->Rank(c->input(0)); + std::vector dimensions_to_reduce; + TF_RETURN_IF_ERROR( + c->GetAttr("dimensions_to_reduce", &dimensions_to_reduce)); + std::set dims_set(dimensions_to_reduce.begin(), + dimensions_to_reduce.end()); + auto dim_in_range = [rank](int64_t dim) { + return dim >= 0 && dim < rank; + }; + const int dimensions_to_reduce_size = dimensions_to_reduce.size(); + if (rank < dimensions_to_reduce_size || + dims_set.size() != dimensions_to_reduce.size() || + !absl::c_all_of(dimensions_to_reduce, dim_in_range)) { + return absl::InvalidArgumentError( + "Invalid dimensions_to_reduce argument to XlaVariadicReduce"); + } + for (int i = 0; i < n; i++) { + c->set_output( + i, c->UnknownShapeOfRank(rank - dimensions_to_reduce.size())); + } + } else { + for (int i = 0; i < n; i++) { + c->set_output(i, c->input(i)); + } + } + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the variadic XLA Reduce operator. + +Semantics are documented at + https://www.tensorflow.org/performance/xla/operation_semantics#variadic_reduce. + +This version is limited to operands of the same dtype. +XlaVariadicReduceV2 is a version that supports heterogeneous operands. + +input: the input tensor(s) +init_value: scalar initial value(s) for the reduction +reducer: a reducer function to apply +dimensions_to_reduce: dimension numbers over which to reduce +)doc"); + +REGISTER_OP("XlaVariadicReduceV2") + .Input("inputs: T") + .Input("init_values: T") + .Attr("T: list(type) >= 1") + .Attr("dimensions_to_reduce: list(int)") + .Attr("reducer: func") + .Output("outputs: T") + .SetShapeFn([](shape_inference::InferenceContext* c) { + std::vector input_shapes; + TF_RETURN_IF_ERROR(c->input("inputs", &input_shapes)); + std::vector init_values_shapes; + TF_RETURN_IF_ERROR(c->input("init_values", &init_values_shapes)); + const int nr_inputs = input_shapes.size(); + if (nr_inputs != init_values_shapes.size()) { + return absl::InvalidArgumentError(absl::StrCat( + "Must specify the same number of inputs and init_values. ", "Got ", + nr_inputs, " and ", init_values_shapes.size())); + } + if (nr_inputs == 0) { + return absl::InvalidArgumentError("Must specify at least one input"); + } + + shape_inference::ShapeHandle input_shape = input_shapes[0]; + for (int i = 1; i < nr_inputs; ++i) { + shape_inference::ShapeHandle merged; + TF_RETURN_WITH_CONTEXT_IF_ERROR( + c->Merge(input_shape, input_shapes[i], &merged), + "All inputs must have the same shape. Input ", i, + " (zero-based) has shape ", c->DebugString(input_shapes[i]), + " incompatible with the shape ", "inferred from previous inputs ", + c->DebugString(input_shape)); + input_shape = merged; + } + // All outputs have the same shape + shape_inference::ShapeHandle output_shape = c->UnknownShape(); + + if (c->RankKnown(input_shape)) { + int rank = c->Rank(input_shape); + + std::vector dimensions_to_reduce; + TF_RETURN_IF_ERROR( + c->GetAttr("dimensions_to_reduce", &dimensions_to_reduce)); + std::set dims_set(dimensions_to_reduce.begin(), + dimensions_to_reduce.end()); + + auto dim_in_range = [rank](int64_t dim) { + return dim >= 0 && dim < rank; + }; + const int dimensions_to_reduce_size = dimensions_to_reduce.size(); + if (rank < dimensions_to_reduce_size || + dims_set.size() != dimensions_to_reduce.size() || + !absl::c_all_of(dimensions_to_reduce, dim_in_range)) { + return absl::InvalidArgumentError( + "Invalid dimensions_to_reduce argument to XlaVariadicReduceV2"); + } + + std::vector output_dims; + for (int64_t i = 0; i < rank; ++i) { + if (dims_set.find(i) == dims_set.end()) { + output_dims.emplace_back(c->Dim(input_shape, i)); + } + } + output_shape = c->MakeShape(output_dims); + } + for (int i = 0; i < nr_inputs; ++i) { + c->set_output(i, output_shape); + } + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the variadic XLA Reduce operator. + +Semantics are documented at + https://www.tensorflow.org/performance/xla/operation_semantics#variadic_reduce. + +This is an expanded version of XlaVariadicReduce, with support for +operands of different dtypes, and improved shape inference. + +inputs: the input tensor(s) +init_values: scalar initial value(s) for the reduction +reducer: a reducer function to apply +dimensions_to_reduce: dimension numbers over which to reduce +)doc"); + +REGISTER_OP("XlaReduceWindow") + .Input("input: T") + .Input("init_value: T") + .Input("window_dimensions: Tindices") + .Input("window_strides: Tindices") + .Input("base_dilations: Tindices") + .Input("window_dilations: Tindices") + .Input("padding: Tindices") + .Attr("T: {numbertype, bool}") + .Attr("Tindices: {int32, int64}") + .Attr("computation: func") + .Output("output: T") + .SetShapeFn(UnchangedRank) + .Doc(R"doc( +Wraps the XLA ReduceWindow operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow . + +input: the input tensor +init_value: a scalar representing the initial value for the reduction +computation: a reducer function to apply +window_dimensions: the shape of the window +window_strides: the inter-window strides +padding: the padding to apply at the start and end of each input dimensions +)doc"); + +REGISTER_OP("XlaRngBitGenerator") + .Input("algorithm: int32") + .Input("initial_state: uint64") + .Input("shape: Tshape") + .Output("output_key: uint64") + .Output("output: dtype") + .Attr("dtype: {uint8, int8, int32, int64, uint32, uint64} = DT_UINT64") + .Attr("Tshape: {int32, int64} = DT_INT32") + .SetShapeFn([](shape_inference::InferenceContext* c) { + shape_inference::ShapeHandle algorithm; + TF_RETURN_IF_ERROR(c->WithRank(c->input(0), 0, &algorithm)); + shape_inference::ShapeHandle initial_state; + TF_RETURN_IF_ERROR(c->WithRank(c->input(1), 1, &initial_state)); + + c->set_output(0, initial_state); + shape_inference::ShapeHandle output; + TF_RETURN_IF_ERROR(c->MakeShapeFromShapeTensor(2, &output)); + c->set_output(1, output); + return absl::OkStatus(); + }) + .Doc(R"doc( +Stateless PRNG bit generator. +Wraps the XLA RngBitGenerator operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#rngbitgenerator. + +algorithm: The PRNG algorithm to use, one of + tf.random.Algorithm.{PHILOX, THREEFRY, AUTO_SELECT}. +initial_state: Initial state for the PRNG algorithm. For THREEFRY, it should be + a u64[2] and for PHILOX a u64[3]. +shape: The output shape of the generated data. +dtype: The type of the tensor. +)doc"); + +REGISTER_OP("XlaSelectAndScatter") + .Input("operand: T") + .Input("window_dimensions: Tindices") + .Input("window_strides: Tindices") + .Input("padding: Tindices") + .Input("source: T") + .Input("init_value: T") + .Attr("T: numbertype") + .Attr("Tindices: {int32, int64}") + .Attr("select: func") + .Attr("scatter: func") + .Output("output: T") + .SetShapeFn(UnchangedRank) + .Doc(R"doc( +Wraps the XLA SelectAndScatter operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#selectandscatter +. + +operand: the input tensor +window_dimensions: the shape of the window +window_strides: the inter-window strides +padding: the padding to apply at the start and end of each input dimensions +source: a tensor of values to scatter +init_value: a scalar representing the initial value for the output tensor +select: a selection function to apply +scatter: a scatter function to apply +)doc"); + +REGISTER_OP("XlaSend") + .Input("tensor: T") + .Attr("T: type") + .Attr("tensor_name: string") + .SetIsStateful() + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +Sends the named tensor to another XLA computation. Wraps the XLA Send operator +documented at + https://www.tensorflow.org/performance/xla/operation_semantics#send . + +tensor: The tensor to send. +tensor_name: A string key that identifies the channel. +)doc"); + +REGISTER_OP("XlaSort") + .Input("input: T") + .Output("output: T") + .Attr("T: type") + .SetShapeFn(shape_inference::UnchangedShape) + .Doc(R"doc( +Wraps the XLA Sort operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#sort +. + +Sorts a tensor. Currently only sorts in ascending order are supported. + +input: A `Tensor` of type T. +output: A `Tensor` of type T. +)doc"); + +REGISTER_OP("XlaKeyValueSort") + .Input("keys: K") + .Input("values: V") + .Output("sorted_keys: K") + .Output("sorted_values: V") + .Attr("K: realnumbertype") + .Attr("V: type") + .SetShapeFn([](shape_inference::InferenceContext* c) { + c->set_output(0, c->input(0)); + c->set_output(1, c->input(1)); + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA Sort operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#sort +. + +Sorts a tensor. Currently only sorts in ascending order are supported. + +keys: A `Tensor` of type K. +values: A `Tensor` of type V. +sorted_keys: A `Tensor` of type K. +sorted_values: A `Tensor` of type V. +)doc"); + +REGISTER_OP("XlaVariadicSort") + .Input("inputs: T") + .Input("dimension: int32") + .Output("outputs: T") + .Attr("T: list(type) >= 1") + .Attr("comparator: func") + .Attr("is_stable: bool") + .SetShapeFn([](shape_inference::InferenceContext* c) { + std::vector input_shapes; + TF_RETURN_IF_ERROR(c->input("inputs", &input_shapes)); + TF_RETURN_IF_ERROR(c->set_output("outputs", input_shapes)); + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA Sort operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#sort +. + +Sorts one or more tensors, with support for custom comparator, dimension, and +is_stable attributes. + +inputs: A list of `Tensor` of identical shape but possibly different types. +dimension: The dimension along which to sort. Must be a compile-time constant. +is_stable: Whether to use stable sort. +comparator: A comparator function to apply to 2*N scalars and returning a + boolean. N is the number of sort inputs. If you want to sort in ascending + order then the comparator should perform a less-than comparison. +outputs: A list of `Tensor` of same shape and types as the `input`. +)doc"); + +// TODO(b/37549631) setting the While Op to always be stateful is too +// conservative. +REGISTER_OP("XlaWhile") + .Input("input: T") + .Output("output: T") + .Attr("T: list(type) >= 0") + .Attr("cond: func") + .Attr("body: func") + .SetIsStateful() + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +output = input; While (Cond(output)) { output = Body(output) } + +input: A list of input tensors whose types are T. +output: A list of output tensors whose types are T. +cond: A function takes 'input' and returns a tensor. If the tensor is + a scalar of non-boolean, the scalar is converted to a boolean + according to the following rule: if the scalar is a numerical + value, non-zero means True and zero means False; if the scalar is + a string, non-empty means True and empty means False. If the + tensor is not a scalar, non-emptiness means True and False + otherwise. +body: A function that takes a list of tensors and returns another + list of tensors. Both lists have the same types as specified by T. +)doc"); + +REGISTER_OP("XlaDequantize") + .Input("input: uint32") + .Output("output: bfloat16") + .Attr("min_range: float") + .Attr("max_range: float") + .Attr("mode: string") + .Attr("transpose_output: bool") + .SetIsStateful() + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +Takes the packed uint32 input and unpacks the input to uint8 to do +Dequantization on device. + +input: Input tensors whose types is uint32, shape is [d0, ..., dn]. +output: Output tensors whose types is bfloat16. If transpose_output is true, + output shape is [dn * 4, dn-1, ..., d1, d0]. If transpose_output + is false, output shape is [d0,..., dn * 4]. +min_range: The minimum scalar value possibly produced for the input. +max_range: The maximum scalar value possibly produced for the input. +mode: String to determine the dequantize mode in {"MIN_COMBINED", "MIN_FIRST", "SCALED"}. +transpose_output: Boolean to determine if output is transposed. transpose_output + is faster when input is large and rank of input is higher than 1. +)doc"); + +REGISTER_OP("XlaEinsum") + .Input("a: T") + .Input("b: T") + .Output("product: T") + .Attr("equation: string") + .Attr("T: {complex64, bfloat16, float}") + .SetShapeFn([](shape_inference::InferenceContext* context) { + std::string equation; + TF_RETURN_IF_ERROR(context->GetAttr("equation", &equation)); + // XlaEinsum supports only two-input einsum equations. + if (!absl::StrContains(equation, ",")) { + return absl::InvalidArgumentError( + absl::StrCat("Expected one \",\" in equation. Got: ", equation)); + } + // Use EinsumShape for the rest of the inference now that we know we must + // have a two-input einsum. + return shape_inference::EinsumShape(context); + }) + .Doc(R"doc( +An op which supports basic einsum op with 2 inputs and 1 output. + +This op has better TPU performance since it doesn't have explicitly reshape and +transpose operations as tf.einsum does. +)doc"); + +REGISTER_OP("XlaSpmdFullToShardShape") + .Input("input: T") + .Output("output: T") + .Attr("T: type") + .Attr("manual_sharding: string") + .Attr("dim: int = -1") + .Attr("unspecified_dims: list(int) = []") + .SetShapeFn([](shape_inference::InferenceContext* c) { + auto input_handle = c->input(0); + if (!c->RankKnown(input_handle)) { + return shape_inference::UnknownShape(c); + } + std::string sharding_attr; + TF_RETURN_IF_ERROR(c->GetAttr("manual_sharding", &sharding_attr)); + int32_t single_dim; + TF_RETURN_IF_ERROR(c->GetAttr("dim", &single_dim)); + xla::OpSharding sharding; + sharding.ParseFromString(sharding_attr); + if (sharding.type() != xla::OpSharding::OTHER) { + return shape_inference::UnchangedShape(c); + } + std::vector dims; + for (int64_t i = 0; i < c->Rank(input_handle); ++i) { + auto dim = c->Value(c->Dim(input_handle, i)); + if (single_dim < 0 || single_dim == i) { + int64_t partitions_i = sharding.tile_assignment_dimensions(i); + if (dim != shape_inference::InferenceContext::kUnknownDim && + partitions_i != 1) { + dim = (dim + partitions_i - 1) / partitions_i; + } + } + dims.push_back(c->MakeDim(dim)); + } + c->set_output(0, c->MakeShape(dims)); + return absl::OkStatus(); + }) + .Doc(R"doc( +An op used by XLA SPMD partitioner to switch from automatic partitioning to +manual partitioning. It annotates the input (full-shape, to be automatically +partitioned) with the same sharding used by manual partitioning, and outputs a +shard-shaped tensor to be consumed by later manually-partitioned ops. If the +shape is not evenly partitionable, the padding region will be masked with 0s. +The conversion can happen partially in subgroups, by specifying the dim +attribute, where only that dim will be converted. +)doc"); + +REGISTER_OP("XlaSpmdShardToFullShape") + .Input("input: T") + .Output("output: T") + .Attr("T: type") + .Attr("manual_sharding: string") + .Attr("full_shape: shape") + .Attr("dim: int = -1") + .Attr("unspecified_dims: list(int) = []") + .SetShapeFn([](shape_inference::InferenceContext* c) { + TensorShape shape_attr; + TF_RETURN_IF_ERROR(c->GetAttr("full_shape", &shape_attr)); + shape_inference::ShapeHandle s; + TF_RETURN_IF_ERROR(c->MakeShapeFromTensorShape(shape_attr, &s)); + c->set_output(0, s); + return absl::OkStatus(); + }) + .Doc(R"doc( +An op used by XLA SPMD partitioner to switch from manual partitioning to +automatic partitioning. It converts the shard-shaped, manually partitioned input +into full-shaped tensor to be partitioned automatically with the same sharding +used by manual partitioning. The conversion can happen partially in subgroups, +by specifying the dim attribute, where only that dim will be converted. +)doc"); + +REGISTER_OP("XlaSharding") + .Input("input: T") + .Output("output: T") + .Attr("T: type") + .Attr("sharding: string = ''") + .Attr("unspecified_dims: list(int) = []") + .SetShapeFn(shape_inference::UnchangedShape) + .Doc(R"doc( +An op which shards the input based on the given sharding attribute. It can +selectively annotate a subset of tensor dimensions by skipping unspecified_dims, +and the sharding annotation should be replicated in those dims. +)doc"); + +REGISTER_OP("XlaReplicaId") + .Output("id: int32") + .SetShapeFn([](shape_inference::InferenceContext* context) { + context->set_output(0, context->MakeShape({})); + return absl::OkStatus(); + }) + .Doc("Replica ID."); + +xla::Shape GetShape(shape_inference::ShapeHandle shape_handle, + shape_inference::InferenceContext* c) { + if (!c->RankKnown(shape_handle)) { + return xla::Shape(); + } + std::vector dims; + std::vector dynamic_dims; + for (int i = 0, rank = c->Rank(shape_handle); i < rank; ++i) { + bool is_dynamic = !c->ValueKnown(c->Dim(shape_handle, i)); + dynamic_dims.push_back(is_dynamic); + dims.push_back(is_dynamic ? xla::Shape::kUnboundedSize + : c->Value(c->Dim(shape_handle, i))); + } + return xla::Shape( + // Type matters only for indices. S64 is the widest possible type. + xla::PrimitiveType::S64, dims, + absl::InlinedVector(dynamic_dims.begin(), dynamic_dims.end())); +} + +REGISTER_OP("XlaGather") + .Input("operand: T") + .Input("start_indices: Tindices") + .Input("slice_sizes: Tindices") + .Attr("dimension_numbers: string") + .Attr("indices_are_sorted: bool") + .Attr("T: {numbertype, bool}") + .Attr("Tindices: {int32, int64}") + .Output("output: T") + .SetShapeFn([](shape_inference::InferenceContext* c) -> absl::Status { + std::string dimension_numbers; + TF_RETURN_IF_ERROR(c->GetAttr("dimension_numbers", &dimension_numbers)); + xla::GatherDimensionNumbers gather_dim_numbers; + if (!gather_dim_numbers.ParseFromString(dimension_numbers)) { + return absl::InvalidArgumentError("Failed to parse dimension_numbers."); + } + VLOG(3) << c->DebugString(); + VLOG(3) << "dim_numbers: " << gather_dim_numbers.DebugString(); + VLOG(3) << "Shapes: operand: " << c->DebugString(c->input(0)) + << ", start_indices: " << c->DebugString(c->input(1)) + << ", slice_sizes: " << c->DebugString(c->input(2)); + + xla::Shape input_shape = GetShape(c->input(0), c); + xla::Shape start_indices_shape = GetShape(c->input(1), c); + xla::Shape slice_sizes_shape = GetShape(c->input(2), c); + + const Tensor* slice_sizes_tensor = c->input_tensor(2); + if (input_shape == xla::Shape() || input_shape.is_unbounded_dynamic() || + start_indices_shape == xla::Shape() || + slice_sizes_shape == xla::Shape()) { + VLOG(3) << "output will be unranked due to unknown or dynamic input " + "shapes."; + return shape_inference::UnknownShape(c); + } + if (slice_sizes_tensor == nullptr || + slice_sizes_tensor->NumElements() == -1) { + VLOG(3) << "output will be unranked due to non-constant slice_sizes."; + return shape_inference::UnknownShape(c); + } + std::vector slice_sizes; + if (slice_sizes_tensor->dtype() == DT_INT32) { + for (int i = 0; i < slice_sizes_tensor->NumElements(); ++i) { + slice_sizes.push_back(slice_sizes_tensor->flat()(i)); + } + } else if (slice_sizes_tensor->dtype() == DT_INT64) { + for (int i = 0; i < slice_sizes_tensor->NumElements(); ++i) { + slice_sizes.push_back(slice_sizes_tensor->flat()(i)); + } + } + VLOG(3) << "slice_sizes [val]: " << absl::StrJoin(slice_sizes, ","); + TF_ASSIGN_OR_RETURN(xla::Shape output_shape, + xla::ShapeInference::InferGatherShape( + input_shape, start_indices_shape, + gather_dim_numbers, slice_sizes)); + std::vector dims; + for (int64_t i = 0; i < output_shape.dimensions().size(); ++i) { + if (output_shape.is_unbounded_dynamic_dimension(i)) { + dims.push_back(c->UnknownDim()); + } else { + dims.push_back(c->MakeDim(output_shape.dimensions(i))); + } + } + c->set_output(0, c->MakeShape(dims)); + VLOG(3) << "output: " << c->DebugString(c->output(0)); + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA Gather operator documented at + https://www.tensorflow.org/xla/operation_semantics#gather +operand: The array we're gathering from. +start_indices: Array containing the starting indices of the slices we gather. +dimension_numbers: A serialized xla::GatherDimensionNumbers proto. +slice_sizes: slice_sizes[i] is the bounds for the slice on dimension i. +indices_are_sorted: Boolean indicating if the indices are sorted. +)doc"); + +REGISTER_OP("XlaScatter") + .Input("operand: T") + .Input("scatter_indices: Tindices") + .Input("updates: T") + .Attr("update_computation: func") + .Attr("dimension_numbers: string") + .Attr("indices_are_sorted: bool") + .Attr("T: {numbertype, bool}") + .Attr("Tindices: {int32, int64}") + .Output("output: T") + .SetShapeFn(shape_inference::UnchangedShape) + .Doc(R"doc( +Wraps the XLA Scatter operator documented at + https://www.tensorflow.org/xla/operation_semantics#scatter. + +operand: Array to be scattered into. +scatter_indices: Array containing the starting indices of the slices that must + be scattered to. +updates: Array containing the values that must be used for scattering. +update_computation: Computation to be used for combining the existing values in + the input array and the updates during scatter. +dimension_numbers: A serialized xla::ScatterDimensionNumbers proto. +indices_are_sorted: Boolean indicating if the indices are sorted. +)doc"); + +REGISTER_OP("XlaAllReduce") + .Input("input: T") + .Input("group_assignment: int32") + .Output("output: T") + .Attr("T: {half, bfloat16, float, int32, uint32}") + .Attr("reduce_op: {'Min', 'Max', 'Mul', 'Add', 'Mean'}") + .Attr("mode: {'CrossReplica', 'CrossReplicaAndPartition'}") + .SetShapeFn(shape_inference::UnchangedShape) + .Doc(R"doc( +Wraps the XLA AllReduce operator + documented at https://www.tensorflow.org/xla/operation_semantics#allreduce. + +input: Array or a non-empty tuple of arrays to reduce across replicas. +group_assignment: Groups between which the reductions are performed. +reduce_op: Reduction computation. +mode: group mode. + CrossReplica: group_assignment contains replica_id. Each group contains the + replicas for the current partition. + CrossReplicaAndPartition: group_assignment contains replica_id. Each group + contains the replicas for all partitions. +)doc"); + +REGISTER_OP("XlaReduceScatter") + .Input("input: T") + .Input("group_assignment: int32") + .Input("scatter_dimension: int32") + .Output("output: T") + .Attr("T: {half, bfloat16, float, int32, uint32}") + .Attr("reduce_op: {'Min', 'Max', 'Mul', 'Add', 'Mean'}") + .SetShapeFn(shape_inference::ReduceScatterShape) + .Doc(R"doc( +Wraps the XLA ReduceScatter operator + documented at https://www.tensorflow.org/xla/operation_semantics#reducescatter. + +input: Array or a non-empty tuple of arrays to reduce across replicas. +group_assignment: Groups between which the reductions are performed. +scatter_dimension: Dimension to scatter. +reduce_op: Reduction computation. +)doc"); + +absl::Status OptimizationBarrierShape(shape_inference::InferenceContext* c) { + for (int i = 0; i < c->num_inputs(); ++i) { + c->set_output(i, c->input(i)); + } + return absl::OkStatus(); +} + +REGISTER_OP("XlaOptimizationBarrier") + .Input("input: T") + .Output("output: T") + .Attr("T: list(type) >= 0") + .SetShapeFn(OptimizationBarrierShape) + .Doc(R"doc( +Wraps the XLA OptimizationBarrier operator. + +Documented at https://www.tensorflow.org/xla/operation_semantics#optimizationbarrier. + +input: A Tuple of Arrays of any type. +)doc"); + +REGISTER_OP("XlaReducePrecision") + .Input("operand: T") + .Output("output: T") + .Attr("T: {bfloat16, half, float, double}") + .Attr("exponent_bits: int") + .Attr("mantissa_bits: int") + .SetShapeFn(shape_inference::UnchangedShape) + .Doc(R"doc( +Wraps the XLA ReducePrecision operator + documented at https://www.tensorflow.org/xla/operation_semantics#reduceprecision. + +operand: array of floating-point type. +exponent_bits: number of exponent bits in lower-precision format +mantissa_bits: number of mantissa bits in lower-precision format +)doc"); + +REGISTER_OP("XlaCustomCall") + .Input("args: T") + .Output("output: dtype") + .Attr("target_name: string") + .Attr("backend_config: string") + .Attr("T: list(type) >= 0") + .Attr("dtype: type") + .Attr("shape: shape") + .SetShapeFn([](shape_inference::InferenceContext* c) { + TensorShape shape_attr; + TF_RETURN_IF_ERROR(c->GetAttr("shape", &shape_attr)); + shape_inference::ShapeHandle s; + TF_RETURN_IF_ERROR(c->MakeShapeFromTensorShape(shape_attr, &s)); + c->set_output(0, s); + return absl::OkStatus(); + }) + .Doc(R"doc( +Wraps the XLA CustomCall operator + documented at https://www.tensorflow.org/xla/operation_semantics#customcall. + +args: A list of `Tensor` with possibly different types. +target_name: Name of the function. A call instruction will be emitted which + targets this symbol name. +backend_config: String, used to encode serialized metadata to the backend. +dtype: Output tensor data type. +shape: Output tensor shape. +)doc"); + +REGISTER_OP("XlaCustomCallV2") + .Input("operands: operand_dtypes") + .Output("results: result_dtypes") + .Attr("call_target_name: string") + .Attr("backend_config: string") + .Attr("has_side_effect: bool") + .Attr("operand_dtypes: list(type) >= 0") + .Attr("result_dtypes: list(type) >= 0") + .Attr("result_shapes: list(shape) >= 0") + .SetShapeFn([](shape_inference::InferenceContext* c) { + std::vector shapes; + TF_RETURN_IF_ERROR(c->GetAttr("result_shapes", &shapes)); + if (shapes.size() != c->num_outputs()) { + return absl::InvalidArgumentError( + absl::StrCat("Unexpected number of result shapes: ", shapes.size(), + " != ", c->num_outputs())); + } + for (int i = 0; i < c->num_outputs(); ++i) { + shape_inference::ShapeHandle shape; + TF_RETURN_IF_ERROR(c->MakeShapeFromTensorShape(shapes[i], &shape)); + c->set_output(i, shape); + } + return absl::OkStatus(); + }) + .Doc(R"doc( +Emits an HLO `CustomCall` operation with multiple outputs. + +As opposed to `XlaCustomCall`, this operation supports multiple outputs. + +See `CustomCall` specification at + https://tensorflow.org/xla/operation_semantics#customcall, +and `mhlo.custom_call` specification at + https://tensorflow.org/mlir/hlo_ops#mhlocustom_call_mlirmhlocustomcallop. + +operands: A sequence of tensors with possibly different types. +call_target_name: Name of the user function. The function signature must conform + to version 3 of the API, see `API_VERSION_STATUS_RETURNING_UNIFIED`. All + operands and results assumed to be in the default layout. +backend_config: A string that encodes a metadata for the backend. +has_side_effect: Indicates whether the custom call has side effects. +result_dtypes: Types of all results. +result_shapes: Shapes of all results. +)doc"); + +REGISTER_OP("XlaCallModule") + .Input("args: Tin") + .Output("output: Tout") + .Attr("version: int") + .Attr("module: string") + .Attr("Sout: list(shape) >= 0") + .Attr("Tout: list(type) >= 0") + .Attr("Tin: list(type) >= 0") + .Attr("dim_args_spec: list(string) = []") + .Attr("platforms: list(string) = []") + .Attr("function_list: list(func) = []") + .Attr("has_token_input_output: bool = false") + .Attr("disabled_checks: list(string) = []") + .Attr("use_shardy_partitioner: bool = false") + .SetIsStateful() + .SetShapeFn([](shape_inference::InferenceContext* c) { + std::vector args_shapes; + TF_RETURN_IF_ERROR(c->input("args", &args_shapes)); + for (int i = 0; i < args_shapes.size(); ++i) { + VLOG(3) << "XlaCallModule.shape_inference args[" << i + << "] : " << c->DebugString(args_shapes[i]); + } + std::vector shapes_attr; + TF_RETURN_IF_ERROR(c->GetAttr("Sout", &shapes_attr)); + for (int i = 0; i < shapes_attr.size(); ++i) { + shape_inference::ShapeHandle s; + TF_RETURN_IF_ERROR( + c->MakeShapeFromPartialTensorShape(shapes_attr[i], &s)); + VLOG(3) << "XlaCallModule.shape_inference out[" << i + << "] : " << c->DebugString(s); + c->set_output(i, s); + } + return absl::OkStatus(); + }) + .Doc(R"doc( +Invokes a StableHLO module. + +This op is used with JAX native serialization in a TensorFlow context with +stability guarantees. + +args: A list of `Tensor` with possibly different types to be passed as arguments + to the `module`. These are the actual arguments and do not include the + platform argument (see `platforms`) nor the dimension arguments (see + `dim_args_spec`). +version: Tracks changes the semantics of the op, to support backwards + compatibility. Minimum supported version is 2. From + version 2, the op carries a StableHLO text or bytecode `module`. From + version 3, the op also supports the `platforms` attribute. From version 4, + the op carries a StableHLO module with compatibility guarantees. From version + 5, XLACallModule can include `stablehlo.custom_call` op to execute tf + functions. From version 6 the op supports the `disabled_checks` attribute. + See more versioning details at https://github.com/search?q=repo%3Atensorflow%2Ftensorflow+path%3Axla_call_module+%22int+kVersionMaximumSupported%22&type=code. +module: A serialized computation, a text or bytecode representation of + an mlir.Module. The return type must be a tuple if and only if the `Sout` is + a list with 0 or more than 1 elements. The length of `Tout` and + `Sout` must match. This op always returns a tuple of results, even if the + module returns a single result. +Tout: List of output tensor data types. +Sout: List of output tensor shapes. +platforms: the list of platforms supported by `module`. The list can contain + the strings "CPU", "CUDA", "ROCM", or "TPU". It is an error to compile + this op for a platform that does not appear in the list. This check can be + disabled using `disabled_checks`. If the list contains more than + one platform, then the `module` takes one additional 0-dimensional + integer-tensor parameter in the first position, encoding the index in + `platforms` of the current compilation platform. This parameter has value 0 + if the plaform is not among `platforms` and the check has been disabled. + The list can be empty in old versions (earlier than 6) to denote that no + platform checking must be performed at loading time. +dim_args_spec: this attribute is not supported anymore. +function_list: This list contains the TensorFlow FunctionDefs that are used by + the XLACallModule. If the XLACallModule contains `stablehlo.custom_call` + operations, they can call TensorFlow graph functions outside of the + XLACallModule. This `function_list` attribute registers the dependency of the + XLACallModule on those functions. This attribute was added in version 5. +has_token_input_output: If true, the embedded StableHLO module's main function + must take a `!stablehlo.token` as its first argument and returns a token as + its first result. This can be used in conjunction with the TF2XLA's side + effect mechanism in order to model side effects. This is used only in versions + prior to version 9. After that, the number and position of tokens among + the arguments and results are obtained from the main function type. This + allows us to support more than one token and not necessarily at the start. +disabled_checks: A list of strings describing the safety checks that were + disabled at serialization time. This attribute was added in version 6. + For more details see + https://github.com/search?q=repo%3Agoogle%2Fjax+path%3Ajax_export+%22class+DisabledSafetyCheck%22&type=code. + This list, supplemented with a comma-separate list of directives specified + using the flag --tf_xla_call_module_disabled_checks, + is used at module loading time to skip the corresponding checks. +use_shardy_partitioner: Indicates whether Shardy is used for SPMD partitioning. +)doc"); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/BUILD b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..c67d7d39cdd9acb4e21be9c92fb1fcb425267886 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/BUILD @@ -0,0 +1,39 @@ +load("//tensorflow:tensorflow.default.bzl", "tf_custom_op_py_library") +load( + "//tensorflow/core/platform:build_config.bzl", + "tf_py_clif_cc", +) + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = [ + "//visibility:public", + ], + licenses = ["notice"], +) + +tf_py_clif_cc( + name = "xla_op_registry", + srcs = ["xla_op_registry.clif"], + pyclif_deps = [ + "//tensorflow/core/framework:kernel_def_pyclif", + ], + deps = [ + "//tensorflow/compiler/tf2xla:xla_compiler", + ], +) + +tf_custom_op_py_library( + name = "xla", + srcs = ["xla.py"], + dso = ["//tensorflow/compiler/tf2xla/ops:_xla_ops.so"], + kernels = [ + "//tensorflow/compiler/tf2xla/ops:xla_ops", + ], + deps = [ + "//tensorflow/compiler/tf2xla/ops:gen_xla_ops", + "//tensorflow/python/ops:random_ops_util", + "//tensorflow/python/ops/numpy_ops:np_utils", + "@xla//xla:xla_data_proto_py", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/xla.py b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/xla.py new file mode 100644 index 0000000000000000000000000000000000000000..1db36f9f4030f7694c82e953444a55ce729c129f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/xla.py @@ -0,0 +1,728 @@ +# 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. +# ============================================================================== +"""Experimental library that exposes XLA operations directly in TensorFlow. + +It is sometimes useful to be able to build HLO programs directly from +TensorFlow. This file provides Tensorflow operators that mirror the semantics of +HLO operators as closely as possible. + +Note: Most of the operators defined in this module are used by the jax2tf +converter (see go/jax2tf for details) and are used in SavedModel produced +by jax2tf. Hence, we need to maintain backwards compatibility for these +operators. Please reach out to the JAX team if you want to make changes. +""" + +from tensorflow.compiler.tf2xla.ops import gen_xla_ops +from xla import xla_data_pb2 +from tensorflow.core.framework import attr_value_pb2 +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 bitwise_ops +from tensorflow.python.ops import gen_math_ops +from tensorflow.python.ops import gen_random_ops +from tensorflow.python.ops import math_ops +from tensorflow.python.ops import random_ops +from tensorflow.python.ops import random_ops_util +from tensorflow.python.ops import special_math_ops +from tensorflow.python.ops.numpy_ops import np_utils + +# TODO(phawkins): provide wrappers for all XLA operators. Currently the missing +# ops include: +# infeed/outfeed (available via tf.contrib.tpu) +# collectives, e.g., cross-replica-sum (available via tf.contrib.tpu) +# conditional +# gather/scatter +# collapse + +# This file reuses builtin names (following XLA's names, so we can call things +# like xla.max), so we capture the builtin versions here. +# pylint: disable=redefined-builtin +_max = max +_min = min +_slice = slice # pylint: disable=invalid-name + +constant = constant_op.constant + +# Unary operators. + +# For most arithmetic operators there is a TensorFlow operator +# that exactly corresponds to each XLA operator. Rather than defining +# XLA-specific variants, we reuse the corresponding TensorFlow operator. +# TODO(phawkins): It would be even better to have TensorFlow operators that 1:1 +# wrap every HLO operator, because that would allow us to be confident that the +# semantics match. + + +def _unary_op(fn): + """Wrapper that restricts `fn` to have the correct signature.""" + + def unary_op_wrapper(x, name=None): + return fn(x, name=name) + + return unary_op_wrapper + + +abs = _unary_op(math_ops.abs) +# TODO(phawkins): implement clz. +conj = _unary_op(math_ops.conj) +cos = _unary_op(math_ops.cos) +ceil = _unary_op(math_ops.ceil) +digamma = _unary_op(math_ops.digamma) +erf = _unary_op(math_ops.erf) +erfc = _unary_op(math_ops.erfc) +erfinv = _unary_op(math_ops.erfinv) +ndtri = _unary_op(math_ops.ndtri) +exp = _unary_op(math_ops.exp) +expm1 = _unary_op(math_ops.expm1) +floor = _unary_op(math_ops.floor) +imag = _unary_op(math_ops.imag) +is_finite = _unary_op(math_ops.is_finite) +lgamma = _unary_op(math_ops.lgamma) +log = _unary_op(math_ops.log) +log1p = _unary_op(math_ops.log1p) +logical_not = _unary_op(math_ops.logical_not) +neg = _unary_op(math_ops.neg) +real = _unary_op(math_ops.real) +# TODO(phawkins): unlike xla::Round, this rounds to even instead of zero for +# numbers halfway between two integers. +round = _unary_op(math_ops.round) +sin = _unary_op(math_ops.sin) +sign = _unary_op(math_ops.sign) +tan = _unary_op(math_ops.tan) +tanh = _unary_op(math_ops.tanh) + +# Bessel +bessel_i0e = _unary_op(special_math_ops.bessel_i0e) +bessel_i1e = _unary_op(special_math_ops.bessel_i1e) + +# Binary operators + +# The main difference between TensorFlow and XLA binary ops is the broadcasting +# semantics. TensorFlow uses Numpy-style broadcasting semantics, whereas XLA +# requires an explicit specification of which dimensions to broadcast if the +# arguments have different ranks. + + +def _broadcasting_binary_op(fn): + """Wraps a binary Tensorflow operator and performs XLA-style broadcasting.""" + + def broadcasting_binary_op_wrapper(x, y, broadcast_dims=None, name=None): + """Inner wrapper function.""" + broadcast_dims = broadcast_dims or [] + broadcast_dims = ops.convert_to_tensor(broadcast_dims, dtypes.int64) + # Rather than relying on having static shape information in the TensorFlow + # graph, we use an XlaBroadcastHelper op that can compute the correct shapes + # at JIT compilation time. + x, y = gen_xla_ops.xla_broadcast_helper(x, y, broadcast_dims) + return fn(x, y, name=name) + + return broadcasting_binary_op_wrapper + + +# Map from TF signed types to TF unsigned types. +_SIGNED_TO_UNSIGNED_TABLE = { + dtypes.int8: dtypes.uint8, + dtypes.int16: dtypes.uint16, + dtypes.int32: dtypes.uint32, + dtypes.int64: dtypes.uint64, +} + +# Map from TF unsigned types to TF signed types. +_UNSIGNED_TO_SIGNED_TABLE = { + dtypes.uint8: dtypes.int8, + dtypes.uint16: dtypes.int16, + dtypes.uint32: dtypes.int32, + dtypes.uint64: dtypes.int64, +} + + +def _shift_right_logical_helper(x, y, name=None): + """Performs an integer right logical shift irrespective of input type.""" + assert y.dtype == x.dtype + dtype = x.dtype + signed = dtype in _SIGNED_TO_UNSIGNED_TABLE + if signed: + unsigned_dtype = _SIGNED_TO_UNSIGNED_TABLE[dtype] + x = math_ops.cast(x, unsigned_dtype) + y = math_ops.cast(y, unsigned_dtype) + output = bitwise_ops.right_shift(x, y, name=name) + if signed: + output = math_ops.cast(output, dtype) + return output + + +def _shift_right_arithmetic_helper(x, y, name=None): + """Performs an integer right arithmetic shift irrespective of input type.""" + assert y.dtype == x.dtype + dtype = x.dtype + unsigned = dtype in _UNSIGNED_TO_SIGNED_TABLE + if unsigned: + signed_dtype = _UNSIGNED_TO_SIGNED_TABLE[dtype] + x = math_ops.cast(x, signed_dtype) + y = math_ops.cast(y, signed_dtype) + output = bitwise_ops.right_shift(x, y, name=name) + if unsigned: + output = math_ops.cast(output, dtype) + return output + + +add = _broadcasting_binary_op(math_ops.add) +sub = _broadcasting_binary_op(math_ops.sub) +mul = _broadcasting_binary_op(math_ops.mul) +div = _broadcasting_binary_op(math_ops.div) +rem = _broadcasting_binary_op(gen_math_ops.mod) +max = _broadcasting_binary_op(math_ops.maximum) +min = _broadcasting_binary_op(math_ops.minimum) +atan2 = _broadcasting_binary_op(math_ops.atan2) +complex = _broadcasting_binary_op(math_ops.complex) +logical_and = _broadcasting_binary_op(math_ops.logical_and) +logical_or = _broadcasting_binary_op(math_ops.logical_or) +logical_xor = _broadcasting_binary_op(math_ops.logical_xor) +eq = _broadcasting_binary_op(math_ops.equal) +ne = _broadcasting_binary_op(math_ops.not_equal) +ge = _broadcasting_binary_op(math_ops.greater_equal) +gt = _broadcasting_binary_op(math_ops.greater) +le = _broadcasting_binary_op(math_ops.less_equal) +lt = _broadcasting_binary_op(math_ops.less) +pow = _broadcasting_binary_op(math_ops.pow) +shift_left = _broadcasting_binary_op(bitwise_ops.left_shift) +shift_right_logical = _broadcasting_binary_op(_shift_right_logical_helper) +shift_right_arithmetic = _broadcasting_binary_op(_shift_right_arithmetic_helper) + +igamma = _broadcasting_binary_op(math_ops.igamma) +igamma_grad_a = _broadcasting_binary_op(gen_math_ops.igamma_grad_a) +random_gamma_grad = _broadcasting_binary_op(gen_random_ops.random_gamma_grad) +igammac = _broadcasting_binary_op(math_ops.igammac) +polygamma = _broadcasting_binary_op(math_ops.polygamma) +zeta = _broadcasting_binary_op(math_ops.zeta) + + +def _binary_op(fn): + """Wrapper that restricts `fn` to have the correct signature.""" + + def binary_op_wrapper(x, y, name=None): + return fn(x, y, name=name) + + return binary_op_wrapper + + +transpose = _binary_op(array_ops.transpose) +rev = _binary_op(array_ops.reverse) + +bitcast_convert_type = array_ops.bitcast + + +def broadcast(x, dims, name=None): + x = ops.convert_to_tensor(x) + shape = array_ops.concat( + [constant_op.constant(dims), array_ops.shape(x)], axis=0 + ) + return array_ops.broadcast_to(x, shape, name=name) + + +def clamp(a, x, b, name=None): + return min(max(a, x, name=name), b, name=name) + + +concatenate = array_ops.concat + + +def conv( + lhs, + rhs, + window_strides, + padding, + lhs_dilation, + rhs_dilation, + dimension_numbers, + feature_group_count=1, + precision_config=None, + preferred_element_type=None, + name=None, + use_v2=False, + batch_group_count=1, +): + """Wraps the XLA ConvGeneralDilated operator. + + ConvGeneralDilated is the most general form of XLA convolution and is + documented at + https://www.tensorflow.org/performance/xla/operation_semantics#conv_convolution + + Args: + lhs: the input tensor + rhs: the kernel tensor + window_strides: the inter-window strides + padding: the padding to apply at the start and end of each input dimensions + lhs_dilation: dilation to apply between input elements + rhs_dilation: dilation to apply between kernel elements + dimension_numbers: a `ConvolutionDimensionNumbers` proto. + feature_group_count: number of feature groups for grouped convolution. + precision_config: a `xla.PrecisionConfig` proto. + preferred_element_type: the result `dtype`. + name: an optional name for the operator. + use_v2: an optional request to use the XlaConvV2 op even if not necessary. + batch_group_count: number of batch groups or grouped filters. + + Returns: + A tensor representing the output of the convolution. + """ + precision_config_proto = "" + if precision_config: + precision_config_proto = precision_config.SerializeToString() + needs_v2 = ( + preferred_element_type + or (lhs.dtype != rhs.dtype) + or batch_group_count > 1 + ) + if preferred_element_type is None: + preferred_element_type = np_utils.result_type(lhs.dtype, rhs.dtype) + if needs_v2 or use_v2: + return gen_xla_ops.xla_conv_v2( + lhs, + rhs, + window_strides=window_strides, + padding=padding, + lhs_dilation=lhs_dilation, + rhs_dilation=rhs_dilation, + feature_group_count=feature_group_count, + batch_group_count=batch_group_count, + dimension_numbers=dimension_numbers.SerializeToString(), + precision_config=precision_config_proto, + preferred_element_type=preferred_element_type, + name=name, + ) + return gen_xla_ops.xla_conv( + lhs, + rhs, + window_strides=window_strides, + padding=padding, + lhs_dilation=lhs_dilation, + rhs_dilation=rhs_dilation, + feature_group_count=feature_group_count, + dimension_numbers=dimension_numbers.SerializeToString(), + precision_config=precision_config_proto, + name=name, + ) + + +convert_element_type = math_ops.cast + + +def dot(lhs, rhs, name=None): + return math_ops.tensordot(lhs, rhs, axes=1, name=name) + + +DotDimensionNumbers = xla_data_pb2.DotDimensionNumbers +PrecisionConfig = xla_data_pb2.PrecisionConfig + + +def dot_general( + lhs, + rhs, + dimension_numbers, + precision_config=None, + preferred_element_type=None, + name=None, + use_v2=False, +): + precision_config_proto = "" + if precision_config: + precision_config_proto = precision_config.SerializeToString() + needs_v2 = preferred_element_type or (lhs.dtype != rhs.dtype) + if preferred_element_type is None: + preferred_element_type = np_utils.result_type(lhs.dtype, rhs.dtype) + if needs_v2 or use_v2: + return gen_xla_ops.xla_dot_v2( + lhs, + rhs, + dimension_numbers=dimension_numbers.SerializeToString(), + precision_config=precision_config_proto, + preferred_element_type=preferred_element_type, + name=name, + ) + return gen_xla_ops.xla_dot( + lhs, + rhs, + dimension_numbers=dimension_numbers.SerializeToString(), + precision_config=precision_config_proto, + name=name, + ) + + +def self_adjoint_eig(a, lower, max_iter, epsilon): + return gen_xla_ops.xla_self_adjoint_eig(a, lower, max_iter, epsilon) + + +def svd(a, max_iter, epsilon, precision_config=None): + precision_config_proto = "" + if precision_config: + precision_config_proto = precision_config.SerializeToString() + return gen_xla_ops.xla_svd(a, max_iter, epsilon, precision_config_proto) + + +dynamic_slice = gen_xla_ops.xla_dynamic_slice +dynamic_update_slice = gen_xla_ops.xla_dynamic_update_slice +einsum = gen_xla_ops.xla_einsum + +# TODO(phawkins): generalize tf.pad to support interior padding, and then remove +# the XLA-specific pad operator. +pad = gen_xla_ops.xla_pad + + +def random_normal(mu, sigma, dims, name=None): + mu = ops.convert_to_tensor(mu) + return random_ops.random_normal( + dims, mean=mu, stddev=sigma, dtype=mu.dtype, name=name + ) + + +def random_uniform(minval, maxval, dims, name=None): + minval = ops.convert_to_tensor(minval) + return random_ops.random_uniform( + dims, minval, maxval, dtype=minval.dtype, name=name + ) + + +def rng_bit_generator(algorithm, initial_state, shape, dtype): + """Stateless PRNG bit generator. + + Wraps the XLA RngBitGenerator operator, documented at + https://www.tensorflow.org/performance/xla/operation_semantics#rngbitgenerator. + + Args: + algorithm: The PRNG algorithm to use, one of tf.random.Algorithm.{PHILOX, + THREEFRY, AUTO_SELECT}. + initial_state: Initial state for the PRNG algorithm. For THREEFRY, it should + be a u64[2] and for PHILOX a u64[3]. + shape: The output shape of the generated data. + dtype: The type of the tensor. + + Returns: + a tuple with a new state and generated data of the given shape. + """ + alg_int = random_ops_util.convert_alg_to_int(algorithm) + return gen_xla_ops.xla_rng_bit_generator( + alg_int, initial_state, shape, dtype=dtype + ) + + +recv = gen_xla_ops.xla_recv +reduce = gen_xla_ops.xla_reduce +variadic_reduce = gen_xla_ops.xla_variadic_reduce_v2 + +ops.no_gradient("XlaVariadicReduce") + + +def reduce_window( + operand, + init, + reducer, + window_dimensions, + window_strides=None, + base_dilations=None, + window_dilations=None, + padding=None, + name=None, +): + """Wraps the XLA ReduceWindow operator. + + ReduceWindow is documented at + https://www.tensorflow.org/performance/xla/operation_semantics#reducewindow . + + Args: + operand: the input tensor + init: a scalar tensor representing the initial value for the reduction + reducer: a reduction function that combines a pair of scalars. + window_dimensions: shape of the window, as a list of integers + window_strides: inter-window strides, as a list of integers. Optional; if + omitted, defaults to strides of 1. + padding: padding to apply to 'operand'. List of (low, high) pairs of + integers that specify the padding to apply before and after each + dimension. Optional; if omitted, defaults to no padding. + name: the operator name, or None. + + Returns: + A tensor that represents the output of the reduce_window operator. + """ + window_strides = window_strides or [1] * len(window_dimensions) + base_dilations = base_dilations or [1] * len(window_dimensions) + window_dilations = window_dilations or [1] * len(window_dimensions) + padding = padding or [(0, 0)] * len(window_dimensions) + return gen_xla_ops.xla_reduce_window( + input=operand, + init_value=init, + window_dimensions=window_dimensions, + window_strides=window_strides, + base_dilations=base_dilations, + window_dilations=window_dilations, + padding=padding, + computation=reducer, + name=name, + ) + + +replica_id = gen_xla_ops.xla_replica_id + +# Set a static bound for the given input value as a hint to Xla compiler, +# returns the same value. +# Usage: +# def f(t, p): +# p = xla.set_bound(p, 3) # Tells xla the constraint that p <= 3. +# return t[:p] # xla knows the bound of the slice is 3. +set_bound = gen_xla_ops.xla_set_bound + +# Make a static dimension into a xla bounded dynamic dimension. The current +# static dimension size will become the bound and the second operand becomes the +# dynamic size of the dimension. +# +# This should mostly be used for testing. +# +# def f(): +# array = tf.convert_to_tensor([[1, 2, 3, 4, 5]]) +# # Tells xla the valid size of the array is 3. +# dim = 0 +# p = xla_set_dynamic_dimension_size(array, dim, 3) +# assert(reduce_sum(p) == 6) # xla knows only the first 3 elements are valid. +set_dynamic_dimension_size = gen_xla_ops.xla_set_dynamic_dimension_size + +# Inverse of xla_set_dynamic_dimension_size. Make an xla bounded dynamic +# dimension into a static dimension. The bound of the size of dimension +# `dim_index` becomes the static dimension size. +remove_dynamic_dimension_size = gen_xla_ops.xla_remove_dynamic_dimension_size + + +def reshape(x, new_sizes, dimensions=None, name=None): + if dimensions is not None: + x = array_ops.transpose(x, dimensions) + x = array_ops.reshape(x, new_sizes, name=name) + return x + + +def select(condition, x, y, name=None): + return array_ops.where(condition, x, y, name) + + +select_and_scatter = gen_xla_ops.xla_select_and_scatter +send = gen_xla_ops.xla_send + + +def slice(x, start_dims, limit_dims, strides): + spec = [ + _slice(start, limit, stride) + for (start, limit, stride) in zip(start_dims, limit_dims, strides) + ] + return x[tuple(spec)] + + +sharding = gen_xla_ops.xla_sharding + + +@ops.RegisterGradient("XlaSharding") +def _sharding_grad(op, grad): + """Gradient for XlaSharding op.""" + sharding_attr = op.get_attr("sharding") + grad_sharding = gen_xla_ops.xla_sharding( + grad, + sharding=sharding_attr, + unspecified_dims=op.get_attr("unspecified_dims"), + ) + # pylint: disable=protected-access + grad_sharding.op._set_attr( + "_XlaSharding", attr_value_pb2.AttrValue(s=sharding_attr) + ) + return [grad_sharding] + + +spmd_full_to_shard_shape = gen_xla_ops.xla_spmd_full_to_shard_shape +spmd_shard_to_full_shape = gen_xla_ops.xla_spmd_shard_to_full_shape + + +@ops.RegisterGradient("XlaSpmdFullToShardShape") +def _spmd_full_to_shard_shape_grad(op, grad): + s2f = gen_xla_ops.xla_spmd_shard_to_full_shape( + grad, + manual_sharding=op.get_attr("manual_sharding"), + full_shape=op.inputs[0].shape.as_list(), + dim=op.get_attr("dim"), + unspecified_dims=op.get_attr("unspecified_dims"), + ) + return [s2f] + + +@ops.RegisterGradient("XlaSpmdShardToFullShape") +def _spmd_shard_to_full_shape_grad(op, grad): + f2s = gen_xla_ops.xla_spmd_full_to_shard_shape( + grad, + manual_sharding=op.get_attr("manual_sharding"), + dim=op.get_attr("dim"), + unspecified_dims=op.get_attr("unspecified_dims"), + ) + return [f2s] + + +sort = gen_xla_ops.xla_sort +key_value_sort = gen_xla_ops.xla_key_value_sort +variadic_sort = gen_xla_ops.xla_variadic_sort +while_loop = gen_xla_ops.xla_while +dequantize = gen_xla_ops.xla_dequantize +custom_call = gen_xla_ops.xla_custom_call + + +def custom_call_v2( + call_target_name, + operands, + result_specs, + backend_config=None, + has_side_effect=None, + name=None, +): + """Emits an HLO `CustomCall` operation with multiple outputs. + + See `CustomCall` specification at + https://tensorflow.org/xla/operation_semantics#customcall, + and `mhlo.custom_call` specification at + https://tensorflow.org/mlir/hlo_ops#mhlocustom_call_mlirmhlocustomcallop. + + Args: + call_target_name: Name of the user function. The function signature must + conform to version 3 of the API, see + `API_VERSION_STATUS_RETURNING_UNIFIED`. All operands and results assumed + to be in the default layout. + operands: A sequence of tensors with possibly different types. + result_specs: A sequence of tensor specs for all results. + backend_config: A string that encodes a metadata for the backend. Empty + string by default. + has_side_effect: Indicates whether the custom call has side effects. `False` + by default. + name: Optional name of the operation. + + Returns: + A tuple of output tensors. + """ + return gen_xla_ops.xla_custom_call_v2( + operands=operands, + call_target_name=call_target_name, + backend_config="" if backend_config is None else backend_config, + has_side_effect=False if has_side_effect is None else has_side_effect, + result_dtypes=tuple(spec.dtype for spec in result_specs), + result_shapes=tuple(spec.shape for spec in result_specs), + name=name, + ) + + +# pylint: disable=g-doc-args +# pylint: disable=g-doc-return-or-yield +def call_module( + args, + *, + version=4, + module, + Tout, + Sout, + platforms=(), + function_list=(), + has_token_input_output=False, + disabled_checks=(), + use_shardy_partitioner=False, +): + """See documentation for the XlaCallModule op. + + https://github.com/search?q=repo%3Atensorflow%2Ftensorflow+path%3Axla_ops.cc+xlacallmodule&type=code + """ + res = gen_xla_ops.xla_call_module( + args, + version=version, + module=module, + dim_args_spec=(), + Tout=Tout, + Sout=Sout, + platforms=platforms, + function_list=function_list, + has_token_input_output=has_token_input_output, + disabled_checks=disabled_checks, + use_shardy_partitioner=use_shardy_partitioner, + ) + # Since XLACallModule op is stateful, zero return function will return the TF + # op under tf.function. It creates trouble for downstream codes. + # Here we force it return empty tuple to work around it. + # TODO(johnqiangzhang): Figure out a better way to handle control dependency. + if isinstance(res, ops.Operation): + res = () + return res + + +def call_module_maximum_supported_version(): + """Maximum version of XlaCallModule op supported. + + See versioning details documentation for the XlaCallModule op at: + https://github.com/search?q=repo%3Atensorflow%2Ftensorflow+path%3Axla_call_module+%22int+kVersionMaximumSupported%22&type=code + """ + return 10 + +# pylint: enable=g-doc-args +# pylint: enable=g-doc-return-or-yield + + +def call_module_disable_check_platform(): + # For use with xla_call_module.disabled_checks. + return "platform" + + +def gather( + operand, + start_indices, + dimension_numbers, + slice_sizes, + indices_are_sorted=False, + name=None, +): + return gen_xla_ops.xla_gather( + operand, + start_indices, + slice_sizes=slice_sizes, + dimension_numbers=dimension_numbers.SerializeToString(), + indices_are_sorted=indices_are_sorted, + name=name, + ) + + +def scatter( + operand, + scatter_indices, + updates, + update_computation, + dimension_numbers, + indices_are_sorted=False, + name=None, +): + return gen_xla_ops.xla_scatter( + operand, + scatter_indices, + updates, + update_computation=update_computation, + dimension_numbers=dimension_numbers.SerializeToString(), + indices_are_sorted=indices_are_sorted, + name=name, + ) + + +def optimization_barrier(*args): + return gen_xla_ops.xla_optimization_barrier(args) + + +def reduce_precision(operand, exponent_bits, mantissa_bits): + return gen_xla_ops.xla_reduce_precision(operand, exponent_bits, mantissa_bits) diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/xla_op_registry.clif b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/xla_op_registry.clif new file mode 100644 index 0000000000000000000000000000000000000000..fc5589d7ce8157edb28d1177e3d0e4588e7ed15a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/python/xla_op_registry.clif @@ -0,0 +1,7 @@ +from "third_party/tensorflow/core/framework/kernel_def_pyclif.h" import * # KernelDef + +from "third_party/tensorflow/compiler/tf2xla/xla_op_registry.h": + namespace `tensorflow`: + def `XlaOpRegistry::DeviceKernels` as + device_kernels(device: str, include_compilation_only_kernels: bool) -> + list diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/rearrange_function_argument.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/rearrange_function_argument.cc new file mode 100644 index 0000000000000000000000000000000000000000..4248042347212b8b1cfd6277a2b0f226547c0ad5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/rearrange_function_argument.cc @@ -0,0 +1,563 @@ +/* Copyright 2019 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/rearrange_function_argument.h" + +#include + +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "xla/status_macros.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/lib/gtl/inlined_vector.h" +#include "tensorflow/core/public/session_options.h" +#include "tensorflow/core/public/version.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { + +namespace { + +// Given original input types and argument index mapping, return the new input +// types. +std::vector ShuffleInputDataTypeAttribute( + const std::vector& in_types, + const std::vector& index_mapping) { + std::vector result(index_mapping.size()); + for (int i = 0, end = in_types.size(); i < end; i++) { + result[index_mapping.at(i)] = in_types[i]; + } + return result; +} + +// Given original input types, check if we need to rewrite the function (by +// checking if all DT_RESOURCE inputs are in the end). If the function needs to +// be rewritten, `resource_input_count` will be set to number of DT_RESOURCE +// inputs, and `index_mapping` will hold a mapping for original input index to +// rearranged input index. +absl::Status InputTypesNeedsRearrange(const std::vector& in_types, + bool* need_rewrite, + int* resource_input_count, + std::vector* index_mapping) { + int first_resource_index = -1; + for (int i = 0, end = in_types.size(); i < end; i++) { + DataType type = in_types[i]; + if (type == DT_RESOURCE) { + first_resource_index = i; + break; + } + } + if (first_resource_index == -1) { + // No resource input. No need to rewrite. + *need_rewrite = false; + return absl::OkStatus(); + } + + *need_rewrite = false; + for (int i = first_resource_index + 1, end = in_types.size(); i < end; i++) { + if (in_types[i] != DT_RESOURCE) { + *need_rewrite = true; + break; + } + } + if (!*need_rewrite) { + return absl::OkStatus(); + } + + *resource_input_count = 0; + for (int i = 0, end = in_types.size(); i < end; i++) { + DataType type = in_types[i]; + if (type == DT_RESOURCE) { + ++(*resource_input_count); + } + } + int non_resource_index = 0, + resource_index = in_types.size() - *resource_input_count; + index_mapping->resize(in_types.size()); + for (int i = 0, end = in_types.size(); i < end; i++) { + if (in_types[i] != DT_RESOURCE) { + (*index_mapping)[i] = non_resource_index; + non_resource_index++; + } else { + (*index_mapping)[i] = resource_index; + resource_index++; + } + } + + return absl::OkStatus(); +} + +// Given mapping between original input index and rearranged input index, +// reorder input edges for the node. +absl::Status ReorderInputEdges(Graph* g, Node* n, + const std::vector& index_mapping) { + std::vector input_edges; + for (const Edge* e : n->in_edges()) { + if (e->IsControlEdge()) { + continue; + } + input_edges.push_back(e); + } + for (const Edge* e : input_edges) { + Node* src = e->src(); + int src_output = e->src_output(); + int dst_input = e->dst_input(); + int new_dst_input = index_mapping.at(dst_input); + g->RemoveEdge(e); + g->AddEdge(src, src_output, n, new_dst_input)->DebugString(); + } + return absl::OkStatus(); +} + +// For While node, given mapping between original input index and rearranged +// input index, reorder output edges for the node. DT_RESOURCE outputs are +// removed from the node and we will use the node's corresponding input for the +// edge. +absl::Status ReorderOutputEdges(Graph* g, Node* n, int input_count, + int resource_input_count, + const std::vector& index_mapping) { + std::vector output_edges; + for (const Edge* e : n->out_edges()) { + if (e->IsControlEdge()) { + continue; + } + output_edges.push_back(e); + } + for (const Edge* e : output_edges) { + int src_output = e->src_output(); + int new_src_output = index_mapping.at(src_output); + Node* dst = e->dst(); + int dst_input = e->dst_input(); + g->RemoveEdge(e); + + if (new_src_output < input_count - resource_input_count) { + g->AddEdge(n, new_src_output, dst, dst_input); + } else { + const Edge* input_edge; + TF_RETURN_IF_ERROR(n->input_edge(new_src_output, &input_edge)); + g->AddEdge(input_edge->src(), input_edge->src_output(), dst, dst_input); + } + } + return absl::OkStatus(); +} + +// Given mapping between original input index and rearranged input index, change +// "index" attribute for _Arg nodes. +void RearrangeArgNodes(const absl::InlinedVector* arg_nodes, + const std::vector& index_mapping) { + for (int i = 0; i < arg_nodes->size(); i++) { + Node* n = (*arg_nodes)[i]; + int new_index = index_mapping.at(i); + n->ClearAttr("index"); + n->AddAttr("index", new_index); + } +} + +// Given all _Retval nodes in the function, return if we need to rewrite the +// function (by checking if we have DT_RESOURCE return values). If we need to +// rewrite the function, `retval_index_mapping` will hold the mapping from +// original _Retval to rearranged _Retval, and `resource_retval_to_arg` will +// hold mapping from DT_RESOURCE _Retval index to its input _Arg index. Here we +// assume that all DT_RESOURCE _Retval nodes come from _Arg nodes directly. +absl::Status CalculateRetvalRearrange( + const absl::InlinedVector& ret_nodes, + std::map* retval_index_mapping, + std::map* resource_retval_to_arg) { + for (int i = 0, end = ret_nodes.size(); i < end; i++) { + Node* n = ret_nodes[i]; + DataType t; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "T", &t)); + if (t != DT_RESOURCE) { + int new_retval_index = retval_index_mapping->size(); + retval_index_mapping->insert(std::make_pair(i, new_retval_index)); + continue; + } + + const Edge* e; + TF_RETURN_IF_ERROR(n->input_edge(0, &e)); + if (!e->src()->IsArg()) { + return absl::UnimplementedError( + absl::StrCat("Resource _Retval node's input does not come from _Arg " + "directly: ", + e->DebugString())); + } + Node* arg = e->src(); + int src_index; + TF_RETURN_IF_ERROR(GetNodeAttr(arg->def(), "index", &src_index)); + resource_retval_to_arg->insert(std::make_pair(i, src_index)); + } + return absl::OkStatus(); +} + +// Given original output types and return value index mapping, return the new +// output types. Notice that DT_RESOURCE will be removed. +std::vector ShuffleOutputDataTypeAttribute( + const std::vector& out_types, + const std::map& index_mapping) { + std::vector result(index_mapping.size()); + for (int i = 0; i < out_types.size(); i++) { + auto iter = index_mapping.find(i); + if (iter != index_mapping.end()) { + result[iter->second] = out_types[i]; + } + } + return result; +} + +// For StatefulPartitionedCall node, given mapping between original input index +// and rearranged input index, reorder output edges for the node. DT_RESOURCE +// outputs are removed from the node and we will use the node's corresponding +// input for the edge. +absl::Status RearrangeOutputEdges( + Node* n, Graph* g, const std::map& retval_index_mapping, + const std::map& resource_retval_to_arg) { + std::vector out_edges; + for (const Edge* e : n->out_edges()) { + if (!e->IsControlEdge()) { + out_edges.push_back(e); + } + } + for (const Edge* e : out_edges) { + Node* dst = e->dst(); + int dst_input = e->dst_input(); + int src_output = e->src_output(); + auto iter = retval_index_mapping.find(src_output); + if (iter == retval_index_mapping.end()) { + TF_RET_CHECK(resource_retval_to_arg.find(src_output) != + resource_retval_to_arg.end()); + g->RemoveEdge(e); + const Edge* input_edge; + TF_RETURN_IF_ERROR( + n->input_edge(resource_retval_to_arg.at(src_output), &input_edge)); + g->AddEdge(input_edge->src(), input_edge->src_output(), dst, dst_input); + } else { + g->RemoveEdge(e); + g->AddEdge(n, iter->second, dst, dst_input); + } + } + return absl::OkStatus(); +} + +// Given mapping between original output index and rearranged output index, +// change "index" attribute for _Retval nodes. Notice that DT_RESOURCE _Retval +// nodes will be removed. +void RearrangeRetvalNodes(const absl::InlinedVector& ret_nodes, + Graph* g, + const std::map& retval_index_mapping) { + for (int i = 0, end = ret_nodes.size(); i < end; i++) { + Node* n = ret_nodes[i]; + auto iter = retval_index_mapping.find(i); + if (iter == retval_index_mapping.end()) { + g->RemoveNode(n); + } else { + n->ClearAttr("index"); + n->AddAttr("index", iter->second); + } + } +} + +absl::Status MaybeRewriteWhileNode( + std::function + get_function_body_fn, + Graph* g, Node* n, FunctionLibraryDefinition* fld, bool* node_rewritten) { + // Check if this While node needs rewrite. + std::vector types; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "T", &types)); + bool input_need_rearrange; + int resource_input_count; + std::vector index_mapping; + TF_RETURN_IF_ERROR(InputTypesNeedsRearrange( + types, &input_need_rearrange, &resource_input_count, &index_mapping)); + if (!input_need_rearrange) { + *node_rewritten = false; + return absl::OkStatus(); + } + + *node_rewritten = true; + + // Modify "T" attribute for this While node. + std::vector new_types = + ShuffleInputDataTypeAttribute(types, index_mapping); + n->ClearAttr("T"); + n->AddAttr("T", new_types); + + // Reorder input and output edges. + TF_RETURN_IF_ERROR(ReorderInputEdges(g, n, index_mapping)); + TF_RETURN_IF_ERROR(ReorderOutputEdges(g, n, types.size(), + resource_input_count, index_mapping)); + + // Modify cond and body functions. + for (auto const& attr_name : std::vector{"cond", "body"}) { + NameAttrList attr_value; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), attr_name, &attr_value)); + const FunctionBody* fbody; + TF_RETURN_IF_ERROR(get_function_body_fn(attr_value, &fbody)); + + // Check that resource _Arg nodes for While node are always returned with + // the same index, and we don't have cases like this: + // tf.while_loop( + // cond, + // lambda resource_var1, resource_var2: [resource_var2, resource_var1], + // [resource_var1, resource_var2]) + if (attr_name == "body") { + for (int i = 0, end = fbody->ret_nodes.size(); i < end; i++) { + Node* n = fbody->ret_nodes[i]; + DataType dtype; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "T", &dtype)); + if (dtype != DT_RESOURCE) { + continue; + } + + Node* input_node; + TF_RETURN_IF_ERROR(n->input_node(0, &input_node)); + while (input_node->IsIdentity()) { + TF_RETURN_IF_ERROR(input_node->input_node(0, &input_node)); + } + if (input_node->IsArg()) { + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(input_node->def(), "index", &index)); + if (index != i) { + return absl::UnimplementedError(absl::StrCat( + "While node ", n->DebugString(), " has resource _Retval[", i, + "] coming from _Arg[", index, "]")); + } + } else { + return absl::UnimplementedError( + absl::StrCat("Encountered node ", input_node->DebugString(), + " while tracing _Arg node for _Retval[", i, + "] of while node ", n->DebugString())); + } + } + } + + RearrangeArgNodes(&fbody->arg_nodes, index_mapping); + if (attr_name == "body") { + for (int i = 0, end = fbody->ret_nodes.size(); i < end; i++) { + Node* n = fbody->ret_nodes[i]; + int new_index = index_mapping.at(i); + if (new_index < types.size() - resource_input_count) { + n->ClearAttr("index"); + n->AddAttr("index", new_index); + } else { + fbody->graph->RemoveNode(n); + } + } + } + + // Save the new FunctionDef. + FunctionDef new_fdef; + std::string new_name = + fld->UniqueFunctionName(absl::StrCat(attr_value.name(), "_rearrange_")); + TF_RETURN_IF_ERROR(GraphToFunctionDef(*fbody->graph, new_name, &new_fdef)); + + const StackTracesMap* stack_traces = fld->GetStackTraces(attr_value.name()); + if (stack_traces != nullptr) { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(new_fdef, *stack_traces)); + } else { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(new_fdef, {})); + } + + // Change node to use rewritten function. + attr_value.set_name(new_name); + n->ClearAttr(attr_name); + n->AddAttr(attr_name, attr_value); + } + return absl::OkStatus(); +} + +absl::Status MaybeRewriteIfNode( + std::function + get_function_body_fn, + Graph* g, Node* n, FunctionLibraryDefinition* fld, bool* node_rewritten, + const FunctionLibraryDefinition* global_fld) { + // This node needs rewrite when either of these is true: + // 1) Tin has DT_RESOURCE which requires rearrange; + // 2) Tout has DT_RESOURCE. + std::vector in_types; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "Tin", &in_types)); + bool input_need_rearrange; + int resource_input_count; + std::vector index_mapping; + TF_RETURN_IF_ERROR(InputTypesNeedsRearrange( + in_types, &input_need_rearrange, &resource_input_count, &index_mapping)); + std::vector out_types; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "Tout", &out_types)); + bool has_resource_output = std::find(out_types.begin(), out_types.end(), + DT_RESOURCE) != out_types.end(); + if (!input_need_rearrange && !has_resource_output) { + *node_rewritten = false; + return absl::OkStatus(); + } + + *node_rewritten = true; + + if (input_need_rearrange) { + // Reorder input edges. + std::vector input_edges; + for (const Edge* e : n->in_edges()) { + if (e->IsControlEdge() || e->dst_input() == 0) { + continue; + } + input_edges.push_back(e); + } + for (const Edge* e : input_edges) { + Node* src = e->src(); + int src_output = e->src_output(); + int dst_input = e->dst_input(); + int new_dst_input = index_mapping.at(dst_input - 1) + 1; + g->RemoveEdge(e); + g->AddEdge(src, src_output, n, new_dst_input)->DebugString(); + } + + // Change Tin attribute. + std::vector new_in_types = + ShuffleInputDataTypeAttribute(in_types, index_mapping); + n->ClearAttr("Tin"); + n->AddAttr("Tin", new_in_types); + } + + std::map resource_retval_to_arg, retval_index_mapping; + for (auto const& attr_name : + std::vector{"then_branch", "else_branch"}) { + NameAttrList f; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), attr_name, &f)); + const FunctionBody* fbody; + TF_RETURN_IF_ERROR(get_function_body_fn(f, &fbody)); + + if (input_need_rearrange) { + // Change _Arg node index. + RearrangeArgNodes(&fbody->arg_nodes, index_mapping); + } + + if (has_resource_output) { + // Resource _Retval must come from resource _Arg directly, or we do + // not support it. + TF_RETURN_IF_ERROR(CalculateRetvalRearrange( + fbody->ret_nodes, &retval_index_mapping, &resource_retval_to_arg)); + + // Change index for _Retval nodes. + RearrangeRetvalNodes(fbody->ret_nodes, fbody->graph, + retval_index_mapping); + } + + // Save the new FunctionDef. + FunctionDef new_fdef; + std::string new_name = + fld->UniqueFunctionName(absl::StrCat(f.name(), "_rearrange_")); + TF_RETURN_IF_ERROR(GraphToFunctionDef(*fbody->graph, new_name, &new_fdef)); + + const StackTracesMap* global_stack_traces = + global_fld ? global_fld->GetStackTraces(f.name()) : nullptr; + const StackTracesMap* local_stack_traces = fld->GetStackTraces(f.name()); + + if (global_stack_traces != nullptr) { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(new_fdef, *global_stack_traces)); + } else if (local_stack_traces != nullptr) { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(new_fdef, *local_stack_traces)); + } else { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(new_fdef, {})); + } + + // Change node to use rewritten function. + f.set_name(new_name); + n->ClearAttr(attr_name); + n->AddAttr(attr_name, f); + } + + if (has_resource_output) { + // Rearrange output edges. + std::vector out_edges; + for (const Edge* e : n->out_edges()) { + if (!e->IsControlEdge()) { + out_edges.push_back(e); + } + } + for (const Edge* e : out_edges) { + Node* dst = e->dst(); + int dst_input = e->dst_input(); + int src_output = e->src_output(); + auto iter = retval_index_mapping.find(src_output); + if (iter == retval_index_mapping.end()) { + TF_RET_CHECK(resource_retval_to_arg.find(src_output) != + resource_retval_to_arg.end()); + g->RemoveEdge(e); + const Edge* input_edge; + TF_RETURN_IF_ERROR(n->input_edge( + resource_retval_to_arg.at(src_output) + 1, &input_edge)); + g->AddEdge(input_edge->src(), input_edge->src_output(), dst, dst_input); + } else { + g->RemoveEdge(e); + g->AddEdge(n, iter->second, dst, dst_input); + } + } + + // Change Tout attribute for the node. + std::vector new_out_types = + ShuffleOutputDataTypeAttribute(out_types, retval_index_mapping); + n->ClearAttr("Tout"); + n->AddAttr("Tout", new_out_types); + } + return absl::OkStatus(); +} + +} // namespace + +absl::Status RearrangeFunctionArguments( + std::function + get_function_body_fn, + Graph* g, FunctionLibraryDefinition* fld, + const FunctionLibraryDefinition* global_fld) { + // Inline StatefulPartitionedCall nodes. + std::vector call_nodes; + for (Node* n : g->nodes()) { + if (n->type_string() == "StatefulPartitionedCall") { + call_nodes.push_back(n); + } + } + for (Node* n : call_nodes) { + NameAttrList func_name_attrs; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), "f", &func_name_attrs)); + const FunctionBody* fbody; + TF_RETURN_IF_ERROR(get_function_body_fn(func_name_attrs, &fbody)); + InlineFunctionBodyOptions opts; + absl::Status s = InlineFunctionBody(*fld, g, n, fbody, opts); + // Inlining might fail because the function is marked with attribute + // _noinline. + s.IgnoreError(); + FixupSourceAndSinkEdges(g); + } + + // Rewrite If/While nodes. + for (Node* n : g->nodes()) { + if (n->IsWhileNode()) { + bool node_rewritten; + TF_RETURN_IF_ERROR(MaybeRewriteWhileNode(get_function_body_fn, g, n, fld, + &node_rewritten)); + } else if (n->IsIfNode()) { + bool node_rewritten; + TF_RETURN_IF_ERROR(MaybeRewriteIfNode(get_function_body_fn, g, n, fld, + &node_rewritten, global_fld)); + } + } + + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/rearrange_function_argument.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/rearrange_function_argument.h new file mode 100644 index 0000000000000000000000000000000000000000..bed42489841176baf68828837aadeb544407f58a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/rearrange_function_argument.h @@ -0,0 +1,42 @@ +/* Copyright 2019 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_REARRANGE_FUNCTION_ARGUMENT_H_ +#define TENSORFLOW_COMPILER_TF2XLA_REARRANGE_FUNCTION_ARGUMENT_H_ + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { + +// For the given graph `g`: +// 1. Rewrite If/While node functions to rearrange arguments and return values, +// so that all resource arguments/return values are placed in the end (as +// required by XlaCompiler), +// 2. Inline StatefulPartitionedCall nodes so we do not need to rearrange +// arguments and return values. +// `get_function_body_fn` is used to instantiate FunctionDef. +// `fld` is used to store rewritten functions. +// `global_fld` is used to potentially supply stack traces for functions when +// they are not found in `fld`. +absl::Status RearrangeFunctionArguments( + std::function + get_function_body_fn, + Graph* g, FunctionLibraryDefinition* fld, + const FunctionLibraryDefinition* global_fld = nullptr); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_REARRANGE_FUNCTION_ARGUMENT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table.cc new file mode 100644 index 0000000000000000000000000000000000000000..e8391f781872cf7dd60d965742ec18c67c17a08f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table.cc @@ -0,0 +1,144 @@ +/* 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/tf2xla/resource_operation_table.h" + +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_map.h" + +namespace tensorflow { +/*static*/ absl::string_view XlaResourceOpInfo::XlaResourceOpKindToString( + XlaResourceOpKind op_kind) { + switch (op_kind) { + case XlaResourceOpKind::kRead: + return "Read"; + case XlaResourceOpKind::kWrite: + return "Write"; + case XlaResourceOpKind::kReadWrite: + return "Modify"; + } +} + +static absl::flat_hash_map* +CreateResourceOpInfoMap() { + auto* result = new absl::flat_hash_map; + + auto add = [&](absl::string_view op, XlaResourceOpKind op_kind, + XlaResourceKind resource_kind) { + auto insert_result = + result->insert({op, XlaResourceOpInfo(op_kind, resource_kind)}); + CHECK(insert_result.second); + }; + + auto kRead = XlaResourceOpKind::kRead; + auto kWrite = XlaResourceOpKind::kWrite; + auto kReadWrite = XlaResourceOpKind::kReadWrite; + + auto kVariable = XlaResourceKind::kVariable; + auto kStack = XlaResourceKind::kStack; + auto kTensorArray = XlaResourceKind::kTensorArray; + + // clang-format off + add("AssignAddVariableOp" , kReadWrite, kVariable); + add("AssignSubVariableOp" , kReadWrite, kVariable); + add("AssignVariableOp" , kWrite, kVariable); + add("AssignVariableXlaConcatND" , kWrite, kVariable); + add("CollectiveReduceV2" , kRead, kVariable); + add("ReadVariableOp" , kRead, kVariable); + add("ReadVariableXlaSplitND" , kRead, kVariable); + add("ResourceApplyAdaMax" , kReadWrite, kVariable); + add("ResourceApplyAdadelta" , kReadWrite, kVariable); + add("ResourceApplyAdagrad" , kReadWrite, kVariable); + add("ResourceApplyAdagradV2" , kReadWrite, kVariable), + add("ResourceApplyAdagradDA" , kReadWrite, kVariable); + add("ResourceApplyAdam" , kReadWrite, kVariable); + add("ResourceApplyAddSign" , kReadWrite, kVariable); + add("ResourceApplyCenteredRMSProp" , kReadWrite, kVariable); + add("ResourceApplyFtrl" , kReadWrite, kVariable); + add("ResourceApplyFtrlV2" , kReadWrite, kVariable); + add("ResourceApplyGradientDescent" , kReadWrite, kVariable); + add("ResourceApplyMomentum" , kReadWrite, kVariable); + add("ResourceApplyKerasMomentum" , kReadWrite, kVariable); + add("ResourceApplyPowerSign" , kReadWrite, kVariable); + add("ResourceApplyProximalAdagrad" , kReadWrite, kVariable); + add("ResourceApplyProximalGradientDescent" , kReadWrite, kVariable); + add("ResourceApplyRMSProp" , kReadWrite, kVariable); + add("ResourceGather" , kRead, kVariable); + add("ResourceScatterAdd" , kReadWrite, kVariable); + add("ResourceScatterDiv" , kReadWrite, kVariable); + add("ResourceScatterMax" , kReadWrite, kVariable); + add("ResourceScatterMin" , kReadWrite, kVariable); + add("ResourceScatterMul" , kReadWrite, kVariable); + add("ResourceScatterNdAdd" , kReadWrite, kVariable); + add("ResourceScatterNdSub" , kReadWrite, kVariable); + add("ResourceScatterNdUpdate" , kReadWrite, kVariable); + add("ResourceScatterSub" , kReadWrite, kVariable); + add("ResourceScatterUpdate" , kReadWrite, kVariable); + add("ResourceStridedSliceAssign" , kReadWrite, kVariable); + add("RngReadAndSkip" , kReadWrite, kVariable); + add("RngSkip" , kReadWrite, kVariable); + add("StatefulStandardNormalV2" , kReadWrite, kVariable); + add("StatefulTruncatedNormal" , kReadWrite, kVariable); + add("StatefulUniform" , kReadWrite, kVariable); + add("StatefulUniformFullInt" , kReadWrite, kVariable); + add("StatefulUniformInt" , kReadWrite, kVariable); + add("VarIsInitializedOp" , kRead, kVariable); + add("VariableShape" , kRead, kVariable); + + add("StackV2" , kWrite, kStack); + add("StackCloseV2" , kRead, kStack); + add("StackPopV2" , kReadWrite, kStack); + add("StackPushV2" , kReadWrite, kStack); + + add("TensorArrayV3" , kWrite, kTensorArray); + add("TensorArrayConcatV3" , kRead, kTensorArray); + add("TensorArrayGatherV3" , kRead, kTensorArray); + add("TensorArrayScatterV3" , kWrite, kTensorArray); + add("TensorArrayGradV3" , kRead, kTensorArray); + add("TensorArrayCloseV3" , kRead, kTensorArray); + add("TensorArrayReadV3" , kRead, kTensorArray); + add("TensorArraySizeV3" , kRead, kTensorArray); + add("TensorArraySplitV3" , kWrite, kTensorArray); + add("TensorArrayWriteV3" , kWrite, kTensorArray); + // clang-format on + + return result; +} + +static const absl::flat_hash_map& +GetStaticResourceOpInfoMap() { + static absl::flat_hash_map* + op_info_map = CreateResourceOpInfoMap(); + return *op_info_map; +} + +const XlaResourceOpInfo* GetResourceOpInfoForOp(absl::string_view op) { + const absl::flat_hash_map& op_infos = + GetStaticResourceOpInfoMap(); + auto it = op_infos.find(op); + return it == op_infos.end() ? nullptr : &it->second; +} + +namespace resource_op_table_internal { +std::vector GetKnownResourceOps() { + std::vector result; + for (const auto& p : GetStaticResourceOpInfoMap()) { + result.push_back(p.first); + } + absl::c_sort(result); + return result; +} +} // namespace resource_op_table_internal +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table.h new file mode 100644 index 0000000000000000000000000000000000000000..4fd8d9e7b9c72be2076b653460728272f48a4c15 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table.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_TF2XLA_RESOURCE_OPERATION_TABLE_H_ +#define TENSORFLOW_COMPILER_TF2XLA_RESOURCE_OPERATION_TABLE_H_ + +#include +#include + +#include "absl/strings/string_view.h" +#include "tensorflow/core/platform/logging.h" + +// Exposes information about the resource operations supported by tf2xla in a +// structured form. + +namespace tensorflow { +enum class XlaResourceOpKind { + kRead, // Only reads from resources. + kWrite, // Only writes to resources. + kReadWrite // Reads from and writes to resources. +}; + +enum class XlaResourceKind { + kVariable, // Operates on resource variables. + kStack, // Operates on stacks. + kTensorArray // Operates on tensor arrays. +}; + +class XlaResourceOpInfo { + public: + explicit XlaResourceOpInfo(XlaResourceOpKind op_kind, + XlaResourceKind resource_kind) + : op_kind_(op_kind), resource_kind_(resource_kind) {} + + XlaResourceOpKind kind() const { return op_kind_; } + XlaResourceKind resource_kind() const { return resource_kind_; } + + static absl::string_view XlaResourceOpKindToString(XlaResourceOpKind op_kind); + + private: + XlaResourceOpKind op_kind_; + XlaResourceKind resource_kind_; +}; + +// Returns a XlaResourceOpInfo describing `op` if it is a resource operation +// supported by tf2xla, otherwise returns null (i.e. if this returns null then +// `op` is either not a resource operation or is unsupported by XLA). +const XlaResourceOpInfo* GetResourceOpInfoForOp(absl::string_view op); + +namespace resource_op_table_internal { +// NB! Implementation detail exposed for unit testing, do not use. +// +// Returns the set of resource operations known by this module. +std::vector GetKnownResourceOps(); +} // namespace resource_op_table_internal + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_RESOURCE_OPERATION_TABLE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..9af317a065f4fffcfbf0cd249392645ec9dee99a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_operation_table_test.cc @@ -0,0 +1,68 @@ +/* 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/tf2xla/resource_operation_table.h" + +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_map.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { +bool IsResourceArgDef(const OpDef::ArgDef& arg_def) { + return arg_def.type() == DT_RESOURCE; +} + +bool HasResourceInputOrOutput(const OpDef& op_def) { + return absl::c_any_of(op_def.input_arg(), IsResourceArgDef) || + absl::c_any_of(op_def.output_arg(), IsResourceArgDef); +} + +TEST(ResourceOperationTableTest, HaveAllResourceOps) { + absl::flat_hash_map known_resource_ops; + for (absl::string_view known_resource_op : + resource_op_table_internal::GetKnownResourceOps()) { + ASSERT_TRUE( + known_resource_ops.insert({std::string(known_resource_op), false}) + .second); + } + + std::vector xla_op_names = XlaOpRegistry::GetAllRegisteredOps(); + for (const std::string& xla_op_name : xla_op_names) { + const OpDef* op_def; + TF_ASSERT_OK(OpRegistry::Global()->LookUpOpDef(xla_op_name, &op_def)); + if (HasResourceInputOrOutput(*op_def)) { + EXPECT_EQ(known_resource_ops.count(xla_op_name), 1) + << "Unknown resource op " << xla_op_name; + known_resource_ops[xla_op_name] = true; + } + } + + std::vector unnecessary_resource_ops; + for (const auto& pair : known_resource_ops) { + if (!pair.second) { + unnecessary_resource_ops.push_back(pair.first); + } + } + + EXPECT_TRUE(unnecessary_resource_ops.empty()) + << "Stale resource ops:\n" + << absl::StrJoin(unnecessary_resource_ops, "\n"); +} +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..263d7391e398a1c2c371511f19684cbe23934c7b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util.cc @@ -0,0 +1,345 @@ +/* Copyright 2019 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/resource_util.h" + +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/container/inlined_vector.h" +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/resource_operation_table.h" +#include "xla/status_macros.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/common_runtime/function_utils.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/protobuf/error_codes.pb.h" + +namespace tensorflow { +namespace { + +using tsl::StatusOr; + +const char kIdentityNOp[] = "IdentityN"; +const char kIfOp[] = "If"; +const char kWhileOp[] = "While"; +const char kArgOp[] = "_Arg"; +const char kRetvalOp[] = "_Retval"; + +const int kMaxCallDepth = 100; + +absl::Status AnalyzeResourceUsage( + const Graph* graph, const std::optional& function_name, + const int call_depth, const absl::flat_hash_set& resource_arg_indices, + FunctionLibraryRuntime* lib_runtime, + absl::flat_hash_map>* + source_to_path); + +bool IsControlFlowV1Node(const Node* n) { + return (n->IsEnter() || n->IsExit() || n->IsSwitch() || n->IsMerge() || + n->IsNextIteration()); +} + +// TODO(ycao): Add this as Tensorflow Node method. +absl::StatusOr> OutputEdgesByIndex( + const Node& n, int idx) { + absl::InlinedVector res; + if (idx >= n.num_outputs()) { + return absl::InvalidArgumentError( + absl::StrCat("Invalid out_edge index: ", idx, ", Node ", n.name(), + " only has ", n.num_outputs(), " outputs.")); + } + + for (const Edge* o : n.out_edges()) { + if (o->src_output() == idx) res.emplace_back(o); + } + return res; +} + +bool IsStackOrTensorArraySource(const Node& n) { + const XlaResourceOpInfo* op_info = GetResourceOpInfoForOp(n.type_string()); + + if (!op_info) return false; + if (op_info->resource_kind() != XlaResourceKind::kStack && + op_info->resource_kind() != XlaResourceKind::kTensorArray) + return false; + return n.num_outputs() > 0 && n.output_type(0) == DataType::DT_RESOURCE; +} + +void PropagateFromStackOrTensorArraySourceOp( + const Node& n, const std::optional& function_name, + absl::flat_hash_map* + user_to_source) { + ResourceUsageAnalysis::NodeInfo src_node_info(function_name, n.name(), + n.type_string()); + for (const Edge* o : n.out_edges()) { + if (o->IsControlEdge()) continue; + if (o->dst()->input_type(o->dst_input()) != DataType::DT_RESOURCE) { + continue; + } + (*user_to_source)[o] = src_node_info; + } +} + +absl::Status PropagateFromArgOp( + const Node& n, const std::optional& function_name, + const absl::flat_hash_set& resource_arg_indices, + absl::flat_hash_map* + user_to_source) { + TF_RET_CHECK(n.type_string() == kArgOp); + + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(n.attrs(), "index", &index)); + if (!resource_arg_indices.contains(index)) return absl::OkStatus(); + + TF_RET_CHECK(function_name.has_value()) + << "ResourceUsageAnalysis does not support analyzing _Arg nodes " + "carrying Stack/TensorArray resource in given graph unless they " + "are in function calls."; + + const ResourceUsageAnalysis::NodeInfo src_node_info(function_name, n.name(), + n.type_string()); + + for (const Edge* o : n.out_edges()) { + if (o->IsControlEdge()) continue; + if (o->dst()->input_type(o->dst_input()) != DataType::DT_RESOURCE) { + continue; + } + (*user_to_source)[o] = src_node_info; + } + + return absl::OkStatus(); +} + +absl::Status UpdateResourceUsageFromFunctionBodyAnalysis( + const Node& call_node, + const std::optional& caller_function_name, + const FunctionBody& fbody, + const absl::flat_hash_map< + ResourceUsageAnalysis::NodeInfo, + absl::flat_hash_set>& + called_function_source_to_path, + absl::flat_hash_map* + user_to_source, + absl::flat_hash_map>* + caller_source_to_path) { + std::unordered_map node_name_index = + fbody.graph->BuildNodeNameIndex(); + for (const auto& it : called_function_source_to_path) { + ResourceUsageAnalysis::NodeInfo src_node_info = it.first; + + // If source is an _Arg, then the true source is actually corresponding + // edge that feeds into function call node with the same index. + if (src_node_info.op_ == kArgOp) { + const Node* arg_src = node_name_index[src_node_info.node_name_]; + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(arg_src->attrs(), "index", &index)); + + const Edge* e; + // TODO(ycao): Allow overriding input_edge to _Arg index mapping. This is + // needed for cond function of while nodes. + TF_RETURN_IF_ERROR(call_node.input_edge(index, &e)); + src_node_info = (*user_to_source)[e]; + } + + for (const auto& dst_node_info : it.second) { + // If user is an _Retval, then the true user is actually corresponding + // edge of that _Retval. + if (dst_node_info.op_ == kRetvalOp) { + const Node* ret_user = node_name_index[dst_node_info.node_name_]; + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(ret_user->attrs(), "index", &index)); + + absl::InlinedVector outs; + // TODO(ycao): Allow overriding _Retval index to call node output edge + // mapping. This is needed for cond function of while nodes. + TF_ASSIGN_OR_RETURN(outs, OutputEdgesByIndex(call_node, index)); + for (const Edge* o : outs) (*user_to_source)[o] = src_node_info; + } else { + (*caller_source_to_path)[src_node_info].emplace(dst_node_info); + } + } + } + + return absl::OkStatus(); +} + +absl::Status PropagateThroughCallOp( + const Node& n, const std::optional& function_name, + const int call_depth, FunctionLibraryRuntime* lib_runtime, + absl::flat_hash_map* + user_to_source, + absl::flat_hash_map>* + source_to_path) { + if (call_depth > kMaxCallDepth) { + return absl::InvalidArgumentError(absl::StrCat( + "Function call stack in given graph is too deep, last function ", + "name is: ", function_name.value())); + } + // resource_arg_indices contains all indices of the input + // arguments that carry Stack/TensorArray resource handles. + absl::flat_hash_set resource_arg_indices; + for (const Edge* e : n.in_edges()) { + if (user_to_source->contains(e)) { + resource_arg_indices.emplace(e->dst_input()); + } + } + + // Instantiate associated function to get function body. + FunctionLibraryRuntime::Handle handle; + TF_RETURN_IF_ERROR(InstantiateFunctionCall(n.def(), lib_runtime, &handle)); + auto release_handle_on_return = + gtl::MakeCleanup([&] { CHECK_OK(lib_runtime->ReleaseHandle(handle)); }); + const FunctionBody* fbody = lib_runtime->GetFunctionBody(handle); + + // Recursively analyze called function for resource sources and users. + absl::flat_hash_map> + called_function_source_to_path; + TF_RETURN_IF_ERROR(AnalyzeResourceUsage( + fbody->graph, n.type_string(), call_depth + 1, resource_arg_indices, + lib_runtime, &called_function_source_to_path)); + + TF_RETURN_IF_ERROR(UpdateResourceUsageFromFunctionBodyAnalysis( + n, function_name, *fbody, called_function_source_to_path, user_to_source, + source_to_path)); + return absl::OkStatus(); +} + +// Analyzes pass through values for Identity and IdentityN ops. +absl::Status PropagateThroughIdentityOp( + const Node& n, + absl::flat_hash_map* + user_to_source) { + TF_RET_CHECK(n.IsIdentity() || n.type_string() == kIdentityNOp); + if (n.IsIdentity()) { + for (const Edge* o : n.out_edges()) { + if (o->IsControlEdge()) continue; + const Edge* in; + TF_RETURN_IF_ERROR(n.input_edge(0, &in)); + if (!user_to_source->contains(in)) continue; + user_to_source->emplace(std::make_pair(o, (*user_to_source)[in])); + } + } else { + for (const Edge* o : n.out_edges()) { + if (o->IsControlEdge()) continue; + const Edge* in; + TF_RETURN_IF_ERROR(n.input_edge(o->src_output(), &in)); + if (!user_to_source->contains(in)) continue; + user_to_source->emplace(std::make_pair(o, (*user_to_source)[in])); + } + } + + return absl::OkStatus(); +} + +absl::Status AnalyzeResourceUsage( + const Graph* graph, const std::optional& function_name, + const int call_depth, const absl::flat_hash_set& resource_arg_indices, + FunctionLibraryRuntime* lib_runtime, + absl::flat_hash_map>* + source_to_path) { + source_to_path->clear(); + + std::vector reverse_post_order; + GetReversePostOrder(*graph, &reverse_post_order, NodeComparatorName{}); + + // user_to_source maps from an edge carrying a Stack or TensorArray resource + // to the node that created this resource. + absl::flat_hash_map + user_to_source; + for (const Node* n : reverse_post_order) { + if (IsControlFlowV1Node(n)) { + return absl::InvalidArgumentError(absl::StrCat( + "AnalyzeResourceUsage does not support control flow v1 node: ", + n->DebugString())); + } + + // TODO(ycao): Support pass-through functional while/if nodes. + if (n->type_string() == kIfOp || n->type_string() == kWhileOp) { + return absl::InvalidArgumentError(absl::StrCat( + "AnalyzeResourceUsage does not yet support control flow v2 " + "node: ", + n->DebugString())); + } + + // Record a resource source edge. + if (IsStackOrTensorArraySource(*n)) { + PropagateFromStackOrTensorArraySourceOp(*n, function_name, + &user_to_source); + continue; + } + + // Arguments that are listed in resource_arg_indices are also considered as + // resource sources. + if (n->IsArg()) { + TF_RETURN_IF_ERROR(PropagateFromArgOp( + *n, function_name, resource_arg_indices, &user_to_source)); + continue; + } + + // Recursively analyze function call ops. + if (IsFunctionCall(*lib_runtime->GetFunctionLibraryDefinition(), *n)) { + TF_RETURN_IF_ERROR(PropagateThroughCallOp(*n, function_name, call_depth, + lib_runtime, &user_to_source, + source_to_path)); + continue; + } + + if (n->IsIdentity() || n->type_string() == kIdentityNOp) { + TF_RETURN_IF_ERROR(PropagateThroughIdentityOp(*n, &user_to_source)); + } + } + + for (const auto& it : user_to_source) { + (*source_to_path)[it.second].emplace(function_name, it.first->dst()->name(), + it.first->dst()->type_string()); + } + + return absl::OkStatus(); +} + +} // anonymous namespace + +/*Static*/ absl::Status ResourceUsageAnalysis::Analyze( + const Graph* graph, FunctionLibraryRuntime* lib_runtime, + absl::flat_hash_map>* + source_to_path) { + return AnalyzeResourceUsage( + graph, /*function_name=*/{}, /*call_depth=*/0, + /*resource_arg_indices=*/absl::flat_hash_set(), lib_runtime, + source_to_path); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d849454c9889a0623ab5bba7218e66e331d2a04b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util.h @@ -0,0 +1,96 @@ +/* Copyright 2019 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_RESOURCE_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_RESOURCE_UTIL_H_ + +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/hash/hash.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { +class ResourceUsageAnalysis { + public: + // NodeInfo is a triple of function_name:node_name:op to uniquely identity a + // node in graph. ResourceUsageAnalysis uses it to represent resource sources + // and users. + class NodeInfo { + public: + std::optional function_name_; + std::string node_name_; + std::string op_; + + NodeInfo() {} + + NodeInfo(const std::optional& function_name, + std::string node_name, std::string op) + : function_name_(function_name), + node_name_(std::move(node_name)), + op_(std::move(op)) {} + + std::string DebugString() const { + return absl::StrJoin({function_name_.value_or(""), node_name_, op_}, ":"); + } + + bool operator==(const NodeInfo& o) const { + return function_name_ == o.function_name_ && node_name_ == o.node_name_ && + op_ == o.op_; + } + + template + friend H AbslHashValue(H h, const NodeInfo& o) { + return H::combine(std::move(h), o.function_name_, o.node_name_, o.op_); + } + }; + + // This method analyzes a Tensorflow graph and finds all operations that + // create Stack/TensorArray resources and all the operations that consume + // resource created by them. + // + // Note that _Arg nodes that introduce resources are not considered sources. + // Note again that Control Flow v1 nodes + // (Enter/Exit/Switch/Merge/NextIteration) are not supported. Graphs contain + // these nodes cause analysis failures. However Control Flow v2 nodes + // (While/If) will be supported. + // + // TODO(b/135628319): Support analyzing functional while/if as pass-through + // ops. + // + // For example, consider following subgraph: + // + // TensorArrayOp -> Identity -> TensorArrayWriteOp + // + // It should be able to tell that TensorArrayWriteOp actually operates on the + // resource created by TensorArrayOp even though there might be + // non-resource-specific operations like Identity (or other pass-through + // operations). + // + // source_to_path maps the nodes that creates resources to all nodes that + // operate on the corresponding resource, not including sources themselves. It + // is cleared upon calling this method. + static absl::Status Analyze( + const Graph* graph, FunctionLibraryRuntime* lib_runtime, + absl::flat_hash_map>* + source_to_path); +}; + +} // namespace tensorflow +#endif // TENSORFLOW_COMPILER_TF2XLA_RESOURCE_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..4971539de2c995c5504f6ef922c7ef3e6e118dd3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/resource_util_test.cc @@ -0,0 +1,534 @@ +/* Copyright 2019 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/resource_util.h" + +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/memory/memory.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/graph/graph_def_builder.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { + +namespace { +ResourceUsageAnalysis::NodeInfo node_info_from_string(absl::string_view s) { + std::vector tokens = absl::StrSplit(s, ':'); + EXPECT_EQ(tokens.size(), 3); + + ResourceUsageAnalysis::NodeInfo node_info; + if (tokens[0].empty()) { + node_info.function_name_ = std::nullopt; + } else { + node_info.function_name_ = std::move(tokens[0]); + } + node_info.node_name_ = std::move(tokens[1]); + node_info.op_ = std::move(tokens[2]); + return node_info; +} + +void AnalyzeAndVerify( + const GraphDef& graphdef, FunctionLibraryDefinition* flib_def, + const absl::flat_hash_map>& + expected) { + auto graph = std::make_unique(flib_def); + TF_EXPECT_OK( + ConvertGraphDefToGraph(GraphConstructorOptions(), graphdef, graph.get())); + + auto pflr = std::make_unique( + nullptr, Env::Default(), /*config=*/nullptr, TF_GRAPH_DEF_VERSION, + flib_def, OptimizerOptions()); + FunctionLibraryRuntime* lib_runtime = + pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); + absl::flat_hash_map> + source_to_path; + TF_EXPECT_OK(ResourceUsageAnalysis::Analyze(graph.get(), lib_runtime, + &source_to_path)); + + absl::flat_hash_map> + expected_source_to_path; + for (auto it : expected) { + auto src_node_info = node_info_from_string(it.first); + for (const std::string& user : it.second) { + expected_source_to_path[src_node_info].emplace( + node_info_from_string(user)); + } + } + + EXPECT_EQ(source_to_path, expected_source_to_path); +} + +} // anonymous namespace + +TEST(ResourceOpAnalyzerTest, SingleResourceSingleUserNoPassThrough) { + FunctionLibraryDefinition flib_def(OpRegistry::Global(), + FunctionDefLibrary()); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_size -> stack_op -> stack_close + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op_builder("stack_op", "StackV2", op_reg); + stack_op_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op = opts.FinalizeBuilder(&stack_op_builder); + + NodeBuilder stack_close_builder("stack_close", "StackCloseV2", op_reg); + stack_close_builder.Input(stack_op); + opts.FinalizeBuilder(&stack_close_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op:StackV2"] = + absl::flat_hash_set({":stack_close:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, SingleResourceSingleUserWithPassThrough) { + FunctionLibraryDefinition flib_def(OpRegistry::Global(), + FunctionDefLibrary()); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_size -> stack_op -> resource_identity -> stack_close + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op_builder("stack_op", "StackV2", op_reg); + stack_op_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op = opts.FinalizeBuilder(&stack_op_builder); + + NodeBuilder resource_identity_builder("resource_identity", "Identity", + op_reg); + resource_identity_builder.Input(stack_op); + Node* resource_identity = opts.FinalizeBuilder(&resource_identity_builder); + + NodeBuilder stack_close_builder("stack_close", "StackCloseV2", op_reg); + stack_close_builder.Input(resource_identity); + opts.FinalizeBuilder(&stack_close_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op:StackV2"] = absl::flat_hash_set( + {":resource_identity:Identity", ":stack_close:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, SingleResourceMultipleUserNoPassThrough) { + FunctionLibraryDefinition flib_def(OpRegistry::Global(), + FunctionDefLibrary()); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_close0 + * / + * stack_size -> stack_op + * \ + * stack_close1 + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op_builder("stack_op", "StackV2", op_reg); + stack_op_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op = opts.FinalizeBuilder(&stack_op_builder); + + NodeBuilder stack_close0_builder("stack_close0", "StackCloseV2", op_reg); + stack_close0_builder.Input(stack_op); + opts.FinalizeBuilder(&stack_close0_builder); + + NodeBuilder stack_close1_builder("stack_close1", "StackCloseV2", op_reg); + stack_close1_builder.Input(stack_op); + opts.FinalizeBuilder(&stack_close1_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op:StackV2"] = absl::flat_hash_set( + {":stack_close0:StackCloseV2", ":stack_close1:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, SingleResourceMultipleUserWithPassThrough) { + FunctionLibraryDefinition flib_def(OpRegistry::Global(), + FunctionDefLibrary()); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_close0 + * / + * stack_size -> stack_op -> resource_identity + * \ + * stack_close1 + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op_builder("stack_op", "StackV2", op_reg); + stack_op_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op = opts.FinalizeBuilder(&stack_op_builder); + + NodeBuilder resource_identity_builder("resource_identity", "Identity", + op_reg); + resource_identity_builder.Input(stack_op); + Node* resource_identity = opts.FinalizeBuilder(&resource_identity_builder); + + NodeBuilder stack_close0_builder("stack_close0", "StackCloseV2", op_reg); + stack_close0_builder.Input(resource_identity); + opts.FinalizeBuilder(&stack_close0_builder); + + NodeBuilder stack_close1_builder("stack_close1", "StackCloseV2", op_reg); + stack_close1_builder.Input(resource_identity); + opts.FinalizeBuilder(&stack_close1_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op:StackV2"] = absl::flat_hash_set( + {":resource_identity:Identity", ":stack_close0:StackCloseV2", + ":stack_close1:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, MultipleResourceMultipleUserNoPassThrough) { + FunctionLibraryDefinition flib_def(OpRegistry::Global(), + FunctionDefLibrary()); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_close0 + * / + * stack_op0 + * / \ + * / stack_close1 + * stack_size + * \ stack_close2 + * \ / + * stack_op1 + * \ + * stack_close3 + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op0_builder("stack_op0", "StackV2", op_reg); + stack_op0_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op0 = opts.FinalizeBuilder(&stack_op0_builder); + + NodeBuilder stack_close0_builder("stack_close0", "StackCloseV2", op_reg); + stack_close0_builder.Input(stack_op0); + opts.FinalizeBuilder(&stack_close0_builder); + + NodeBuilder stack_close1_builder("stack_close1", "StackCloseV2", op_reg); + stack_close1_builder.Input(stack_op0); + opts.FinalizeBuilder(&stack_close1_builder); + + NodeBuilder stack_op1_builder("stack_op1", "StackV2", op_reg); + stack_op1_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op1 = opts.FinalizeBuilder(&stack_op1_builder); + + NodeBuilder stack_close2_builder("stack_close2", "StackCloseV2", op_reg); + stack_close2_builder.Input(stack_op1); + opts.FinalizeBuilder(&stack_close2_builder); + + NodeBuilder stack_close3_builder("stack_close3", "StackCloseV2", op_reg); + stack_close3_builder.Input(stack_op1); + opts.FinalizeBuilder(&stack_close3_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op0:StackV2"] = absl::flat_hash_set( + {":stack_close0:StackCloseV2", ":stack_close1:StackCloseV2"}); + expected[":stack_op1:StackV2"] = absl::flat_hash_set( + {":stack_close2:StackCloseV2", ":stack_close3:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, MultipleResourceMultipleUserWithPassThrough) { + FunctionLibraryDefinition flib_def(OpRegistry::Global(), + FunctionDefLibrary()); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* I + * stack_op0 ----> d ---> stack_close0 + * / e + * / n + * stack_size ------------------> t + * \ i + * \ t + * stack_op1 ----> y ---> stack_close0 + * N + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op0_builder("stack_op0", "StackV2", op_reg); + stack_op0_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op0 = opts.FinalizeBuilder(&stack_op0_builder); + + NodeBuilder stack_op1_builder("stack_op1", "StackV2", op_reg); + stack_op1_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op1 = opts.FinalizeBuilder(&stack_op1_builder); + + NodeBuilder identity_n_builder("identity_n", "IdentityN", op_reg); + identity_n_builder.Input({stack_op0, stack_size_placeholder, stack_op1}); + + NodeBuilder stack_close0_builder("stack_close0", "StackCloseV2", op_reg); + stack_close0_builder.Input(stack_op0); + opts.FinalizeBuilder(&stack_close0_builder); + + NodeBuilder stack_close1_builder("stack_close1", "StackCloseV2", op_reg); + stack_close1_builder.Input(stack_op0); + opts.FinalizeBuilder(&stack_close1_builder); + + NodeBuilder stack_close2_builder("stack_close2", "StackCloseV2", op_reg); + stack_close2_builder.Input(stack_op1); + opts.FinalizeBuilder(&stack_close2_builder); + + NodeBuilder stack_close3_builder("stack_close3", "StackCloseV2", op_reg); + stack_close3_builder.Input(stack_op1); + opts.FinalizeBuilder(&stack_close3_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op0:StackV2"] = absl::flat_hash_set( + {":stack_close0:StackCloseV2", ":stack_close1:StackCloseV2"}); + expected[":stack_op1:StackV2"] = absl::flat_hash_set( + {":stack_close2:StackCloseV2", ":stack_close3:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, ResourcePassThroughFunction) { + auto library = std::make_unique(); + /* + * pass_through_function: + * + * _Arg -> Identity -> _Retval + */ + *library->add_function() = FunctionDefHelper::Define( + /*function_name=*/"pass_through_function", + /*arg_def=*/{"in: resource"}, + /*ret_def=*/{"out: resource"}, + /*attr_def=*/{}, + /*node_def=*/ + {{{"out"}, "Identity", {"in"}, {{"T", DataType::DT_RESOURCE}}}}); + + FunctionLibraryDefinition flib_def(OpRegistry::Global(), *library); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_size -> stack_op -> pass_through_function -> stack_close + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op_builder("stack_op", "StackV2", op_reg); + stack_op_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op = opts.FinalizeBuilder(&stack_op_builder); + + NodeBuilder pass_through_fn_builder("pass_through_fn", + "pass_through_function", op_reg); + pass_through_fn_builder.Input(stack_op); + Node* pass_through_fn = opts.FinalizeBuilder(&pass_through_fn_builder); + + NodeBuilder stack_close_builder("stack_close", "StackCloseV2", op_reg); + stack_close_builder.Input(pass_through_fn); + opts.FinalizeBuilder(&stack_close_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op:StackV2"] = absl::flat_hash_set( + {":stack_close:StackCloseV2", ":pass_through_fn:pass_through_function", + "pass_through_function:out:Identity"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, ResourceUserInFunction) { + auto library = std::make_unique(); + /* + * resource_user_function: + * + * _Arg -> Identity -> StackCloseV2 + */ + *library->add_function() = FunctionDefHelper::Define( + /*function_name=*/"resource_user_function", + /*arg_def=*/{"in: resource"}, + /*ret_def=*/{}, + /*attr_def=*/{}, + /*node_def=*/ + {{{"stack_close"}, + "StackCloseV2", + {"in"}, + {{"T", DataType::DT_RESOURCE}}}}); + + FunctionLibraryDefinition flib_def(OpRegistry::Global(), *library); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_size -> stack_op -> resource_user_function + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder stack_op_builder("stack_op", "StackV2", op_reg); + stack_op_builder.Input(stack_size_placeholder).Attr("elem_type", DT_FLOAT); + Node* stack_op = opts.FinalizeBuilder(&stack_op_builder); + + NodeBuilder resource_user_fn_builder("resource_user_function", + "resource_user_function", op_reg); + resource_user_fn_builder.Input(stack_op); + opts.FinalizeBuilder(&resource_user_fn_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected[":stack_op:StackV2"] = absl::flat_hash_set( + {":resource_user_function:resource_user_function", + "resource_user_function:stack_close:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +TEST(ResourceOpAnalyzerTest, ResourceSourceInFunction) { + auto library = std::make_unique(); + /* + * resource_source_function: + * + * _Arg -> StackV2 -> _Retval + */ + *library->add_function() = FunctionDefHelper::Define( + /*function_name=*/"resource_source_function", + /*arg_def=*/{"in: int32"}, + /*ret_def=*/{"out: resource"}, + /*attr_def=*/{}, + /*node_def=*/ + {{{"out"}, "StackV2", {"in"}, {{"elem_type", DataType::DT_FLOAT}}}}); + + FunctionLibraryDefinition flib_def(OpRegistry::Global(), *library); + GraphDefBuilder builder(GraphDefBuilder::kFailImmediately, &flib_def); + auto opts = builder.opts(); + auto op_reg = opts.op_registry(); + + { + /* + * stack_size -> resource_source_function -> stack_close + */ + NodeBuilder stack_size_placeholder_builder("stack_size", "Placeholder", + op_reg); + stack_size_placeholder_builder.Attr("dtype", DT_INT32); + Node* stack_size_placeholder = + opts.FinalizeBuilder(&stack_size_placeholder_builder); + + NodeBuilder resource_source_fn_builder("resource_source_function", + "resource_source_function", op_reg); + resource_source_fn_builder.Input(stack_size_placeholder); + Node* resource_source_function = + opts.FinalizeBuilder(&resource_source_fn_builder); + + NodeBuilder stack_close_builder("stack_close", "StackCloseV2", op_reg); + stack_close_builder.Input(resource_source_function); + opts.FinalizeBuilder(&stack_close_builder); + } + + GraphDef graphdef; + TF_EXPECT_OK(builder.ToGraphDef(&graphdef)); + + absl::flat_hash_map> expected; + expected["resource_source_function:out:StackV2"] = + absl::flat_hash_set({":stack_close:StackCloseV2"}); + AnalyzeAndVerify(graphdef, &flib_def, expected); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/shape_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/shape_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b9fe55d7d39103fcb328b5881a8f7223452f59a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/shape_util.cc @@ -0,0 +1,280 @@ +/* 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/shape_util.h" + +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "xla/layout_util.h" +#include "xla/shape_util.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { +namespace { + +absl::Status PopulateInfeedLayoutVector(const xla::Shape& shape, + std::vector* layouts) { + if (shape.IsTuple()) { + int64_t tuple_elements = xla::ShapeUtil::TupleElementCount(shape); + for (int64_t i = 0; i < tuple_elements; ++i) { + const xla::Shape& subshape = + xla::ShapeUtil::GetTupleElementShape(shape, i); + TF_RETURN_IF_ERROR(PopulateInfeedLayoutVector(subshape, layouts)); + } + } else if (xla::LayoutUtil::HasLayout(shape)) { + for (auto dim : xla::LayoutUtil::MinorToMajor(shape)) { + layouts->push_back(dim); + } + } else { + layouts->insert(layouts->end(), shape.dimensions().size(), -1); + } + return absl::OkStatus(); +} + +// Populate the output layout unless the minor_to_major array contains all -1 +// value, in which case the layout is considered missing and the API returns +// false. +absl::StatusOr MakeLayout(absl::Span minor_to_major, + xla::Layout* layout) { + if (std::all_of(minor_to_major.begin(), minor_to_major.end(), + [](int64_t dim) { return dim == -1; })) { + return false; + } + std::vector dim_present(minor_to_major.size(), false); + for (auto dim : minor_to_major) { + const int minor_to_major_size = minor_to_major.size(); + if (dim < 0 || dim >= minor_to_major_size) { + return absl::InvalidArgumentError( + absl::StrCat("Layout dimension out of range: dim=", dim, + " rank=", minor_to_major.size())); + } + if (dim_present[dim]) { + return absl::InvalidArgumentError( + absl::StrCat("Repeated layout dimension: dim=", dim)); + } + dim_present[dim] = true; + } + *layout = xla::LayoutUtil::MakeLayout(minor_to_major); + return true; +} + +absl::Status AssignLayout( + absl::Span minor_to_major, + const std::function& layout_func, + xla::Shape* shape) { + xla::Layout layout; + TF_ASSIGN_OR_RETURN(bool has_layout, MakeLayout(minor_to_major, &layout)); + if (!has_layout && layout_func) { + layout = layout_func(*shape); + } + *shape->mutable_layout() = layout; + return absl::OkStatus(); +} + +} // namespace + +// Convert an XLA Shape into the equivalent TensorFlow shape. +absl::Status XLAShapeToTensorShape(const xla::Shape& shape, + TensorShape* tensor_shape) { + if (shape.IsTuple()) { + return absl::InvalidArgumentError( + absl::StrCat("XLA shape ", xla::ShapeUtil::HumanString(shape), + " cannot be converted to a TensorShape")); + } + *tensor_shape = TensorShape(); + for (int i = 0; i < shape.dimensions().size(); ++i) { + TF_RETURN_IF_ERROR(tensor_shape->AddDimWithStatus(shape.dimensions(i))); + } + return absl::OkStatus(); +} + +// Convert a TensorShape into the equivalent XLA Shape proto. +absl::Status TensorShapeToXLAShape(DataType dtype, + const PartialTensorShape& tensor_shape, + xla::Shape* shape) { + xla::PrimitiveType type; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype, &type)); + *shape = TensorShapeToXLAShape(type, tensor_shape); + return absl::OkStatus(); +} + +absl::Status TensorShapeToBoundedXLAShape( + DataType dtype, const PartialTensorShape& tensor_shape, + const TensorShape& bound, xla::Shape* shape) { + xla::PrimitiveType type; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype, &type)); + if (tensor_shape.unknown_rank()) { + // For unknown shape, create a rank 1 size 0 tensor. + *shape = xla::ShapeUtil::MakeShapeWithDenseLayout(type, {0}, {0}); + return absl::OkStatus(); + } + + if (tensor_shape.dims() != bound.dims()) { + return absl::InvalidArgumentError(absl::StrCat( + "`tensor_shape` and `bound` have different ranks. tensor_shape=", + tensor_shape.dims(), "vs bound=", bound.dims())); + } + + int rank = tensor_shape.dims(); + std::vector dimensions(rank); + std::vector layout(rank); + for (int d = 0; d < rank; ++d) { + if (bound.dim_size(d) < 0) { + return absl::InvalidArgumentError( + absl::StrCat("Bound dimension ", d, " has unknown size.")); + } + if (tensor_shape.dim_size(d) > 0 && + bound.dim_size(d) != tensor_shape.dim_size(d)) { + return absl::InvalidArgumentError(absl::StrCat( + "Bounding shape does not match dynamic shape for known dimension ", d, + tensor_shape.dim_size(d), " vs ", bound.dim_size(d))); + } + dimensions[d] = bound.dim_size(d); + } + // XLA uses minor-to-major; Tensorflow uses major-to-minor. + std::iota(layout.rbegin(), layout.rend(), 0); + xla::Shape result = + xla::ShapeUtil::MakeShapeWithDenseLayout(type, dimensions, layout); + for (int d = 0; d < rank; ++d) { + if (tensor_shape.dim_size(d) < 0) { + result.set_dynamic_dimension(d, true); + } + } + *shape = result; + return absl::OkStatus(); +} + +xla::Shape TensorShapeToXLAShape(xla::PrimitiveType type, + const PartialTensorShape& tensor_shape) { + if (tensor_shape.unknown_rank()) { + // For unknown shape, create a rank 1 size 0 tensor. + return xla::ShapeUtil::MakeShapeWithDenseLayout(type, {0}, {0}); + } + int rank = tensor_shape.dims(); + std::vector dimensions(rank); + std::vector layout(rank); + for (int d = 0; d < rank; ++d) { + dimensions[d] = tensor_shape.dim_size(d); + if (dimensions[d] < 0) { + LOG(WARNING) << "Unable to convert TF shape with dynamic size to XLA " + "shape; returning unknown sentinel value"; + return xla::ShapeUtil::MakeShapeWithDenseLayout(type, {0}, {0}); + } + } + // XLA uses minor-to-major; Tensorflow uses major-to-minor. + std::iota(layout.rbegin(), layout.rend(), 0); + xla::Shape result = + xla::ShapeUtil::MakeShapeWithDenseLayout(type, dimensions, layout); + return result; +} + +// Convert a TensorShape into the equivalent XLA Shape proto. +absl::Status TensorShapeToXLAShape(DataType dtype, + const TensorShape& tensor_shape, + xla::Shape* shape) { + xla::PrimitiveType type; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(dtype, &type)); + *shape = TensorShapeToXLAShape(type, tensor_shape); + return absl::OkStatus(); +} + +absl::StatusOr TensorShapeToXLAShape( + DataType dtype, const TensorShape& tensor_shape) { + xla::Shape out; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dtype, tensor_shape, &out)); + return out; +} + +xla::Shape TensorShapeToXLAShape(xla::PrimitiveType type, + const TensorShape& tensor_shape) { + int rank = tensor_shape.dims(); + std::vector dimensions(rank); + std::vector layout(rank); + for (int d = 0; d < rank; ++d) { + dimensions[d] = tensor_shape.dim_size(d); + } + // XLA uses minor-to-major; Tensorflow uses major-to-minor. + std::iota(layout.rbegin(), layout.rend(), 0); + + return xla::ShapeUtil::MakeShapeWithDenseLayout(type, dimensions, layout); +} + +absl::StatusOr> GetShapeLayoutVector(const xla::Shape& shape) { + std::vector layouts; + TF_RETURN_IF_ERROR(PopulateInfeedLayoutVector(shape, &layouts)); + return layouts; +} + +absl::Status GetShapeWithLayout( + const xla::Shape& input_shape, absl::Span minor_to_major, + const std::function& layout_func, + xla::Shape* output_shape) { + if (input_shape.IsTuple()) { + int64_t tuple_elements = xla::ShapeUtil::TupleElementCount(input_shape); + std::vector shapes; + shapes.reserve(tuple_elements); + size_t position = 0; + for (int64_t i = 0; i < tuple_elements; ++i) { + const xla::Shape& shape = + xla::ShapeUtil::GetTupleElementShape(input_shape, i); + if (shape.IsTuple()) { + return absl::InvalidArgumentError( + absl::StrCat("Nested tuples not supported: ", + xla::ShapeUtil::HumanString(input_shape))); + } + int64_t rank = shape.dimensions().size(); + if (position + rank > minor_to_major.size()) { + return absl::InvalidArgumentError(absl::StrCat( + "Not enough layout attribute elements: position=", position, + " rank=", rank, " elements=", minor_to_major.size())); + } + shapes.push_back(shape); + TF_RETURN_IF_ERROR(AssignLayout( + absl::Span(minor_to_major).subspan(position, rank), + layout_func, &shapes.back())); + position += rank; + + VLOG(4) << "Shape[" << i + << "] = " << xla::ShapeUtil::HumanStringWithLayout(shapes.back()); + } + if (position != minor_to_major.size()) { + return absl::InvalidArgumentError(absl::StrCat( + "Too many elements passed in the layout attribute: position=", + position, " size=", minor_to_major.size())); + } + *output_shape = xla::ShapeUtil::MakeTupleShape(shapes); + } else { + int64_t rank = input_shape.dimensions().size(); + const int64_t minor_to_major_size = minor_to_major.size(); + if (rank != minor_to_major_size) { + return absl::InvalidArgumentError( + absl::StrCat("Wrong number of layout attribute elements: rank=", rank, + " elements=", minor_to_major.size())); + } + *output_shape = input_shape; + TF_RETURN_IF_ERROR(AssignLayout(minor_to_major, layout_func, output_shape)); + + VLOG(4) << "Shape[] = " + << xla::ShapeUtil::HumanStringWithLayout(*output_shape); + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/shape_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/shape_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f2953760497d3b2e94700debf5fb72d92bf4217b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/shape_util.h @@ -0,0 +1,87 @@ +/* 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. +==============================================================================*/ + +// Utilities for working with XLA shapes. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_SHAPE_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_SHAPE_UTIL_H_ + +#include + +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Convert an XLA Shape into the equivalent TensorFlow shape. May fail since +// not all XLA shapes can be represented as TensorShapes. +absl::Status XLAShapeToTensorShape(const xla::Shape& shape, + TensorShape* tensor_shape); + +// Convert a TensorShape into the equivalent XLA Shape proto. Unlike Tensorflow, +// XLA shapes include the type. Not all `dtype` values can be represented by +// XLA, so this conversion may fail. +absl::Status TensorShapeToXLAShape(DataType dtype, + const TensorShape& tensor_shape, + xla::Shape* shape); + +absl::StatusOr TensorShapeToXLAShape( + DataType dtype, const TensorShape& tensor_shape); + +// Converts a TensorShape into the equivalent XLA Shape proto, taking an +// xla::PrimitiveType to specify the element type. This never fails. +xla::Shape TensorShapeToXLAShape(xla::PrimitiveType type, + const TensorShape& tensor_shape); + +// Convert a PartialTensorShape into the equivalent XLA Shape proto. An shape +// with unknown rank is represented by an r1 with empty dimension. +absl::Status TensorShapeToXLAShape(DataType dtype, + const PartialTensorShape& tensor_shape, + xla::Shape* shape); + +// Convert a PartialTensorShape into the equivalent XLA Shape proto. An shape +// with unknown rank is represented by an r1 with empty dimension. +xla::Shape TensorShapeToXLAShape(xla::PrimitiveType type, + const PartialTensorShape& tensor_shape); + +absl::Status TensorShapeToBoundedXLAShape( + DataType dtype, const PartialTensorShape& tensor_shape, + const TensorShape& bound, xla::Shape* shape); + +// Given an XLA shape with layouts, builds a layout vector in the form able to +// be fed to ops like InfeedEnqueue/InfeedEnqueueTuple/XRTAllocateV2/.... +// THe returned vector is a linearized sequence of the minor-to-major values of +// the layouts held within the input shape. +// In case the input shape is a tuple, the minor-to-major values will be in the +// order of the tuple elements within the tuple shape. +// If a shape (or a subshape of a tuple shape) has missing layout, a rank long +// sequence of -1 values will be emitted. +absl::StatusOr> GetShapeLayoutVector(const xla::Shape& shape); + +// Given the input shape and a linearized sequence of the minor-to-major values +// of the layouts, create the output shape by rewriting the input shape layouts. +// If a layout is missing (has -1 values) for a matching tuple subshape, the +// layout_func will be called, if not nullptr. +absl::Status GetShapeWithLayout( + const xla::Shape& input_shape, absl::Span minor_to_major, + const std::function& layout_func, + xla::Shape* output_shape); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_SHAPE_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..5b4a93f1a9eddad601449ad1c2ab3117c2adfb82 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util.cc @@ -0,0 +1,246 @@ +/* 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/sharding_util.h" + +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/xla_sharding_util.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/service/spmd/shardy/stablehlo_round_trip/stablehlo_import.h" +#include "xla/shape.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/util/device_name_utils.h" + +namespace tensorflow { +namespace { +const char kDeviceSuffixReplicatedCore[] = "REPLICATED_CORE"; +const char kShardingAttribute[] = "_XlaSharding"; +const char kShardingAttributeV2[] = "_XlaShardingV2"; +const char kXlaShardingOp[] = "XlaSharding"; +const char kShardingOpAttribute[] = "sharding"; +} // namespace + +namespace { +xla::OpMetadata CreateOpMetadata(const std::string& op_type, + const std::string& op_name) { + xla::OpMetadata metadata; + metadata.set_op_type(op_type); + metadata.set_op_name(op_name); + return metadata; +} + +void AssignOpMetadataToSharding(xla::OpSharding& sharding, + const std::string& op_type, + const std::string& op_name) { + auto metadata = CreateOpMetadata(op_type, op_name); + if (sharding.type() == xla::OpSharding::TUPLE) { + for (auto& sharding_element : *sharding.mutable_tuple_shardings()) { + *sharding_element.add_metadata() = metadata; + } + } else { + *sharding.add_metadata() = metadata; + } +} + +absl::Status CoreOutOfRangeError(int core, int num_cores_per_replica) { + return absl::InvalidArgumentError( + absl::StrCat("Invalid replicated core id: ", core, + "; num_cores_per_replica=", num_cores_per_replica)); +} +} // namespace + +absl::StatusOr> ParseShardingFromDevice( + const std::string& device_name, int num_cores_per_replica, + std::optional explicit_sharding, + std::optional metadata) { + if (device_name.empty()) { + return explicit_sharding; + } + DeviceNameUtils::ParsedName parsed_device; + if (!DeviceNameUtils::ParseFullName(device_name, &parsed_device)) { + return absl::InvalidArgumentError( + absl::StrCat("Malformed assigned device '", device_name, "'")); + } + + if (explicit_sharding.has_value()) { + return explicit_sharding; + } else if (!parsed_device.has_type || !parsed_device.has_id || + !absl::StrContains(parsed_device.type, + kDeviceSuffixReplicatedCore)) { + return std::optional(); + } else { + const int core = parsed_device.id; + if (core < 0 || core >= num_cores_per_replica) { + return CoreOutOfRangeError(core, num_cores_per_replica); + } + auto sharding = xla::sharding_builder::SingleDevice(core); + if (metadata.has_value()) { + *sharding.add_metadata() = metadata.value(); + } + return std::optional(sharding); + } +} + +absl::StatusOr> ParseShardingFromDevice( + const NodeDef& node_def, int num_cores_per_replica, bool add_metadata) { + const std::string& device_name = node_def.device(); + TF_ASSIGN_OR_RETURN(std::optional sharding, + GetShardingFromNodeDef(node_def, add_metadata)); + return ParseShardingFromDevice( + device_name, num_cores_per_replica, sharding, + add_metadata ? std::optional( + CreateOpMetadata(node_def.op(), node_def.name())) + : std::nullopt); +} + +absl::StatusOr> ParseShardingFromDevice( + const Node& node, int num_cores_per_replica, bool add_metadata) { + std::string device_name = node.assigned_device_name(); + if (device_name.empty()) { + device_name = node.requested_device(); + } + TF_ASSIGN_OR_RETURN(std::optional sharding, + GetShardingFromNodeDef(node.def(), add_metadata)); + return ParseShardingFromDevice( + device_name, num_cores_per_replica, sharding, + add_metadata ? std::optional( + CreateOpMetadata(node.type_string(), node.name())) + : std::nullopt); +} + +absl::StatusOr> ParseShardingFromEdgeSource( + const Edge& edge, int num_cores_per_replica, bool add_metadata) { + if (edge.src() == nullptr) { + return absl::InvalidArgumentError(absl::StrCat( + "Null src for ParseShardingFromEdgeSource edge=", edge.DebugString())); + } + TF_ASSIGN_OR_RETURN(std::optional sharding, + ParseShardingFromDevice( + *edge.src(), num_cores_per_replica, add_metadata)); + if (sharding.has_value() && + sharding.value().type() == xla::OpSharding::TUPLE) { + if (edge.src_output() < 0 || + edge.src_output() >= sharding.value().tuple_shardings_size()) { + return absl::InvalidArgumentError( + absl::StrCat("Tuple index out of bound: edge=", edge.DebugString(), + " sharding=", sharding->DebugString())); + } + std::optional subsharding = + sharding.value().tuple_shardings(edge.src_output()); + return subsharding; + } + return sharding; +} + +void SetShardingDeviceAssignmentFromNode(const Node& src, Node* dst) { + std::string device_name = src.assigned_device_name(); + if (device_name.empty()) { + device_name = src.requested_device(); + } + dst->set_assigned_device_name(device_name); + if (const AttrValue* attr = src.attrs().Find(kShardingAttribute)) { + dst->AddAttr(kShardingAttribute, *attr); + } +} + +namespace { + +absl::StatusOr> GetShardingFromNodeDefInternal( + const NodeDef& node_def, bool add_metadata, const char* attribute) { + if (!HasNodeAttr(node_def, attribute)) { + return std::optional(); + } + std::string value; + xla::OpSharding sharding; + TF_RETURN_IF_ERROR(GetNodeAttr(node_def, attribute, &value)); + if (tensorflow::DecodeShardingAttribute(value, sharding).failed()) { + return xla::InvalidArgument( + "Experimental %s attribute was not a valid encoded xla::OpSharding " + "proto.", + attribute); + } + if (add_metadata) { + AssignOpMetadataToSharding(sharding, node_def.op(), node_def.name()); + } + return std::optional(sharding); +} + +} // namespace + +absl::StatusOr> GetShardingFromNodeDef( + const NodeDef& node_def, bool add_metadata) { + TF_ASSIGN_OR_RETURN(auto sharding_attribute, + GetShardingFromNodeDefInternal(node_def, add_metadata, + kShardingAttribute)); + + // kShardingOpAttribute is only defined for 'XlaSharding' op + xla::OpSharding primary_sharding; + if (node_def.op() == kXlaShardingOp) { + TF_ASSIGN_OR_RETURN(auto sharding_op_attribute, + GetShardingFromNodeDefInternal(node_def, add_metadata, + kShardingOpAttribute)); + if (!sharding_op_attribute.has_value()) { + return sharding_attribute; + } + primary_sharding = sharding_op_attribute.value(); + } else { + if (!sharding_attribute.has_value()) { + return std::optional(); + } + primary_sharding = sharding_attribute.value(); + } + + TF_ASSIGN_OR_RETURN(auto shardingv2, + GetShardingFromNodeDefInternal(node_def, add_metadata, + kShardingAttributeV2)); + + if (!shardingv2.has_value()) { + return primary_sharding; + } + + if (tensorflow::VerifyShardingEquivalent(primary_sharding, shardingv2.value()) + .failed()) { + return absl::InvalidArgumentError(absl::StrCat( + "XlaSharding attribute was not equivalent to XlaShardingV2 " + "attribute: ", + primary_sharding.DebugString(), " vs ", + shardingv2.value().DebugString())); + } + return shardingv2; +} + +absl::Status addSdyShardingFrontendAttribute(xla::XlaBuilder* builder, + xla::XlaOp op, xla::Shape shape, + bool is_single_arg) { + if (!builder->sharding().has_value()) { + return absl::OkStatus(); + } + + return builder->SetInstructionFrontendAttribute( + op, std::string(xla::HloSharding::kShardingFrontendAttrName), + xla::sdy::convertToSdySharding(builder->sharding().value(), shape, + /*openDims=*/false, + /*inlineMesh=*/true, is_single_arg)); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util.h new file mode 100644 index 0000000000000000000000000000000000000000..f42454ac4dbe1bf2479d19430adc5fb4e1d5bde5 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util.h @@ -0,0 +1,69 @@ +/* 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_SHARDING_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_SHARDING_UTIL_H_ + +#include + +#include "xla/hlo/builder/sharding_builder.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/status_macros.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// Parses the op sharding from the 'replicated core' device_name . +// Returns an error: +// - if the device name is invalid. +// - the core is parsed and is out of the range [0, num_cores_per_replica). +// +// Otherwise, returns either: +// - explicit_sharding if explicit_sharding.has_value() +// - a non-value if there is no assigned core or +// - a sharding set as per xla::sharding_builder::SingleDevice. +absl::StatusOr> ParseShardingFromDevice( + const std::string& device_name, int num_cores_per_replica, + std::optional explicit_sharding = std::nullopt, + std::optional metadata = std::nullopt); + +absl::StatusOr> ParseShardingFromDevice( + const Node& node, int num_cores_per_replica, bool add_metadata); + +absl::StatusOr> ParseShardingFromDevice( + const NodeDef& node_def, int num_cores_per_replica, bool add_metadata); + +absl::StatusOr> ParseShardingFromEdgeSource( + const Edge& edge, int num_cores_per_replica, bool add_metadata); + +void SetShardingDeviceAssignmentFromNode(const Node& src, Node* dst); + +// Get sharding inforamtion from node. +absl::StatusOr> GetShardingFromNodeDef( + const NodeDef& node_def, bool add_metadata); + +// Add shardy shardings in the frontend attributes of the op by converting +// existing hlo shardings set in the builder. +// +// Note: The mesh is inlined within sharding attribute instead of being stored +// separately, because shardings are generated per op and stored in their +// frontend attributes. +absl::Status addSdyShardingFrontendAttribute(xla::XlaBuilder* builder, + xla::XlaOp op, xla::Shape shape, + bool is_single_arg = false); +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_SHARDING_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..a4099f2b17f85d857c517794786b90bd4031aa9b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/sharding_util_test.cc @@ -0,0 +1,264 @@ +/* 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/sharding_util.h" + +#include +#include + +#include +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/shape_util.h" +#include "xla/tsl/lib/core/status_test_util.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { + +TEST(CoreUtilTest, ParseShardingFromDevice) { + Graph graph(OpRegistry::Global()); + + auto core_from_sharding = + [](std::optional sharding) -> int64_t { + if (sharding.has_value() && + sharding.value().type() == xla::OpSharding::MAXIMAL) { + return sharding.value().tile_assignment_devices(0); + } else { + return -1; + } + }; + + auto parse_status = ParseShardingFromDevice("", 1); + TF_EXPECT_OK(parse_status.status()); + EXPECT_EQ(-1, core_from_sharding(parse_status.value())); + parse_status = ParseShardingFromDevice("", 100); + TF_EXPECT_OK(parse_status.status()); + EXPECT_EQ(-1, core_from_sharding(parse_status.value())); + + parse_status = ParseShardingFromDevice("/device:A_REPLICATED_CORE:-1", 100); + EXPECT_FALSE(parse_status.ok()); + + parse_status = ParseShardingFromDevice("/device:A_REPLICATED_CORE:55", 100); + TF_EXPECT_OK(parse_status.status()); + EXPECT_EQ(55, core_from_sharding(parse_status.value())); + + parse_status = ParseShardingFromDevice("/device:A_REPLICATED_CORE:100", 100); + EXPECT_FALSE(parse_status.ok()); + + parse_status = ParseShardingFromDevice("/cpu:0", 100); + TF_EXPECT_OK(parse_status.status()); + EXPECT_EQ(-1, core_from_sharding(parse_status.value())); +} + +struct ShardingParams { + std::string op_name; + std::string primary_sharding_attr; +}; + +// Tests GetShardingFromNodeDef for getting the sharding from the expected +// attribute. +class ShardingMetadataAttributesTest + : public ::testing::TestWithParam {}; + +TEST_P(ShardingMetadataAttributesTest, GetShardingFromNodeDef) { + const ShardingParams& params = GetParam(); + + AttrValue xla_sharding_v1; + xla_sharding_v1.set_s("{devices=[2,1]0,1}"); + AttrValue xla_sharding_v2; + xla_sharding_v2.set_s("{devices=[2,1]<=[2]}"); + AttrValue xla_sharding_v1_diff; + xla_sharding_v1_diff.set_s("{devices=[2,1]1,0}"); + AttrValue index; + index.set_i(0); + AttrValue type; + type.set_type(DataType::DT_FLOAT); + + NodeDef node1; + node1.set_op(params.op_name); + node1.set_name("with_sharding"); + node1.mutable_attr()->insert({{params.primary_sharding_attr, xla_sharding_v1}, + {"index", index}, + {"T", type}}); + auto sharding1 = GetShardingFromNodeDef(node1, /*add_metadata=*/false); + TF_ASSERT_OK(sharding1.status()); + EXPECT_TRUE(sharding1->has_value()); + EXPECT_EQ(sharding1->value().tile_assignment_devices_size(), 2); + EXPECT_EQ(sharding1->value().tile_assignment_devices(0), 0); + EXPECT_EQ(sharding1->value().tile_assignment_devices(1), 1); + + NodeDef node2; + node2.set_op(params.op_name); + node2.set_name("with_sharding_and_XlaShardingV2_consistent"); + node2.mutable_attr()->insert({{params.primary_sharding_attr, xla_sharding_v1}, + {"_XlaShardingV2", xla_sharding_v2}, + {"index", index}, + {"T", type}}); + auto sharding2 = GetShardingFromNodeDef(node2, /*add_metadata=*/false); + TF_ASSERT_OK(sharding2.status()); + EXPECT_TRUE(sharding2->has_value()); + EXPECT_EQ(sharding2->value().tile_assignment_devices_size(), 0); + + NodeDef node3; + node3.set_op(params.op_name); + node3.set_name("with_sharding_and_XlaShardingV2_inconsistent"); + node3.mutable_attr()->insert( + {{params.primary_sharding_attr, xla_sharding_v1_diff}, + {"_XlaShardingV2", xla_sharding_v2}, + {"index", index}, + {"T", type}}); + auto sharding3 = GetShardingFromNodeDef(node3, /*add_metadata=*/false); + EXPECT_FALSE(sharding3.status().ok()); + EXPECT_THAT( + sharding3.status().message(), + ::testing::HasSubstr( + "Sharding attribute was not equivalent to XlaShardingV2 attribute")); +} + +INSTANTIATE_TEST_SUITE_P(ShardingMetadataAttributesTestCases, + ShardingMetadataAttributesTest, + ::testing::ValuesIn({ + {"XlaSharding", "sharding"}, + {"_Arg", "_XlaSharding"}, + }), + [](const ::testing::TestParamInfo< + ShardingMetadataAttributesTest::ParamType>& info) { + return info.param.op_name; + }); + +class ShardingWithMetadataTest + : public ::testing::TestWithParam {}; + +TEST_P(ShardingWithMetadataTest, GetShardingFromNode) { + NodeDef node_def; + { + node_def.set_op("_Arg"); + node_def.set_name("arg"); + AttrValue xla_sharding; + xla_sharding.set_s(""); + AttrValue index; + index.set_i(0); + AttrValue type; + type.set_type(DataType::DT_FLOAT); + node_def.mutable_attr()->insert( + {{"_XlaSharding", xla_sharding}, {"index", index}, {"T", type}}); + } + + auto check_metadata = [](const xla::OpSharding& sharding) { + ASSERT_EQ(sharding.metadata_size(), 1); + const auto& metadata = sharding.metadata(0); + EXPECT_EQ(metadata.op_type(), "_Arg"); + EXPECT_EQ(metadata.op_name(), "arg"); + }; + + auto test_sharding_metadata = + [&check_metadata]( + const std::function>()>& + fn) { + auto status_or_sharding = fn(); + TF_ASSERT_OK(status_or_sharding.status()); + ASSERT_TRUE(status_or_sharding.value().has_value()); + auto& sharding = status_or_sharding.value(); + ASSERT_TRUE(sharding.has_value()); + if (sharding->type() == xla::OpSharding::TUPLE) { + EXPECT_TRUE(sharding->metadata().empty()); + for (const auto& sharding_element : sharding->tuple_shardings()) { + check_metadata(sharding_element); + } + } else { + check_metadata(sharding.value()); + } + }; + + { + test_sharding_metadata([&node_def]() { + return GetShardingFromNodeDef(node_def, /*add_metadata=*/true); + }); + } + + { + test_sharding_metadata([&node_def]() { + return ParseShardingFromDevice(node_def, /*num_cores_per_replica=*/1, + /*add_metadata=*/true); + }); + } + + { + Graph graph(OpRegistry::Global()); + absl::Status status; + Node* node = graph.AddNode(node_def, &status); + TF_ASSERT_OK(status); + + test_sharding_metadata([node]() { + return ParseShardingFromDevice(*node, /*num_cores_per_replica=*/1, + /*add_metadata=*/true); + }); + } +} + +xla::OpSharding CreateTupleSharding() { + xla::OpSharding sharding; + sharding.set_type(xla::OpSharding::TUPLE); + sharding.add_tuple_shardings()->set_type(xla::OpSharding::REPLICATED); + sharding.add_tuple_shardings()->set_type(xla::OpSharding::REPLICATED); + return sharding; +} + +INSTANTIATE_TEST_SUITE_P(GetShardingFromNode, ShardingWithMetadataTest, + ::testing::Values(xla::sharding_builder::Replicate(), + CreateTupleSharding())); + +TEST(AddSdyShardingFrontendAttributeTest, NoSharding) { + xla::XlaBuilder builder("test_builder"); + xla::XlaOp param = xla::Parameter( + &builder, 0, xla::ShapeUtil::MakeShape(xla::F32, {}), "p0"); + EXPECT_FALSE(builder.sharding().has_value()); + TF_EXPECT_OK(addSdyShardingFrontendAttribute( + &builder, param, xla::ShapeUtil::MakeShape(xla::F32, {}))); +} + +TEST(AddSdyShardingFrontendAttributeTest, WithSharding) { + xla::XlaBuilder builder("test_builder"); + xla::OpSharding opSharding; + opSharding.set_type(xla::OpSharding::OTHER); + opSharding.add_tile_assignment_dimensions(2); + opSharding.add_tile_assignment_dimensions(4); + opSharding.add_iota_reshape_dims(8); + opSharding.add_iota_transpose_perm(0); + xla::XlaScopedShardingAssignment assign_sharding(&builder, opSharding); + + xla::XlaOp param = xla::Parameter( + &builder, 0, xla::ShapeUtil::MakeShape(xla::F32, {2, 3}), "p0"); + TF_EXPECT_OK(addSdyShardingFrontendAttribute( + &builder, param, xla::ShapeUtil::MakeShape(xla::F32, {2, 3}), + /*is_single_arg=*/true)); + + TF_ASSERT_OK_AND_ASSIGN(xla::XlaComputation computation, builder.Build()); + const xla::HloModuleProto& hloModuleProto = computation.proto(); + + const xla::HloInstructionProto& instruction = + hloModuleProto.computations(0).instructions(0); + + EXPECT_TRUE(instruction.frontend_attributes().map().contains( + xla::HloSharding::kShardingFrontendAttrName)); + EXPECT_EQ(instruction.frontend_attributes().map().at( + xla::HloSharding::kShardingFrontendAttrName), + "#sdy.sharding, " + "[{\"_axis_0\"}, {\"_axis_1\"}]>"); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/side_effect_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/side_effect_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..8476af608bc082fbb86b374c2bfd8c7b672e1311 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/side_effect_util.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 "tensorflow/compiler/tf2xla/side_effect_util.h" + +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/numbers.h" +#include "absl/strings/str_cat.h" +#include "absl/types/span.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/str_util.h" + +namespace tensorflow { + +const char kXlaTokenInputNodesAttrName[] = "_xla_token_input_nodes"; + +const char kXlaTokenArgNodeName[] = "_xla_token_arg_node"; + +const char kXlaHasHostTransferAttrName[] = "_xla_has_host_transfer"; + +const char kXlaReplicaIdAttrName[] = "_xla_replica_id"; + +const char kXlaIsPlaceholderForTailOcAttrName[] = + "_xla_is_placeholder_for_tail_oc"; + +const char kXlaOriginalOutsideCompilationNodeName[] = + "_xla_original_oc_node_name"; + +absl::Status SetDeviceOrdinalAttributeForNode(Node* node, int device_ordinal) { + if (!HasNodeAttr(node->def(), kXlaHasHostTransferAttrName)) { + return absl::InvalidArgumentError( + absl::StrCat("Node ", node->DebugString(), " does not have attribute ", + kXlaHasHostTransferAttrName)); + } + + if (node->type_string() == "_XlaRecvAtHost" || + node->type_string() == "_XlaSendFromHost") { + node->ClearAttr("device_ordinal"); + node->AddAttr("device_ordinal", device_ordinal); + } else if (node->IsIfNode()) { + AttrValue device_ordinal_value; + device_ordinal_value.set_i(device_ordinal); + for (const std::string& attr_name : + std::vector{"then_branch", "else_branch"}) { + NameAttrList branch_func; + TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func)); + (*branch_func.mutable_attr())["_device_ordinal"] = device_ordinal_value; + node->ClearAttr(attr_name); + node->AddAttr(attr_name, branch_func); + } + } else if (node->IsWhileNode()) { + AttrValue device_ordinal_value; + device_ordinal_value.set_i(device_ordinal); + for (const std::string& attr_name : + std::vector{"cond", "body"}) { + NameAttrList branch_func; + TF_RETURN_IF_ERROR(GetNodeAttr(node->attrs(), attr_name, &branch_func)); + (*branch_func.mutable_attr())["_device_ordinal"] = device_ordinal_value; + node->ClearAttr(attr_name); + node->AddAttr(attr_name, branch_func); + } + } else if (HasNodeAttr(node->def(), "_device_ordinal")) { + // Function call node containing outside compilation. + node->ClearAttr("_device_ordinal"); + node->AddAttr("_device_ordinal", device_ordinal); + } else { + return absl::InternalError(absl::StrCat( + "Unknown node type to set 'device_ordinal': ", node->DebugString())); + } + return absl::OkStatus(); +} + +std::set CalculateTokenInputsForOutputToken(const Graph& g) { + std::set results; + Node* first_side_effecting_node_on_path = nullptr; + ReverseDFS( + g, + [&](Node* n) { + std::vector token_input_nodes; + if (!GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName, + &token_input_nodes) + .ok() || + token_input_nodes.empty()) { + return; + } + + if (first_side_effecting_node_on_path != nullptr) { + return; + } + + first_side_effecting_node_on_path = n; + std::string original_node_name; + CHECK_OK(GetNodeAttr(n->def(), kXlaOriginalOutsideCompilationNodeName, + &original_node_name)); + results.insert(original_node_name); + }, + [&](Node* n) { + if (first_side_effecting_node_on_path == n) { + first_side_effecting_node_on_path = nullptr; + } + }, + NodeComparatorName()); + return results; +} + +bool HasSideEffectingNodes(const Graph& g) { + for (Node* n : g.nodes()) { + std::vector token_input_nodes; + if (GetNodeAttr(n->attrs(), kXlaTokenInputNodesAttrName, &token_input_nodes) + .ok() && + !token_input_nodes.empty()) { + return true; + } + } + return false; +} + +absl::Status ParseHostComputeCoreList( + absl::Span list_from_attr, + std::map* host_compute_core) { + for (const auto& hc_core : list_from_attr) { + std::vector parts = str_util::Split(hc_core, ":"); + if (parts.size() != 2) { + return absl::InvalidArgumentError( + absl::StrCat("Malformed host_compute_core entry ", hc_core, + " should be :.")); + } + int core; + if (!absl::numbers_internal::safe_strto32_base(parts[1], &core, 10)) { + return absl::InvalidArgumentError( + absl::StrCat("Malformed host_compute_core entry ", hc_core, + " part after ':' should be an integer.")); + } + if (host_compute_core->find(parts[0]) != host_compute_core->end()) { + return absl::InvalidArgumentError(absl::StrCat( + "Duplicate host_compute_core entry for cluster ", parts[0])); + } + (*host_compute_core)[parts[0]] = core; + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/side_effect_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/side_effect_util.h new file mode 100644 index 0000000000000000000000000000000000000000..388ffb4a91fb7ac6a595bd683475917b0dbbc31f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/side_effect_util.h @@ -0,0 +1,70 @@ +/* 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_TF2XLA_SIDE_EFFECT_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_SIDE_EFFECT_UTIL_H_ + +#include + +#include "tensorflow/core/graph/graph.h" + +namespace tensorflow { + +// Side-effecting nodes will have this attribute set. Its value is the list of +// node names which this node has side-effect dependencies on. +// +// Nodes like HostCompute, SendToHost, RecvFromHost always have this attribute, +// because they always have side-effect. +// If and While nodes may or may not have this attribute, depending on whether +// their bodies have side-effecting nodes. +extern const char kXlaTokenInputNodesAttrName[]; + +// This node name is used in kXlaTokenInputNodesAttrName attr to signal that a +// node has side-effect dependency on current graph's token input. +extern const char kXlaTokenArgNodeName[]; + +// This node have XlaRecvAtHost/XlaSendFromHost in its associated functions. +extern const char kXlaHasHostTransferAttrName[]; + +// This attribute is the replica id for an outside compilation node node. +extern const char kXlaReplicaIdAttrName[]; + +// This node is a Placeholder node added for tail outside compilation. +extern const char kXlaIsPlaceholderForTailOcAttrName[]; + +// This attribute is the original node name for this node. +extern const char kXlaOriginalOutsideCompilationNodeName[]; + +// Sets device ordinal attribute for nodes with attribute +// `kXlaHasHostTransferAttrName`. +absl::Status SetDeviceOrdinalAttributeForNode(Node* node, int device_ordinal); + +// Calculates side-effect dependencies for the graph's token output. +// Returns a set of node names representing these dependencies. +std::set CalculateTokenInputsForOutputToken(const Graph& g); + +// Returns whether a graph contains side-effecting nodes. +bool HasSideEffectingNodes(const Graph& g); + +// Parse the mapping from outside_compilation_subgraph name to core number, +// which is specified in an attr as a list of strings +// :. +absl::Status ParseHostComputeCoreList( + absl::Span list_from_attr, + std::map* host_compute_core); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_SIDE_EFFECT_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/test_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/test_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..361896a2ed5162486f1d0f82d0aebd7801a847d8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/test_util.cc @@ -0,0 +1,43 @@ +/* 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/test_util.h" + +#include "xla/status_macros.h" +#include "tensorflow/core/framework/node_def.pb.h" + +namespace tensorflow { + +absl::Status InstantiateFunctionForTest( + const std::string& name, const FunctionLibraryDefinition& library, + InstantiationResultForTest* result) { + const FunctionDef* fdef = library.Find(name); + TF_RET_CHECK(fdef != nullptr); + + auto get_func_sig = [&library](const std::string& op, const OpDef** sig) { + return library.LookUpOpDef(op, sig); + }; + InstantiationResult inst; + TF_RETURN_IF_ERROR( + InstantiateFunction(*fdef, AttrSlice(), get_func_sig, &inst)); + result->arg_types = inst.arg_types; + result->ret_types = inst.ret_types; + for (NodeDef& n : inst.nodes) { + *result->gdef.add_node() = std::move(n); + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/test_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/test_util.h new file mode 100644 index 0000000000000000000000000000000000000000..d8039e7b73617d240d422c85840b4cdf25dad84f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/test_util.h @@ -0,0 +1,60 @@ +/* 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. +==============================================================================*/ + +// Helper functions for tests. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_TEST_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TEST_UTIL_H_ + +#include +#include +#include + +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/graph_def_util.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/util/equal_graph_def.h" + +namespace tensorflow { + +// Same as InstantiationResult, but has a GraphDef instead of just nodes. +struct InstantiationResultForTest { + DataTypeVector arg_types; + DataTypeVector ret_types; + GraphDef gdef; +}; + +// Instantiates a function, producing a GraphDef to compare against the +// expected graph. +absl::Status InstantiateFunctionForTest( + const std::string& name, const FunctionLibraryDefinition& library, + InstantiationResultForTest* result); + +} // namespace tensorflow + +// Variant of TF_EXPECT_GRAPH_EQ that also compares internal attributes for +// equality. +#define TF_EXPECT_GRAPH_EQ_INTERNAL(expected, actual) \ + do { \ + string diff; \ + EqualGraphDefOptions eq_options; \ + eq_options.ignore_internal_attrs = false; \ + EXPECT_TRUE(EqualGraphDef(actual, expected, &diff, eq_options)) \ + << diff << "\nActual: " << SummarizeGraphDef(actual); \ + } while (false) + +#endif // TENSORFLOW_COMPILER_TF2XLA_TEST_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.cc new file mode 100644 index 0000000000000000000000000000000000000000..9334b31108934afdaf77002f2c2187e7c8d4149d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.cc @@ -0,0 +1,172 @@ +/* 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/tf2xla.h" + +#include +#include +#include +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/aot/aot_only_var_handle_op.h" +#include "tensorflow/compiler/tf2xla/graph_compiler_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 "xla/hlo/builder/xla_computation.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/graph_def_util.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/versions.pb.h" +#include "tensorflow/core/graph/algorithm.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/dump_graph.h" + +namespace tensorflow { + +namespace { + +// Converts the TensorFlow graph into an XLA computation, by executing the +// graph symbolically, with each op building up the XLA HLO. +absl::Status ConvertGraphToXla(std::unique_ptr graph, + const tf2xla::Config& config, + xla::Client* client, + xla::XlaComputation* computation) { + XlaOpRegistry::RegisterCompilationKernels(); + for (Node* node : graph->nodes()) { + node->set_assigned_device_name( + absl::StrCat("/device:", DEVICE_CPU_XLA_JIT)); + } + std::vector xla_args; + TF_RETURN_IF_ERROR(CreateXlaArgs(*graph, &xla_args)); + + PopulateXlaArgs(config, &xla_args); + // Compile the graph into an XLA computation. + XlaCompiler::Options compiler_options; + compiler_options.client = client; + compiler_options.device_type = DeviceType(DEVICE_CPU_XLA_JIT); + compiler_options.flib_def = &graph->flib_def(); + compiler_options.graph_def_version = graph->versions().producer(); + compiler_options.allow_cpu_custom_calls = true; + + XlaCompiler compiler(compiler_options); + + XlaCompiler::CompilationResult result; + + XlaCompiler::CompileOptions options; + options.alias_resource_update = true; + TF_RETURN_IF_ERROR(compiler.CompileGraph( + options, "tfcompile", std::move(graph), xla_args, &result)); + *computation = std::move(*result.computation); + + int num_const_results = 0; + for (int i = 0, end = result.outputs.size(); i < end; ++i) { + // Ending up with const results (i.e. output args) is an error, since it + // means that one or more fetches that the user specified will be dropped + // from the generated function. It's most likely a configuration error, + // since the user shouldn't be asking for output args that end up as consts. + // + // TODO(toddw): Provide a way for the user to access const output args, + // e.g. perhaps hard-coded into the header, or somehow copied into the + // output buffers. + if (result.outputs[i].is_constant) { + ++num_const_results; + LOG(ERROR) << "ConstRetVal index:" << i + << " value:" << result.outputs[i].constant_value.DebugString(); + } + } + if (num_const_results > 0) { + return absl::UnimplementedError( + absl::StrCat("Conversion from TensorFlow graph to XLA resulted in ", + num_const_results, + " constant results. The configuration of " + "the output args (i.e. fetch ids) is probably wrong.")); + } + { + // Verify that the readonly bits on variables are set correctly by the user. + std::vector updated_inputs(xla_args.size()); + for (const XlaCompiler::ResourceUpdate& update : result.resource_updates) { + updated_inputs[update.input_index] = true; + } + int64_t input_index = xla_args.size() - config.variable_size(); + for (const tf2xla::Variable& variable : config.variable()) { + if (variable.readonly() == updated_inputs[input_index]) { + return absl::InvalidArgumentError(absl::StrCat( + "Variable \"", variable.node_name(), "\" is marked as ", + variable.readonly() ? "" : "not ", "readonly, but is ", + updated_inputs[input_index] ? "" : "not ", + "modified by the computation.")); + } + ++input_index; + } + } + return absl::OkStatus(); +} + +absl::Status ConvertVarHandlesToAotVarHandles(GraphDef* graph_def) { + auto update_var_handle_op_node = [](NodeDef& node) -> absl::Status { + if (node.op() == "VarHandleOp") { + node.set_op(tfcompile::kXlaAotOnlyVarHandleOp); + const auto& it = node.attr().find("allowed_devices"); + if (it != node.attr().end()) { + if (!it->second.list().s().empty()) { + return absl::InvalidArgumentError( + "VarHandleOp with non-empty allowed devices is not supported."); + } + node.mutable_attr()->erase("allowed_devices"); + } + } + return absl::OkStatus(); + }; + for (auto& node : *graph_def->mutable_node()) { + TF_RETURN_IF_ERROR(update_var_handle_op_node(node)); + } + for (auto& fn : *graph_def->mutable_library()->mutable_function()) { + for (auto& node : *fn.mutable_node_def()) { + TF_RETURN_IF_ERROR(update_var_handle_op_node(node)); + } + } + return absl::OkStatus(); +} + +} // namespace + +absl::Status ConvertGraphDefToXla(GraphDef graph_def, + const tf2xla::Config& config, + xla::Client* client, + xla::XlaComputation* computation) { + std::unique_ptr graph; + TF_RETURN_IF_ERROR(ConvertVarHandlesToAotVarHandles(&graph_def)); + TF_RETURN_IF_ERROR(InitGraph(graph_def, config, &graph)); + TF_RETURN_IF_ERROR( + ConvertGraphToXla(std::move(graph), config, client, computation)); + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.h new file mode 100644 index 0000000000000000000000000000000000000000..bd3a8bb211c521b17f0dcdb9f134ad14f87225ae --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.h @@ -0,0 +1,53 @@ +/* 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_TF2XLA_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TF2XLA_H_ + +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "xla/client/client.h" +#include "xla/hlo/builder/xla_computation.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +// Converts a tensorflow::GraphDef into an xla::XlaComputation. The given +// `config` specifies the portion of the graph to convert, via feeds and +// fetches. Each feed is a positional input argument for the generated +// computation, while each fetch is a positional output argument. +// +// The computation is built in the context of the given `client`, which may +// subsequently be used to compile or execute the computation. +absl::Status ConvertGraphDefToXla(GraphDef graph_def, + const tf2xla::Config& config, + xla::Client* client, + xla::XlaComputation* computation); + +// Similar to ConvertGraphDefToXla, but uses MLIR and handle debug information. +// +// debug_info_filename: the file for the debug information proto. +// debug_info_path_begin_marker: if not empty, file pathes in the debug +// information are trimmed from the beginning to the first appearance of the +// marker. +absl::Status ConvertGraphDefToXlaViaMlir( + GraphDef graph_def, const tf2xla::Config& config, + xla::XlaComputation* computation, absl::string_view debug_info_filename, + absl::string_view debug_info_path_begin_marker); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_TF2XLA_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.proto b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.proto new file mode 100644 index 0000000000000000000000000000000000000000..05c133f15173c87b90d1625a99d1f2cb2165727d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla.proto @@ -0,0 +1,70 @@ +syntax = "proto3"; + +package tensorflow.tf2xla; + +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "Tf2XlaProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.tf2xla"; + +// TensorId identifies a tensor in a TensorFlow graph, by specifying the output +// index of a particular node in the graph. If the output of the named node +// feeds into other node(s), this corresponds to one or more edges. Otherwise +// it doesn't correspond to any existing edges at all, e.g. for output nodes. +message TensorId { + string node_name = 1; + int64 output_index = 2; +} + +// Feed represents a single feed tensor in the graph, which corresponds to an +// input argument for the generated computation. +message Feed { + TensorId id = 1; + TensorShapeProto shape = 2; + string name = 3; // Optional name for generated code. + + // Optional data type. This is not normally required, as the graph itself + // contains this information. However, if the node being fed is an op that is + // not linked into the binary, then the type cannot be inferred from the node; + // in this case, the type should be set here. + DataType type = 4; +} + +// Fetch represents a single fetch tensor in the graph, which corresponds to an +// output argument for the generated computation. +message Fetch { + TensorId id = 1; + string name = 2; // Optional name for generated code. + + // Optional shape and data type. If specified, may be used for validation. + TensorShapeProto shape = 3; + DataType type = 4; +} + +// Variable represents a resource variable with the given name, shape and type. +message Variable { + string node_name = 1; + string name = + 2; // Optional name for generated code. If empty, node_name will be used. + TensorShapeProto shape = 3; + DataType type = 4; + + // Flag for variables that are never assigned. Assignments to a read-only + // variable or unassigned variables that are not read-only are invalid. + bool readonly = 5; +} + +// Config represents configuration information for tf2xla conversion. +message Config { + // Each feed is a positional input argument for the generated computation. + // The order of each entry matches the order of each input argument. + repeated Feed feed = 1; + // Each fetch is a positional output argument for the generated computation. + // The order of each entry matches the order of each output argument. + repeated Fetch fetch = 2; + // Each variable is a named input and output of the generated computation. + repeated Variable variable = 3; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_defs.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_defs.h new file mode 100644 index 0000000000000000000000000000000000000000..385eccb0bac26665c952317a8df8cc1c8b81caee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_defs.h @@ -0,0 +1,65 @@ +/* Copyright 2022 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_TF2XLA_DEFS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TF2XLA_DEFS_H_ + +#include + +#include "absl/strings/string_view.h" + +namespace tensorflow { + +// Marks a node for XLA compilation. The attribute value indicates the +// compilation device type. +inline constexpr absl::string_view kCompileDeviceTypeAttr = + "_xla_compile_device_type"; +// Marks a node for XLA compilation. +inline constexpr absl::string_view kMustCompileAttr = "_XlaMustCompile"; +// Marks a node for replication. The attribute value indicates the replication +// metadata op. +inline constexpr absl::string_view kReplicationInfoAttr = "_replication_info"; +// Marks a node for XLA-TPU compilation. The attribute value indicates the +// associated compilation cluster and replication metadata op. +inline constexpr absl::string_view kTpuReplicateAttr = "_tpu_replicate"; +// Marks a node inside of an XLA compilation cluster to be placed outside of the +// cluster. +inline constexpr absl::string_view kXlaOutsideCompilationAttr = + "_xla_outside_compilation"; +// Frontend attributes ID. +inline constexpr absl::string_view kXlaFrontendAttributesAttrName = + "_XlaFrontendAttributes"; +// Device types. +inline constexpr absl::string_view kDeviceAttr = "device"; +inline constexpr absl::string_view kCpuDevice = "CPU"; +inline constexpr absl::string_view kGpuDevice = "GPU"; +inline constexpr absl::string_view kTpuDevice = "TPU"; +inline constexpr absl::string_view kEmptyDevice = ""; +// Device type may be empty in ops such as TF.PartitionedCall. +inline constexpr std::array kValidDeviceTypes = { + kCpuDevice, kGpuDevice, kTpuDevice, kEmptyDevice}; +// Attributes that need to be propagated during rewrites (e.g., in +// functionalization). +inline constexpr std::array kAttrsToPropagate = { + kCompileDeviceTypeAttr, + kReplicationInfoAttr, + kXlaFrontendAttributesAttrName, + kXlaOutsideCompilationAttr, + kTpuReplicateAttr, +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_TF2XLA_DEFS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset.cc new file mode 100644 index 0000000000000000000000000000000000000000..a82278efa9d24bc6acb06d2dc62a088d6e9c87b3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset.cc @@ -0,0 +1,96 @@ +/* Copyright 2023 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/tf2xla_opset.h" + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/kernel_def.pb.h" + +namespace tensorflow { + +const int SUPPORTED_DEVICES_NUM = 2; +static const char* const SUPPORTED_DEVICES[SUPPORTED_DEVICES_NUM] = { + DEVICE_GPU_XLA_JIT, DEVICE_CPU_XLA_JIT}; + +bool IsSupportedBackend(absl::string_view device_name) { + for (int i = 0; i < SUPPORTED_DEVICES_NUM; i++) { + if (SUPPORTED_DEVICES[i] == device_name) return true; + } + return false; +} + +absl::Status RegisterBackends(absl::string_view device_name) { + if (!IsSupportedBackend(device_name)) { + return absl::InvalidArgumentError( + absl::StrCat(device_name, " is not supported. Supported devices are ", + absl::StrJoin(SUPPORTED_DEVICES, ", "))); + } + // All backends need to be registered before DeviceKernels is called + // because it calls RegisterCompilationKernels which will only run 1x, + // meaning if a device is registered afterwards the ops for that device + // will not be included. + auto op_filter = [](KernelDef* kdef) { + if (kdef->op() == "Const") { + AddDtypeToKernelDefConstraint("dtype", DT_STRING, kdef); + } + if (kdef->op() == "Assert") { + AddDtypeToKernelDefConstraint("T", DT_STRING, kdef); + } + return true; + }; + + // Backends might already be registered due to preprocesser macros defined + // in xla_op_registery.h so this first checks to see if they are registered + // already because re-registering the same device will cause a failure. + if (!XlaOpRegistry::IsBackendRegistered(DEVICE_GPU_XLA_JIT)) { + static auto gpu_backend = + XlaBackendRegistrar(DEVICE_GPU_XLA_JIT, kGpuAllTypes, op_filter); + } + if (!XlaOpRegistry::IsBackendRegistered(DEVICE_CPU_XLA_JIT)) { + static auto cpu_backend = + XlaBackendRegistrar(DEVICE_CPU_XLA_JIT, kCpuAllTypes, op_filter); + } + if (!XlaOpRegistry::IsBackendRegistered(std::string(device_name))) { + return absl::InternalError( + absl::StrCat(device_name, " is not registered.")); + } + return absl::OkStatus(); +} + +absl::StatusOr> GetRegisteredXlaOpsForDevice( + absl::string_view device_name) { + auto status = RegisterBackends(device_name); + if (!status.ok()) return status; + + std::vector kernel_defs = + XlaOpRegistry::DeviceKernels(std::string(device_name), true); + std::vector op_names; + op_names.reserve(kernel_defs.size()); + for (const auto& kernel_def : kernel_defs) { + op_names.push_back(kernel_def->op()); + } + std::sort(op_names.begin(), op_names.end()); + return op_names; +} +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset.h new file mode 100644 index 0000000000000000000000000000000000000000..200ecc30c417de9ad3f527128150ddd29fdb21ff --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset.h @@ -0,0 +1,30 @@ +/* Copyright 2023 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_TF2XLA_OPSET_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TF2XLA_OPSET_H_ + +#include +#include + +#include "absl/status/statusor.h" + +namespace tensorflow { + +absl::StatusOr> GetRegisteredXlaOpsForDevice( + absl::string_view device_name); + +} // namespace tensorflow +#endif // TENSORFLOW_COMPILER_TF2XLA_TF2XLA_OPSET_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..f3c6d7a24e8313fd9f8c52a9ebd70644f8c33a62 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_opset_test.cc @@ -0,0 +1,62 @@ +/* Copyright 2023 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/tf2xla_opset.h" + +#include +#include +#include + +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { + +TEST(GeXlaOpsForDeviceTest, InvalidDeviceToRegister) { + absl::StatusOr> result = + GetRegisteredXlaOpsForDevice("Invalid_Device"); + EXPECT_FALSE(result.ok()); +} +TEST(GeXlaOpsForDeviceTest, GetGpuNames) { + absl::StatusOr> result = + GetRegisteredXlaOpsForDevice("XLA_GPU_JIT"); + EXPECT_GT(result.value().size(), 0); + auto matmul = + std::find(result.value().begin(), result.value().end(), "MatMul"); + auto max = std::find(result.value().begin(), result.value().end(), "Max"); + auto min = std::find(result.value().begin(), result.value().end(), "Min"); + EXPECT_TRUE((matmul != result.value().end())); + EXPECT_TRUE((max != result.value().end())); + EXPECT_TRUE((min != result.value().end())); + EXPECT_LT(matmul, max); + EXPECT_LT(max, min); +} +TEST(GeXlaOpsForDeviceTest, GetCpuNames) { + absl::StatusOr> result = + GetRegisteredXlaOpsForDevice("XLA_CPU_JIT"); + EXPECT_GT(result.value().size(), 0); + auto matmul = + std::find(result.value().begin(), result.value().end(), "MatMul"); + auto max = std::find(result.value().begin(), result.value().end(), "Max"); + auto min = std::find(result.value().begin(), result.value().end(), "Min"); + EXPECT_TRUE((matmul != result.value().end())); + EXPECT_TRUE((max != result.value().end())); + EXPECT_TRUE((min != result.value().end())); + EXPECT_LT(matmul, max); + EXPECT_LT(max, min); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops.cc new file mode 100644 index 0000000000000000000000000000000000000000..c88cd50171f33d4303d1e8002dccf818e646abd1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops.cc @@ -0,0 +1,101 @@ +/* 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/tf2xla_supported_ops.h" + +#include +#include +#include +#include + +#include "absl/strings/str_join.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/kernel_def.pb.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/init_main.h" +#include "tensorflow/core/util/command_line_flags.h" + +namespace tensorflow { +namespace tf2xla { +namespace { + +void PrintSupportedOps(const std::string& device, + const std::string& regen_run) { + XlaOpRegistry::RegisterCompilationKernels(); + + std::vector kdefs = + XlaOpRegistry::DeviceKernels(device, + /*include_compilation_only_kernels=*/true); + std::sort( + kdefs.begin(), kdefs.end(), + [](const KernelDef* a, const KernelDef* b) { return a->op() < b->op(); }); + + std::cout << "**Supported operators for device: " << device << "**\n\n" + << "Operator | Type Constraint\n" + << "-------- | ---------------" << std::endl; + for (const KernelDef* kdef : kdefs) { + std::vector constraints; + constraints.reserve(kdef->constraint().size()); + for (const KernelDef::AttrConstraint& constraint : kdef->constraint()) { + std::vector types; + const auto& allowed_values = constraint.allowed_values().list().type(); + types.reserve(allowed_values.size()); + for (int type : allowed_values) { + types.push_back(DataTypeString(static_cast(type))); + } + std::sort(types.begin(), types.end()); + constraints.push_back("`" + constraint.name() + "={" + + absl::StrJoin(types, ",") + "}`"); + } + std::cout << "`" << kdef->op() << "` | " + << absl::StrJoin(constraints, "
") << std::endl; + } + + std::cout << "\nTo regenerate this table, run:\n\n```shell\n" + << regen_run << " --device=" << device << "\n```" << std::endl; +} + +} // namespace + +void SupportedOpsMain(int argc, char** argv, const char* regen_run) { + std::vector device_names = XlaOpRegistry::BackendNames(); + std::sort(device_names.begin(), device_names.end()); + + // Set up and parse flags. + std::string device; + std::vector flag_list = { + {"device", &device, + "Name of the compilation device for which to print supported ops, " + "one of: " + + absl::StrJoin(device_names, ",")}, + }; + std::string usage = Flags::Usage(argv[0], flag_list); + bool parsed_flags_ok = Flags::Parse(&argc, argv, flag_list); + QCHECK(parsed_flags_ok) << "\n" << usage; + QCHECK(XlaOpRegistry::IsBackendRegistered(device)) + << "\nUnknown device: " << device << "\n" + << usage; + + // Run the program. + port::InitMain(usage.c_str(), &argc, &argv); + QCHECK(argc == 1) << "\nERROR: This command does not take any arguments " + "other than flags\n\n" + << usage; + PrintSupportedOps(device, regen_run); +} + +} // namespace tf2xla +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f5b589b6da743a395bc5b3891bced5dde8134a40 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops.h @@ -0,0 +1,33 @@ +/* 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_TF2XLA_SUPPORTED_OPS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TF2XLA_SUPPORTED_OPS_H_ + +namespace tensorflow { +namespace tf2xla { + +// The implementation of a main function for a binary that prints a table of +// supported tf2xla operators for a given device, along with their type +// constraints, to stdout. +// +// Pass the argc and argv from main, unmodified. Use regen_run to specify the +// command used to regenerate the table. +void SupportedOpsMain(int argc, char** argv, const char* regen_run); + +} // namespace tf2xla +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_TF2XLA_SUPPORTED_OPS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops_main.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops_main.cc new file mode 100644 index 0000000000000000000000000000000000000000..35a9b0f8f8bc22678183bfd75f6994b26a419626 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_supported_ops_main.cc @@ -0,0 +1,22 @@ +/* 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/tf2xla_supported_ops.h" + +int main(int argc, char** argv) { + const char* regen_run = + "bazel run -c opt -- tensorflow/compiler/tf2xla:tf2xla_supported_ops"; + tensorflow::tf2xla::SupportedOpsMain(argc, argv, regen_run); +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..f7172d3c80eaa979746d7eb0712255a41c5eb865 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_test.cc @@ -0,0 +1,392 @@ +/* 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/tf2xla.h" + +#include + +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "xla/client/client_library.h" +#include "xla/client/local_client.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/attr_value_util.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/statusor.h" +#include "tensorflow/core/platform/stringpiece.h" +#include "tensorflow/core/platform/test.h" +#include "tsl/platform/tensor_float_32_utils.h" + +namespace tensorflow { +namespace { + +class ConvertGraphDefToXlaWithTF32Disabled : public ::testing::Test { + public: + ConvertGraphDefToXlaWithTF32Disabled() { + tsl::enable_tensor_float_32_execution(false); + } + ~ConvertGraphDefToXlaWithTF32Disabled() override { + tsl::enable_tensor_float_32_execution(true); + } +}; + +AttrValue TypeAttrValue(DataType type) { + AttrValue attr_value; + SetAttrValue(type, &attr_value); + return attr_value; +} + +AttrValue StringAttrValue(absl::string_view str) { + AttrValue attr_value; + SetAttrValue(str, &attr_value); + return attr_value; +} + +AttrValue IntAttrValue(int i) { + AttrValue attr_value; + SetAttrValue(i, &attr_value); + return attr_value; +} + +AttrValue IntVectorAttrValue(const std::vector& ints) { + AttrValue attr_value; + SetAttrValue(ints, &attr_value); + return attr_value; +} + +TensorShapeProto TensorShape(const std::vector& dims) { + TensorShapeProto shape; + for (int i = 0; i < dims.size(); ++i) { + shape.add_dim(); + shape.mutable_dim(i)->set_size(dims[i]); + } + return shape; +} + +GraphDef SumGraph() { + GraphDef graph_def; + NodeDef* x = graph_def.add_node(); + x->set_name("x"); + x->set_op("Placeholder"); + (*x->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32); + NodeDef* y = graph_def.add_node(); + y->set_name("y"); + y->set_op("Placeholder"); + (*y->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32); + NodeDef* sum = graph_def.add_node(); + sum->set_name("sum"); + sum->set_op("Add"); + sum->add_input("x"); + sum->add_input("y"); + (*sum->mutable_attr())["T"] = TypeAttrValue(DT_INT32); + return graph_def; +} + +tf2xla::Config SumConfig() { + tf2xla::Config config; + config.add_feed()->mutable_id()->set_node_name("x"); + config.add_feed()->mutable_id()->set_node_name("y"); + config.add_fetch()->mutable_id()->set_node_name("sum"); + return config; +} + +TEST(ConvertGraphDefToXla, Sum) { + GraphDef graph_def = SumGraph(); + tf2xla::Config config = SumConfig(); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + // Set up arguments. + auto x_literal = xla::LiteralUtil::CreateR0(10); + auto y_literal = xla::LiteralUtil::CreateR0(32); + auto x_global_or = client->TransferToServer(x_literal); + auto y_global_or = client->TransferToServer(y_literal); + TF_EXPECT_OK(x_global_or.status()); + TF_EXPECT_OK(y_global_or.status()); + std::unique_ptr x_global = std::move(x_global_or.value()); + std::unique_ptr y_global = std::move(y_global_or.value()); + + // Execute and check result. + auto result_or = + client->ExecuteAndTransfer(computation, {x_global.get(), y_global.get()}); + TF_EXPECT_OK(result_or.status()); + xla::Literal result = std::move(result_or.value()); + EXPECT_EQ("(\ns32[] 42\n)", result.ToString()); + + config.mutable_feed(0)->mutable_id()->set_output_index( + 123); /* invalid output_index */ + EXPECT_TRUE(absl::IsInvalidArgument( + ConvertGraphDefToXla(graph_def, config, client, &computation))); +} + +GraphDef EinsumGraph(DataType dtype = DT_FLOAT) { + GraphDef graph_def; + NodeDef* x = graph_def.add_node(); + x->set_name("x"); + x->set_op("Placeholder"); + (*x->mutable_attr())["dtype"] = TypeAttrValue(dtype); + NodeDef* y = graph_def.add_node(); + y->set_name("y"); + y->set_op("Placeholder"); + (*y->mutable_attr())["dtype"] = TypeAttrValue(dtype); + NodeDef* einsum = graph_def.add_node(); + einsum->set_name("einsum"); + einsum->set_op("Einsum"); + einsum->add_input("x"); + einsum->add_input("y"); + (*einsum->mutable_attr())["equation"] = StringAttrValue("ij,jk->ik"); + (*einsum->mutable_attr())["T"] = TypeAttrValue(dtype); + (*einsum->mutable_attr())["N"] = IntAttrValue(2); + return graph_def; +} + +tf2xla::Config EinsumConfig() { + tf2xla::Config config; + + tf2xla::Feed* x_feed = config.add_feed(); + x_feed->mutable_id()->set_node_name("x"); + *x_feed->mutable_shape() = TensorShape({2, 2}); + + tf2xla::Feed* y_feed = config.add_feed(); + y_feed->mutable_id()->set_node_name("y"); + *y_feed->mutable_shape() = TensorShape({2, 2}); + + config.add_fetch()->mutable_id()->set_node_name("einsum"); + return config; +} + +TEST(ConvertGraphDefToXla, EinsumIsConvertedToDotWithDefaultPrecision) { + GraphDef graph_def = EinsumGraph(); + tf2xla::Config config = EinsumConfig(); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + int num_dots = 0; + const xla::HloModuleProto& module_proto = computation.proto(); + for (const xla::HloComputationProto& computation_proto : + module_proto.computations()) { + for (const xla::HloInstructionProto& instruction_proto : + computation_proto.instructions()) { + if (instruction_proto.opcode() == "dot") { + num_dots++; + ASSERT_EQ(instruction_proto.precision_config().operand_precision_size(), + 2); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(0), + xla::PrecisionConfig::DEFAULT); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(1), + xla::PrecisionConfig::DEFAULT); + } + } + } + EXPECT_EQ(num_dots, 1); +} + +TEST_F(ConvertGraphDefToXlaWithTF32Disabled, + EinsumIsConvertedToDotWithHighestPrecision) { + GraphDef graph_def = EinsumGraph(); + tf2xla::Config config = EinsumConfig(); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + int num_dots = 0; + const xla::HloModuleProto& module_proto = computation.proto(); + for (const xla::HloComputationProto& computation_proto : + module_proto.computations()) { + for (const xla::HloInstructionProto& instruction_proto : + computation_proto.instructions()) { + if (instruction_proto.opcode() == "dot") { + num_dots++; + ASSERT_EQ(instruction_proto.precision_config().operand_precision_size(), + 2); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(0), + xla::PrecisionConfig::HIGHEST); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(1), + xla::PrecisionConfig::HIGHEST); + } + } + } + EXPECT_EQ(num_dots, 1); +} + +TEST_F(ConvertGraphDefToXlaWithTF32Disabled, + EinsumIsConvertedToDotWithDefaultPrecisionIfNotF32) { + GraphDef graph_def = EinsumGraph(DT_BFLOAT16); + tf2xla::Config config = EinsumConfig(); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + int num_dots = 0; + const xla::HloModuleProto& module_proto = computation.proto(); + for (const xla::HloComputationProto& computation_proto : + module_proto.computations()) { + for (const xla::HloInstructionProto& instruction_proto : + computation_proto.instructions()) { + if (instruction_proto.opcode() == "dot") { + num_dots++; + ASSERT_EQ(instruction_proto.precision_config().operand_precision_size(), + 2); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(0), + xla::PrecisionConfig::DEFAULT); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(1), + xla::PrecisionConfig::DEFAULT); + } + } + } + EXPECT_EQ(num_dots, 1); +} + +GraphDef Conv2DGraph() { + GraphDef graph_def; + NodeDef* x = graph_def.add_node(); + x->set_name("x"); + x->set_op("Placeholder"); + (*x->mutable_attr())["dtype"] = TypeAttrValue(DT_FLOAT); + NodeDef* y = graph_def.add_node(); + y->set_name("y"); + y->set_op("Placeholder"); + (*y->mutable_attr())["dtype"] = TypeAttrValue(DT_FLOAT); + NodeDef* einsum = graph_def.add_node(); + einsum->set_name("conv2d"); + einsum->set_op("Conv2D"); + einsum->add_input("x"); + einsum->add_input("y"); + (*einsum->mutable_attr())["T"] = TypeAttrValue(DT_FLOAT); + (*einsum->mutable_attr())["padding"] = StringAttrValue("VALID"); + (*einsum->mutable_attr())["strides"] = IntVectorAttrValue({1, 1, 1, 1}); + return graph_def; +} + +tf2xla::Config Conv2DConfig() { + tf2xla::Config config; + tf2xla::Feed* x_feed = config.add_feed(); + x_feed->mutable_id()->set_node_name("x"); + *x_feed->mutable_shape() = TensorShape({1, 1, 2, 2}); + + tf2xla::Feed* y_feed = config.add_feed(); + y_feed->mutable_id()->set_node_name("y"); + *y_feed->mutable_shape() = TensorShape({1, 1, 2, 2}); + config.add_fetch()->mutable_id()->set_node_name("conv2d"); + return config; +} + +TEST(ConvertGraphDefToXla, Conv2DIsConvertedToConvolutionWithDefaultPrecision) { + GraphDef graph_def = Conv2DGraph(); + tf2xla::Config config = Conv2DConfig(); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + int num_convolutions = 0; + const xla::HloModuleProto& module_proto = computation.proto(); + for (const xla::HloComputationProto& computation_proto : + module_proto.computations()) { + for (const xla::HloInstructionProto& instruction_proto : + computation_proto.instructions()) { + if (instruction_proto.opcode() == "convolution") { + num_convolutions++; + ASSERT_EQ(instruction_proto.precision_config().operand_precision_size(), + 2); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(0), + xla::PrecisionConfig::DEFAULT); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(1), + xla::PrecisionConfig::DEFAULT); + } + } + } + EXPECT_EQ(num_convolutions, 1); +} + +TEST_F(ConvertGraphDefToXlaWithTF32Disabled, + Conv2DIsConvertedToConvolutionWithHighestPrecision) { + GraphDef graph_def = Conv2DGraph(); + tf2xla::Config config = Conv2DConfig(); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + int num_convolutions = 0; + const xla::HloModuleProto& module_proto = computation.proto(); + for (const xla::HloComputationProto& computation_proto : + module_proto.computations()) { + for (const xla::HloInstructionProto& instruction_proto : + computation_proto.instructions()) { + if (instruction_proto.opcode() == "convolution") { + num_convolutions++; + ASSERT_EQ(instruction_proto.precision_config().operand_precision_size(), + 2); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(0), + xla::PrecisionConfig::HIGHEST); + EXPECT_EQ(instruction_proto.precision_config().operand_precision(1), + xla::PrecisionConfig::HIGHEST); + } + } + } + EXPECT_EQ(num_convolutions, 1); +} + +TEST(ConvertGraphDefToXla, SumWithUnusedArgument) { + GraphDef graph_def = SumGraph(); + tf2xla::Config config = SumConfig(); + NodeDef* unused = graph_def.add_node(); + unused->set_name("unused"); + unused->set_op("Placeholder"); + (*unused->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32); + config.add_feed()->mutable_id()->set_node_name("unused"); + + xla::LocalClient* client = xla::ClientLibrary::LocalClientOrDie(); + xla::XlaComputation computation; + TF_EXPECT_OK(ConvertGraphDefToXla(graph_def, config, client, &computation)); + + // Set up arguments. + auto x_literal = xla::LiteralUtil::CreateR0(10); + auto y_literal = xla::LiteralUtil::CreateR0(32); + auto x_global_or = client->TransferToServer(x_literal); + auto y_global_or = client->TransferToServer(y_literal); + auto unused_global_or = client->TransferToServer(y_literal); + TF_EXPECT_OK(x_global_or.status()); + TF_EXPECT_OK(y_global_or.status()); + TF_EXPECT_OK(unused_global_or.status()); + std::unique_ptr x_global = std::move(x_global_or.value()); + std::unique_ptr y_global = std::move(y_global_or.value()); + std::unique_ptr unused_global = + std::move(unused_global_or.value()); + + // Execute and check result. + auto result_or = client->ExecuteAndTransfer( + computation, {x_global.get(), y_global.get(), unused_global.get()}); + TF_EXPECT_OK(result_or.status()); + xla::Literal result = std::move(result_or.value()); + EXPECT_EQ("(\ns32[] 42\n)", result.ToString()); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..17a503c32dfd83aa7d2ded1fdeb9c00738d59e53 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util.cc @@ -0,0 +1,1150 @@ +/* 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/tf2xla_util.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/container/flat_hash_set.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/sharding_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/common_runtime/function_body.h" +#include "tensorflow/core/common_runtime/function_def_utils.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/graph_def_util.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#include "tensorflow/core/framework/node_def.pb.h" +#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/tensor_shape.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/versions.pb.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/graph/graph_debug_info_builder.h" +#include "tensorflow/core/graph/graph_node_util.h" +#include "tensorflow/core/graph/tensor_id.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { + +namespace { + +absl::Status ValidateTensorId(const tf2xla::TensorId& id) { + if (id.node_name().empty()) { + return absl::InvalidArgumentError("TensorId node_name must be non-empty"); + } + if (id.output_index() < 0) { + return absl::InvalidArgumentError("TensorId output_index must be positive"); + } + return absl::OkStatus(); +} + +absl::Status CheckNameDuplicates(const std::string& kind, + const std::string& name, + std::set* names) { + if (!name.empty()) { + if (!names->insert(name).second) { + return absl::InvalidArgumentError( + absl::StrCat("duplicate ", kind, " name: ", name)); + } + } + return absl::OkStatus(); +} + +absl::Status CheckFeedFetchNameConflicts(const std::string& kind, + const std::set& names) { + // We don't allow the feeds or fetches to contain both "foo" and "foo_data", + // since that will cause a collision in codegen symbols. + for (const std::string& name : names) { + const std::string name_data(name + "_data"); + if (names.find(name_data) != names.end()) { + return absl::InvalidArgumentError(absl::StrCat( + "conflicting ", kind, " name: ", name, " and ", name_data)); + } + } + return absl::OkStatus(); +} + +// For graph `g`, copy all function call nodes' FunctionDef from `lookup_fld` to +// `fld`. This is to ensure that `fld` can instantiate FunctionDef of graph `g`. +absl::Status CopyAssociatedFunctions( + Graph* g, const FunctionLibraryDefinition* lookup_fld, + FunctionLibraryDefinition* fld) { + for (Node* n : g->op_nodes()) { + for (const auto& associated_function : + GetAssociatedFunctions(*n, lookup_fld)) { + switch (associated_function.type()) { + case AssociatedFunctionInfo::kFunctionCallNode: { + const FunctionDef* fdef = + lookup_fld->Find(associated_function.func_name()); + if (!fdef) { + return absl::InternalError(absl::StrCat( + "Cannot find function ", associated_function.func_name(), + " for function call node ", n->DebugString())); + } + TF_RETURN_IF_ERROR(fld->AddFunctionDef(*fdef)); + break; + } + case AssociatedFunctionInfo::kSymbolicGradient: + case AssociatedFunctionInfo::kFunctionAttr: + break; + } + } + } + return absl::OkStatus(); +} + +// Replaces the single edge feeding into {dst,dst_input} with a new +// src/src_output specified by {with,with_output}. +absl::StatusOr ReplaceEdge(Graph* g, Node* dst, int dst_input, + Node* with, int with_output) { + NodeDef replace_def = dst->def(); + *replace_def.mutable_input(dst_input) = with->name(); + TF_ASSIGN_OR_RETURN(Node * replace_node, ReplaceNode(g, dst, replace_def)); + const Edge* usage_edge; + TF_RETURN_IF_ERROR(replace_node->input_edge(dst_input, &usage_edge)); + g->RemoveEdge(usage_edge); + g->AddEdge(with, with_output, replace_node, dst_input); + return replace_node; +} + +// Replaces usages of the given `src_output` index of the given `src` node with +// the given `replacement` node (assumes the :0 output of `replacement`). +absl::Status ReplaceSrcOutputUsageWithNode(Graph* g, Node* src, int src_output, + Node* replacement) { + VLOG(1) << "Replace usages of output " << src_output << " of node " + << (VLOG_IS_ON(3) ? src->DebugString() : src->name()) << " with " + << (VLOG_IS_ON(3) ? replacement->DebugString() : replacement->name()); + // Collect all usages of the specified src output (src->out_edges() iterator + // will not be stable under modifications). + struct OutEdgeInfo { + int dst_node_id, dst_input; + }; + std::vector usages; + for (const Edge* e : src->out_edges()) { + if (e->IsControlEdge() || e->src_output() != src_output) { + continue; + } + usages.push_back({e->dst()->id(), e->dst_input()}); + } + + // Now, replace each usage. + for (int i = 0, end = usages.size(); i < end; i++) { + // Make a copy of `usage_node`, and change its input to const node. + Node* usage_node = g->FindNodeId(usages[i].dst_node_id); + VLOG(2) << " Replace usage by " << usage_node->DebugString(); + // Note: Replacement output index is presumed to be 0. + TF_ASSIGN_OR_RETURN( + Node * replace_node, + ReplaceEdge(g, usage_node, usages[i].dst_input, replacement, 0)); + // Later entries in `usages` might have `usage_node` as dst node, but + // `usage_node` is removed. Replace such entries with `replace_node`. + for (int j = i + 1, end = usages.size(); j < end; j++) { + if (usages[j].dst_node_id == usages[i].dst_node_id) { + usages[j].dst_node_id = replace_node->id(); + } + } + } + return absl::OkStatus(); +} + +// For graph `g`, replaces _Arg nodes whose "index" attribute is in +// `const_input_index_to_node` with Const nodes. +absl::Status ReplaceArgUsageWithConstNode( + Graph* g, + const absl::flat_hash_map& const_input_index_to_node) { + // Collect all _Arg nodes. + absl::flat_hash_map arg_nodes; + for (Node* n : g->op_nodes()) { + if (n->IsArg()) { + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); + arg_nodes[index] = n; + } + } + + for (const auto& iter : const_input_index_to_node) { + int arg_index = iter.first; + VLOG(2) << "Replace usages of _Arg " << arg_index; + NodeDef const_def = iter.second->def(); + const_def.set_name(g->NewName(const_def.name())); + TF_ASSIGN_OR_RETURN(Node * const_node, g->AddNode(const_def)); + Node* arg_node = arg_nodes[arg_index]; + TF_RETURN_IF_ERROR( + ReplaceSrcOutputUsageWithNode(g, arg_node, 0, const_node)); + } + return absl::OkStatus(); +} + +// Replaces the single input to _Retval nodes with an index in the keys of +// const_input_index_to_node with the single output of the corresponding _Arg +// node. +absl::Status ReplaceRetvalInputWithArg( + Graph* g, + const absl::flat_hash_map& const_input_index_to_node) { + absl::flat_hash_map arg_nodes; + absl::flat_hash_map ret_nodes; + for (Node* n : g->op_nodes()) { + if (n->IsRetval() || n->IsArg()) { + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); + if (n->IsRetval()) { + ret_nodes[index] = n; + } else { + arg_nodes[index] = n; + } + } + } + + for (const auto& iter : const_input_index_to_node) { + int arg_index = iter.first; + VLOG(2) << "Bind _Retval " << arg_index << " to _Arg " << arg_index; + TF_RETURN_IF_ERROR( + ReplaceEdge(g, ret_nodes[arg_index], 0, arg_nodes[arg_index], 0) + .status()); + } + return absl::OkStatus(); +} + +// For a node's function attr (e.g. then/else branch for "If" nodes), rewrites +// the function to replace _Arg nodes in `const_input_index_to_node` with Const +// inputs. +absl::Status PropagateConstIntoFuncAttr( + Node* n, const std::string& attr_name, + const absl::flat_hash_map& const_input_index_to_node, + const FunctionLibraryDefinition* lookup_fld, FunctionLibraryDefinition* fld, + bool passthrough_arg_to_retval = false) { + VLOG(1) << "Propagate const into " << attr_name << " of node " << n->name(); + // Instantiate the function. + NameAttrList func_attr; + TF_RETURN_IF_ERROR(GetNodeAttr(n->def(), attr_name, &func_attr)); + const FunctionDef* fdef = lookup_fld->Find(func_attr.name()); + if (!fdef) { + return absl::InternalError(absl::StrCat( + "Cannot find function ", func_attr.name(), " for node ", n->name())); + } + std::unique_ptr fbody; + TF_RETURN_IF_ERROR(FunctionDefToBodyHelper( + *fdef, AttrSlice(&func_attr.attr()), lookup_fld, &fbody)); + + // Rewrite _Arg usages with Const node. + Graph* func_graph = fbody->graph; + TF_RETURN_IF_ERROR( + ReplaceArgUsageWithConstNode(func_graph, const_input_index_to_node)); + if (passthrough_arg_to_retval) { + TF_RETURN_IF_ERROR( + ReplaceRetvalInputWithArg(func_graph, const_input_index_to_node)); + } + + // Save rewritten function. + FunctionDef replace_fdef; + std::string new_func_name = + fld->UniqueFunctionName(absl::StrCat(func_attr.name(), "_const_")); + const StackTracesMap* stack_traces = + lookup_fld->GetStackTraces(func_attr.name()); + TF_RETURN_IF_ERROR( + GraphToFunctionDef(*func_graph, new_func_name, &replace_fdef)); + if (stack_traces != nullptr) { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(replace_fdef, *stack_traces)); + } else { + TF_RETURN_IF_ERROR(fld->AddFunctionDef(replace_fdef, {})); + } + + VLOG(1) << "replace func " << func_attr.name() << " with " << new_func_name; + // Change the node to use rewritten function. + func_attr.set_name(new_func_name); + n->ClearAttr(attr_name); + n->AddAttr(attr_name, func_attr); + + // Copy associated functions. + TF_RETURN_IF_ERROR(CopyAssociatedFunctions(func_graph, lookup_fld, fld)); + + return absl::OkStatus(); +} + +// For an "If" node in graph `g`, if it has Const node inputs, rewrite its +// then/else branch function to replace _Arg nodes with those Const inputs. +absl::Status PropagateConstIntoIfNode( + Graph* g, Node* if_node, const FunctionLibraryDefinition* lookup_fld, + FunctionLibraryDefinition* fld) { + // Notice that first input for If node is predicate; other inputs are function + // inputs. + absl::flat_hash_map const_input_index_to_node; + for (int i = 1; i < if_node->num_inputs(); i++) { + const Node* input_node; + TF_RETURN_IF_ERROR(if_node->input_node(i, &input_node)); + if (input_node->type_string() == "Const") { + const_input_index_to_node[i - 1] = input_node; + } + } + if (const_input_index_to_node.empty()) { + return absl::OkStatus(); + } + + // Rewrite "then_branch" and "else_branch" function, replace usage of those + // _Arg nodes with corresponding const node. + for (const auto& attr_name : + std::vector{"then_branch", "else_branch"}) { + TF_RETURN_IF_ERROR(PropagateConstIntoFuncAttr( + if_node, attr_name, const_input_index_to_node, lookup_fld, fld)); + } + + return absl::OkStatus(); +} + +using GraphCache = + absl::flat_hash_map>; + +absl::StatusOr FindOrInsert( + GraphCache* cache, const NameAttrList& body_attr, + const FunctionLibraryDefinition* lookup_fld, + const FunctionLibraryDefinition* fallback_fld) { + const std::string name = body_attr.name(); + std::unique_ptr& value = (*cache)[name]; + if (!value) { + const FunctionDef* body_func = lookup_fld->Find(name); + if (!body_func && fallback_fld != nullptr) { + body_func = fallback_fld->Find(name); + } + if (!body_func) { + return absl::InternalError( + absl::StrCat("Traverse: Cannot find body function ", name)); + } + std::unique_ptr fbody; + absl::Status s = FunctionDefToBodyHelper( + *body_func, AttrSlice(&body_attr.attr()), lookup_fld, &fbody); + if (!s.ok() && fallback_fld != nullptr) { + TF_RETURN_IF_ERROR(FunctionDefToBodyHelper( + *body_func, AttrSlice(&body_attr.attr()), fallback_fld, &fbody)); + } + value = std::move(fbody); + } + return value.get(); +} +// Determines whether a loop body is invariant for the given argument index. +absl::StatusOr IsLoopInvariant( + const FunctionBody* loop_body, int index, + const FunctionLibraryDefinition* lookup_fld, + const FunctionLibraryDefinition* fallback_fld, GraphCache* cache); + +// Traces backward through non-modifying ops such as Identity and loop-invariant +// While, to find a preceding source edge. +absl::StatusOr TraverseUnmodifiedPathBackward( + const Edge* src, const FunctionLibraryDefinition* lookup_fld, + const FunctionLibraryDefinition* fallback_fld, GraphCache* cache) { + const Edge* e = src; + VLOG(2) << "Traverse: Begin at " << e->DebugString(); + // TODO(b/184727356): Also traverse If/Case nodes. + // Begin walking back from the output node. + while (IsConstTraversableOpType(e->src())) { + VLOG(3) << e->DebugString(); + + if (e->src()->IsWhileNode()) { + NameAttrList body_attr; + TF_RETURN_IF_ERROR(GetNodeAttr(e->src()->def(), "body", &body_attr)); + TF_ASSIGN_OR_RETURN( + FunctionBody * fbody, + FindOrInsert(cache, body_attr, lookup_fld, fallback_fld)); + TF_ASSIGN_OR_RETURN(bool is_loop_invariant, + IsLoopInvariant(fbody, e->src_output(), lookup_fld, + fallback_fld, cache)); + if (!is_loop_invariant) { + VLOG(2) << "Non-loop-invariant: index " << e->src_output() << " of " + << body_attr.name(); + break; + } + } // if While|StatelessWhile + // Proceed backward to the src's input corresponding with the output index. + TF_RETURN_IF_ERROR(e->src()->input_edge(e->src_output(), &e)); + } + VLOG(2) << "Traverse: Finish at " << e->DebugString(); + + return e; +} + +// Determines whether a loop body is invariant for the given argument index. +absl::StatusOr IsLoopInvariant( + const FunctionBody* loop_body, int index, + const FunctionLibraryDefinition* lookup_fld, + const FunctionLibraryDefinition* fallback_fld, GraphCache* cache) { + const Edge* e; + TF_RETURN_IF_ERROR(loop_body->ret_nodes[index]->input_edge(0, &e)); + TF_ASSIGN_OR_RETURN( + const Edge* reachable, + TraverseUnmodifiedPathBackward(e, lookup_fld, fallback_fld, cache)); + if (reachable->src()->id() == loop_body->arg_nodes[index]->id()) { + VLOG(2) << "Index " << index << " is loop invariant."; + return true; + } + VLOG(2) << "Index " << index << " not loop invariant: " + << "walk backward from " << e->src()->DebugString() << " to " + << reachable->src()->DebugString() << " did not reach " + << loop_body->arg_nodes[index]->DebugString(); + return false; +} + +// For a "While" node in graph `g`, if it has Const node inputs, rewrite its +// cond/body function to replace _Arg nodes with those Const inputs. Then, +// propagate these Const to consumers of the relevant outputs of the while loop. +absl::Status PropagateConstIntoAndAroundWhileNode( + Graph* g, Node* while_node, const FunctionLibraryDefinition* lookup_fld, + FunctionLibraryDefinition* fld) { + VLOG(1) << "Propagate const into " << while_node->name(); + + // For "While" node, we should only replace _Arg nodes which are loop + // invariants. For such _Arg nodes, the return value's input will come + // directly from the corresponding arg. + absl::flat_hash_map const_input_index_to_node; + absl::flat_hash_map const_input_index_to_mutable_node; + NameAttrList body_attr; + TF_RETURN_IF_ERROR(GetNodeAttr(while_node->def(), "body", &body_attr)); + const std::string fn_name = body_attr.name(); + const FunctionDef* body_func = lookup_fld->Find(fn_name); + if (!body_func) { + return absl::InternalError( + absl::StrCat("Propagate: Cannot find body function ", fn_name, + " for While node ", while_node->name())); + } + std::unique_ptr fbody; + TF_RETURN_IF_ERROR(FunctionDefToBodyHelper( + *body_func, AttrSlice(&body_attr.attr()), lookup_fld, &fbody)); + GraphCache cache; + for (int i = 0; i < while_node->num_inputs(); i++) { + // Check if i-th retval's input comes from i-th arg directly. + // For resource variable input of While nodes, TF2XLA convention is to place + // them at the end of all inputs (after all data inputs), and *not* return + // them. So number of While node inputs might be larger than number of its + // outputs. + if (i >= body_func->signature().output_arg_size()) { + break; + } + + const Edge* input_edge; + TF_RETURN_IF_ERROR(while_node->input_edge(i, &input_edge)); + TF_ASSIGN_OR_RETURN(input_edge, TraverseUnmodifiedPathBackward( + input_edge, lookup_fld, fld, &cache)); + if (!input_edge->src()->IsConstant()) { + VLOG(2) << "Input " << i << " is not Const; is " + << input_edge->src()->type_string(); + continue; + } + + TF_ASSIGN_OR_RETURN( + bool is_loop_invariant, + IsLoopInvariant(fbody.get(), i, lookup_fld, fld, &cache)); + if (!is_loop_invariant) { + VLOG(2) << "While state not loop-invariant; not propagating Const " << i; + continue; + } + VLOG(2) << "While state is loop-invariant; propagating Const " << i; + + const_input_index_to_mutable_node[i] = input_edge->src(); + const_input_index_to_node[i] = input_edge->src(); + } + if (const_input_index_to_node.empty()) { + return absl::OkStatus(); + } + + // Rewrite "cond" and "body" function, replace usage of those _Arg nodes with + // corresponding const node. + for (const auto& attr_name : std::vector{"cond", "body"}) { + TF_RETURN_IF_ERROR(PropagateConstIntoFuncAttr( + while_node, attr_name, const_input_index_to_node, lookup_fld, fld, + /*passthrough_arg_to_retval=*/attr_name == "body")); + } + + // Rewrite usages of the output edges corresponding to loop-invariant const + // inputs to refer instead to the Const node. + for (const auto& it : const_input_index_to_mutable_node) { + TF_RETURN_IF_ERROR( + ReplaceSrcOutputUsageWithNode(g, while_node, it.first, it.second)); + } + return absl::OkStatus(); +} + +} // namespace + +absl::StatusOr IsLoopInvariant( + const FunctionBody* loop_body, int index, + const FunctionLibraryDefinition* lookup_fld) { + GraphCache cache; + return IsLoopInvariant(loop_body, index, lookup_fld, + /*fallback_fld=*/nullptr, &cache); +} + +absl::Status ValidateConfig(const tf2xla::Config& config) { + std::set names; + for (const tf2xla::Feed& feed : config.feed()) { + TF_RETURN_IF_ERROR(ValidateTensorId(feed.id())); + TF_RETURN_IF_ERROR(TensorShape::IsValidShape(feed.shape())); + TF_RETURN_IF_ERROR(CheckNameDuplicates("feed", feed.name(), &names)); + } + TF_RETURN_IF_ERROR(CheckFeedFetchNameConflicts("feed", names)); + names.clear(); + for (const tf2xla::Fetch& fetch : config.fetch()) { + TF_RETURN_IF_ERROR(ValidateTensorId(fetch.id())); + TF_RETURN_IF_ERROR(CheckNameDuplicates("fetch", fetch.name(), &names)); + } + TF_RETURN_IF_ERROR(CheckFeedFetchNameConflicts("fetch", names)); + if (config.fetch().empty()) { + return absl::InvalidArgumentError("fetches must be specified"); + } + return absl::OkStatus(); +} + +absl::Status AddPlaceholdersForFeeds( + const tf2xla::Config& config, const OpRegistryInterface* op_registry, + std::unordered_map* feed_remapping, + GraphDef* graph_def) { + struct PlaceholderInfo { + const tf2xla::Feed* feed = nullptr; // point to Feed in . + std::string placeholder_name; + DataType data_type = DT_INVALID; + }; + + // Put each fed tensor into a map by name:port. A map is used for determinism + // when creating placeholders (genrules want deterministic output). + std::map placeholder_info; + for (int i = 0; i < config.feed_size(); ++i) { + const tf2xla::Feed* feed = &config.feed(i); + const std::string name_port = TensorIdToString(feed->id()); + PlaceholderInfo& info = placeholder_info[name_port]; + info.feed = feed; + info.placeholder_name = absl::StrCat("aot_feed_", feed->id().output_index(), + "/", feed->id().node_name()); + (*feed_remapping)[name_port] = info.placeholder_name; + } + + // Verify node exists and determine data type. + std::unordered_map name_to_node; + for (int i = 0; i < graph_def->node_size(); ++i) { + name_to_node[graph_def->node(i).name()] = &graph_def->node(i); + } + for (auto it = placeholder_info.begin(); it != placeholder_info.end(); ++it) { + PlaceholderInfo& info = it->second; + const tf2xla::TensorId& feed_id = info.feed->id(); + + // Find the existing node and determine data type. + auto node_it = name_to_node.find(feed_id.node_name()); + if (node_it == name_to_node.end()) { + return absl::NotFoundError( + absl::StrCat("Can't find feed node: ", TensorIdToString(feed_id))); + } + const NodeDef* existing = node_it->second; + + if (info.feed->type() != DT_INVALID) { + info.data_type = info.feed->type(); + } else { + // Build the node in order to infer its type. + + // Must first add default attrs as well, so do this in a copied GraphDef. + GraphDef gd; + *gd.mutable_versions() = graph_def->versions(); + *gd.add_node() = *existing; + MergeDebugInfo(NodeDebugInfo(*existing), gd.mutable_node(0)); + TF_RETURN_IF_ERROR( + AddDefaultAttrsToGraphDef(&gd, *op_registry, 0 /*node_offset*/)); + + // Now build the node from the copied node def. + Graph g(op_registry); + g.set_versions(graph_def->versions()); + TF_ASSIGN_OR_RETURN(Node * feed_node, g.AddNode(gd.node(0))); + + if (info.feed->id().output_index() < feed_node->num_outputs()) { + info.data_type = + BaseType(feed_node->output_type(info.feed->id().output_index())); + } else { + return absl::InvalidArgumentError(absl::StrCat( + "Invalid output_index ", info.feed->id().output_index(), + " for feed node ", info.feed->id().node_name())); + } + } + } + + // Create placeholders. Note that we could avoid creating a placeholder for + // feeds which are already placeholders, but we omit that to avoid more cases + // in this code. + for (auto it = placeholder_info.begin(); it != placeholder_info.end(); ++it) { + const PlaceholderInfo& info = it->second; + // TODO(shikharagarwal): Add original node information. + NodeDef* d = graph_def->add_node(); + d->set_name(info.placeholder_name); + d->set_op("Placeholder"); + auto& attr_map = *d->mutable_attr(); + attr_map["dtype"].set_type(info.data_type); + *attr_map["shape"].mutable_shape() = info.feed->shape(); + } + + // Rewrite references to the fed tensors to refer to the placeholder. + for (int i = 0; i < graph_def->node_size(); ++i) { + NodeDef* node_def = graph_def->mutable_node(i); + for (int j = 0; j < node_def->input_size(); ++j) { + auto id = ParseTensorName(node_def->input(j)); + auto it = placeholder_info.find(id.ToString()); + if (it != placeholder_info.end()) { + node_def->set_input(j, it->second.placeholder_name); + } + } + } + + return absl::OkStatus(); +} + +absl::Status PruneGraphDefInto(const tf2xla::Config& config, const GraphDef& in, + GraphDef* out) { + *out = in; + out->clear_node(); + + // Tensors needed for feeding. + std::set> feed_tensors; + for (const tf2xla::Feed& feed : config.feed()) { + feed_tensors.insert( + std::make_pair(feed.id().node_name(), feed.id().output_index())); + } + + // Maps node name to reachability. + std::unordered_map> node_by_name; + for (const NodeDef& node : in.node()) { + node_by_name[node.name()] = std::pair(false, &node); + } + + // Traverse. + std::queue name_queue; + for (int i = 0; i < config.fetch_size(); ++i) { + name_queue.push(config.fetch(i).id().node_name()); + } + while (!name_queue.empty()) { + const std::string name = name_queue.front(); + name_queue.pop(); + + auto find_it = node_by_name.find(name); + if (find_it == node_by_name.end()) { + return absl::InvalidArgumentError( + absl::StrCat("While pruning graph, node ", name, + " needed but not found in the graph.")); + } + auto& map_entry = find_it->second; + if (map_entry.first) { + continue; + } + map_entry.first = true; + + // Push input nodes of the currently visited node to name_queue. + for (const std::string& in_edge : map_entry.second->input()) { + auto id = ParseTensorName(in_edge); + const std::string node_name = std::string(id.first); + if (feed_tensors.find(std::make_pair(node_name, id.second)) == + feed_tensors.end()) { + name_queue.push(node_name); + } else { + // The input tensor is from an edge that is being fed. Therefore, + // we skip recursing down that edge, to avoid requiring nodes that + // may not be needed (note that the input node may still be added + // to name_queue later if one of its output edges is not being fed). + } + } + } + + // Copy over, preserving order of original and only nodes that are reachable + // from the fetches. + out->mutable_node()->Reserve(in.node_size()); + for (const NodeDef& node : in.node()) { + if (node_by_name[node.name()].first) { + *out->add_node() = node; + } + } + return absl::OkStatus(); +} + +std::string TensorIdToString(const tf2xla::TensorId& id) { + return absl::StrCat(id.node_name(), ":", id.output_index()); +} + +absl::Status SetNodeShardingFromNeighbors(Node* n, bool out_edges) { + int core = -1; + const Node* matching_node = nullptr; + for (const Edge* edge : (out_edges ? n->out_edges() : n->in_edges())) { + if (edge->IsControlEdge()) continue; + const Node* possible_match = out_edges ? edge->dst() : edge->src(); + TF_ASSIGN_OR_RETURN( + std::optional sharding, + ParseShardingFromDevice( + *possible_match, + /*num_cores_per_replica=*/std::numeric_limits::max(), + /*add_metadata=*/false)); + if (sharding && sharding->type() == xla::OpSharding::MAXIMAL) { + const int core_annotation = sharding.value().tile_assignment_devices(0); + if (core == -1 || core > core_annotation) { + core = core_annotation; + matching_node = possible_match; + } + } + } + if (matching_node != nullptr) { + n->set_assigned_device_name(matching_node->assigned_device_name()); + n->set_requested_device(matching_node->requested_device()); + } + return absl::OkStatus(); +} + +void AddDtypeToKernelDefConstraint(absl::string_view name, DataType dtype, + KernelDef* kdef) { + for (KernelDef::AttrConstraint& constraint : *kdef->mutable_constraint()) { + if (constraint.name() == name) { + constraint.mutable_allowed_values()->mutable_list()->add_type(dtype); + } + } +} + +namespace { +uint32_t 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_t 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 counter(InitialRandomSeed()); + uint32_t seed = counter.fetch_add(2); + std::srand(seed); + return std::rand() | 1; +} + +// TODO(b/77601805): add tests for associated function related stuff. +bool HasAssociatedFunction(const NodeDef& node_def, + const FunctionLibraryDefinition* fld) { + if (fld->Contains(node_def.op())) { + return true; + } + + if (node_def.op() == FunctionLibraryDefinition::kGradientOp) { + // Gradient op has "f" attr, which is set to the function we are getting + // gradient for. We need to functionalize the gradient function. + return true; + } + + if (node_def.op() == "XlaHostCompute") { + // XlaHostCompute has "shape_inference_graph" func attr, but that's not + // related to graph execution. + return false; + } + + for (const auto& iter : node_def.attr()) { + if (iter.second.has_func()) { + return true; + } + } + + return false; +} + +std::vector GetAssociatedFunctions( + const Node& node, const FunctionLibraryDefinition* fld) { + std::vector results; + const std::string& op = node.type_string(); + if (fld->Contains(op)) { + // This is a function call node. + AttrValueMap attrs(node.attrs().begin(), node.attrs().end()); + results.emplace_back(AssociatedFunctionInfo::FunctionCall(op, attrs)); + } else if (node.type_string() == FunctionLibraryDefinition::kGradientOp) { + // This is a SymbolicGradient op. + AttrValueMap attrs(node.attrs().begin(), node.attrs().end()); + results.emplace_back(AssociatedFunctionInfo::SymbolicGradient(op, attrs)); + } else if (node.type_string() == "XlaHostCompute") { + // XlaHostCompute has "shape_inference_graph" func attr, but that's not + // related to graph execution. + } else { + // Collect all function attrs for the node. + for (auto& iter : node.attrs()) { + if (iter.second.has_func()) { + VLOG(2) << "Found function attr for node " << node.name() << ": " + << iter.first << " = " << iter.second.func().name(); + results.emplace_back(AssociatedFunctionInfo::FunctionAttr( + iter.second.func().name(), iter.second.func().attr(), iter.first)); + } + } + } + return results; +} + +absl::Status RewriteAssociatedFunction( + Graph* graph, Node* node, FunctionLibraryDefinition* fld, + const AssociatedFunctionInfo& associated_function, + const std::string& rewritten_function_name) { + switch (associated_function.type()) { + case AssociatedFunctionInfo::kFunctionCallNode: { + // Change this node to call the new function. + NodeDebugInfo debug_info(*node); + NodeDefBuilder builder(node->name(), rewritten_function_name, fld, + &debug_info); + for (const auto& attr : node->attrs()) { + builder.Attr(attr.first, attr.second); + } + for (int i = 0; i < node->num_inputs(); i++) { + Node* input_node; + TF_RETURN_IF_ERROR(node->input_node(i, &input_node)); + builder.Input(input_node->name(), i, node->input_type(i)); + } + builder.Device(node->assigned_device_name().empty() + ? node->requested_device() + : node->assigned_device_name()); + NodeDef node_def; + TF_RETURN_IF_ERROR(builder.Finalize(&node_def)); + TF_ASSIGN_OR_RETURN(Node * new_node, graph->AddNode(node_def)); + for (auto edge : node->in_edges()) { + graph->AddEdge(edge->src(), edge->src_output(), new_node, + edge->dst_input()); + } + for (auto edge : node->out_edges()) { + graph->AddEdge(new_node, edge->src_output(), edge->dst(), + edge->dst_input()); + } + graph->RemoveNode(node); + break; + } + case AssociatedFunctionInfo::kSymbolicGradient: { + NameAttrList func; + TF_RETURN_IF_ERROR(GetNodeAttr( + node->attrs(), FunctionLibraryDefinition::kFuncAttr, &func)); + GradientDef gradient_def; + gradient_def.set_function_name(func.name()); + gradient_def.set_gradient_func(rewritten_function_name); + std::string original_grad_func = fld->FindGradient(func.name()); + if (original_grad_func.empty()) { + TF_RETURN_IF_ERROR(fld->AddGradientDef(gradient_def)); + } else if (original_grad_func != rewritten_function_name) { + TF_RETURN_IF_ERROR(fld->ReplaceGradient(gradient_def)); + } + break; + } + case AssociatedFunctionInfo::kFunctionAttr: { + // Change function attr to rewritten functions. + NameAttrList func; + TF_RETURN_IF_ERROR( + GetNodeAttr(node->attrs(), associated_function.attr_name(), &func)); + // Save the original function name in case TFRT fallbacks to use + // TPUPartitionedCall op in the runtime. + if (node->type_string() == "TPUPartitionedCall") { + node->AddAttr("_orig_f", func.name()); + } + node->ClearAttr(associated_function.attr_name()); + func.set_name(rewritten_function_name); + node->AddAttr(associated_function.attr_name(), func); + break; + } + } + + return absl::OkStatus(); +} + +absl::Status CachedFunctionHandles::GetOrInstantiate( + const std::string& func_name, AttrSlice attrs, + FunctionLibraryRuntime::Handle* handle) { + std::string canonicalized_name = Canonicalize(func_name, attrs); + auto iter = handles_.find(canonicalized_name); + if (iter != handles_.end()) { + *handle = iter->second; + return absl::OkStatus(); + } + + TF_RETURN_IF_ERROR(flr_->Instantiate(func_name, attrs, handle)); + handles_[canonicalized_name] = *handle; + return absl::OkStatus(); +} + +absl::Status CachedFunctionHandles::ReleaseAllHandles() { + absl::Status result; + for (const auto& iter : handles_) { + result.Update(flr_->ReleaseHandle(iter.second)); + } + handles_.clear(); + return result; +} + +absl::StatusOr ReplaceNode(Graph* g, Node* n, const NodeDef& node_def) { + // Create the replacement node. + TF_ASSIGN_OR_RETURN(Node * new_node, g->AddNode(node_def)); + + // Record original node's output edges and remove them first. This is to avoid + // multiple producers for dst nodes' input. + std::vector out_edge_info; + std::vector out_edges; + for (const Edge* edge : n->out_edges()) { + out_edges.push_back(edge); + out_edge_info.push_back( + {edge->dst(), edge->src_output(), edge->dst_input()}); + } + for (const Edge* edge : out_edges) { + g->RemoveEdge(edge); + } + + // Add original node's input and output edges to the replacement node. + for (const Edge* in_edge : n->in_edges()) { + g->AddEdge(in_edge->src(), in_edge->src_output(), new_node, + in_edge->dst_input()); + } + for (const OutEdgeInfo& out_edge : out_edge_info) { + g->AddEdge(new_node, out_edge.src_output, out_edge.dst, out_edge.dst_input); + } + + // Remove the original node. + g->RemoveNode(n); + + return new_node; +} + +absl::StatusOr BuildIdentityNode( + Graph* graph, const std::string& node_name, DataType dtype, + const Node* input, std::optional requested_device) { + // Create identity node. + NodeDef ndef; + ndef.set_name(node_name); + ndef.set_op("Identity"); + if (input) { + ndef.add_input(input->name()); + } + if (requested_device) { + ndef.set_device(*requested_device); + } + AddNodeAttr("T", dtype, &ndef); + TF_ASSIGN_OR_RETURN(Node * id_node, graph->AddNode(ndef)); + return id_node; +} + +absl::Status PropagateConstIntoFunctionalNodes( + Graph* g, const FunctionLibraryDefinition* lookup_fld, + FunctionLibraryDefinition* fld) { + absl::flat_hash_set done_node_ids; + + // Because we may propagate Const around a while node as well as into it, + // we restart the op_nodes() iterator after each pass and keep track of which + // nodes we've already dealt with. + bool should_continue = true; + while (should_continue) { + should_continue = false; + for (Node* n : g->op_nodes()) { + if (!done_node_ids.contains(n->id())) { + if (n->IsIfNode()) { + VLOG(1) << "PropagateConstIntoIfNode: " << n->name(); + TF_RETURN_IF_ERROR(PropagateConstIntoIfNode(g, n, lookup_fld, fld)); + done_node_ids.emplace(n->id()); + VLOG(1) << "Done PropagateConstIntoIfNode: " << n->name(); + } else if (n->IsWhileNode()) { + VLOG(1) << "PropagateConstIntoWhileNode: " << n->name(); + TF_RETURN_IF_ERROR( + PropagateConstIntoAndAroundWhileNode(g, n, lookup_fld, fld)); + done_node_ids.emplace(n->id()); + should_continue = true; + VLOG(1) << "Done PropagateConstIntoWhileNode: " << n->name(); + break; + } + } + } + } + return absl::OkStatus(); +} + +absl::Status PruneUnreachableFunctionsFromGraph( + const Graph& g, FunctionLibraryDefinition* fld) { + GraphDef graph_def; + g.ToGraphDef(&graph_def); + FunctionLibraryDefinition reachable_functions = + fld->ReachableDefinitions(graph_def); + for (const std::string& func_name : fld->ListFunctionNames()) { + if (!reachable_functions.Find(func_name)) { + TF_RETURN_IF_ERROR(fld->RemoveFunction(func_name)); + } + } + return absl::OkStatus(); +} + +absl::Status RewriteTensorListWithConstElement(Graph* g, + FunctionLibraryDefinition* fld) { + for (Node* n : g->nodes()) { + if (n->type_string() != "EmptyTensorList") { + continue; + } + + // Find the forward While op. + std::vector fwd_while_edges; + for (const Edge* e : n->out_edges()) { + if (!e->IsControlEdge() && e->dst()->IsWhileNode()) { + fwd_while_edges.push_back(e); + } + } + if (fwd_while_edges.size() != 1) { + // No forward While op found, or multiple forward While ops. + continue; + } + + // Find the backward While op. + Node* fwd_while = fwd_while_edges[0]->dst(); + int fwd_while_dst_input = fwd_while_edges[0]->dst_input(); + std::vector bwd_while_edges; + for (const Edge* e : fwd_while->out_edges()) { + if (e->src_output() == fwd_while_dst_input && e->dst()->IsWhileNode()) { + bwd_while_edges.push_back(e); + } + } + if (bwd_while_edges.size() != 1) { + // No backward While op found, or multiple backward While ops. + continue; + } + + Node* bwd_while = bwd_while_edges[0]->dst(); + int bwd_while_dst_input = bwd_while_edges[0]->dst_input(); + + // Look into forward While body function and check if TensorListPushBack op + // has a Const input. + NameAttrList fwd_body_attr; + CHECK_OK(GetNodeAttr(fwd_while->def(), "body", &fwd_body_attr)); + const FunctionDef* fwd_body = fld->Find(fwd_body_attr.name()); + if (!fwd_body) { + return absl::InvalidArgumentError( + absl::StrCat("Cannot find function ", fwd_body_attr.name(), + " for While node ", fwd_while->DebugString())); + } + std::unique_ptr fwd_fbody; + CHECK_OK(FunctionDefToBodyHelper( + *fwd_body, AttrSlice(&fwd_body_attr.attr()), fld, &fwd_fbody)); + + // Find the TensorListPushBack node; it's one of fwd_arg's successors. + Node* fwd_arg = fwd_fbody->arg_nodes[fwd_while_dst_input]; + std::vector tl_push_nodes; + for (const Edge* out_edge : fwd_arg->out_edges()) { + if (out_edge->dst()->type_string() == "TensorListPushBack") { + tl_push_nodes.push_back(out_edge->dst()); + } + } + if (tl_push_nodes.size() != 1) { + // No TensorListPushBack found, or multiple TensorListPushBack. + continue; + } + + // Get input for the TensorListPushBack node. + Node* input_node; + CHECK_OK(tl_push_nodes[0]->input_node(1, &input_node)); + if (input_node->type_string() != "Const") { + // Input for the TensorList is not Const node. + continue; + } + + NodeDef const_input_nodedef = input_node->def(); + + // Rewrite backward While body function, replace usages of + // TensorListPopBack with a Const node. + NameAttrList bwd_body_attr; + CHECK_OK(GetNodeAttr(bwd_while->def(), "body", &bwd_body_attr)); + const FunctionDef* bwd_body = fld->Find(bwd_body_attr.name()); + if (!bwd_body) { + return absl::InvalidArgumentError( + absl::StrCat("Cannot find function ", bwd_body_attr.name(), + " for While node ", bwd_while->DebugString())); + } + std::unique_ptr bwd_fbody; + CHECK_OK(FunctionDefToBodyHelper( + *bwd_body, AttrSlice(&bwd_body_attr.attr()), fld, &bwd_fbody)); + + // Find the TensorListPopBack node; it's one of bwd_arg's successors. + Node* bwd_arg = bwd_fbody->arg_nodes[bwd_while_dst_input]; + std::vector tl_pop_nodes; + for (const Edge* out_edge : bwd_arg->out_edges()) { + if (out_edge->dst()->type_string() == "TensorListPopBack") { + tl_pop_nodes.push_back(out_edge->dst()); + } + } + if (tl_pop_nodes.size() != 1) { + // No TensorListPopBack found, or multiple TensorListPopBack. + continue; + } + + // Replace TensorListPopBack usages with Const node. + std::vector edges_to_replace; + for (const Edge* e : tl_pop_nodes[0]->out_edges()) { + if (e->src_output() == 1) { + edges_to_replace.push_back(e); + } + } + if (edges_to_replace.empty()) { + continue; + } + const_input_nodedef.set_name( + bwd_fbody->graph->NewName(const_input_nodedef.name())); + TF_ASSIGN_OR_RETURN(Node * const_node, + bwd_fbody->graph->AddNode(const_input_nodedef)); + for (const Edge* e : edges_to_replace) { + Node* dst = e->dst(); + int dst_input = e->dst_input(); + bwd_fbody->graph->RemoveEdge(e); + bwd_fbody->graph->AddEdge(const_node, 0, dst, dst_input); + } + + // Add rewritten backward While body function. + FunctionDef new_fdef; + std::string new_name = fld->UniqueFunctionName( + absl::StrCat(bwd_body_attr.name(), "_tl_rewrite_")); + TF_RETURN_IF_ERROR( + GraphToFunctionDef(*bwd_fbody->graph, new_name, &new_fdef)); + TF_RETURN_IF_ERROR(fld->AddFunctionDef(new_fdef)); + + // Change backward While op to use the new body function. + bwd_body_attr.set_name(new_name); + bwd_while->ClearAttr("body"); + bwd_while->AddAttr("body", bwd_body_attr); + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util.h new file mode 100644 index 0000000000000000000000000000000000000000..715035b9c133c301fea83adb3dbeb52d802fcdcb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util.h @@ -0,0 +1,229 @@ +/* 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_TF2XLA_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TF2XLA_UTIL_H_ + +#include + +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/tf2xla_defs.h" +#include "xla/status_macros.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/kernel_def.pb.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/lib/core/status.h" + +namespace tensorflow { + +// ValidateConfig returns OK iff config is valid. +absl::Status ValidateConfig(const tf2xla::Config& config); + +// Modifies to include placeholders for each fed tensor, and +// update references to the fed tensors to refer to the placeholders. +// The existing nodes referenced by the feeds are not removed or modified +// (except where their input edges are modified by the replacement of other +// feeds). +absl::Status AddPlaceholdersForFeeds( + const tf2xla::Config& config, const OpRegistryInterface* op_registry, + std::unordered_map* feed_remapping, + GraphDef* graph_def); + +// Returns in a copy of , pruned to only include fetches from +// . +absl::Status PruneGraphDefInto(const tf2xla::Config& config, const GraphDef& in, + GraphDef* out); + +// Returns node:port for the given . +std::string TensorIdToString(const tf2xla::TensorId& id); + +// Updates the sharding of based on the sharding of its neighbors. +// If is true, outgoing edges from are considered; else incoming +// edges are considered. +absl::Status SetNodeShardingFromNeighbors(Node* n, bool out_edges); + +// Add an allowed data type to the AttrConstraint with the given name. +void AddDtypeToKernelDefConstraint(absl::string_view name, DataType dtype, + KernelDef* kdef); + +// Returns the next random seed to use for seeding xla rng. +uint32_t GetXLARandomSeed(); + +// Indicates how a FunctionDef is associated with a graph node (e.g. the node is +// a function call, or the node has function attrs). +class AssociatedFunctionInfo { + public: + enum AssociatedFunctionType { + kFunctionAttr = 0, + kFunctionCallNode = 1, + kSymbolicGradient = 2, + }; + + // The function is an attr of the node. + static AssociatedFunctionInfo FunctionAttr(const std::string& func_name, + const AttrValueMap& attrs, + const std::string& attr_name) { + return AssociatedFunctionInfo(kFunctionAttr, func_name, attrs, attr_name); + } + + // The node is a function call. + static AssociatedFunctionInfo FunctionCall(const std::string& func_name, + const AttrValueMap& attrs) { + // attr_name will not be used in this case. + return AssociatedFunctionInfo(kFunctionCallNode, func_name, attrs, + /*attr_name=*/""); + } + + // The node is a SymbolicGradient op. + static AssociatedFunctionInfo SymbolicGradient(const std::string& func_name, + const AttrValueMap& attrs) { + // attr_name will not be used in this case. + return AssociatedFunctionInfo(kSymbolicGradient, func_name, attrs, + /*attr_name=*/""); + } + + AssociatedFunctionType type() const { return type_; } + + const std::string& func_name() const { return func_name_; } + + const std::string& attr_name() const { return attr_name_; } + + const AttrValueMap& attrs() const { return attrs_; } + + private: + AssociatedFunctionInfo(AssociatedFunctionType type, + const std::string& func_name, + const AttrValueMap& attrs, + const std::string& attr_name) + : type_(type), + func_name_(func_name), + attrs_(attrs), + attr_name_(attr_name) {} + + // Available for all instances. + AssociatedFunctionType type_; + std::string func_name_; + AttrValueMap attrs_; + + // Only available if the function is defined in an attr. + std::string attr_name_; +}; + +// Returns if the NodeDef has associated function. +bool HasAssociatedFunction(const NodeDef& node_def, + const FunctionLibraryDefinition* fld); + +// Gets functions associated with the node. Current cases: +// 1. For function call node, its function name; +// 2. For SymbolicGradient op, returned func_name will be "SymbolicGradient", +// and returned attrs will be this node's attributes; +// 3. For nodes like XlaWhile/XlaIf, all their function attributes. +std::vector GetAssociatedFunctions( + const Node& node, const FunctionLibraryDefinition* fld); + +// Changes associated functions for the node. Current cases: +// 1. For function call node, creates a new node with the new function name and +// remove the old node; +// 2. For SymbolicGradient op, add or replace GradientDef in +// FunctionLibraryDefinition; +// 3. For nodes like XlaWhile/XlaIf, modify their function attributes. +absl::Status RewriteAssociatedFunction( + Graph* graph, Node* node, FunctionLibraryDefinition* fld, + const AssociatedFunctionInfo& associated_function, + const std::string& rewritten_function_name); + +// Class to act as cache for FunctionLibraryRuntime::Handle objects. +class CachedFunctionHandles { + public: + CachedFunctionHandles(FunctionLibraryRuntime* flr) : flr_(flr) {} + + // Populates `handle` for requested function and attributes. If we have + // instantiated the function with the same attributes before, `handle` will be + // cached handle; otherwise instantiate the function and populate `handle`. + absl::Status GetOrInstantiate(const std::string& func_name, AttrSlice attrs, + FunctionLibraryRuntime::Handle* handle); + + // Releases all handles in the cache. Returns first non-OK status if any; + // returns OK otherwise. + absl::Status ReleaseAllHandles(); + + ~CachedFunctionHandles() { ReleaseAllHandles().IgnoreError(); } + + private: + FunctionLibraryRuntime* flr_; + std::map handles_; + + CachedFunctionHandles(const CachedFunctionHandles&) = delete; + void operator=(const CachedFunctionHandles&) = delete; +}; + +// Struct for node's output edge info. +struct OutEdgeInfo { + Node* dst; + int src_output, dst_input; +}; + +// Replaces node `n` with a new node whose NodeDef is `node_def`. +absl::StatusOr ReplaceNode(Graph* g, Node* n, const NodeDef& node_def); + +// Helper function that builds an Identity node. +absl::StatusOr BuildIdentityNode( + Graph* graph, const std::string& node_name, DataType dtype, + const Node* input, std::optional requested_device); + +// For "If"/"While" nodes, if some of their inputs are Const nodes, rewrite +// body functions to use the Const nodes instead of original _Arg nodes. +// +// For example, say we have the following computation: +// shape = constant_op.constant([1]) +// return tf.cond(pred, lambda: tf.ones(shape), lambda: tf.zeros(shape)) +// If we do not rewrite then/else function, they will use _Arg node as shape +// input for tf.ones/tf.zeros. But XLA requires that shape input to be compile +// time constant, so XLA compilation will fail. This rewriting process will +// change the shape input to Const node. +absl::Status PropagateConstIntoFunctionalNodes( + Graph* g, const FunctionLibraryDefinition* lookup_fld, + FunctionLibraryDefinition* fld); + +// Prunes unreachable FunctionDefs from FunctionLibraryDefinition. +absl::Status PruneUnreachableFunctionsFromGraph(const Graph& g, + FunctionLibraryDefinition* fld); + +// Finds the following pattern in the graph: +// 1) EmptyTensorList -> forward While op -> backward While op, +// 2) in forward While op, a Const node is pushed, +// 3) in backward While op, data is popped from the tensor list. +// And rewrites backward While op to use Const node instead of TensorListPopBack +// result. +// TODO(b/128633174) remove the TensorList and related TensorList ops. +absl::Status RewriteTensorListWithConstElement(Graph* g, + FunctionLibraryDefinition* fld); + +inline bool IsConstTraversableOpType(const Node* node) { + return node->type_string() == "Identity" || + node->type_string() == "IdentityN" || node->IsWhileNode(); +} + +// Determines whether a loop body is invariant for the given argument index. +absl::StatusOr IsLoopInvariant( + const FunctionBody* loop_body, int index, + const FunctionLibraryDefinition* lookup_fld); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_TF2XLA_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..29a81c47872a2abdd1cf572cb0a8ed9a260c636e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/tf2xla_util_test.cc @@ -0,0 +1,519 @@ +/* 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/tf2xla_util.h" + +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/array_ops.h" +#include "tensorflow/cc/ops/const_op.h" +#include "tensorflow/cc/ops/function_ops.h" +#include "tensorflow/cc/ops/functional_ops.h" +#include "tensorflow/cc/ops/list_ops.h" +#include "tensorflow/cc/ops/math_ops.h" +#include "tensorflow/cc/ops/no_op.h" +#include "tensorflow/compiler/tf2xla/sharding_util.h" +#include "xla/tsl/lib/core/status_test_util.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/function_def_utils.h" +#include "tensorflow/core/common_runtime/process_function_library_runtime.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { +namespace { + +void ExpectErrorContains(const absl::Status& status, absl::string_view str) { + EXPECT_NE(absl::OkStatus(), status); + EXPECT_TRUE(absl::StrContains(status.message(), str)) + << "expected error: " << status.message() << " to contain: " << str; +} + +TEST(ValidateConfig, Good) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + feed->mutable_id()->set_output_index(123); + feed->set_name("foo_debug"); + feed = config.add_feed(); + feed->mutable_id()->set_node_name("bar"); + feed->mutable_id()->set_output_index(0); + tf2xla::Fetch* fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("baz"); + fetch->mutable_id()->set_output_index(456); + fetch->set_name("baz_debug"); + fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("banana"); + fetch->mutable_id()->set_output_index(0); + TF_EXPECT_OK(ValidateConfig(config)); +} + +TEST(ValidateConfig, BadEmpty) { + tf2xla::Config config; + ExpectErrorContains(ValidateConfig(config), "fetches must be specified"); +} + +TEST(ValidateConfig, BadNoFetch) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + ExpectErrorContains(ValidateConfig(config), "fetches must be specified"); +} + +TEST(ValidateConfig, BadFeedNodeName) { + tf2xla::Config config; + config.add_feed(); + ExpectErrorContains(ValidateConfig(config), "node_name must be non-empty"); +} + +TEST(ValidateConfig, BadFeedOutputIndex) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + feed->mutable_id()->set_output_index(-1); + ExpectErrorContains(ValidateConfig(config), "output_index must be positive"); +} + +TEST(ValidateConfig, BadFetchNodeName) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + config.add_fetch(); + ExpectErrorContains(ValidateConfig(config), "node_name must be non-empty"); +} + +TEST(ValidateConfig, BadFetchOutputIndex) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + tf2xla::Fetch* fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("bar"); + fetch->mutable_id()->set_output_index(-1); + ExpectErrorContains(ValidateConfig(config), "output_index must be positive"); +} + +TEST(ValidateConfig, DuplicateFeedName) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + feed->set_name("dup"); + feed = config.add_feed(); + feed->mutable_id()->set_node_name("bar"); + feed->set_name("dup"); + ExpectErrorContains(ValidateConfig(config), "duplicate feed name"); +} + +TEST(ValidateConfig, DuplicateFetchName) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + tf2xla::Fetch* fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("bar"); + fetch->set_name("dup"); + fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("baz"); + fetch->set_name("dup"); + ExpectErrorContains(ValidateConfig(config), "duplicate fetch name"); +} + +TEST(ValidateConfig, ConflictingFeedName) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + feed->set_name("conflict"); + feed = config.add_feed(); + feed->mutable_id()->set_node_name("bar"); + feed->set_name("conflict_data"); + ExpectErrorContains(ValidateConfig(config), "conflicting feed name"); +} + +TEST(ValidateConfig, ConflictingFetchName) { + tf2xla::Config config; + tf2xla::Feed* feed = config.add_feed(); + feed->mutable_id()->set_node_name("foo"); + tf2xla::Fetch* fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("bar"); + fetch->set_name("conflict"); + fetch = config.add_fetch(); + fetch->mutable_id()->set_node_name("baz"); + fetch->set_name("conflict_data"); + ExpectErrorContains(ValidateConfig(config), "conflicting fetch name"); +} + +static tf2xla::Config FetchesConfig(std::vector fetches) { + tf2xla::Config config; + for (const auto& fetch_node_name : fetches) { + auto* fetch = config.add_fetch(); + fetch->set_name(absl::StrCat("fetch_", fetch_node_name)); + fetch->mutable_id()->set_node_name(fetch_node_name); + } + return config; +} + +TEST(PruneGraphDefInto, Basic) { + GraphDef def; + auto* n = def.add_node(); + n->set_name("a"); + n->add_input("b:0"); + n->add_input("^c"); + + GraphDef copy; + ExpectErrorContains(PruneGraphDefInto(FetchesConfig({"missing"}), def, ©), + "node missing needed"); + ExpectErrorContains(PruneGraphDefInto(FetchesConfig({"a"}), def, ©), + "node b needed"); + + n = def.add_node(); + n->set_name("b"); + ExpectErrorContains(PruneGraphDefInto(FetchesConfig({"a"}), def, ©), + "node c needed"); + n->add_input("d:1"); + + n = def.add_node(); + n->set_name("c"); + n->add_input("d:1"); + + n = def.add_node(); + n->set_name("d"); + + // Graph is full, no pruning done. + // Graph right now has diamond from d: + // d --> b --> a + // d --> c --> a + TF_EXPECT_OK(PruneGraphDefInto(FetchesConfig({"a"}), def, ©)); + EXPECT_EQ(def.DebugString(), copy.DebugString()); + GraphDef pruned_a = copy; + + // Add some unrelated fields that use b and c, but are not needed for a. + n = def.add_node(); + n->set_name("e"); + n->add_input("^d"); + n->add_input("b:2"); + copy.Clear(); + TF_EXPECT_OK(PruneGraphDefInto(FetchesConfig({"a"}), def, ©)); + EXPECT_EQ(pruned_a.DebugString(), copy.DebugString()); + + // Fetch "a" and "e" to get the original graph. + copy.Clear(); + TF_EXPECT_OK(PruneGraphDefInto(FetchesConfig({"a", "e"}), def, ©)); + EXPECT_EQ(def.DebugString(), copy.DebugString()); +} + +TEST(SetNodeShardingFromNeighbors, Basic) { + // Builds a graph that adds two Tensors. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); + auto c = ops::Add(scope.WithOpName("C"), a, b); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + Node* a_node = nullptr; + Node* b_node = nullptr; + Node* c_node = nullptr; + for (Node* n : graph->nodes()) { + if (n->name() == "A") a_node = n; + if (n->name() == "B") b_node = n; + if (n->name() == "C") c_node = n; + } + + const int num_cores_per_replica = 4; + + a_node->set_assigned_device_name("foo"); + EXPECT_FALSE(SetNodeShardingFromNeighbors(c_node, /*out_edges=*/false).ok()); + + // Test where one input to c_node has a device. + a_node->set_assigned_device_name("/device:TPU_REPLICATED_CORE:2"); + TF_ASSERT_OK(SetNodeShardingFromNeighbors(c_node, /*out_edges=*/false)); + auto parse_status = ParseShardingFromDevice(*c_node, num_cores_per_replica, + /*add_metadata=*/false); + TF_ASSERT_OK(parse_status.status()); + ASSERT_TRUE(parse_status.value().has_value()); + EXPECT_EQ(2, parse_status.value().value().tile_assignment_devices(0)); + + // Test where two inputs to c_node have a device. + b_node->set_assigned_device_name("/device:TPU_REPLICATED_CORE:1"); + TF_ASSERT_OK(SetNodeShardingFromNeighbors(c_node, /*out_edges=*/false)); + parse_status = ParseShardingFromDevice(*c_node, num_cores_per_replica, + /*add_metadata=*/false); + TF_ASSERT_OK(parse_status.status()); + ASSERT_TRUE(parse_status.value().has_value()); + EXPECT_EQ(1, parse_status.value().value().tile_assignment_devices(0)); + + // Test setting based on out edges. + TF_ASSERT_OK(SetNodeShardingFromNeighbors(a_node, /*out_edges=*/true)); + parse_status = ParseShardingFromDevice(*a_node, num_cores_per_replica, + /*add_metadata=*/false); + TF_ASSERT_OK(parse_status.status()); + ASSERT_TRUE(parse_status.value().has_value()); + EXPECT_EQ(1, parse_status.value().value().tile_assignment_devices(0)); +} + +REGISTER_OP("One") + .Output("y: T") + .Attr("T: {float, double, int32, int64}") + .Doc(R"doc( +Returns a tensor with a single element (1) of type T. + +y: A scalar in type T. + +)doc"); + +// Tests that CachedFunctionHandles class works. +TEST(CachedFunctionHandles, Basic) { + FunctionDef func = FunctionDefHelper::Define( + // Name + "TestFunc", + // Args + {}, + // Return values + {"y:T"}, + // Attr def + {"T:{float, double, int32, int64}"}, + // Nodes + { + {{"y"}, "One", {}, {{"T", "$T"}}}, + }); + FunctionDefLibrary proto; + *proto.add_function() = func; + FunctionLibraryDefinition fld(OpRegistry::Global(), proto); + std::unique_ptr pflr( + new ProcessFunctionLibraryRuntime( + /*device_mgr=*/nullptr, Env::Default(), /*config=*/nullptr, + TF_GRAPH_DEF_VERSION, &fld, OptimizerOptions())); + FunctionLibraryRuntime* flr = + pflr->GetFLR(ProcessFunctionLibraryRuntime::kDefaultFLRDevice); + + CachedFunctionHandles cached_function_handles(flr); + + // Tests that GetOrInstantiate() works. + FunctionLibraryRuntime::Handle first_handle; + AttrValue attr; + attr.set_type(DT_FLOAT); + AttrValueMap attrs; + attrs["T"] = attr; + TF_ASSERT_OK(cached_function_handles.GetOrInstantiate( + "TestFunc", AttrSlice(&attrs), &first_handle)); + + // Tests that we can get FunctionBody. + const FunctionBody* body = flr->GetFunctionBody(first_handle); + EXPECT_NE(body, nullptr); + + // Tests that GetOrInstantiate() returns cached handle when called with same + // function name and attributes. + FunctionLibraryRuntime::Handle second_handle; + TF_ASSERT_OK(cached_function_handles.GetOrInstantiate( + "TestFunc", AttrSlice(&attrs), &second_handle)); + EXPECT_EQ(first_handle, second_handle); + + // Tests that GetOrInstantiate() returns new handle when called with same + // function name but different attributes. + attr.set_type(DT_INT32); + attrs["T"] = attr; + FunctionLibraryRuntime::Handle third_handle; + TF_ASSERT_OK(cached_function_handles.GetOrInstantiate( + "TestFunc", AttrSlice(&attrs), &third_handle)); + EXPECT_NE(first_handle, third_handle); + + // Tests that ReleaseAllHandles() works. + TF_EXPECT_OK(cached_function_handles.ReleaseAllHandles()); +} + +TEST(PropagateConstIntoFunctionalNodes, WhileLoopWithResourceInput) { + FunctionLibraryDefinition fld(OpRegistry::Global(), FunctionDefLibrary()); + { + // Cond graph & body graph. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto pred = ops::_Arg(scope.WithOpName("pred"), DT_BOOL, 0); + auto input = ops::_Arg(scope.WithOpName("input"), DT_RESOURCE, 1); + auto ret = ops::_Retval(scope.WithOpName("ret"), pred, 0); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + FunctionDef cond_fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "cond", &cond_fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(cond_fdef)); + FunctionDef body_fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "body", &body_fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(body_fdef)); + } + Scope scope = Scope::NewRootScope().ExitOnError(); + auto pred = ops::Const(scope.WithOpName("pred"), false, TensorShape({})); + auto input = ops::Const(scope.WithOpName("input"), 0, TensorShape({})); + NameAttrList cond_fn, body_fn; + cond_fn.set_name("cond"); + body_fn.set_name("body"); + auto while_op = + ops::While(scope.WithOpName("while"), + std::initializer_list{pred, input}, cond_fn, body_fn); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + + TF_EXPECT_OK(PropagateConstIntoFunctionalNodes(&graph, &fld, &fld)); +} + +TEST(PropagateConstIntoFunctionalNodes, CopiedConstNodeHasUniqueName) { + FunctionLibraryDefinition fld(OpRegistry::Global(), FunctionDefLibrary()); + { + // Cond graph & body graph. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto pred = ops::_Arg(scope.WithOpName("arg0"), DT_BOOL, 0); + auto input = ops::_Arg(scope.WithOpName("arg1"), DT_BOOL, 1); + auto duplicate_name = ops::NoOp(scope.WithOpName("duplicate_name")); + auto ret = ops::_Retval(scope.WithOpName("ret"), pred, 0); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + FunctionDef cond_fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "cond", &cond_fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(cond_fdef)); + FunctionDef body_fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "body", &body_fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(body_fdef)); + } + Scope scope = Scope::NewRootScope().ExitOnError(); + auto pred = + ops::Const(scope.WithOpName("duplicate_name"), false, TensorShape({})); + auto input = ops::Const(scope.WithOpName("input"), false, TensorShape({})); + NameAttrList cond_fn, body_fn; + cond_fn.set_name("cond"); + body_fn.set_name("body"); + auto while_op = + ops::While(scope.WithOpName("while"), + std::initializer_list{pred, input}, cond_fn, body_fn); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + + TF_EXPECT_OK(PropagateConstIntoFunctionalNodes(&graph, &fld, &fld)); + + // Check that in rewritten body function, the NoOp node still has name + // "duplicate_name", and the copied Const node has name "duplicate_name/_0". + auto node_name_index = graph.BuildNodeNameIndex(); + Node* while_node = node_name_index["while"]; + ASSERT_NE(while_node, nullptr); + TF_ASSERT_OK(GetNodeAttr(while_node->def(), "body", &body_fn)); + const FunctionDef* rewritten_body_fn = fld.Find(body_fn.name()); + ASSERT_NE(rewritten_body_fn, nullptr); + std::unordered_map nodes; + for (const NodeDef& node_def : rewritten_body_fn->node_def()) { + nodes[node_def.name()] = node_def; + } + auto noop_def = nodes.find("duplicate_name"); + ASSERT_NE(noop_def, nodes.end()); + EXPECT_EQ(noop_def->second.op(), "NoOp"); + auto const_def = nodes.find("duplicate_name/_0"); + ASSERT_NE(const_def, nodes.end()); + EXPECT_EQ(const_def->second.op(), "Const"); +} + +TEST(PropagateConstIntoFunctionalNodes, RewriteTensorListWithConstMember) { + FunctionLibraryDefinition fld(OpRegistry::Global(), FunctionDefLibrary()); + { + // Cond graph + Scope scope = Scope::NewRootScope().ExitOnError(); + auto input = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); + auto result = + ops::Const(scope.WithOpName("result"), false, TensorShape({})); + auto ret = ops::_Retval(scope.WithOpName("ret"), result, 0); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "cond", &fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(fdef)); + } + { + // Forward body graph + Scope scope = Scope::NewRootScope().ExitOnError(); + auto input = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); + auto element = ops::Const(scope.WithOpName("element"), 0, TensorShape({})); + auto push = + ops::TensorListPushBack(scope.WithOpName("push"), input, element); + auto ret = ops::_Retval(scope.WithOpName("ret"), push.output_handle, 0); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "fwd_body", &fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(fdef)); + } + { + // Backward body graph + Scope scope = Scope::NewRootScope().ExitOnError(); + auto input = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); + auto shape = ops::Const(scope.WithOpName("element"), -1, TensorShape({})); + auto pop = + ops::TensorListPopBack(scope.WithOpName("pop"), input, shape, DT_INT32); + auto identity = ops::Identity(scope.WithOpName("identity"), pop.tensor); + auto ret = ops::_Retval(scope.WithOpName("ret"), pop.output_handle, 0); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(graph, "bwd_body", &fdef)); + TF_ASSERT_OK(fld.AddFunctionDef(fdef)); + } + Scope scope = Scope::NewRootScope().ExitOnError(); + auto shape = ops::Const(scope.WithOpName("element"), -1, TensorShape({})); + auto max_num_elements = + ops::Const(scope.WithOpName("max_num_elements"), 10, TensorShape({})); + auto tl = ops::EmptyTensorList(scope.WithOpName("tl"), shape, + max_num_elements, DT_INT32); + NameAttrList cond_fn, fwd_body_fn, bwd_body_fn; + cond_fn.set_name("cond"); + fwd_body_fn.set_name("fwd_body"); + bwd_body_fn.set_name("bwd_body"); + auto fwd_while_op = + ops::While(scope.WithOpName("fwd_while"), + std::initializer_list{tl}, cond_fn, fwd_body_fn); + auto bwd_while_op = + ops::While(scope.WithOpName("bwd_while"), + std::initializer_list{fwd_while_op.output[0]}, cond_fn, + bwd_body_fn); + Graph graph(OpRegistry::Global()); + TF_ASSERT_OK(scope.ToGraph(&graph)); + + TF_EXPECT_OK(RewriteTensorListWithConstElement(&graph, &fld)); + + // Check that in rewritten backward While body function, the Identity node now + // has Const node as input. + const FunctionDef* bwd_body = fld.Find("bwd_body_tl_rewrite_0"); + ASSERT_NE(bwd_body, nullptr); + std::unique_ptr bwd_fbody; + CHECK_OK(FunctionDefToBodyHelper(*bwd_body, AttrSlice(), &fld, &bwd_fbody)); + auto node_name_index = bwd_fbody->graph->BuildNodeNameIndex(); + const Node* identity = node_name_index.at("identity"); + ASSERT_NE(identity, nullptr); + const Node* input; + TF_ASSERT_OK(identity->input_node(0, &input)); + EXPECT_EQ(input->type_string(), "Const"); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util.cc new file mode 100644 index 0000000000000000000000000000000000000000..9589811e70b0a1cb344f91ed81918513c21556a6 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util.cc @@ -0,0 +1,157 @@ +/* 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/type_util.h" + +#include "absl/container/flat_hash_map.h" +#include "absl/status/status.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +absl::Status DataTypeToPrimitiveType(DataType data_type, + xla::PrimitiveType* type) { + switch (data_type) { + case tensorflow::DT_BOOL: + *type = xla::PRED; + return absl::OkStatus(); + case tensorflow::DT_INT2: + *type = xla::S2; + return absl::OkStatus(); + case tensorflow::DT_INT4: + *type = xla::S4; + return absl::OkStatus(); + case tensorflow::DT_INT8: + case tensorflow::DT_QINT8: + *type = xla::S8; + return absl::OkStatus(); + case tensorflow::DT_INT16: + case tensorflow::DT_QINT16: + *type = xla::S16; + return absl::OkStatus(); + case tensorflow::DT_INT32: + case tensorflow::DT_QINT32: + *type = xla::S32; + return absl::OkStatus(); + case tensorflow::DT_INT64: + *type = xla::S64; + return absl::OkStatus(); + case tensorflow::DT_UINT2: + *type = xla::U2; + return absl::OkStatus(); + case tensorflow::DT_UINT4: + *type = xla::U4; + return absl::OkStatus(); + case tensorflow::DT_UINT8: + case tensorflow::DT_QUINT8: + *type = xla::U8; + return absl::OkStatus(); + case tensorflow::DT_UINT16: + case tensorflow::DT_QUINT16: + *type = xla::U16; + return absl::OkStatus(); + case tensorflow::DT_UINT32: + *type = xla::U32; + return absl::OkStatus(); + case tensorflow::DT_UINT64: + *type = xla::U64; + return absl::OkStatus(); + case tensorflow::DT_FLOAT8_E5M2: + *type = xla::F8E5M2; + return absl::OkStatus(); + case tensorflow::DT_FLOAT8_E4M3FN: + *type = xla::F8E4M3FN; + return absl::OkStatus(); + case tensorflow::DT_FLOAT8_E4M3FNUZ: + *type = xla::F8E4M3FNUZ; + return absl::OkStatus(); + case tensorflow::DT_FLOAT8_E4M3B11FNUZ: + *type = xla::F8E4M3B11FNUZ; + return absl::OkStatus(); + case tensorflow::DT_FLOAT8_E5M2FNUZ: + *type = xla::F8E5M2FNUZ; + return absl::OkStatus(); + case tensorflow::DT_FLOAT4_E2M1FN: + *type = xla::F4E2M1FN; + return absl::OkStatus(); + case tensorflow::DT_BFLOAT16: + *type = xla::BF16; + return absl::OkStatus(); + case tensorflow::DT_HALF: + *type = xla::F16; + return absl::OkStatus(); + case tensorflow::DT_FLOAT: + *type = xla::F32; + return absl::OkStatus(); + case tensorflow::DT_DOUBLE: + *type = xla::F64; + return absl::OkStatus(); + case tensorflow::DT_COMPLEX64: + *type = xla::C64; + return absl::OkStatus(); + case tensorflow::DT_COMPLEX128: + *type = xla::C128; + return absl::OkStatus(); + default: + return absl::InvalidArgumentError( + absl::StrCat("Unsupported type in DataTypeToPrimitiveType: '", + DataTypeString(data_type), "'")); + } +} + +absl::StatusOr EncodePrimitiveTypeAsDataType( + xla::PrimitiveType type) { + static const absl::flat_hash_map& + data_type_map = *new absl::flat_hash_map({ + {xla::PRED, DT_BOOL}, + {xla::F8E5M2, DT_FLOAT8_E5M2}, + {xla::F8E4M3FN, DT_FLOAT8_E4M3FN}, + {xla::F8E4M3FNUZ, DT_FLOAT8_E4M3FNUZ}, + {xla::F8E4M3B11FNUZ, DT_FLOAT8_E4M3B11FNUZ}, + {xla::F8E5M2FNUZ, DT_FLOAT8_E5M2FNUZ}, + {xla::F4E2M1FN, DT_FLOAT4_E2M1FN}, + {xla::BF16, DT_BFLOAT16}, + {xla::F16, DT_HALF}, + {xla::F32, DT_FLOAT}, + {xla::F64, DT_DOUBLE}, + {xla::C64, DT_COMPLEX64}, + {xla::S2, DT_INT2}, + {xla::S4, DT_INT4}, + {xla::S8, DT_INT8}, + {xla::S16, DT_INT16}, + {xla::S32, DT_INT32}, + {xla::S64, DT_INT64}, + {xla::U2, DT_UINT2}, + {xla::U4, DT_UINT4}, + {xla::U8, DT_UINT8}, + {xla::U16, DT_UINT16}, + {xla::U32, DT_UINT32}, + {xla::U64, DT_UINT64}, + {xla::C128, DT_COMPLEX128}, + }); + + auto it = data_type_map.find(type); + if (it == data_type_map.end()) { + return absl::InvalidArgumentError( + absl::StrCat("Unsupported type in PrimitiveTypeToDataType ", type)); + } + return it->second; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util.h new file mode 100644 index 0000000000000000000000000000000000000000..a702e517ada0252c80ec94bd0ca4998618f3af0d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util.h @@ -0,0 +1,42 @@ +/* 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_TYPE_UTIL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_TYPE_UTIL_H_ + +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// Converts a Tensorflow DataType to an XLA PrimitiveType. +absl::Status DataTypeToPrimitiveType(DataType data_type, + xla::PrimitiveType* type); + +// Converts an XLA PrimitiveType to a TensorFlow DataType. +// Caution: The mapping from TF types to XLA types is not one-to-one: for +// example, both DT_INT8 and DT_QINT8 map to xla::S8. So the inverse is not a +// uniquely defined function. This is fine if you want a way to encode an XLA +// object as a TensorFlow object (e.g., in XRT); whereas if you started with a +// TensorFlow object in the first place, you most likely should preserve the +// original TensorFlow type, rather than trying to convert an XLA type back into +// a TensorFlow type. +absl::StatusOr EncodePrimitiveTypeAsDataType(xla::PrimitiveType type); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_TYPE_UTIL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..87f06ba2531c093ed6c8530bfd649924da0c1c2c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/type_util_test.cc @@ -0,0 +1,91 @@ +/* Copyright 2023 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/type_util.h" + +#include + +#include "absl/status/statusor.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { + +// Conversion utilities should support any primitive type, +// excluding string, resource, variant, invalid. +bool DataTypeSupportsXlaConversion(DataType dt) { + switch (dt) { + case DataType::DT_STRING: + case DataType::DT_RESOURCE: + case DataType::DT_VARIANT: + case DataType::DT_INVALID: + return false; + default: + // All other types should be supported. + break; + } + return !IsRefType(dt); +} + +TEST(DataTypeToPrimitiveTypeTest, AllDataTypesSupported) { + for (int i = tensorflow::DataType_MIN; i < tensorflow::DataType_MAX; ++i) { + if (tensorflow::DataType_IsValid(i)) { + DataType dt = static_cast(i); + if (DataTypeSupportsXlaConversion(dt)) { + xla::PrimitiveType out_type; + EXPECT_TRUE(DataTypeToPrimitiveType(dt, &out_type).ok()); + } + } + } +} + +TEST(EncodePrimitiveTypeAsDataType, AllPrimitiveTypesSupported) { + for (int i = tensorflow::DataType_MIN; i < tensorflow::DataType_MAX; ++i) { + DataType dt = static_cast(i); + xla::PrimitiveType xla_type; + // If conversion to primitive type works, then the reverse mapping should + // also work. + if (DataTypeToPrimitiveType(dt, &xla_type).ok()) { + absl::StatusOr data_type_or = + EncodePrimitiveTypeAsDataType(xla_type); + EXPECT_TRUE(data_type_or.ok()); + // Non-quantized inputs should map directly back to the original type. + if (!DataTypeIsQuantized(dt)) { + EXPECT_EQ(*data_type_or, dt); + } + } + } +} + +TEST(EncodePrimitiveTypeAsDataType, QuantizedTypesMapToUnquantized) { + static std::array quantized_inputs = { + DT_QINT8, DT_QINT16, DT_QINT32, DT_QUINT8, DT_QUINT16}; + static std::array expected_outputs = { + DT_INT8, DT_INT16, DT_INT32, DT_UINT8, DT_UINT16}; + + for (int i = 0; i < quantized_inputs.size(); ++i) { + xla::PrimitiveType xla_type; + EXPECT_TRUE(DataTypeToPrimitiveType(quantized_inputs[i], &xla_type).ok()); + absl::StatusOr data_type_or = + EncodePrimitiveTypeAsDataType(xla_type); + EXPECT_TRUE(data_type_or.ok()); + EXPECT_EQ(*data_type_or, expected_outputs[i]); + } +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.cc new file mode 100644 index 0000000000000000000000000000000000000000..69bec093a1539a7e456682ebe1b7146fa1315560 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.cc @@ -0,0 +1,149 @@ +/* Copyright 2020 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/xla_argument.h" + +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/types/variant.h" +#include "llvm/ADT/STLExtras.h" +#include "tensorflow/compiler/tf2xla/xla_argument.pb.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/shape.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" + +namespace tensorflow { + +bool XlaArgument::operator==(const XlaArgument& other) const { + if (std::tie(kind, resource_kind, type, name, initialized, max_array_size, + tensor_array_gradients) != + std::tie(other.kind, other.resource_kind, other.type, other.name, + other.initialized, other.max_array_size, + other.tensor_array_gradients)) { + return false; + } + if (absl::holds_alternative(shape)) { + if (!absl::holds_alternative(other.shape)) { + return false; + } + if (!xla::Shape::Equal()(absl::get(shape), + absl::get(other.shape))) { + return false; + } + } else { + if (!absl::holds_alternative(other.shape)) { + return false; + } + if (absl::get(shape) != absl::get(other.shape)) { + return false; + } + } + if (constant_value.shape() != other.constant_value.shape()) { + return false; + } + if (is_same_data_across_replicas != other.is_same_data_across_replicas) { + return false; + } + return constant_value.tensor_data() == other.constant_value.tensor_data(); +} + +tf2xla::XlaArgumentProto XlaArgument::ToProto() const { + tf2xla::XlaArgumentProto proto; + proto.set_kind(static_cast(kind)); + proto.set_type(type); + if (std::holds_alternative(shape)) { + *proto.mutable_shape()->mutable_xla_shape() = + std::get(shape).ToProto(); + } else if (std::holds_alternative(shape)) { + *proto.mutable_shape()->mutable_tensor_shape() = + std::get(shape).AsProto(); + } + constant_value.AsProtoTensorContent(proto.mutable_constant_value()); + if (value_bound.has_value()) { + value_bound->AsProtoTensorContent(proto.mutable_value_bound()); + } + if (value_dynamism.has_value()) { + value_dynamism->AsProtoTensorContent(proto.mutable_value_dynamism()); + } + proto.set_name(name); + proto.set_node_name(node_name); + proto.set_resource_kind(static_cast(resource_kind)); + proto.set_initialized(initialized); + proto.set_fast_mem(fast_mem); + proto.set_max_array_size(max_array_size); + proto.mutable_tensor_array_gradients()->Add(tensor_array_gradients.begin(), + tensor_array_gradients.end()); + proto.set_is_same_data_across_replicas(is_same_data_across_replicas); + proto.set_requires_broadcast(requires_broadcast); + return proto; +} + +absl::StatusOr XlaArgument::FromProto( + const tf2xla::XlaArgumentProto& proto) { + XlaArgument arg; + arg.kind = static_cast(proto.kind()); + arg.type = proto.type(); + if (proto.has_shape()) { + if (proto.shape().has_xla_shape()) { + TF_ASSIGN_OR_RETURN(arg.shape, + xla::Shape::FromProto(proto.shape().xla_shape())); + } else if (proto.shape().has_tensor_shape()) { + arg.shape = TensorShape(proto.shape().tensor_shape()); + } else { + return absl::InvalidArgumentError("Shape is not set."); + } + } + if (proto.has_constant_value() && + !arg.constant_value.FromProto(proto.constant_value())) { + return absl::InvalidArgumentError("Constant value is invalid."); + } + if (proto.has_value_bound()) { + Tensor value_bound; + if (!value_bound.FromProto(proto.value_bound())) { + return absl::InvalidArgumentError("Value bound is invalid."); + } + arg.value_bound = value_bound; + } + if (proto.has_value_dynamism()) { + Tensor value_dynamism; + if (!value_dynamism.FromProto(proto.value_dynamism())) { + return absl::InvalidArgumentError("Value dynamism is invalid."); + } + arg.value_dynamism = value_dynamism; + } + arg.name = proto.name(); + arg.node_name = proto.node_name(); + arg.resource_kind = static_cast(proto.resource_kind()); + arg.initialized = proto.initialized(); + arg.fast_mem = proto.fast_mem(); + arg.max_array_size = proto.max_array_size(); + arg.tensor_array_gradients.insert(proto.tensor_array_gradients().begin(), + proto.tensor_array_gradients().end()); + arg.is_same_data_across_replicas = proto.is_same_data_across_replicas(); + arg.requires_broadcast = proto.requires_broadcast(); + return arg; +} + +bool AnyUninitializedResourceArg(absl::Span args) { + return llvm::any_of(args, [](const XlaArgument& arg) { + return arg.kind == XlaArgument::kResource && arg.type == DT_INVALID; + }); +} + +} // end namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.h new file mode 100644 index 0000000000000000000000000000000000000000..3b8d7e85ccb79580dd204b7a7f426d8a9fd2edac --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.h @@ -0,0 +1,151 @@ +/* Copyright 2020 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_XLA_ARGUMENT_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_ARGUMENT_H_ + +#include +#include +#include +#include +#include +#include + +#include "absl/container/inlined_vector.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/host_compute_metadata.pb.h" +#include "tensorflow/compiler/tf2xla/xla_argument.pb.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/shape.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/util/managed_stack_trace.h" + +namespace tensorflow { + +// Describes how to derive the value of each _Arg node in the graph/function +// being compiled. There must be one Argument for each _Arg index. +struct XlaArgument { + enum Kind { + // Default value; not a valid kind. + kInvalid, + + // Argument is a compile-time constant. No associated runtime parameter. + kConstant, + + // Argument is a Variable, TensorArray, or Stack resource. Has an + // associated runtime parameter iff `initialized` is true. + kResource, + + // A resource variable with a constant value known at compile time. + kConstantResource, + + // Argument is a run-time parameter. + kParameter, + + // Argument is an XLA token. + kToken, + + // Argument is a TensorList. + kTensorList, + }; + + Kind kind = kInvalid; + + // The type of the argument. If the argument is a resource, this + // is the type of the variable's value, not DT_RESOURCE. + DataType type = DT_INVALID; + + // The shape of the argument. For: + // * a parameter: the shape of the parameter. We allow setting the xla shape + // if known. This helps avoid conversions to and from TensorShape. + // * a constant: ignored; the shape given by constant_value is used + // instead. + // * an uninitialized resource: ignored. We don't yet know the shape of an + // uninitialized resource (otherwise we would have initialized it!) + // * an initialized variable: the shape of the variable's value. + // * an initialized TensorArray or Stack resource: the shape of an entry in + // the TensorArray/Stack. Note this is the size of a single entry, not the + // XLA data structure that represents the complete stack/array. + std::variant shape; + + // The value of the argument, if it is a compile-time constant. Must be a + // host-memory tensor. + Tensor constant_value; + + // The upper bounds of the value. + std::optional value_bound; + + // Indicates whether each value is dynamic or constant. + std::optional value_dynamism; + + // The name of this argument, used for debugging. + std::string name; + + // The name of TensorFlow _Arg node, used for debugging. + std::string node_name; + + // For a kResource, what kind of resource is it? + XlaResource::Kind resource_kind = XlaResource::kInvalid; + + // For a kResource, has this resource been initialized? + bool initialized = false; + + // For a kResource, is this resource on Fast Memory. + bool fast_mem = false; + + // For a TensorArray or Stack resource, what is the array's declared size? + // (Used for lazy initialization.) + int64_t max_array_size = -1; + + // TensorArray resource parameters are passed as (array, gradient array 0, + // ..., gradient array k), where the gradient arrays are in the same order + // as `tensor_array_gradients`. + std::set tensor_array_gradients; + + // Whether this argument will receive the same data across all replicas. + bool is_same_data_across_replicas = false; + + bool operator==(const XlaArgument& other) const; + + // Returns a human-readable summary of the argument. + std::string HumanString() const; + + // Returns the dimension sizes for either TensorShape or xla::Shape. + std::vector DimensionSizes() const; + absl::InlinedVector DimensionSizesAsInlinedVector() const; + + // Returns the human-readable string for either TensorShape or xla::Shape. + std::string ShapeHumanString() const; + + // Whether to broadcast this parameter to all replicas before use. + // When true, xla_compiler should input/output alias this arg to prevent + // unnecessary HBM usage. + bool requires_broadcast = false; + std::optional definition_stack_trace; + + // Converts between proto and struct. + tf2xla::XlaArgumentProto ToProto() const; + static absl::StatusOr FromProto( + const tf2xla::XlaArgumentProto& proto); +}; + +// Returns true if any of `args` is an uninitialized resource variable. +bool AnyUninitializedResourceArg(absl::Span args); + +} // end namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_ARGUMENT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.proto b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.proto new file mode 100644 index 0000000000000000000000000000000000000000..2f91591ba262d7eaf9dd34ec5a9eeb093bd54c63 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument.proto @@ -0,0 +1,37 @@ +syntax = "proto3"; + +package tensorflow.tf2xla; + +import "xla/xla_data.proto"; +import "tensorflow/core/framework/tensor.proto"; +import "tensorflow/core/framework/tensor_shape.proto"; +import "tensorflow/core/framework/types.proto"; + +option cc_enable_arenas = true; +option java_outer_classname = "Tf2XlaProtos"; +option java_multiple_files = true; +option java_package = "org.tensorflow.tf2xla"; + +message XlaArgumentProto { + int32 kind = 1; + DataType type = 2; + message Shape { + oneof shape { + TensorShapeProto tensor_shape = 1; + xla.ShapeProto xla_shape = 2; + } + } + optional Shape shape = 3; + TensorProto constant_value = 4; + optional TensorProto value_bound = 5; + optional TensorProto value_dynamism = 6; + string name = 7; + string node_name = 8; + int32 resource_kind = 9; + bool initialized = 10; + bool fast_mem = 11; + int64 max_array_size = 12; + repeated string tensor_array_gradients = 13; + bool is_same_data_across_replicas = 14; + bool requires_broadcast = 15; +} diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..1eaede60143934355717ed02e61b532535d16513 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_argument_test.cc @@ -0,0 +1,213 @@ +/* Copyright 2026 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/xla_argument.h" + +#include +#include +#include +#include +#include + +#include "tensorflow/compiler/tf2xla/xla_argument.pb.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/shape.h" +#include "xla/tsl/platform/statusor.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/tensor_shape.pb.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { + +TEST(XlaArgumentToProto, ShapeIsTensorShape) { + XlaArgument arg; + arg.shape = TensorShape({1, 2, 3}); + tf2xla::XlaArgumentProto proto = arg.ToProto(); + + EXPECT_TRUE(proto.has_shape()); + EXPECT_TRUE(proto.shape().has_tensor_shape()); + EXPECT_EQ(proto.shape().tensor_shape().dim_size(), 3); + EXPECT_EQ(proto.shape().tensor_shape().dim(0).size(), 1); + EXPECT_EQ(proto.shape().tensor_shape().dim(1).size(), 2); + EXPECT_EQ(proto.shape().tensor_shape().dim(2).size(), 3); + EXPECT_FALSE(proto.shape().has_xla_shape()); +} + +TEST(XlaArgumentToProto, ShapeIsXlaShape) { + XlaArgument arg; + arg.shape = xla::Shape(xla::F32, {1, 2, 3}); + tf2xla::XlaArgumentProto proto = arg.ToProto(); + + EXPECT_TRUE(proto.has_shape()); + EXPECT_FALSE(proto.shape().has_tensor_shape()); + EXPECT_TRUE(proto.shape().has_xla_shape()); + EXPECT_EQ(proto.shape().xla_shape().element_type(), xla::F32); + EXPECT_EQ(proto.shape().xla_shape().dimensions_size(), 3); + EXPECT_EQ(proto.shape().xla_shape().dimensions(0), 1); + EXPECT_EQ(proto.shape().xla_shape().dimensions(1), 2); + EXPECT_EQ(proto.shape().xla_shape().dimensions(2), 3); +} + +TEST(XlaArgumentToProto, ShapeIsMonostate) { + XlaArgument arg; + tf2xla::XlaArgumentProto proto = arg.ToProto(); + EXPECT_FALSE(proto.has_shape()); +} + +TEST(XlaArgumentToProto, AllFields) { + XlaArgument arg; + arg.kind = XlaArgument::kConstant; + arg.type = DT_FLOAT; + arg.shape = TensorShape({1, 2, 3}); + Tensor constant_value(DT_FLOAT, TensorShape({1, 2, 3})); + auto constant_value_map = constant_value.tensor(); + constant_value_map.setZero(); + constant_value_map(0, 0, 0) = 1.0f; + constant_value_map(0, 0, 1) = 2.0f; + arg.constant_value = std::move(constant_value); + Tensor value_bound(DT_FLOAT, TensorShape({1, 2, 3})); + auto value_bound_map = value_bound.tensor(); + value_bound_map.setZero(); + value_bound_map(0, 0, 0) = 3.0f; + value_bound_map(0, 0, 1) = 4.0f; + arg.value_bound = std::move(value_bound); + // value_dynamism is intentionally not set to test how std::optional is + // handled. + arg.name = "name"; + arg.node_name = "node_name"; + arg.resource_kind = XlaResource::kVariable; + arg.initialized = true; + arg.fast_mem = false; + arg.max_array_size = 10; + arg.tensor_array_gradients = {"gradient_0", "gradient_1"}; + arg.is_same_data_across_replicas = true; + arg.requires_broadcast = false; + + tf2xla::XlaArgumentProto proto = arg.ToProto(); + EXPECT_EQ(proto.kind(), static_cast(XlaArgument::kConstant)); + EXPECT_EQ(proto.type(), DT_FLOAT); + EXPECT_TRUE(proto.has_shape()); + EXPECT_TRUE(proto.shape().has_tensor_shape()); + EXPECT_EQ(proto.shape().tensor_shape().dim_size(), 3); + EXPECT_EQ(proto.shape().tensor_shape().dim(0).size(), 1); + EXPECT_EQ(proto.shape().tensor_shape().dim(1).size(), 2); + EXPECT_EQ(proto.shape().tensor_shape().dim(2).size(), 3); + EXPECT_TRUE(proto.has_constant_value()); + EXPECT_TRUE(proto.has_value_bound()); + EXPECT_FALSE(proto.has_value_dynamism()); + EXPECT_EQ(proto.name(), "name"); + EXPECT_EQ(proto.node_name(), "node_name"); + EXPECT_EQ(proto.resource_kind(), static_cast(XlaResource::kVariable)); + EXPECT_TRUE(proto.initialized()); + EXPECT_FALSE(proto.fast_mem()); + EXPECT_EQ(proto.max_array_size(), 10); + EXPECT_EQ(proto.tensor_array_gradients_size(), 2); + EXPECT_EQ(proto.tensor_array_gradients(0), "gradient_0"); + EXPECT_EQ(proto.tensor_array_gradients(1), "gradient_1"); + EXPECT_TRUE(proto.is_same_data_across_replicas()); + EXPECT_FALSE(proto.requires_broadcast()); + + TF_ASSERT_OK_AND_ASSIGN(XlaArgument arg_from_proto, + XlaArgument::FromProto(proto)); + EXPECT_EQ(arg, arg_from_proto); +} + +TEST(XlaArgumentFromProto, ShapeIsTensorShape) { + tf2xla::XlaArgumentProto proto; + proto.mutable_shape()->mutable_tensor_shape()->add_dim()->set_size(1); + proto.mutable_shape()->mutable_tensor_shape()->add_dim()->set_size(2); + proto.mutable_shape()->mutable_tensor_shape()->add_dim()->set_size(3); + + TF_ASSERT_OK_AND_ASSIGN(XlaArgument arg, XlaArgument::FromProto(proto)); + EXPECT_TRUE(std::holds_alternative(arg.shape)); + EXPECT_EQ(std::get(arg.shape), TensorShape({1, 2, 3})); +} + +TEST(XlaArgumentFromProto, ShapeIsXlaShape) { + tf2xla::XlaArgumentProto proto; + proto.mutable_shape()->mutable_xla_shape()->set_element_type(xla::F32); + proto.mutable_shape()->mutable_xla_shape()->add_dimensions(1); + proto.mutable_shape()->mutable_xla_shape()->add_dimensions(2); + proto.mutable_shape()->mutable_xla_shape()->add_dimensions(3); + + TF_ASSERT_OK_AND_ASSIGN(XlaArgument arg, XlaArgument::FromProto(proto)); + EXPECT_TRUE(std::holds_alternative(arg.shape)); + EXPECT_EQ(std::get(arg.shape), xla::Shape(xla::F32, {1, 2, 3})); +} + +TEST(XlaArgumentFromProto, ShapeIsMonostate) { + tf2xla::XlaArgumentProto proto; + TF_ASSERT_OK_AND_ASSIGN(XlaArgument arg, XlaArgument::FromProto(proto)); + EXPECT_TRUE(std::holds_alternative(arg.shape)); +} + +TEST(XlaArgumentFromProto, AllFields) { + tf2xla::XlaArgumentProto proto; + proto.set_kind(static_cast(XlaArgument::kConstant)); + proto.set_type(DT_FLOAT); + proto.mutable_shape()->mutable_tensor_shape()->add_dim()->set_size(1); + proto.mutable_shape()->mutable_tensor_shape()->add_dim()->set_size(2); + proto.mutable_shape()->mutable_tensor_shape()->add_dim()->set_size(3); + Tensor constant_value(DT_FLOAT, TensorShape({1, 2, 3})); + auto constant_value_map = constant_value.tensor(); + constant_value_map.setZero(); + constant_value_map(0, 0, 0) = 1.0f; + constant_value_map(0, 0, 1) = 2.0f; + constant_value.AsProtoTensorContent(proto.mutable_constant_value()); + Tensor value_bound(DT_FLOAT, TensorShape({1, 2, 3})); + auto value_bound_map = value_bound.tensor(); + value_bound_map.setZero(); + value_bound_map(0, 0, 0) = 3.0f; + value_bound_map(0, 0, 1) = 4.0f; + value_bound.AsProtoTensorContent(proto.mutable_value_bound()); + proto.set_name("name"); + proto.set_node_name("node_name"); + proto.set_resource_kind(static_cast(XlaResource::kVariable)); + proto.set_initialized(true); + proto.set_fast_mem(false); + proto.set_max_array_size(10); + proto.add_tensor_array_gradients("gradient_0"); + proto.add_tensor_array_gradients("gradient_1"); + proto.set_is_same_data_across_replicas(true); + proto.set_requires_broadcast(false); + + TF_ASSERT_OK_AND_ASSIGN(XlaArgument arg, XlaArgument::FromProto(proto)); + EXPECT_EQ(arg.kind, XlaArgument::kConstant); + EXPECT_EQ(arg.type, DT_FLOAT); + EXPECT_TRUE(std::holds_alternative(arg.shape)); + EXPECT_EQ(std::get(arg.shape), TensorShape({1, 2, 3})); + test::ExpectEqual(arg.constant_value, constant_value); + ASSERT_TRUE(arg.value_bound.has_value()); + test::ExpectEqual(arg.value_bound.value(), value_bound); + EXPECT_FALSE(arg.value_dynamism.has_value()); + EXPECT_EQ(arg.name, "name"); + EXPECT_EQ(arg.node_name, "node_name"); + EXPECT_EQ(arg.resource_kind, XlaResource::kVariable); + EXPECT_TRUE(arg.initialized); + EXPECT_FALSE(arg.fast_mem); + EXPECT_EQ(arg.max_array_size, 10); + EXPECT_EQ(arg.tensor_array_gradients.size(), 2); + EXPECT_EQ(*arg.tensor_array_gradients.begin(), "gradient_0"); + EXPECT_EQ(*std::next(arg.tensor_array_gradients.begin()), "gradient_1"); + EXPECT_TRUE(arg.is_same_data_across_replicas); + EXPECT_FALSE(arg.requires_broadcast); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compilation_device.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compilation_device.cc new file mode 100644 index 0000000000000000000000000000000000000000..8551963edd07210cca01935549e9d8e00457aa2c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compilation_device.cc @@ -0,0 +1,153 @@ +/* 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/xla_compilation_device.h" + +#include +#include + +#include "tensorflow/compiler/tf2xla/frontend_attributes_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/sharding_util.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/common_runtime/local_device.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/platform/mem.h" + +namespace tensorflow { + +// The XlaCompilationAllocator doesn't actually back any Tensors with storage +// buffers of values: instead for each Tensor it stores a +// XlaExpression which corresponds to the XLA computation +// represented by the Tensor. +class XlaCompilationAllocator : public Allocator { + public: + XlaCompilationAllocator() {} + ~XlaCompilationAllocator() override {} + + std::string Name() override { return "xla_compilation"; } + + void* AllocateRaw(size_t alignment, size_t num_bytes) override { + // Regardless of the size requested, always allocates an XlaExpression. + // Respects the alignment request because there is alignment checking even + // for Tensors whose data is never accessed. + void* p = tsl::port::AlignedMalloc( + sizeof(XlaExpression), static_cast(alignment)); + XlaExpression* expression = reinterpret_cast(p); + new (expression) XlaExpression(); + return expression; + } + + void DeallocateRaw(void* ptr) override { + XlaExpression* expression = reinterpret_cast(ptr); + expression->~XlaExpression(); + port::AlignedFree(ptr); + } + + // Make sure that even tensors with 0 elements have allocated + // buffers, so they get ids to track. + // + // NOTE: It is the caller's responsibility to track whether an allocated + // object is a buffer or an opaque handle. In particular, when this allocator + // is used, the caller must not run any constructors or destructors for + // complex objects, since there is no backing store for the tensor in which to + // place their outputs. + bool AllocatesOpaqueHandle() const override { return true; } +}; + +XlaCompilationDevice::XlaCompilationDevice(const SessionOptions& options, + DeviceType type) + : LocalDevice(options, Device::BuildDeviceAttributes( + absl::StrCat("/device:", type.type(), ":0"), + type, Bytes(256 << 20), DeviceLocality(), + absl::StrCat("device: XLA compilation device ", + type.type()))), + allocator_(new XlaCompilationAllocator()) {} + +XlaCompilationDevice::~XlaCompilationDevice() {} + +Allocator* XlaCompilationDevice::GetAllocator(AllocatorAttributes attr) { + return allocator_.get(); +} + +// Attaches location from the node stack trace to metadata. As a heuristic, +// picks the last frame which does not contain the "tensorflow/python" substring +// (making exception for frames containing "test" to allow for testing the +// feature). +static void AttachLocationToMetadata(xla::OpMetadata& metadata, + OpKernel* op_kernel, XlaContext& context) { + if (const AbstractStackTrace* stack_trace = + context.StackTraceForNodeName(op_kernel->def().name())) { + if (std::optional frame = stack_trace->LastUserFrame()) { + metadata.set_source_file(frame->file_name); + metadata.set_source_line(frame->line_number); + } + } +} + +void XlaCompilationDevice::Compute(OpKernel* op_kernel, + OpKernelContext* context) { + VLOG(4) << "XlaCompilationDevice::Compute " + << FormatNodeDefForError(op_kernel->def()); + XlaContext& xla_context = XlaContext::Get(context); + auto* b = xla_context.builder(); + xla::OpMetadata metadata; + metadata.set_op_type(op_kernel->type_string()); + metadata.set_op_name(op_kernel->name()); + AttachLocationToMetadata(metadata, op_kernel, xla_context); + b->SetOpMetadata(metadata); + + auto sharding_parse_result = + ParseShardingFromDevice(op_kernel->def(), std::numeric_limits::max(), + /*add_metadata=*/false); + OP_REQUIRES_OK(context, sharding_parse_result.status()); + std::optional op_sharding = sharding_parse_result.value(); + + auto frontend_attributes_result = + GetFrontendAttributesFromAttrSlice(AttrSlice(op_kernel->def())); + OP_REQUIRES_OK(context, frontend_attributes_result.status()); + std::optional attributes = + frontend_attributes_result.value(); + + xla::FrontendAttributes merged_attributes = b->frontend_attributes(); + if (attributes.has_value()) { + merged_attributes.mutable_map()->insert(attributes.value().map().begin(), + attributes.value().map().end()); + } + xla::XlaScopedFrontendAttributesAssignment assign_frontend_attributes( + b, std::move(merged_attributes)); + + // If no sharding metadata is found, XLA is free to use whatever device it + // wants. In practice this usually has the effect of placing things on device + // 0. + xla::XlaScopedShardingAssignment assign_sharding(b, op_sharding); + op_kernel->Compute(context); + + b->ClearOpMetadata(); + VLOG(4) << "Done"; +} + +absl::Status XlaCompilationDevice::Sync() { return absl::OkStatus(); } + +absl::Status XlaCompilationDevice::MakeTensorFromProto( + const TensorProto& tensor_proto, const AllocatorAttributes alloc_attrs, + Tensor* tensor) { + return absl::InvalidArgumentError( + "XLACompilationDevice::MakeTensorFromProto should not be called"); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compilation_device.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compilation_device.h new file mode 100644 index 0000000000000000000000000000000000000000..b9410d26df3159b80f972474632c59113e2c5c41 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compilation_device.h @@ -0,0 +1,69 @@ +/* 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_XLA_COMPILATION_DEVICE_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILATION_DEVICE_H_ + +#include + +#include "tensorflow/core/common_runtime/local_device.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mem.h" +#include "tensorflow/core/public/session_options.h" + +namespace tensorflow { + +// Class is defined in xla_compilation_device.cc, reference +// included here only so the XlaCompilationDevice allocator_ member can be +// declared. +class XlaCompilationAllocator; + +// This is a 'dummy' TensorFlow device that is only used to execute a +// subgraph of XLA compilation Ops to construct a compiled version +// of the subgraph's computation. It has a 'dummy' allocator that +// backs each Tensor with an XlaExpression. The shape of the Tensor +// matches the shape of XlaExpression. +// +// We deliberately don't register a device factory because we *never* +// want placement to put Ops on a compilation device. The device is created +// manually, not using a factory. +// +// XLA compilation is not thread-safe. OpKernels registered on the +// XlaCompilationDevice must not use threads or concurrency. +class XlaCompilationDevice : public LocalDevice { + public: + XlaCompilationDevice(const SessionOptions& options, DeviceType type); + + ~XlaCompilationDevice() override; + + Allocator* GetAllocator(AllocatorAttributes attr) override; + + void Compute(OpKernel* op_kernel, OpKernelContext* context) override; + + absl::Status Sync() override; + + absl::Status MakeTensorFromProto(const TensorProto& tensor_proto, + const AllocatorAttributes alloc_attrs, + Tensor* tensor) override; + + private: + std::unique_ptr allocator_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILATION_DEVICE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc new file mode 100644 index 0000000000000000000000000000000000000000..238f1b5c4243d625c105cf44087681f0c53c172f --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.cc @@ -0,0 +1,199 @@ +/* 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/xla_compiled_cpu_function.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/allocator.h" +#include "xla/backends/cpu/runtime/rng_state_lib.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +namespace { + +int32_t GetResultIndex(const int32_t* result_index_table, int32_t num_results) { + auto it = + std::min_element(result_index_table, result_index_table + num_results); + + if (it == result_index_table + num_results) { + return -1; + } + return *it; +} + +} // namespace + +XlaCompiledCpuFunction::XlaCompiledCpuFunction(const StaticData& static_data, + AllocMode alloc_mode) + : function_library_symbol_map_(&static_data.function_library_symbol_map_), + temp_allocation_index_(static_data.temp_allocation_index_), + thunk_run_impl_(static_data.thunk_run_impl_), + result_index_(GetResultIndex(static_data.result_index_table_, + static_data.num_results_)), + buffer_table_(new void*[static_data.num_buffers_]), + buffer_infos_(static_data.buffer_infos_), + num_buffers_(static_data.num_buffers_), + num_results_(static_data.num_results_), + result_index_table_(static_data.result_index_table_), + arg_index_table_(static_data.arg_index_table_), + num_args_(static_data.num_args_), + num_variables_(static_data.num_variables_), + arg_shape_infos_(static_data.arg_shape_infos_), + result_shape_infos_(static_data.result_shape_infos_), + arg_names_(static_data.arg_names_), + variable_names_(static_data.variable_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_VARIABLES_RESULTS_PROFILES_AND_TEMPS; + // Allocate arg and temp buffers. + alloc_buffer_table_ = tensorflow::MallocContiguousBuffers( + absl::MakeConstSpan(static_data.buffer_infos_, static_data.num_buffers_), + /*allocate_entry_params=*/allocate_entry_params, buffer_table_, + /*annotate_initialized=*/true); + // 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_t[static_data.profile_counters_size_](); + } + + // Setup constants. + if (!static_data.embedded_constant_buffers_.empty()) { + size_t embedded_constant_buffers_idx = 0; + for (size_t i = 0; i < num_buffers(); ++i) { + if (!buffer_infos()[i].is_constant()) { + continue; + } + + const auto& [buffer_size, buffer_data] = + static_data + .embedded_constant_buffers_[embedded_constant_buffers_idx++]; + + CHECK(buffer_size == buffer_infos()[i].size()); + + buffer_table()[i] = buffer_data; + } + + CHECK(embedded_constant_buffers_idx == + static_data.embedded_constant_buffers_.size()); + } + + // Setup rng states + { + rng_states_.reserve(static_data.rng_state_deltas_.size()); + for (int64_t delta : static_data.rng_state_deltas_) { + rng_states_.emplace_back(std::make_unique(delta)); + } + } +} + +bool XlaCompiledCpuFunction::Run() { + return thunk_run_impl_(buffer_table_, &run_options_, rng_states_); +} + +XlaCompiledCpuFunction::~XlaCompiledCpuFunction() { + FreeContiguous(alloc_buffer_table_); + delete[] buffer_table_; + delete[] profile_counters_; +} + +namespace { + +constexpr int kNotFound = -1; + +// Linear search through `names` looking for a match with `name`. Returns -1 if +// the name isn't found, or is empty. +// +// REQUIRES: `names` is a nullptr-terminated array. +int LookupNameIndex(absl::string_view name, const char** names) { + // Hitting this assert means that there is no name-to-index data available; + // for AOT try the setting the tfcompile --gen_name_to_index flag. + assert(names != nullptr); + + if (name.empty()) { + return kNotFound; + } + for (int index = 0; names[index] != nullptr; ++index) { + if (name == names[index]) { + return index; + } + } + return kNotFound; +} + +} // namespace + +int XlaCompiledCpuFunction::LookupArgIndex(const std::string& name) const { + return LookupNameIndex(name, arg_names_); +} + +int XlaCompiledCpuFunction::LookupVariableIndex(absl::string_view name) const { + int index = LookupNameIndex(name, variable_names_); + if (index == kNotFound) { + return kNotFound; + } + return num_args_ - num_variables_ + index; +} + +int XlaCompiledCpuFunction::LookupResultIndex(const std::string& name) const { + return LookupNameIndex(name, result_names_); +} + +const char* XlaCompiledCpuFunction::GetArgName(const int index) const { + assert(arg_names_ != nullptr); + if (index < 0 || index >= num_args_) { + std::cerr << "XlaCompiledCpuFunction::GetArgName: index '" << index + << "' out of range [0, " << num_args_ << "].\n"; + return nullptr; + } + return arg_names_[index]; +} + +const char* XlaCompiledCpuFunction::GetVariableName(int index) const { + assert(variable_names_ != nullptr); + if (index < 0 || index >= num_variables_) { + std::cerr << "XlaCompiledCpuFunction::GetVariableName: index '" << index + << "' out of range [0, " << num_variables_ << ").\n"; + return nullptr; + } + return variable_names_[index]; +} + +const char* XlaCompiledCpuFunction::GetResultName(int index) const { + assert(result_names_ != nullptr); + if (index < 0 || index >= num_results_) { + std::cerr << "XlaCompiledCpuFunction::GetResultName: index '" << index + << "' out of range [0, " << num_results_ << ").\n"; + return nullptr; + } + return result_names_[index]; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h new file mode 100644 index 0000000000000000000000000000000000000000..a44bbcb60eb88c3fbcab841ba6db80ea02bdcaec --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h @@ -0,0 +1,582 @@ +/* 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_XLA_COMPILED_CPU_FUNCTION_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILED_CPU_FUNCTION_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/encoded_buffer_allocation_info.h" +#include "xla/backends/cpu/alignment.h" +#include "xla/backends/cpu/buffer_allocation_info.h" +#include "xla/backends/cpu/runtime/rng_state_lib.h" +#include "xla/executable_run_options.h" +#include "xla/service/custom_call_status_internal.h" +#include "tensorflow/core/platform/types.h" + +// Forward-declare, rather than include, to reduce code size for users that +// never use this functionality. +namespace xla { +class ProgramShapeProto; +class HloProfilePrinterData; + +namespace cpu { + +class AotCompiledFunctionLibrary; +class CompilationResultProto; +class CpuExecutable; +class NanoRtExecutable; + +} // namespace cpu +} // namespace xla + +namespace tensorflow { + +// Forward-declare so that it can access StaticData. +class XlaCompiledCpuFunctionThunks; + +// Represents a function compiled by XLA, produced via either JIT or AOT. +// +// The Run method invokes the actual computation, with inputs read from arg +// buffers, and outputs written to result buffers. Each Run call may also use a +// set of temporary buffers for the computation. +// +// By default each instance of this class manages its own arg, result and temp +// buffers. The AllocMode constructor parameter may be used to modify the buffer +// allocation strategy. +// +// Under the default allocation strategy, this class is thread-compatible: +// o Calls to non-const methods require exclusive access to the object. +// o Concurrent calls to const methods are OK, if those calls are made while it +// is guaranteed that no thread may call a non-const method. +class XlaCompiledCpuFunction { + public: + // Type of the raw XLA Classic function, produced by either JIT or AOT. + using RawFunction = void (*)(void* result, + const xla::ExecutableRunOptions* run_options, + const void** args, void** temps, + XlaCustomCallStatus*, int64_t* profile_counters); + + // Simple struct to describe a tensor's shape. + // Note: this is a poor man's substitute for xla::ShapeProto, but we cannot + // depend on protobuf's in this library. + // TODO(ecg): extend ShapeInfo to support tuples, if needed. + struct ShapeInfo { + const int32_t* dimensions = nullptr; + int32_t num_dimensions = 0; + }; + + // 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. + // + // The contents of StaticData are XLA-internal implementation details and + // should not be relied on by clients (and therefore are private). + class StaticData { + public: + bool has_thunk_sequence() const { + return compilation_result_proto_ != nullptr; + } + + private: + // start thunk execution specific + const xla::cpu::CompilationResultProto* compilation_result_proto_ = nullptr; + + absl::flat_hash_map< + std::string, + /*xla::cpu::AotCompiledFunctionLibrary::FunctionPtr*/ void*> + function_library_symbol_map_; + + std::optional temp_allocation_index_ = std::nullopt; + // end thunk execution specific + + // Serialized thunk execution specific (used for AOT to avoid binary size + // issues) + std::function>&)> + thunk_run_impl_ = nullptr; + + std::vector> embedded_constant_buffers_; + + std::vector rng_state_deltas_; + // End serialized thunk execution specific + + // Contains information about the buffers used by the XLA computation. + const xla::cpu::BufferAllocationInfo* buffer_infos_ = nullptr; + int32_t num_buffers_ = 0; + + // Result parameter i is described by + // buffer_infos[result_index_table[i]]. + const int32_t* result_index_table_ = nullptr; + + // There are num_results result parameters. + int64_t num_results_ = 0; + + // Entry parameter i is described by + // buffer_infos[arg_index_table[i]]. + const int32_t* arg_index_table_ = nullptr; + + // There are num_args entry parameters. + int64_t num_args_ = 0; + + // There are num_variables variables. + int64_t num_variables_ = 0; + + // The 0-based index of the result tuple, in the temp buffers. + size_t result_index_ = 0; + + const ShapeInfo* arg_shape_infos_ = nullptr; + const ShapeInfo* result_shape_infos_ = nullptr; + + // [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** variable_names_ = nullptr; + const char** result_names_ = nullptr; + + // [Optional] Arg and result shapes. + const xla::ProgramShapeProto* program_shape_ = nullptr; + + // [Optional] Profile printer data. Null if profiling is disabled. + 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_t profile_counters_size_ = 0; + + // Only XlaCompiledCpuFunction is allowed to read and write the above + // fields. + friend class XlaCompiledCpuFunction; + friend class XlaCompiledCpuFunctionThunks; + }; + + // AllocMode controls the buffer allocation mode. + enum class AllocMode { + // Allocate all buffers - args, results, profile and temps. + ARGS_VARIABLES_RESULTS_PROFILES_AND_TEMPS, + + // Only allocate result, profile and temp buffers. + // Use set_arg_data to set argument buffers before Run is called. + RESULTS_PROFILES_AND_TEMPS_ONLY, + }; + + explicit XlaCompiledCpuFunction( + const StaticData& static_data, + AllocMode alloc_mode = + AllocMode::ARGS_VARIABLES_RESULTS_PROFILES_AND_TEMPS); + virtual ~XlaCompiledCpuFunction(); + + XlaCompiledCpuFunction(const XlaCompiledCpuFunction&) = delete; + XlaCompiledCpuFunction& operator=(const XlaCompiledCpuFunction&) = delete; + XlaCompiledCpuFunction(XlaCompiledCpuFunction&&) = default; + XlaCompiledCpuFunction& operator=(XlaCompiledCpuFunction&&) = default; + + // Sets the intra-op thread pool used to run individual ops concurrently. + virtual void set_thread_pool(const Eigen::ThreadPoolDevice* pool) { + run_options_.set_intra_op_thread_pool(pool); + } + + // Runs the computation, with inputs read from arg buffers, and outputs + // written to result buffers. Returns true on success and false on failure. + virtual bool Run(); + + // Returns the error message from the previous failed Run call. + // + // TODO(fschneider): For now this always returns an empty string because there + // is no support for error reporting in XLA. Remove this once all callers are + // updated. + std::string error_msg() const { return error_msg_; } + + void set_error_msg(absl::string_view error_msg) { error_msg_ = error_msg; } + + // ------------------------------ + // Arg methods for managing input buffers. Buffers are in row-major order. + + // Returns the buffer for the positional argument at the given `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_results() const { return num_results_; } + + int num_args() const { return num_args_; } + + int num_variables() const { return num_variables_; } + + // 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(); + } + + int result_size(int idx) const { + assert(idx < num_results()); + return buffer_infos_[result_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 + // AllocMode; if the AllocMode is RESULTS_AND_TEMPS_ONLY, this method must be + // called for each positional argument, in order to set the argument buffers. + // + // Allocated memory must be aligned to the size specified by + // xla::cpu::MinAlign(). + // + // Aliasing of argument and result buffers is not allowed, and results in + // undefined behavior. + void set_arg_data(size_t index, const void* data) { + assert((arg_size(index) < xla::cpu::MinAlign() || + (uintptr_t)data % xla::cpu::MinAlign() == 0) && + "Underaligned pointer!"); + // The const_cast is safe because the generated code does not write to arg + // buffers. + // + // buffer_table_ contains pointers to buffers that _will_ be written to by + // generated code so it would be misleading to make buffer_table_ a `const + // void**`. + buffer_table_[arg_index_table_[index]] = const_cast(data); + } + + // Profile counters for this XLA computation. + // + // When Hlo profiling is enabled (`hlo_profiling_enabled()` return true in + // this case) these counters are non-null and are automatically populated by + // `Run`. The counters can then be pretty-printed using + // `hlo_profile_printer()`. + // + // When Hlo profiling is disabled, this accessor returns null. + const int64_t* profile_counters() const { return profile_counters_; } + + // Returns the buffer for the positional result at the given `index`. + void* result_data(size_t index) { + return buffer_table_[result_index_table_[index]]; + } + const void* result_data(size_t index) const { + return buffer_table_[result_index_table_[index]]; + } + + // ------------------------------ + // Methods for extracting optional metadata. + + // Returns true iff data is available for the Lookup{Arg,Variable,Result}Index + // methods. E.g. the data might not be compiled into the binary for AOT. + bool HasNameIndices() const { + return arg_names_ != nullptr && variable_names_ != nullptr && + result_names_ != nullptr; + } + + // Returns the 0-based index for the argument with the given `name`. + // Returns -1 if the name wasn't found, or data isn't available. + // + // The index remains constant for every instance of XlaCompiledCpuFunction + // generated from the same static data, and might not be cheap to determine. + // Recommended usage is to capture this in a variable for re-use. + int LookupArgIndex(const std::string& name) const; + + // Returns the 0-based index for the variable with the given `name`. + // Returns -1 if the name wasn't found, or data isn't available. + // + // The index remains constant for every instance of XlaCompiledCpuFunction + // generated from the same static data, and might not be cheap to determine. + // Recommended usage is to capture this in a variable for re-use. + int LookupVariableIndex(absl::string_view name) const; + + // Returns the 0-based index for the result with the given `name`. + // Returns -1 if the name wasn't found, or data isn't available. + // + // The index remains constant for every instance of XlaCompiledCpuFunction + // generated from the same static data, and might not be cheap to determine. + // Recommended usage is to capture this in a variable for re-use. + int LookupResultIndex(const std::string& name) const; + + // Returns the name of the argument at `index`. + // Returns nullptr if `HasNameIndices() == false` or `index` is out of range. + const char* GetArgName(int index) const; + + // Returns the name of the variable at `index`. + // Returns nullptr if `HasNameIndices() == false` or `index` is out of range. + const char* GetVariableName(int index) const; + + // Returns the name of the result at `index`. + // Returns nullptr if `HasNameIndices() == false` or `index` is out of range. + const char* GetResultName(int index) const; + + // Returns the shape of the args and results. May return nullptr if the + // program shape isn't available. + const xla::ProgramShapeProto* ProgramShape() const { return program_shape_; } + + bool hlo_profiling_enabled() const { + return hlo_profile_printer_data_ != nullptr; + } + const xla::HloProfilePrinterData& hlo_profile_printer_data() const { + assert(hlo_profiling_enabled()); + return *hlo_profile_printer_data_; + } + + const absl::flat_hash_map< + std::string, + /*xla::cpu::AotCompiledFunctionLibrary::FunctionPtr*/ void*>& + function_library_symbol_map() const { + return *function_library_symbol_map_; + } + + const xla::ExecutableRunOptions* run_options() const { return &run_options_; } + + protected: + virtual bool is_thunk_mode() const { return true; } + + std::optional temp_allocation_index() const { + return temp_allocation_index_; + } + + const xla::cpu::BufferAllocationInfo* buffer_infos() const { + return buffer_infos_; + } + + int32_t num_buffers() const { return num_buffers_; } + + void** buffer_table() const { return buffer_table_; } + + // --------------------------------------------------------------------------- + // Accessors for reading from and writing to instances of `StaticData`. + // + // Classes generated by tfcompile can call these because the generated classes + // inherit from `XlaCompiledCpuFunction`. `XlaJitCompiledCpuFunction` can + // call these because it is explicitly added as a friend. + + static void set_static_data_function_library_symbol_map( + StaticData* static_data, + absl::flat_hash_map< + std::string, + /*xla::cpu::AotCompiledFunctionLibrary::FunctionPtr*/ void*> + function_library_symbol_map) { + static_data->function_library_symbol_map_ = + std::move(function_library_symbol_map); + } + + static void set_static_data_compilation_result_proto( + StaticData* static_data, + const xla::cpu::CompilationResultProto* compilation_result_proto) { + static_data->compilation_result_proto_ = compilation_result_proto; + } + + static void set_static_data_thunk_run_impl( + StaticData* static_data, + std::function>&)> + thunk_run_impl) { + static_data->thunk_run_impl_ = std::move(thunk_run_impl); + } + + static void set_static_data_embedded_constant_buffers( + StaticData* static_data, + std::vector> embedded_constant_buffers) { + static_data->embedded_constant_buffers_ = + std::move(embedded_constant_buffers); + } + + static void set_static_data_rng_state_deltas( + StaticData* static_data, std::vector rng_state_deltas) { + static_data->rng_state_deltas_ = std::move(rng_state_deltas); + } + + static void set_static_data_buffer_infos( + StaticData* static_data, + const xla::cpu::BufferAllocationInfo* buffer_infos) { + static_data->buffer_infos_ = buffer_infos; + } + + static void set_static_data_num_buffers(StaticData* static_data, + size_t num_buffers) { + static_data->num_buffers_ = num_buffers; + } + + static void set_static_data_result_index_table( + StaticData* static_data, const int32_t* result_index_table) { + static_data->result_index_table_ = result_index_table; + } + + static void set_static_data_num_results(StaticData* static_data, + int64_t num_results) { + static_data->num_results_ = num_results; + } + + static void set_static_data_arg_index_table(StaticData* static_data, + const int32_t* arg_index_table) { + static_data->arg_index_table_ = arg_index_table; + } + + static void set_static_data_num_args(StaticData* static_data, + int64_t num_args) { + static_data->num_args_ = num_args; + } + + static void set_static_data_num_variables(StaticData* static_data, + int64_t num_variables) { + static_data->num_variables_ = num_variables; + } + + static void set_static_data_temp_allocation_index( + StaticData* static_data, + const std::optional temp_allocation_index) { + static_data->temp_allocation_index_ = temp_allocation_index; + } + + static void set_static_data_result_index(StaticData* static_data, + size_t result_index) { + static_data->result_index_ = result_index; + } + + static void set_static_data_arg_shape_infos(StaticData* static_data, + const ShapeInfo* shape_infos) { + static_data->arg_shape_infos_ = shape_infos; + } + + static void set_static_data_result_shape_infos(StaticData* static_data, + const ShapeInfo* shape_infos) { + static_data->result_shape_infos_ = shape_infos; + } + + static void set_static_data_arg_names(StaticData* static_data, + const char** arg_names) { + static_data->arg_names_ = arg_names; + } + + static void set_static_data_variable_names(StaticData* static_data, + const char** variable_names) { + static_data->variable_names_ = variable_names; + } + + static void set_static_data_result_names(StaticData* static_data, + const char** result_names) { + static_data->result_names_ = result_names; + } + + static void set_static_data_program_shape( + StaticData* static_data, const xla::ProgramShapeProto* program_shape) { + static_data->program_shape_ = program_shape; + } + + static void set_static_data_hlo_profile_printer_data( + StaticData* static_data, + const xla::HloProfilePrinterData* hlo_profile_printer_data) { + static_data->hlo_profile_printer_data_ = hlo_profile_printer_data; + } + + static const xla::HloProfilePrinterData* + get_static_data_hlo_profile_printer_data(StaticData* static_data) { + return static_data->hlo_profile_printer_data_; + } + + static void set_static_data_profile_counters_size( + StaticData* static_data, int64_t profile_counters_size) { + static_data->profile_counters_size_ = profile_counters_size; + } + + // TODO(ezhulenev): This is a no-op after removing xla runtime, however it is + // still required for building some targets. Figure out why and delete! + static void set_static_data_use_xla_runtime(StaticData* static_data, bool) {} + + private: + const absl::flat_hash_map< + std::string, + /*xla::cpu::AotCompiledFunctionLibrary::FunctionPtr*/ void*>* + function_library_symbol_map_; + + const std::optional temp_allocation_index_; + + std::function>&)> + thunk_run_impl_ = nullptr; + + std::vector> rng_states_; + + const size_t result_index_; + + // 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 xla::cpu::BufferAllocationInfo* const buffer_infos_; + const int32_t num_buffers_; + + // Indices of expanded result tuple. + const int32_t num_results_; + const int32_t* const result_index_table_; + + // 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. + const int32_t* const arg_index_table_; + + // The number of incoming arguments. + const int32_t num_args_; + + // The number of incoming variables. + const int32_t num_variables_; + + // Shapes of the input arguments. + const ShapeInfo* const arg_shape_infos_; + + // Shapes of the results. + const ShapeInfo* const result_shape_infos_; + + // Backing memory for buffer_table_ and args_, the latter depending on + // AllocMode. + void* alloc_buffer_table_ = nullptr; + + // Backing memory for profiling counters. + int64_t* profile_counters_ = nullptr; + + // Options and context passed to the compiled function. + xla::ExecutableRunOptions run_options_; + + // Optional metadata. + const char** arg_names_ = nullptr; + const char** variable_names_ = nullptr; + const char** result_names_ = nullptr; + const xla::ProgramShapeProto* program_shape_ = nullptr; + const xla::HloProfilePrinterData* hlo_profile_printer_data_ = nullptr; + + std::string error_msg_ = ""; + + // Add `XlaJitCompiledCpuFunction` as a friend so that it can access the + // `set_static_data_*` static methods above. + friend class XlaJitCompiledCpuFunction; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILED_CPU_FUNCTION_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_factory.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_factory.cc new file mode 100644 index 0000000000000000000000000000000000000000..f92e23604f132c7950d3dbd846ea1a36166837aa --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_factory.cc @@ -0,0 +1,49 @@ +/* Copyright 2025 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/xla_compiled_cpu_function_factory.h" + +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" + +namespace tensorflow { +namespace xla_compiled_cpu_function_factory { + +// Weak symbol to allow for the thunk factory to be registered by the +// xla_compiled_cpu_function_thunk_factory_registerer. This is a workaround that +// allows us to link in the thunk runtime without breaking AOT size constraints. +std::unique_ptr CreateXlaCompiledCpuFunctionThunks( + const XlaCompiledCpuFunction::StaticData& static_data, + XlaCompiledCpuFunction::AllocMode alloc_mode) __attribute__((weak)); + +absl::StatusOr> Create( + const XlaCompiledCpuFunction::StaticData& static_data, + XlaCompiledCpuFunction::AllocMode alloc_mode) { + if (static_data.has_thunk_sequence()) { + if (CreateXlaCompiledCpuFunctionThunks == nullptr) { + return absl::InternalError( + "XlaCompiledCpuFunctionThunks factory is not registered"); + } + return CreateXlaCompiledCpuFunctionThunks(static_data, alloc_mode); + } else { + return std::make_unique(static_data, alloc_mode); + } +} + +} // namespace xla_compiled_cpu_function_factory +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_factory.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_factory.h new file mode 100644 index 0000000000000000000000000000000000000000..aba69b2bcff3c7a398f2c5fa9fcfab8f8bc891f8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_factory.h @@ -0,0 +1,38 @@ +/* Copyright 2025 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_XLA_COMPILED_CPU_FUNCTION_FACTORY_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILED_CPU_FUNCTION_FACTORY_H_ + +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" + +namespace tensorflow { +namespace xla_compiled_cpu_function_factory { + +// A utility function to create an XlaCompiledCpuFunction. +absl::StatusOr> Create( + const XlaCompiledCpuFunction::StaticData& static_data, + XlaCompiledCpuFunction::AllocMode alloc_mode = XlaCompiledCpuFunction:: + AllocMode::ARGS_VARIABLES_RESULTS_PROFILES_AND_TEMPS); + +} // namespace xla_compiled_cpu_function_factory +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILED_CPU_FUNCTION_FACTORY_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunk_factory_registerer.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunk_factory_registerer.cc new file mode 100644 index 0000000000000000000000000000000000000000..dcc4b7d749059945a53ce9624450d24398af5df8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunk_factory_registerer.cc @@ -0,0 +1,32 @@ +/* Copyright 2025 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 + +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.h" + +namespace tensorflow { +namespace xla_compiled_cpu_function_factory { + +std::unique_ptr CreateXlaCompiledCpuFunctionThunks( + const XlaCompiledCpuFunction::StaticData& static_data, + XlaCompiledCpuFunction::AllocMode alloc_mode) { + return std::make_unique(static_data, + alloc_mode); +} + +} // namespace xla_compiled_cpu_function_factory +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.cc new file mode 100644 index 0000000000000000000000000000000000000000..454742ce4b07b8b1a39bf663b35f158004e7419d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.cc @@ -0,0 +1,128 @@ +/* Copyright 2025 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/xla_compiled_cpu_function_thunks.h" + +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/status/status.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" +#include "xla/backends/cpu/codegen/aot_compiled_function_library.h" +#include "xla/backends/cpu/nanort/nanort_executable.h" +#include "xla/backends/cpu/runtime/function_library.h" +#include "xla/service/cpu/cpu_aot_compilation_result.h" +#include "xla/tsl/concurrency/async_value_ref.h" + +namespace tensorflow { + +XlaCompiledCpuFunctionThunks::XlaCompiledCpuFunctionThunks( + const StaticData& static_data, AllocMode alloc_mode) + : XlaCompiledCpuFunction(static_data, alloc_mode) { + CHECK(static_data.compilation_result_proto_ != nullptr); + + std::unique_ptr function_library = + std::make_unique( + function_library_symbol_map()); + + auto aot_compilation_result = xla::cpu::CpuAotCompilationResult::FromString( + static_data.compilation_result_proto_->SerializeAsString(), + std::move(function_library)); + + // To load a CPU executable we don't need a compiler or a stream executor. + CHECK_OK(aot_compilation_result.status()); + // NO_CDC: aot_compilation_result is checked to be OK above. + auto cpu_executable = + std::move(*aot_compilation_result.value()).LoadExecutable(); + + CHECK_OK(cpu_executable.status()); + auto executable_or_err = + // NO_CDC: cpu_executable is checked to be OK above. + xla::cpu::NanoRtExecutable::Create(std::move(cpu_executable.value())); + + CHECK_OK(executable_or_err.status()); + // NO_CDC: executable_or_err is checked to be OK above. + executable_ = std::move(executable_or_err.value()); +} + +bool XlaCompiledCpuFunctionThunks::Run() { + auto ret = Execute(GenerateNanortArgs(), GenerateNanortResults(), + GenerateNanortPreallocatedTemp()); + + if (!ret.ok()) { + set_error_msg(ret.message()); + } + + return ret.ok(); +} + +std::vector +XlaCompiledCpuFunctionThunks::GenerateNanortArgs() { + std::vector arguments; + arguments.reserve(num_args()); + for (int i = 0; i < num_args(); ++i) { + arguments.push_back( + xla::cpu::NanoRtExecutable::Argument(arg_data(i), arg_size(i))); + } + + return arguments; +} + +std::vector +XlaCompiledCpuFunctionThunks::GenerateNanortResults() { + std::vector results; + results.reserve(num_results()); + for (int i = 0; i < num_results(); ++i) { + results.push_back( + xla::cpu::NanoRtExecutable::Result(result_data(i), result_size(i))); + } + + return results; +} + +xla::cpu::NanoRtExecutable::PreallocatedTemp +XlaCompiledCpuFunctionThunks::GenerateNanortPreallocatedTemp() { + xla::cpu::NanoRtExecutable::PreallocatedTemp temp; + + auto temp_allocation_index = this->temp_allocation_index(); + if (temp_allocation_index.has_value()) { + temp = xla::cpu::NanoRtExecutable::PreallocatedTemp( + static_cast(buffer_table()[*temp_allocation_index]), + buffer_infos()[*temp_allocation_index].size()); + } + + return temp; +} + +absl::Status XlaCompiledCpuFunctionThunks::Execute( + absl::Span arguments, + absl::Span results, + xla::cpu::NanoRtExecutable::PreallocatedTemp temp) { + auto event = + executable_->Execute(arguments, results, temp, thunk_run_options_); + tsl::BlockUntilReady(event); + + if (!event.IsConcrete()) { + return event.GetError(); + } + + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.h new file mode 100644 index 0000000000000000000000000000000000000000..ace78fd7e07b4bbdf1bdbd02cca07771c9e6eb0c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.h @@ -0,0 +1,66 @@ +/* Copyright 2025 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_XLA_COMPILED_CPU_FUNCTION_THUNKS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILED_CPU_FUNCTION_THUNKS_H_ + +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" +#include "xla/backends/cpu/nanort/nanort_executable.h" +#include "xla/executable_run_options.h" +#include "xla/service/cpu/executable.pb.h" +#include "xla/tsl/platform/threadpool.h" + +namespace tensorflow { + +class XlaCompiledCpuFunctionThunks : public XlaCompiledCpuFunction { + public: + explicit XlaCompiledCpuFunctionThunks( + const StaticData& static_data, + AllocMode alloc_mode = + AllocMode::ARGS_VARIABLES_RESULTS_PROFILES_AND_TEMPS); + + bool Run() override; + + bool is_thunk_mode() const override { return true; } + + void set_thread_pool(const Eigen::ThreadPoolDevice* pool) override { + thunk_run_options_.set_intra_op_thread_pool(pool); + } + + protected: + std::vector GenerateNanortArgs(); + std::vector GenerateNanortResults(); + xla::cpu::NanoRtExecutable::PreallocatedTemp GenerateNanortPreallocatedTemp(); + + private: + // For NanoRtExecutable. + absl::Status Execute( + absl::Span arguments, + absl::Span results, + xla::cpu::NanoRtExecutable::PreallocatedTemp temp); + + std::unique_ptr executable_; + xla::cpu::NanoRtExecutable::ExecuteOptions thunk_run_options_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILED_CPU_FUNCTION_THUNKS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler.cc new file mode 100644 index 0000000000000000000000000000000000000000..70df405d8260e4a81c21bd91823a4b500dd16cae --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler.cc @@ -0,0 +1,1893 @@ +/* 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/xla_compiler.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "tensorflow/compiler/mlir/tf2xla/mlir_bridge_rollout_policy.h" +#include "absl/algorithm/container.h" +#include "absl/container/flat_hash_map.h" +#include "absl/memory/memory.h" +#include "absl/status/status.h" +#include "absl/strings/string_view.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/variant.h" +#include "tensorflow/compiler/jit/defs.h" +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/compiler/jit/shape_inference.h" +#include "tensorflow/compiler/jit/xla_compile_util.h" +#include "tensorflow/compiler/mlir/tensorflow/utils/attribute_utils.h" +#include "tensorflow/compiler/mlir/tf2xla/api/v1/compile_mlir_util.h" +#include "tensorflow/compiler/mlir/utils/array_container_utils.h" +#include "tensorflow/compiler/tf2xla/graph_compiler.h" +#include "tensorflow/compiler/tf2xla/layout_util.h" +#include "tensorflow/compiler/tf2xla/rearrange_function_argument.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/sharding_util.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/tf2xla_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_compilation_device.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/client/client_library.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/protobuf_util.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/spmd/shardy/constants.h" +#include "xla/service/spmd/shardy/stablehlo_round_trip/stablehlo_import.h" +#include "xla/service/spmd/shardy/utils.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/executor.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/common_runtime/graph_optimizer.h" +#include "tensorflow/core/framework/attr_value_util.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/graph_debug_info.pb.h" +#include "tensorflow/core/framework/metrics.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/lib/gtl/cleanup.h" +#include "tensorflow/core/lib/hash/hash.h" +#include "tensorflow/core/platform/logging.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/protobuf/error_codes.pb.h" +#include "tensorflow/core/tpu/tpu_defs.h" +#include "tensorflow/core/util/debug_data_dumper.h" +#include "tensorflow/core/util/dump_graph.h" +#include "tsl/platform/errors.h" +#include "tsl/platform/tensor_float_32_utils.h" + +namespace tensorflow { +namespace { + +// Name of component for error logging. This name is fixed and required to +// enable logging. +constexpr char kSingleOpComponent[] = "TF2XLA_XLA_COMPILER_COMPILE_SINGLE_OP"; +constexpr char kCompileFunctionComponent[] = + "TF2XLA_XLA_COMPILER_COMPILE_FUNCTION"; + +// Checks that arguments `args` match types `types`. +absl::Status CheckSignature(const DataTypeVector& types, + absl::Span args) { + if (args.size() != types.size()) { + return absl::InternalError( + absl::StrCat("Compilation arguments have ", args.size(), + " elements while function has ", types.size())); + } + for (int i = 0, end = types.size(); i < end; ++i) { + // Don't perform type checks on resource variables and tensor + // lists (DT_VARIANT) as we have to trick the type system in order to + // plumb them through. DT_VARIANTS are wrapped in a DT_UINT8 tensor. + if (types[i] != args[i].type && types[i] != DT_RESOURCE && + types[i] != DT_VARIANT) { + return absl::InternalError(absl::StrCat( + "Argument ", i, " has declared type ", DataTypeString(args[i].type), + " but function parameter has type ", DataTypeString(types[i]))); + } + } + return absl::OkStatus(); +} + +// Uses the _Arg and _Retval nodes in the graph to determine an OpSharding for +// each argument and return value. +absl::StatusOr< + std::pair, std::map>> +ComputeArgAndRetvalShardings(const Graph& graph) { + auto get_sharding_for_node = + [](const Node* n) -> absl::StatusOr> { + TF_ASSIGN_OR_RETURN( + auto sharding, + ParseShardingFromDevice(*n, std::numeric_limits::max(), + /*add_metadata=*/false)); + return sharding; + }; + std::map arg_shardings; + std::map retval_shardings; + for (const Node* n : graph.nodes()) { + if (n->IsArg()) { + TF_ASSIGN_OR_RETURN(auto sharding, get_sharding_for_node(n)); + if (!sharding.has_value()) continue; + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); + TF_RET_CHECK(index >= 0) << "Negative _Arg index"; + arg_shardings[index] = std::move(*sharding); + } else if (n->IsRetval()) { + TF_ASSIGN_OR_RETURN(auto sharding, get_sharding_for_node(n)); + if (!sharding.has_value()) continue; + int index; + TF_RETURN_IF_ERROR(GetNodeAttr(n->attrs(), "index", &index)); + TF_RET_CHECK(index >= 0) << "Negative _Retval index"; + retval_shardings[index] = std::move(*sharding); + } + } + return std::make_pair(std::move(arg_shardings), std::move(retval_shardings)); +} + +// Due to the wonkiness with Resource Cleanup, changing how resources are +// cleaned up here need to change how resources are cleaned up in +// graph_compiler_test. +// LINT.IfChange(ExecuteGraph) +absl::Status ExecuteGraph(XlaContext* xla_context, std::unique_ptr graph, + XlaCompilationDevice* device, + FunctionLibraryRuntime* flib, int64_t step_id) { + // Resource cleanup is a bit messy. XlaContext is a ref-countd resource; the + // resource manager takes ownership via Create, and unrefs via Cleanup. We + // explicitly add a reference to ensure the refcount at entry is maintained at + // all exit points; Create and Cleanup are always called in this function. + // + // The Executor requires us to use ScopedStepContainer. We wrap it in a + // unique_ptr so we can capture the cleanup status in the end. + xla_context->Ref(); + absl::Status status; + auto step_container = std::make_unique( + step_id, [&status, device](const std::string& name) { + status = device->resource_manager()->Cleanup(name); + }); + TF_RETURN_IF_ERROR(step_container->Create(device->resource_manager(), + XlaContext::kXlaContextResourceName, + xla_context)); + + GraphCompiler graph_compiler(device, graph.get(), flib, step_container.get()); + TF_RETURN_IF_ERROR(graph_compiler.Compile()); + // Explicitly clean up the step container, to capture the cleanup status. + step_container.reset(); + return status; +} +// LINT.ThenChange(//tensorflow/compiler/tf2xla/graph_compiler_test.cc) + +// Builds the XLA computation. +// - `args` is the list of input arguments +// - `retvals` is the list of retvals produced by _Retval operators, in index +// order. +// - `arg_shardings` and `retval_shardings` are mapping from arg/return indices +// to sharding. +// - If `return_updated_values_for_all_resources` is true, all resources will be +// included in `resource_updates`, regardless of whether their value changed. +// - Sets `*num_nonconst_outputs` to the number of outputs of the `computation`. +// - Sets `*resource_updates` to a description of resources whose values are +// written by the computation; the variable writes are the last +// - `resource_updates.size()` return values from the computation. Each entry in +// `resource_updates` is a ResourceUpdate, whose `index` is the index of a +// resource variable argument to the computation to be updated, and `type` is +// the type of the final output. +absl::Status BuildComputation( + const std::vector& args, + const std::vector& retvals, + const std::map& arg_shardings, + const std::map& retval_shardings, + const std::vector>& resources, + std::unique_ptr token_output, + const XlaShapeLayoutHelpers::ShapeDeterminationFns& shape_determination_fns, + bool is_entry_computation, bool return_updated_values_for_all_resources, + bool always_return_tuple, bool use_tuple_arg, bool alias_resource_update, + xla::XlaBuilder* builder, xla::XlaComputation* computation, + int* num_computation_outputs, int* num_nonconst_outputs, + std::vector* outputs, + std::vector* resource_updates, + xla::Shape* output_shape, absl::Span input_mapping, + std::string& result_tuple_sdy_sharding, bool use_shardy_partitioner) { + // Attach a common operator name as metadata. This has no semantic effect — it + // merely makes the HLO graph more readable when visualized via TensorBoard, + // since TensorBoard forms groups out of operators with similar names. + xla::OpMetadata retval_metadata; + retval_metadata.set_op_name("XLA_Retvals"); + builder->SetOpMetadata(retval_metadata); + VLOG(1) << "Building new computation"; + auto cleanup = gtl::MakeCleanup([builder]() { builder->ClearOpMetadata(); }); + + // Builds a no-op XLA computation. We need to set the sharding of outputs, but + // cannot change the sharding of the existing output op. To do this, we build + // a new identity op to which shardings can be applied. + auto identity_op = [builder, is_entry_computation, use_shardy_partitioner]( + xla::XlaOp op, + const std::optional& sharding) + -> absl::StatusOr { + xla::XlaScopedShardingAssignment assign_sharding(builder, sharding); + xla::XlaOp copy_op = xla::Copy(op); + if (is_entry_computation && use_shardy_partitioner) { + // Add shardy shardings only for entry computation, as we only need to add + // it for wrapper main added in tensorflow. + TF_RETURN_IF_ERROR(addSdyShardingFrontendAttribute( + builder, copy_op, builder->GetShape(copy_op).value())); + } + return copy_op; + }; + + std::vector elems; + elems.reserve(retvals.size()); + + // Keeps track of sharding of each retval. If a retval is not in this list, + // replicate sharding is used. The first element is the output index, second + // element is the sharding. + std::unordered_map retval_index_and_sharding; + for (int i = 0, end = retvals.size(); i < end; ++i) { + XlaCompiler::OutputDescription& output = (*outputs)[i]; + const XlaExpression& retval = retvals[i]; + output.type = retval.dtype(); + switch (retval.kind()) { + case XlaExpression::Kind::kConstant: + output.is_constant = true; + output.constant_value = *retval.constant_value(); + output.shape = output.constant_value.shape(); + break; + + case XlaExpression::Kind::kTensorList: { + output.is_tensor_list = true; + xla::XlaOp value = retval.handle(); + elems.push_back(value); + break; + } + + case XlaExpression::Kind::kXlaOp: { + output.is_constant = false; + TF_ASSIGN_OR_RETURN(output.shape, retval.GetShape()); + xla::XlaOp value = retval.handle(); + auto it = retval_shardings.find(i); + std::optional sharding = + it == retval_shardings.end() ? std::optional() + : it->second; + if (it != retval_shardings.end()) { + retval_index_and_sharding[elems.size()] = it->second; + } + if (shape_determination_fns.shape_representation_fn) { + TF_ASSIGN_OR_RETURN(auto original_shape, builder->GetShape(value)); + TF_ASSIGN_OR_RETURN(value, + ReshapeWithCorrectRepresentationAndSharding( + builder, value, original_shape, + shape_determination_fns, sharding, + /*fast_mem=*/false)); + } + if (it != retval_shardings.end()) { + // Apply the sharding to the output, if there is a core assignment. + TF_ASSIGN_OR_RETURN(value, identity_op(value, sharding)); + } + + elems.push_back(value); + break; + } + + case XlaExpression::Kind::kResource: + // Resources will be pushed into elems later when processing resource + // arguments below. + output.is_constant = false; + output.input_index = retval.resource()->arg_num(); + output.shape = retval.resource()->shape(); + break; + + case XlaExpression::Kind::kInvalid: + return absl::InvalidArgumentError( + "Invalid expression returned by computation. " + "This probably means a return value was not set."); + } + } + *num_nonconst_outputs = elems.size(); + + // Add return values for resources whose values have changed. + std::vector arg_resources; + arg_resources.reserve(resources.size()); + for (const auto& resource : resources) { + if (resource->arg_num() >= 0) { + arg_resources.push_back(resource.get()); + } + } + std::sort(arg_resources.begin(), arg_resources.end(), + [](const XlaResource* a, const XlaResource* b) { + return a->arg_num() < b->arg_num(); + }); + + absl::flat_hash_map argument_to_xla_arg; + for (int xla_arg = 0; xla_arg < input_mapping.size(); xla_arg++) { + argument_to_xla_arg[input_mapping[xla_arg]] = xla_arg; + } + + std::vector aliases; + for (const XlaResource* resource : arg_resources) { + DCHECK_LT(resource->arg_num(), args.size()); + const XlaCompiler::Argument& arg = args[resource->arg_num()]; + auto it = arg_shardings.find(resource->arg_num()); + bool modified = !resource->value().IsIdenticalTo(resource->initial_value()); + // TensorArray gradients were modified if their values changed or there are + // any newly created gradients. + for (const auto& grad : resource->tensor_array_gradients()) { + modified = + modified || + !grad.second->value().IsIdenticalTo(grad.second->initial_value()) || + arg.tensor_array_gradients.count(grad.first) == 0; + } + + if (return_updated_values_for_all_resources || modified || + arg.requires_broadcast) { + resource_updates->emplace_back(); + XlaCompiler::ResourceUpdate& update = resource_updates->back(); + update.input_index = resource->arg_num(); + update.type = resource->type(); + update.shape = resource->shape(); + update.modified = modified; + int param_num = use_tuple_arg ? 0 : update.input_index; + if (is_entry_computation && + arg.resource_kind != XlaResource::kTensorArray && + alias_resource_update && argument_to_xla_arg.count(param_num)) { + // Assuming tuple arg and results are used. + xla::ShapeIndex param_index = + use_tuple_arg ? xla::ShapeIndex({update.input_index}) + : xla::ShapeIndex{}; + int xla_param_num = argument_to_xla_arg[param_num]; + int64_t output_index_num = elems.size(); + xla::ShapeIndex output_index = xla::ShapeIndex({output_index_num}); + VLOG(3) << "Storing alias: " << output_index.ToString() << ": (" + << xla_param_num << ", " << param_index.ToString() << ")"; + aliases.push_back({output_index, xla_param_num, param_index}); + } + for (const auto& grad : resource->tensor_array_gradients()) { + update.tensor_array_gradients_accessed.insert(grad.first); + } + + xla::XlaOp handle; + TF_RETURN_IF_ERROR(resource->Pack(&handle, builder)); + auto sharding = it == arg_shardings.end() + ? std::optional() + : it->second; + // Set layout of the retval to device representation layout. + if (shape_determination_fns.layout_preference_fn && + shape_determination_fns.shape_representation_fn) { + TF_ASSIGN_OR_RETURN(auto original_shape, builder->GetShape(handle)); + TF_ASSIGN_OR_RETURN( + handle, ReshapeWithCorrectRepresentationAndSharding( + builder, handle, original_shape, + shape_determination_fns, sharding, arg.fast_mem)); + } + + // Request that the value be returned on a specific core. + if (it != arg_shardings.end()) { + retval_index_and_sharding[elems.size()] = it->second; + } + // Ensures the correct sharding is applied to the output. + TF_ASSIGN_OR_RETURN(handle, identity_op(handle, sharding)); + elems.push_back(handle); + } + } + + // If we have token output, append it as the last one. + if (token_output) { + elems.push_back(*token_output); + } + + *num_computation_outputs = elems.size(); + + // Builds the XLA computation. We *always* form a tuple here to ensure that + // the output value is the last thing added into the XLA computation, even + // if there is only one output value. + xla::XlaOp tuple; + if (retval_index_and_sharding.empty() || !is_entry_computation) { + tuple = xla::Tuple(builder, elems); + } else { + std::vector elem_shapes; + for (const auto& elem : elems) { + TF_ASSIGN_OR_RETURN(xla::Shape elem_shape, + elem.builder()->GetShape(elem)); + elem_shapes.push_back(elem_shape); + } + xla::Shape shape = xla::ShapeUtil::MakeTupleShape(elem_shapes); + // Copy specified sharding from retval_index_and_sharding. + std::vector sharding_elems; + for (int i = 0, end = elems.size(); i < end; i++) { + const auto& iter = retval_index_and_sharding.find(i); + TF_RET_CHECK(iter != retval_index_and_sharding.end()); + const xla::OpSharding& sub_op_sharding = iter->second; + TF_ASSIGN_OR_RETURN(xla::HloSharding sub_sharding, + xla::HloSharding::FromProto(sub_op_sharding)); + if (elem_shapes[i].IsTuple()) { + const std::vector sub_sharding_elems = + sub_sharding.tuple_elements(); + const int64_t sub_sharding_elems_size = sub_sharding_elems.size(); + TF_RET_CHECK(sub_sharding_elems_size == + xla::ShapeUtil::GetLeafCount(elem_shapes[i])); + for (const auto& sub_sharding_elem : sub_sharding_elems) { + sharding_elems.push_back(sub_sharding_elem); + } + } else { + sharding_elems.push_back(sub_sharding); + } + } + xla::HloSharding modified_sharding = + xla::HloSharding::Tuple(shape, sharding_elems); + xla::OpSharding op_sharding = modified_sharding.ToProto(); + // Assign proper sharding to the tuple instruction. + xla::XlaScopedShardingAssignment assign_sharding(builder, op_sharding); + tuple = xla::Tuple(builder, elems); + if (use_shardy_partitioner && builder->sharding().has_value()) { + result_tuple_sdy_sharding = + xla::sdy::convertToSdySharding(op_sharding, shape, + /*openDims=*/false, + /*inlineMesh=*/true); + } + } + bool returns_tuple = always_return_tuple || elems.size() != 1; + VLOG(3) << "Computation returns a tuple=" << returns_tuple; + if (!returns_tuple) { + xla::GetTupleElement(tuple, 0); + + for (xla::XlaBuilder::InputOutputAlias& alias : aliases) { + if (alias.output_index == xla::ShapeIndex({0})) { + VLOG(3) << "For aliased parameter " << alias.param_number << ": " + << alias.param_index.ToString() + << " normalizing output_index from {0} to {}, as a scalar is " + "returned from the cluster"; + alias.output_index = xla::ShapeIndex({}); + } + } + } + + for (xla::XlaBuilder::InputOutputAlias& alias : aliases) { + builder->SetUpAlias(alias.output_index, alias.param_number, + alias.param_index); + } + TF_ASSIGN_OR_RETURN(*computation, builder->Build()); + + TF_ASSIGN_OR_RETURN(auto program_shape, computation->GetProgramShape()); + *output_shape = program_shape.result(); + return absl::OkStatus(); +} + +} // namespace + +std::string XlaCompiler::Argument::HumanString() const { + std::string common; + if (!name.empty()) { + common = absl::StrCat(" name=", name); + } + absl::StrAppend(&common, " type=", DataTypeString(type), + " shape=", ShapeHumanString()); + absl::StrAppend( + &common, " is_same_data_across_replicas=", is_same_data_across_replicas); + switch (kind) { + case kInvalid: + return "invalid"; + case kConstant: + return absl::StrCat("kind=constant", common, + " value=", constant_value.DebugString()); + case kConstantResource: + return absl::StrCat("kind=constant-resource", common, + " value=", constant_value.DebugString()); + case kResource: { + std::string output = absl::StrCat( + "kind=resource", common, + " resource_kind=", XlaResource::KindToString(resource_kind), + " initialized=", initialized, " is_fast_mem=", fast_mem); + if (max_array_size >= 0) { + absl::StrAppend(&output, " max_array_size=", max_array_size); + } + if (!tensor_array_gradients.empty()) { + absl::StrAppend(&output, " tensor_array_gradients=", + absl::StrJoin(tensor_array_gradients, ",")); + } + return output; + } + case kParameter: + return absl::StrCat("kind=parameter", common); + case kTensorList: + return absl::StrCat("kind=tensorlist", common); + case kToken: + return absl::StrCat("token", common); + } +} + +std::vector XlaCompiler::Argument::DimensionSizes() const { + if (absl::holds_alternative(shape)) { + return xla::InlinedVectorToVector(std::get(shape).dim_sizes()); + } else { + return xla::SpanToVector(std::get(shape).dimensions()); + } +} + +absl::InlinedVector +XlaCompiler::Argument::DimensionSizesAsInlinedVector() const { + if (absl::holds_alternative(shape)) { + return std::get(shape).dim_sizes(); + } else { + auto v = std::get(shape).dimensions(); + return absl::InlinedVector(v.begin(), v.end()); + } +} + +std::string XlaCompiler::Argument::ShapeHumanString() const { + if (absl::holds_alternative(shape)) { + return std::get(shape).DebugString(); + } else { + return std::get(shape).ToProto().DebugString(); + } +} + +XlaCompiler::XlaCompiler(XlaCompiler::Options options) + : options_(options), + initialization_status_(absl::OkStatus()), + next_step_id_(1), + device_(new XlaCompilationDevice(SessionOptions(), options_.device_type)), + device_mgr_(absl::WrapUnique(device_)) { + CHECK(!options_.device_type.type_string().empty()); + if (options_.populate_resource_manager) { + initialization_status_ = + (*options_.populate_resource_manager)(device_->resource_manager()); + } + + local_flib_def_.reset(new FunctionLibraryDefinition(OpRegistry::Global(), + FunctionDefLibrary())); + local_pflr_.reset(new ProcessFunctionLibraryRuntime( + &device_mgr_, Env::Default(), /*config=*/nullptr, + options.graph_def_version, local_flib_def_.get(), OptimizerOptions())); + pflr_.reset(new ProcessFunctionLibraryRuntime( + &device_mgr_, Env::Default(), /*config=*/nullptr, + options.graph_def_version, options.flib_def, OptimizerOptions())); + + local_flib_runtime_ = local_pflr_->GetFLR(device_->name()); + flib_runtime_ = pflr_->GetFLR(device_->name()); + + // The default layout preference is no preference and the default shape + // representation function is the identity. + XlaShapeLayoutHelpers::ShapeDeterminationFns& shape_determination_fns = + options_.shape_determination_fns; + if (!shape_determination_fns.shape_representation_fn) { + shape_determination_fns.shape_representation_fn = + IdentityShapeRepresentationFn(); + } + if (!shape_determination_fns.layout_preference_fn) { + shape_determination_fns.layout_preference_fn = UseNoPreferenceLayoutFn(); + } +} + +XlaCompiler::~XlaCompiler() = default; + +int64_t XlaCompiler::NextStepId() { return next_step_id_++; } + +uint64_t XlaCompiler::SignatureHash::operator()( + const std::pair>& signature) const { + return std::hash()(signature.first); +} + +static absl::Status GetFunctionBody(const NameAttrList& function, + FunctionLibraryRuntime* flib_runtime, + const FunctionBody** fbody) { + FunctionLibraryRuntime::Handle handle; + TF_RETURN_IF_ERROR(flib_runtime->Instantiate( + function.name(), AttrSlice(&function.attr()), &handle)); + + *fbody = flib_runtime->GetFunctionBody(handle); + TF_RET_CHECK(*fbody); + return absl::OkStatus(); +} + +absl::Status XlaCompiler::FindFunctionBody(const NameAttrList& function, + const FunctionBody** fbody, + const ConfigProto** config_proto) { + // The function may be in either the local_flib_runtime_ or flib_runtime_. + // Look up the function in local first and if it is not found then look up the + // function in flib_runtime_. + auto status = GetFunctionBody(function, local_flib_runtime_, fbody); + if (!status.ok()) { + if (!absl::IsNotFound(status)) { + return status; + } + TF_RETURN_WITH_CONTEXT_IF_ERROR( + GetFunctionBody(function, flib_runtime_, fbody), + "Local lookup failed with: ", status.message()); + if (config_proto) { + *config_proto = flib_runtime_->config_proto(); + } + VLOG(4) << "Function " << function.name() << " in flib_runtime_"; + } else { + if (config_proto) { + *config_proto = local_flib_runtime_->config_proto(); + } + VLOG(4) << "Function " << function.name() << " in local_flib_runtime_"; + } + return absl::OkStatus(); +} + +std::unique_ptr XlaCompiler::GetGraph(const FunctionBody* fbody) { + std::unique_ptr graph(new Graph(options_.flib_def)); + CopyGraph(*fbody->graph, graph.get()); + + bool is_inside_mustcompile = false; + TryGetNodeAttr(AttrSlice(&fbody->record->fdef().attr()), kXlaMustCompileAttr, + &is_inside_mustcompile); + + // Performs a first function inlining pass before shape inference, since + // otherwise shape inference can't see inside functions and a comprehensive + // shape_map, including function ops, is needed to constant-propagate Shape + // Ops below. + auto flags = GetBuildXlaOpsPassFlags(); + OptimizerOptions opts; + opts.set_opt_level(OptimizerOptions::L0); + opts.set_do_common_subexpression_elimination(false); + opts.set_do_function_inlining(true); + opts.set_do_constant_folding(!flags->tf_xla_disable_constant_folding); + GraphOptimizer optimizer(opts); + // Do not constant fold nodes that output DT_VARIANT type tensors. + // XLA does not support Const nodes of Variant type since it needs + // to know the original ops to be able to compile them to the relevant + // XLA form. + // TODO(srbs): This filter is a little conservative. E.g. a subgraph of + // the form: + // Const + // | + // EmptyTensorList -> TensorListPushBack -> TensorListPopBack -> Op + // | + // (Discard popped list) + // + // Would have been reduced to "Const -> Op" without this filter. + // However since we are only allowed to specify the filter at the "Node" + // level there is no good way to allow the above behavior. So we + // disallow any sort of constant folding on Variant nodes for now. + // + // Also do not consider constant folding Shape ops. When there is a dynamic + // dimension in a tensor, TF2XLA currently represent them as the static + // upperbound shape, which can be constant folded and then lose the info + // that this Shape is dynamic. + auto cf_consider_fn = [](const Node* n) { + for (const auto& output_arg : n->op_def().output_arg()) { + if (output_arg.type() == DT_VARIANT) { + return false; + } + } + const auto& ts = n->type_string(); + // XLA has special logic to handle dynamic shapes, don't constant fold + // them. + if (ts == "Shape" || ts == "ShapeN" || ts == "Size") { + return false; + } + return true; + }; + GraphOptimizer::Options graph_optimizer_options; + graph_optimizer_options.cf_consider_fn = cf_consider_fn; + graph_optimizer_options.inline_multi_device_functions = true; + graph_optimizer_options.inline_impl_selection_group_functions = true; + graph_optimizer_options.inline_with_single_device_body_placer = true; + graph_optimizer_options.ignore_noinline = is_inside_mustcompile; + + { + GraphShapeInfo shape_info; + InferShapes(graph.get(), /*arg_shapes=*/{}, + flib_runtime_->GetFunctionLibraryDefinition(), &shape_info) + .IgnoreError(); + auto node_name_index = graph->BuildNodeNameIndex(); + std::unordered_map> shape_map; + for (const auto& node_shape_info : shape_info) { + const std::string& node_name = node_shape_info.first; + const std::vector& output_shapes = node_shape_info.second; + const auto& node_iter = node_name_index.find(node_name); + if (node_iter != node_name_index.end()) { + auto& partial_shapes = shape_map[node_name]; + for (const auto& inferred_shape : output_shapes) { + partial_shapes.push_back(inferred_shape.shape); + } + } + } + graph_optimizer_options.shape_map = &shape_map; + optimizer.Optimize(flib_runtime_, flib_runtime_->env(), + /*device=*/nullptr, &graph, graph_optimizer_options); + } + + // Run shape inference on the graph and optimize the graph again. + GraphShapeInfo shape_info; + InferShapes(graph.get(), /*arg_shapes=*/{}, + flib_runtime_->GetFunctionLibraryDefinition(), &shape_info) + .IgnoreError(); + auto node_name_index = graph->BuildNodeNameIndex(); + std::unordered_map> shape_map; + for (const auto& node_shape_info : shape_info) { + const std::string& node_name = node_shape_info.first; + const std::vector& output_shapes = node_shape_info.second; + const auto& node_iter = node_name_index.find(node_name); + if (node_iter != node_name_index.end()) { + auto& partial_shapes = shape_map[node_name]; + for (const auto& inferred_shape : output_shapes) { + partial_shapes.push_back(inferred_shape.shape); + } + } + } + graph_optimizer_options.shape_map = &shape_map; + optimizer.Optimize(flib_runtime_, flib_runtime_->env(), + /*device=*/nullptr, &graph, graph_optimizer_options); + + return graph; +} + +// Collects all control rets from `orig_control_ret_nodes` that are still valid, +// keeping the same order. +std::vector GetValidControlRets( + absl::Span orig_control_ret_nodes, const Graph& graph) { + // Build map from control ret node name to index. + // We use Node name instead of Node* here to index into the map as we populate + // the map with nodes in FunctionDef control_ret_nodes and later query it + // using the nodes in `graph`. The Node pointers would be different but the + // Node name is expected to remain the same between the two. + absl::flat_hash_map control_ret_nodes_map; + for (int i = 0; i < orig_control_ret_nodes.size(); ++i) { + const Node* n = orig_control_ret_nodes[i]; + control_ret_nodes_map[n->name()] = i; + } + // Check which control rets are still valid. + std::vector is_valid_control_ret(orig_control_ret_nodes.size(), false); + int num_valid_control_rets = 0; + for (const Node* n : graph.nodes()) { + auto iter = control_ret_nodes_map.find(n->name()); + if (iter != control_ret_nodes_map.end()) { + ++num_valid_control_rets; + is_valid_control_ret[iter->second] = true; + } + } + // Return valid control rets in same order as they appear in + // `orig_control_ret_nodes`. + std::vector valid_control_rets; + valid_control_rets.reserve(num_valid_control_rets); + for (int i = 0; i < orig_control_ret_nodes.size(); ++i) { + if (is_valid_control_ret[i]) { + valid_control_rets.push_back(orig_control_ret_nodes[i]->name()); + } + } + return valid_control_rets; +} + +absl::Status XlaCompiler::CompileSingleOp( + const XlaCompiler::CompileOptions& compile_options, + const XlaCompiler::SingleOpCompileArgument& single_op_compile_argument, + absl::Span args, XlaCompiler::CompilationResult* result) { + const NodeDef& node_def = single_op_compile_argument.node_def; + TF_ASSIGN_OR_RETURN( + auto graph, + CreateSingleOpGraph(node_def, args, + single_op_compile_argument.output_dtypes)); + + *result = {}; + absl::Status status = ADD_SOURCE_LOCATION(CompileGraph( + compile_options, node_def.name(), std::move(graph), args, result)); + if (status.ok()) { + tensorflow::metrics::IncrementPhase2XlaCompilerCounter( + tensorflow::metrics::Phase2XlaCompilerMetric:: + kCompileSingleOpXlaBuilderSuccess); + } else { + tensorflow::metrics::IncrementPhase2XlaCompilerCounter( + tensorflow::metrics::Phase2XlaCompilerMetric:: + kCompileSingleOpXlaBuilderFailure); + tsl::error_logging::Log(mlir::TF::kBridgeComponent, kSingleOpComponent, + status.ToString()) + .IgnoreError(); + } + return status; +} + +absl::Status XlaCompiler::CompileFunction( + const XlaCompiler::CompileOptions& options, + const NameAttrList& fn_name_attrs, + absl::Span args, + XlaCompiler::CompilationResult* result) { + std::string function_id = + Canonicalize(fn_name_attrs.name(), AttrSlice(&fn_name_attrs.attr())); + VLOG(1) << "XlaCompiler::CompileFunction " << function_id; + + const std::vector arg_vector(args.begin(), args.end()); + auto it = cache_.find({function_id, arg_vector}); + if (it != cache_.end()) { + *result = it->second; + return absl::OkStatus(); + } + + const FunctionBody* fbody; + const ConfigProto* config = nullptr; + TF_RETURN_IF_ERROR(FindFunctionBody(fn_name_attrs, &fbody, &config)); + + std::optional config_proto; + if (config) { + config_proto = *config; + } + + TF_RETURN_WITH_CONTEXT_IF_ERROR( + CheckSignature(fbody->arg_types, args), + "Signature check failure while compiling: ", fn_name_attrs.name()); + + // Set shapes for _Arg nodes. They are useful for constant folding (e.g. an + // Xla op requires a compile-time constant input, and that input is shape of + // an _Arg node. + for (int i = 0, end = args.size(); i < end; i++) { + // Skip resource variables and tensor lists. + DataType dtype; + TF_RETURN_IF_ERROR(GetNodeAttr(fbody->arg_nodes[i]->def(), "T", &dtype)); + if (dtype == DT_RESOURCE || dtype == DT_VARIANT) { + continue; + } + + if (absl::holds_alternative(args[i].shape)) { + xla::Shape xla_shape = std::get(args[i].shape); + TensorShape tensor_shape; + // If xla_shape is dynamic, prevent constant folding by not setting + // output_shapes. + if (XLAShapeToTensorShape(xla_shape, &tensor_shape).ok() && + xla_shape.is_static()) { + fbody->arg_nodes[i]->ClearAttr("_output_shapes"); + fbody->arg_nodes[i]->AddAttr("_output_shapes", + std::vector{tensor_shape}); + } + } else { + TensorShape tensor_shape = std::get(args[i].shape); + fbody->arg_nodes[i]->ClearAttr("_output_shapes"); + fbody->arg_nodes[i]->AddAttr("_output_shapes", + std::vector{tensor_shape}); + } + } + + std::unique_ptr graph = GetGraph(fbody); + + // _Arg and _Retval nodes don't exist in the stored subgraph for the function; + // they are added by the function body looked up. Therefore, they don't have + // core assignments here. + // Attempt to assign a core to each _Retval and _Arg. Chooses the + // lowest-numbered core that consumes the argument. We choose the + // lowest-numbered core so the assignment is deterministic. + for (Node* n : graph->nodes()) { + if (n->IsArg()) { + TF_RETURN_IF_ERROR(SetNodeShardingFromNeighbors(n, /*out_edges=*/true)); + } + } + // Do _Retval as a second loop, in case the retval's input is an _Arg (which + // may have gotten a device assignment from the first loop). + for (Node* n : graph->nodes()) { + if (n->IsRetval()) { + TF_RETURN_IF_ERROR(SetNodeShardingFromNeighbors(n, /*out_edges=*/false)); + } + } + + if (VLOG_IS_ON(2)) { + VLOG(2) << "XlaCompiler::CompileFunction: " + << DumpGraphToFile( + absl::StrCat("xla_compile_function_", function_id), *graph); + } + + VLOG(1) << "===================================================="; + + VLOG(1) << "CompileFunction with XlaBuilder"; + auto status = + CompileGraph(options, function_id, std::move(graph), args, result); + if (!status.ok()) { + tensorflow::metrics::IncrementPhase2XlaCompilerCounter( + tensorflow::metrics::Phase2XlaCompilerMetric:: + kCompileFunctionXlaBuilderFailure); + ::tsl::errors::AppendToMessage( + &status, "tf2xla conversion failed while converting ", + std::move(function_id), + ". Run with TF_DUMP_GRAPH_PREFIX=/path/to/dump/dir and " + "--vmodule=xla_compiler=2 to obtain a dump of the compiled " + "functions."); + tsl::error_logging::Log(mlir::TF::kBridgeComponent, + kCompileFunctionComponent, status.ToString()) + .IgnoreError(); + return status; + } + + tensorflow::metrics::IncrementPhase2XlaCompilerCounter( + tensorflow::metrics::Phase2XlaCompilerMetric:: + kCompileFunctionXlaBuilderSuccess); + VLOG(1) << "===================================================="; + cache_[{function_id, arg_vector}] = *result; + return absl::OkStatus(); +} + +// Computes the XLA shape for argument 'arg'. +absl::Status XlaCompiler::XLAShapeForArgument( + const XlaCompiler::Argument& arg, bool is_entry_computation, + const std::optional& arg_sharding, + xla::Shape* xla_shape) const { + switch (arg.kind) { + case XlaCompiler::Argument::kConstant: + LOG(FATAL) << "Unreachable case"; + case XlaCompiler::Argument::kParameter: { + if (is_entry_computation) { + TensorShape shape; + if (std::holds_alternative(arg.shape)) { + shape = std::get(arg.shape); + } else { + TF_RETURN_IF_ERROR( + XLAShapeToTensorShape(std::get(arg.shape), &shape)); + } + auto layout_preference = + options_.shape_determination_fns.layout_preference_fn( + shape, arg.type, arg.kind); + TF_ASSIGN_OR_RETURN( + *xla_shape, + options_.shape_determination_fns.shape_representation_fn( + shape, arg.type, + /*use_fast_memory=*/false, layout_preference)); + TF_RETURN_IF_ERROR(RewriteLayoutWithShardedShape( + arg_sharding, /*use_fast_memory=*/false, + options_.shape_determination_fns, xla_shape)); + // If the arg is dynamic then we update the shape to reflect that. The + // layout etc above lose it by forcing a swap to TensorShape. + if (std::holds_alternative(arg.shape) && + std::get(arg.shape).is_dynamic()) { + xla::Shape dynamic_shape = std::get(arg.shape); + for (int i = 0; i < xla_shape->dimensions().size(); ++i) { + xla_shape->set_dynamic_dimension( + i, dynamic_shape.is_dynamic_dimension(i)); + } + } + } else { + if (std::holds_alternative(arg.shape)) { + *xla_shape = std::get(arg.shape); + } else { + TF_RETURN_IF_ERROR(TensorShapeToXLAShape( + arg.type, std::get(arg.shape), xla_shape)); + } + } + return absl::OkStatus(); + } + case XlaCompiler::Argument::kTensorList: { + TF_RET_CHECK(absl::holds_alternative(arg.shape)); + *xla_shape = std::get(arg.shape); + return absl::OkStatus(); + } + case XlaCompiler::Argument::kConstantResource: + case XlaCompiler::Argument::kResource: { + TF_RET_CHECK(arg.initialized); + + switch (arg.resource_kind) { + case XlaResource::kVariable: { + TF_RET_CHECK(absl::holds_alternative(arg.shape)); + auto layout_preference = + options_.shape_determination_fns.layout_preference_fn( + std::get(arg.shape), arg.type, arg.kind); + TF_ASSIGN_OR_RETURN( + *xla_shape, + options_.shape_determination_fns.shape_representation_fn( + std::get(arg.shape), arg.type, + /*use_fast_memory=*/arg.fast_mem, layout_preference)); + TF_RETURN_IF_ERROR(RewriteLayoutWithShardedShape( + arg_sharding, arg.fast_mem, options_.shape_determination_fns, + xla_shape)); + return absl::OkStatus(); + } + case XlaResource::kTensorArray: { + if (arg.max_array_size < 0) { + return absl::InvalidArgumentError( + "Negative max_array_size in XLAShapeForArgument"); + } + TF_RET_CHECK(absl::holds_alternative(arg.shape)); + TensorShape shape; + TF_RETURN_IF_ERROR(shape.AddDimWithStatus(arg.max_array_size)); + shape.AppendShape(std::get(arg.shape)); + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(arg.type, shape, xla_shape)); + + if (!arg.tensor_array_gradients.empty()) { + std::vector tuple_shape( + arg.tensor_array_gradients.size() + 1, *xla_shape); + *xla_shape = xla::ShapeUtil::MakeTupleShape(tuple_shape); + } + return absl::OkStatus(); + } + case XlaResource::kStack: { + if (arg.max_array_size < 0) { + return absl::InvalidArgumentError( + "Negative max_array_size in XLAShapeForArgument"); + } + TF_RET_CHECK(absl::holds_alternative(arg.shape)); + TensorShape shape; + TF_RETURN_IF_ERROR(shape.AddDimWithStatus(arg.max_array_size)); + shape.AppendShape(std::get(arg.shape)); + xla::Shape buffer_shape; + TF_RETURN_IF_ERROR( + TensorShapeToXLAShape(arg.type, shape, &buffer_shape)); + *xla_shape = xla::ShapeUtil::MakeTupleShape( + {buffer_shape, xla::ShapeUtil::MakeShape(xla::S32, {})}); + return absl::OkStatus(); + } + + case XlaResource::kInvalid: + return absl::InternalError( + "Invalid resource type in XLAShapeForArgument()"); + } + } + case XlaCompiler::Argument::kToken: { + *xla_shape = xla::ShapeUtil::MakeTokenShape(); + return absl::OkStatus(); + } + case XlaCompiler::Argument::kInvalid: + return absl::InternalError( + "Invalid argument type in XLAShapeForArgument()"); + } +} + +/* static */ +void XlaCompiler::PopulateArgumentFromResource(const XlaResource& resource, + Argument* arg) { + arg->initialized = resource.initialized(); + arg->kind = XlaCompiler::Argument::kResource; + arg->resource_kind = resource.kind(); + + arg->type = resource.type(); + arg->shape = resource.shape(); + arg->max_array_size = resource.max_array_size(); + for (const auto& gradient : resource.tensor_array_gradients()) { + arg->tensor_array_gradients.insert(gradient.first); + } + arg->name = resource.name(); +} + +XlaCompiler::SingleOpCompileArgument::SingleOpCompileArgument( + const OpKernelContext& ctx) { + std::vector output_dtypes(ctx.num_outputs()); + for (int i = 0; i < output_dtypes.size(); ++i) { + output_dtypes[i] = ctx.expected_output_dtype(i); + } + this->output_dtypes = output_dtypes; + this->node_def = ctx.op_kernel().def(); + auto* config_proto = ctx.function_library()->config_proto(); + if (config_proto != nullptr) { + this->config_proto = *config_proto; + } +} + +// Builds XLA computations for each of the arguments to the computation. +// `args` are the arguments to the computation. +absl::Status XlaCompiler::BuildArguments( + const Graph& graph, const std::vector& args, + bool use_tuple_arg, xla::XlaBuilder* builder, XlaContext* context, + const std::map& arg_shardings, + std::vector* arg_expressions, + std::vector* input_to_args, std::vector* input_shapes, + std::string& args_tuple_sdy_sharding, bool is_entry_computation) { + arg_expressions->resize(args.size()); + + // Argument numbers of arguments and resources that are to be passed to the + // XLA computation as runtime parameters. `input_to_args[a] = b` means that + // the a'th XLA input corresponds to the b'th original arg indexes. + input_to_args->clear(); + input_to_args->reserve(args.size()); + + // Fills in constant arguments, and computes non-constant argument order. + for (std::vector::size_type i = 0; i < args.size(); + ++i) { + const XlaCompiler::Argument& arg = args[i]; + XlaExpression& arg_expression = (*arg_expressions)[i]; + switch (arg.kind) { + case XlaCompiler::Argument::kConstantResource: + case XlaCompiler::Argument::kResource: { + TF_RET_CHECK(arg.resource_kind != XlaResource::kInvalid); + TF_RET_CHECK(absl::holds_alternative(arg.shape)); + // TODO(phawkins): this code assumes that resource arguments do not + // alias. + XlaResource* resource = + context->AddResource(std::make_unique( + arg.resource_kind, i, arg.name, arg.type, + std::get(arg.shape), xla::XlaOp(), + /*max_array_size=*/arg.max_array_size, + /*tensor_array_gradients=*/arg.tensor_array_gradients, + /*tensor_array_multiple_writes_aggregate=*/true, + arg.definition_stack_trace)); + arg_expression = + arg.kind == XlaCompiler::Argument::kResource + ? XlaExpression::Resource(resource) + : XlaExpression::ConstantResource(arg.constant_value, resource); + if (arg.initialized) { + input_to_args->push_back(i); + } + break; + } + case XlaCompiler::Argument::kParameter: + case XlaCompiler::Argument::kTensorList: + case XlaCompiler::Argument::kToken: { + input_to_args->push_back(i); + break; + } + case XlaCompiler::Argument::kConstant: + arg_expression = XlaExpression::Constant(arg.constant_value); + break; + case XlaCompiler::Argument::kInvalid: + return absl::InternalError( + "Unreachable case in BuildArguments() while filling constant args"); + } + } + + if (input_to_args->empty() && !use_tuple_arg) { + return absl::OkStatus(); + } + + // `arg_to_inputs[c] = d` means that the c'th original arg index corresponds + // to the d'th XLA input. Note that the value -1 corresponds to constants, or + // other args that don't correspond to an input. + std::vector arg_to_inputs(args.size(), -1); + for (int i = 0, end = input_to_args->size(); i < end; i++) { + arg_to_inputs[input_to_args->at(i)] = i; + } + + std::vector arg_shapes(input_to_args->size()); + for (std::vector::size_type i = 0; i < input_to_args->size(); ++i) { + // Computes the shapes of non-constant arguments. + auto arg_sharding = arg_shardings.find((*input_to_args)[i]); + std::optional sharding; + if (arg_sharding != arg_shardings.end()) { + TF_ASSIGN_OR_RETURN(auto hlo_sharding, + xla::HloSharding::FromProto(arg_sharding->second)); + sharding = hlo_sharding; + } + TF_RETURN_IF_ERROR(XLAShapeForArgument(args[(*input_to_args)[i]], + is_entry_computation, sharding, + &arg_shapes[i])); + } + + if (use_tuple_arg) { + input_shapes->push_back(xla::ShapeUtil::MakeTupleShape(arg_shapes)); + } else { + *input_shapes = arg_shapes; + } + + // Attach a common operator name as metadata. This has no semantic effect — it + // merely makes the HLO graph more readable when visualized via TensorBoard, + // since TensorBoard forms groups out of operators with similar names. + xla::OpMetadata arg_metadata; + arg_metadata.set_op_name("XLA_Args"); + builder->SetOpMetadata(arg_metadata); + + // Build parameter handles for non-constant arguments. + std::vector arg_handles(input_to_args->size()); + if (use_tuple_arg) { + xla::XlaOp tuple; + if (is_entry_computation) { + xla::OpSharding tuple_sharding; + tuple_sharding.set_type(xla::OpSharding::TUPLE); + for (int64_t parameter : *input_to_args) { + auto it = arg_shardings.find(parameter); + *tuple_sharding.add_tuple_shardings() = + it == arg_shardings.end() ? xla::sharding_builder::SingleDevice(0) + : it->second; + } + std::vector is_same_across_replicas; + for (int i = 0, end = input_to_args->size(); i < end; ++i) { + // Add an entry to is_same_across_replicas for every leaf buffer. + is_same_across_replicas.insert( + is_same_across_replicas.end(), + xla::ShapeUtil::GetLeafCount(arg_shapes[i]), + args[input_to_args->at(i)].is_same_data_across_replicas); + } + xla::XlaScopedShardingAssignment assign_tuple_sharding( + builder, input_to_args->empty() ? std::optional() + : tuple_sharding); + tuple = xla::Parameter(builder, 0, (*input_shapes)[0], "arg_tuple", + is_same_across_replicas); + if (options_.use_shardy_partitioner && builder->sharding().has_value()) { + args_tuple_sdy_sharding = + xla::sdy::convertToSdySharding(tuple_sharding, (*input_shapes)[0], + /*openDims=*/false, + /*inlineMesh=*/true); + } + } else { + tuple = xla::Parameter(builder, 0, (*input_shapes)[0], "arg_tuple"); + } + + for (std::vector::size_type i = 0; i < input_to_args->size(); ++i) { + auto it = arg_shardings.find(i); + xla::XlaScopedShardingAssignment assign_sharding( + builder, it == arg_shardings.end() ? std::optional() + : it->second); + auto& arg = args[input_to_args->at(i)]; + + xla::OpMetadata arg_metadata; + arg_metadata.set_op_name(arg.node_name); + builder->SetOneShotOpMetadata(arg_metadata); + arg_handles[i] = xla::GetTupleElement(tuple, i); + if (is_entry_computation && options_.use_shardy_partitioner) { + // Add shardy shardings only for entry computation, as we only need to + // add it for wrapper main added in tensorflow. + TF_RETURN_IF_ERROR(addSdyShardingFrontendAttribute( + builder, arg_handles[i], arg_shapes[i])); + } + } + } else { + for (std::vector::size_type i = 0; i < input_to_args->size(); ++i) { + auto it = arg_shardings.find(i); + xla::XlaScopedShardingAssignment assign_sharding( + builder, it == arg_shardings.end() ? std::optional() + : it->second); + if (is_entry_computation) { + // Add an entry to is_same_across_replicas for every leaf buffer. + std::vector is_same_across_replicas( + xla::ShapeUtil::GetLeafCount((*input_shapes)[i]), + args[input_to_args->at(i)].is_same_data_across_replicas); + arg_handles[i] = + xla::Parameter(builder, i, (*input_shapes)[i], + absl::StrCat("arg", i), is_same_across_replicas); + if (options_.use_shardy_partitioner) { + TF_RETURN_IF_ERROR(addSdyShardingFrontendAttribute( + builder, arg_handles[i], (*input_shapes)[i], + /*is_single_arg=*/true)); + } + } else { + arg_handles[i] = xla::Parameter(builder, i, (*input_shapes)[i], + absl::StrCat("arg", i)); + } + } + } + + builder->ClearOpMetadata(); + + // Fill in the handles in non-constant arguments, and reshape parameters + // back to their correct shapes. + VLOG(2) << "XLA computation inputs:"; + for (std::vector::size_type i = 0; i < input_to_args->size(); ++i) { + const XlaCompiler::Argument& arg = args[input_to_args->at(i)]; + VLOG(2) << " XLA arg " << i + << " shape: " << xla::ShapeUtil::HumanString(arg_shapes[i]) + << " name: " << arg.name << " TF arg " << input_to_args->at(i) + << " node name: " << arg.node_name + << (arg_shardings.find(i) == arg_shardings.end() + ? "" + : absl::StrCat(" sharding: ", + arg_shardings.at(i).DebugString())); + XlaExpression& arg_expression = (*arg_expressions)[input_to_args->at(i)]; + switch (arg.kind) { + case XlaCompiler::Argument::kConstantResource: + case XlaCompiler::Argument::kResource: { + TF_RET_CHECK(arg.initialized); + XlaResource* resource = arg_expression.resource(); + TF_RETURN_IF_ERROR(resource->SetFromPack(arg.tensor_array_gradients, + arg_handles[i], builder)); + VLOG(2) << " resource: num_gradients: " + << arg.tensor_array_gradients.size(); + break; + } + case XlaCompiler::Argument::kParameter: + // Reshape parameters back to their correct shapes. + // TODO(b/76097077): propagate device assignments onto arguments and + // return values of functions, and then reshape unconditionally. + if (is_entry_computation) { + arg_expression = XlaExpression::XlaOp( + xla::Reshape(arg_handles[i], arg.DimensionSizes()), arg.type); + } else { + arg_expression = XlaExpression::XlaOp(arg_handles[i], arg.type); + if (arg.value_bound) { + TF_RET_CHECK(arg.value_dynamism); + // Propagate upper bound and value dynamism to arg_expression. + arg_expression.set_value_bound(arg.value_bound.value()); + arg_expression.set_value_dynamism(arg.value_dynamism.value()); + } + } + break; + case XlaCompiler::Argument::kTensorList: { + arg_expression = XlaExpression::TensorList(arg_handles[i]); + break; + } + case XlaCompiler::Argument::kToken: { + arg_expression = XlaExpression::XlaOp(arg_handles[i], arg.type); + break; + } + case XlaCompiler::Argument::kConstant: + case XlaCompiler::Argument::kInvalid: + return absl::InternalError( + "Unreachable case in BuildArguments() while filling handles"); + } + } + + return absl::OkStatus(); +} + +namespace { + +// Check that the ops of all non-functional nodes have been registered. +absl::Status ValidateFunctionDef(const FunctionDef* fdef, + const FunctionLibraryDefinition& flib_def) { + for (const NodeDef& node : fdef->node_def()) { + const std::string& op = node.op(); + if (op == FunctionLibraryDefinition::kGradientOp || flib_def.Find(op)) { + continue; + } + const OpDef* op_def; + TF_RETURN_IF_ERROR(OpRegistry::Global()->LookUpOpDef(op, &op_def)); + } + return absl::OkStatus(); +} + +// If node is PartitionedCall or StatefulPartitionedCall, returns the +// name from the "f" attr, else returns node.def().op(). +// Returned pointer points to the internal string either in node's attributes +// or in its NodeDef. This pointer is valid as long as the node has not been +// modified. +absl::Status GetPotentialFunctionName(const Node& node, + const std::string** name) { + if (node.IsPartitionedCall()) { + const AttrValue* attr_value; + TF_RETURN_IF_ERROR( + node.attrs().Find(FunctionLibraryDefinition::kFuncAttr, &attr_value)); + if (!attr_value->has_func()) { + return absl::InvalidArgumentError( + absl::StrCat("The attribute value for attribute 'f' in node ", + node.DebugString(), " does not have 'func' field set")); + } + *name = &attr_value->func().name(); + return absl::OkStatus(); + } + *name = &node.type_string(); + return absl::OkStatus(); +} + +// Check that the graph doesn't have any invalid nodes (e.g. incompatible with +// given device_type, invalid data type, missing attributes...) +absl::Status ValidateGraph(const Graph* graph, + const FunctionLibraryDefinition& flib_def, + const DeviceType& device_type, + const std::string& name) { + // Make sure the XLA compilation kernels are registered. This operation is + // idempotent so it is fine if someone called it already. + XlaOpRegistry::RegisterCompilationKernels(); + + auto maybe_error = [&](const Node* node, + const absl::Status& s) -> absl::Status { + if (!s.ok()) { + std::string errmsg = absl::StrCat( + "Detected unsupported operations when trying to compile graph ", name, + " on ", device_type.type_string(), ": ", node->def().op(), " (", + s.message(), ")", FormatNodeForError(*node)); + if (absl::StrContains(device_type.type_string(), "TPU")) { + absl::StrAppend(&errmsg, + "\nOne approach is to outside compile the unsupported " + "ops to run on CPUs by enabling soft placement " + "`tf.config.set_soft_device_placement(True)`." + " This has a potential performance penalty.\n"); + } + if (std::shared_ptr stack_trace = + node->GetStackTrace()) { + absl::StrAppend( + &errmsg, "\nThe op is created at: \n", + stack_trace->ToString({/*show_line_contents =*/true, + /*filter_common_prefix =*/true, + /*drop_internal_frames =*/true})); + } + + return absl::InvalidArgumentError(errmsg); + } + return absl::OkStatus(); + }; + + for (const Node* node : graph->nodes()) { + if (node->type_string() == FunctionLibraryDefinition::kGradientOp) { + continue; + } + const std::string* function_name; + TF_RETURN_IF_ERROR(GetPotentialFunctionName(*node, &function_name)); + const FunctionDef* fdef = flib_def.Find(*function_name); + absl::Status s; + if (fdef) { + s = ValidateFunctionDef(fdef, flib_def); + TF_RETURN_IF_ERROR(maybe_error(node, s)); + continue; + } + const OpDef* op_def; + s = OpRegistry::Global()->LookUpOpDef(node->def().op(), &op_def); + TF_RETURN_IF_ERROR(maybe_error(node, s)); + TF_RETURN_IF_ERROR(ValidateNodeDef(node->def(), *op_def)); + s = FindKernelDef(device_type, node->def(), nullptr, nullptr); + TF_RETURN_IF_ERROR(maybe_error(node, s)); + } + return absl::OkStatus(); +} + +void ConvertConstantsToExpressions(xla::XlaBuilder* builder, + absl::Span expressions) { + for (XlaExpression& expression : expressions) { + if (expression.kind() == XlaExpression::Kind::kConstant) { + expression = + XlaExpression::XlaOp(expression.AsXlaOp(builder), expression.dtype()); + } + } +} + +} // namespace + +// A temporary dummy stack trace, used to identify locations where stack trace +// info is being lost, and to clarify how stack trace info is otherwise being +// handled in individual passes. This class and its usage below will be removed +// once we have robust end-to-end metadata handling. +// TODO(b/265059672): Remove when end-to-end stack trace handling is in place +class DummyStackTrace : public AbstractStackTrace { + absl::Span ToFrames() const override { return frames_; } + std::vector ToUncachedFrames() const override { return frames_; } + + StackFrame LastUserFrame() const override { return frames_.back(); } + + std::vector GetUserFrames(int /*limit*/) const override { + return frames_; + } + + std::string ToString(const TracePrintingOptions& opts) const override { + auto frame = LastUserFrame(); + return absl::StrCat(frame.file_name, ":", frame.line_number, ":", + frame.function_name); + } + + std::vector frames_{ + StackFrame({"dummy_file_name", 10, "dummy_function_name"})}; +}; + +namespace { +const xla::HloInstructionProto* FindInstructionById( + const xla::HloComputationProto& computation, int64_t id) { + auto iter = + absl::c_find_if(computation.instructions(), + [id](const xla::HloInstructionProto& instruction) { + return instruction.id() == id; + }); + if (iter == computation.instructions().end()) { + return nullptr; + } + return &(*iter); +} + +bool ShouldAddPrecisionToInstruction( + const xla::HloInstructionProto& instruction, + const xla::HloComputationProto& computation) { + static constexpr std::array kOpsPossiblyUsingTF32 = { + "dot", "convolution"}; + if (!absl::c_linear_search(kOpsPossiblyUsingTF32, instruction.opcode())) { + return false; + } + if (instruction.shape().element_type() == xla::F32) { + return true; + } + return absl::c_any_of(instruction.operand_ids(), [&](int64_t operand_id) { + const xla::HloInstructionProto* operand = + FindInstructionById(computation, operand_id); + return operand && operand->shape().element_type() == xla::F32; + }); +} + +// Add precisions configs to the HLO module to avoid TensorFloat32 computations +// in XLA. +// +// Some operations, such as Einsum are converted through MlirXlaOpKernel, which +// doesn't set the precisions, so we set them all here. +// +void IncreasePrecisionsToAvoidTF32(xla::HloModuleProto& module) { + xla::PrecisionConfig precision_config; + precision_config.add_operand_precision(xla::PrecisionConfig::HIGHEST); + precision_config.add_operand_precision(xla::PrecisionConfig::HIGHEST); + + for (xla::HloComputationProto& computation : *module.mutable_computations()) { + for (xla::HloInstructionProto& instruction : + *computation.mutable_instructions()) { + if (ShouldAddPrecisionToInstruction(instruction, computation)) { + *instruction.mutable_precision_config() = precision_config; + } + } + } +} + +} // namespace + +absl::Status XlaCompiler::CompileGraph( + const XlaCompiler::CompileOptions& options, const std::string& name, + std::unique_ptr graph, absl::Span args, + CompilationResult* result) { + VLOG(1) << "Executing graph symbolically to populate XlaBuilder.: " << name; + if (VLOG_IS_ON(2) || DEBUG_DATA_DUMPER()->ShouldDump(name, kDebugGroupMain)) { + VLOG(2) << "XlaCompiler::CompileGraph: " + << DumpGraphToFile(absl::StrCat("xla_compile_graph_", name), *graph, + flib_runtime_->GetFunctionLibraryDefinition()); + } + + DummyStackTrace stack_trace; + for (auto node : graph->nodes()) { + if (node->GetStackTrace() == nullptr) { + node->SetStackTrace(std::make_shared(stack_trace)); + } + } + + TF_RETURN_IF_ERROR(PropagateConstIntoFunctionalNodes( + graph.get(), options_.flib_def, local_flib_def_.get())); + TF_RETURN_IF_ERROR(RearrangeFunctionArguments( + [this](const NameAttrList& function, const FunctionBody** fbody) { + return FindFunctionBody(function, fbody); + }, + graph.get(), local_flib_def_.get(), + pflr_->GetFunctionLibraryDefinition())); + + // Report the error here if initialization failed. + TF_RETURN_IF_ERROR(initialization_status_); + + // Detect invalid nodes. + // FunctionalizeControlFlow may remove some nodes from the graph. + TF_RETURN_IF_ERROR(ValidateGraph(graph.get(), *options_.flib_def, + options_.device_type, name)); + auto builder = std::make_unique(name); + XlaContext* context = new XlaContext(this, builder.get(), graph.get()); + core::ScopedUnref context_unref(context); + + std::vector real_args(args.begin(), args.end()); + int token_input_index = -1; + std::unique_ptr token_output; + if (options.add_token_input_output) { + // Add extra token input. + token_input_index = real_args.size(); + + XlaCompiler::Argument token_arg; + token_arg.kind = XlaCompiler::Argument::kToken; + real_args.push_back(token_arg); + } + + std::map arg_shardings; + std::map retval_shardings; + TF_ASSIGN_OR_RETURN(std::tie(arg_shardings, retval_shardings), + ComputeArgAndRetvalShardings(*graph)); + + std::vector arg_expressions; + std::string args_tuple_sdy_sharding; + TF_RETURN_IF_ERROR( + BuildArguments(*graph, real_args, options.use_tuple_arg, builder.get(), + context, arg_shardings, &arg_expressions, + &result->input_mapping, &result->xla_input_shapes, + args_tuple_sdy_sharding, options.is_entry_computation)); + context->set_args(std::move(arg_expressions)); + + PushNodeTokenMapping(); + // Use std::set instead of std::unordered_set to ensure determinism. + std::set output_node_token_inputs; + if (token_input_index != -1) { + // Original token comes from input. + auto arg_expression = context->args()[token_input_index]; + TF_RETURN_IF_ERROR( + SetNodeToken(kXlaTokenArgNodeName, arg_expression.handle())); + + // Calculate token inputs for output token. + output_node_token_inputs = CalculateTokenInputsForOutputToken(*graph); + + // If there's no side-effecting op in the graph, use token input as token + // output. + if (output_node_token_inputs.empty()) { + output_node_token_inputs.insert(kXlaTokenArgNodeName); + } + } else if (options.is_entry_computation) { + // Original token is manually created. + if (HasSideEffectingNodes(*graph)) { + TF_RETURN_IF_ERROR( + SetNodeToken(kXlaTokenArgNodeName, xla::CreateToken(builder.get()))); + } + } + + absl::Status execute_status = ExecuteGraph(context, std::move(graph), device_, + flib_runtime_, NextStepId()); + if (!execute_status.ok()) { + VLOG(1) << "Failed executing graph " << name; + return execute_status; + } + if (token_input_index != -1) { + // Add extra token output. + std::vector token_inputs; + for (const auto& node_name : output_node_token_inputs) { + auto token_or = GetNodeToken(node_name); + TF_RETURN_IF_ERROR(token_or.status()); + token_inputs.push_back(token_or.value()); + } + token_output = std::make_unique( + xla::AfterAll(builder.get(), token_inputs)); + } + TF_RETURN_IF_ERROR(PopNodeTokenMapping()); + + int num_nonconst_outputs; + int num_computation_outputs; + result->computation = std::make_shared(); + result->outputs.resize(context->retvals().size()); + std::vector retvals = context->retvals(); + ConvertConstantsToExpressions(builder.get(), + absl::Span(retvals)); + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns{ + UseNoPreferenceLayoutFn(), IdentityShapeRepresentationFn()}; + std::string result_tuple_sdy_sharding; + TF_RETURN_IF_ERROR(BuildComputation( + real_args, retvals, arg_shardings, retval_shardings, context->resources(), + std::move(token_output), + options.is_entry_computation ? options_.shape_determination_fns + : shape_determination_fns, + options.is_entry_computation, + options.return_updated_values_for_all_resources, + options.always_return_tuple, options.use_tuple_arg, + options.alias_resource_update, builder.get(), result->computation.get(), + &num_computation_outputs, &num_nonconst_outputs, &result->outputs, + &result->resource_updates, &result->xla_output_shape, + result->input_mapping, result_tuple_sdy_sharding, + options_.use_shardy_partitioner)); + + // Add Shardy sharding attributes for tuple arguments and results to the + // module's frontend attributes. These are stored at the module level + // because instruction-level frontend attributes are lost when tuples are + // flattened during HLO to StableHLO conversion. + auto setModuleFrontendAttribute = [&](absl::string_view key, + absl::string_view value) { + result->computation->mutable_proto() + ->mutable_frontend_attributes() + ->mutable_map() + ->try_emplace(key, value); + }; + if (!args_tuple_sdy_sharding.empty()) { + setModuleFrontendAttribute( + xla::sdy::toStringView(xla::sdy::kInTupleShardings), + args_tuple_sdy_sharding); + setModuleFrontendAttribute(xla::sdy::toStringView(xla::sdy::kUseTupleArgs), + "True"); + } + if (!result_tuple_sdy_sharding.empty()) { + setModuleFrontendAttribute( + xla::sdy::toStringView(xla::sdy::kOutTupleShardings), + result_tuple_sdy_sharding); + } + + for (const auto& [key, send] : host_compute_sends_) { + auto* d2h = result->host_compute_metadata.add_device_to_host(); + *d2h = send; + + for (int i = 0; i < d2h->metadata_size(); ++i) { + const std::string channel_name = + GetDeviceToHostChannelName(d2h->key(), i); + xla::ChannelHandle handle; + TF_RETURN_IF_ERROR(GetDeviceToHostChannelHandle(channel_name, &handle)); + d2h->mutable_metadata(i)->set_channel_id(handle.handle()); + } + } + for (const auto& [key, recv] : host_compute_recvs_) { + auto* h2d = result->host_compute_metadata.add_host_to_device(); + *h2d = recv; + + for (int i = 0; i < h2d->metadata_size(); ++i) { + const std::string channel_name = + GetHostToDeviceChannelName(h2d->key(), i); + xla::ChannelHandle handle; + TF_RETURN_IF_ERROR(GetHostToDeviceChannelHandle(channel_name, &handle)); + h2d->mutable_metadata(i)->set_channel_id(handle.handle()); + } + } + + if (!tsl::tensor_float_32_execution_enabled()) { + IncreasePrecisionsToAvoidTF32(*result->computation->mutable_proto()); + } + + VLOG(2) << "Outputs: total: " << context->retvals().size() + << " nonconstant: " << num_nonconst_outputs; + VLOG(2) << "XLA output shape: " + << xla::ShapeUtil::HumanStringWithLayout(result->xla_output_shape); + result->collective_info = context->GetCollectiveInfo(); + return absl::OkStatus(); +} + +xla::ChannelHandle XlaCompiler::NewChannel( + xla::ChannelHandle::ChannelType type) { + xla::ChannelHandle new_handle; + absl::MutexLock lock(channel_mutex_); + // Create a new channel handle with a unique value. + new_handle.set_handle(next_channel_++); + new_handle.set_type(type); + return new_handle; +} + +absl::Status XlaCompiler::GetChannelHandle(const std::string& key, + xla::ChannelHandle* channel) { + auto result = channels_.emplace(key, xla::ChannelHandle()); + if (result.second) { + result.first->second = NewChannel(xla::ChannelHandle::DEVICE_TO_DEVICE); + } + *channel = result.first->second; + VLOG(1) << "Channel: " << key << " " << channel->DebugString(); + return absl::OkStatus(); +} + +absl::Status XlaCompiler::GetHostToDeviceChannelHandle( + const std::string& key, xla::ChannelHandle* channel) { + auto result = channels_.emplace(key, xla::ChannelHandle()); + if (result.second) { + result.first->second = NewChannel(xla::ChannelHandle::HOST_TO_DEVICE); + } + *channel = result.first->second; + VLOG(1) << "Host to device channel: " << key << " " << channel->DebugString(); + return absl::OkStatus(); +} + +absl::Status XlaCompiler::GetDeviceToHostChannelHandle( + const std::string& key, xla::ChannelHandle* channel) { + auto result = channels_.emplace(key, xla::ChannelHandle()); + if (result.second) { + result.first->second = NewChannel(xla::ChannelHandle::DEVICE_TO_HOST); + } + *channel = result.first->second; + VLOG(1) << "Device to host channel: " << key << " " << channel->DebugString(); + return absl::OkStatus(); +} + +namespace { + +void SetTransfer(const std::string& key, absl::Span types, + absl::Span shapes, + tf2xla::HostTransferMetadata* transfer) { + transfer->set_key(key); + CHECK(types.size() == shapes.size()); + for (int i = 0, end = types.size(); i < end; ++i) { + tf2xla::TensorMetadata* metadata = transfer->add_metadata(); + metadata->set_type(types[i]); + shapes[i].AsProto(metadata->mutable_shape()); + } +} + +} // namespace + +absl::Status XlaCompiler::SetDeviceToHostMetadata( + const std::string& key, absl::Span types, + absl::Span shapes) { + if (host_compute_sends_.find(key) != host_compute_sends_.end()) { + tf2xla::HostTransferMetadata& existing_transfer = host_compute_sends_[key]; + tf2xla::HostTransferMetadata new_transfer; + SetTransfer(key, types, shapes, &new_transfer); + if (xla::protobuf_util::HaveSameSerialization(existing_transfer, + new_transfer)) { + return absl::OkStatus(); + } else { + return absl::InvalidArgumentError(absl::StrCat( + "Duplicate calls to SetDeviceToHostMetadata with key ", key)); + } + } + tf2xla::HostTransferMetadata& transfer = host_compute_sends_[key]; + SetTransfer(key, types, shapes, &transfer); + return absl::OkStatus(); +} + +absl::Status XlaCompiler::GetDeviceToHostShapes( + const std::string& key, std::vector* shapes) const { + const auto iter = host_compute_sends_.find(key); + if (iter == host_compute_sends_.end()) { + return absl::InvalidArgumentError( + absl::StrCat("No host compute send shapes registered for key ", key)); + } + shapes->clear(); + for (int i = 0; i < iter->second.metadata_size(); ++i) { + TensorShape shape(iter->second.metadata(i).shape()); + shapes->push_back(shape); + } + return absl::OkStatus(); +} + +absl::Status XlaCompiler::SetHostToDeviceMetadata( + const std::string& key, absl::Span types, + absl::Span shapes) { + if (host_compute_recvs_.find(key) != host_compute_recvs_.end()) { + tf2xla::HostTransferMetadata& existing_transfer = host_compute_recvs_[key]; + tf2xla::HostTransferMetadata new_transfer; + SetTransfer(key, types, shapes, &new_transfer); + if (xla::protobuf_util::HaveSameSerialization(existing_transfer, + new_transfer)) { + return absl::OkStatus(); + } else { + return absl::InvalidArgumentError(absl::StrCat( + "Duplicate calls to SetHostToDeviceMetadata with key ", key)); + } + } + tf2xla::HostTransferMetadata& transfer = host_compute_recvs_[key]; + SetTransfer(key, types, shapes, &transfer); + return absl::OkStatus(); +} + +absl::Status XlaCompiler::GetHostComputeControlDependency( + const std::string& host_compute_name, xla::XlaOp* handle) { + const auto iter = host_compute_control_output_.find(host_compute_name); + if (iter == host_compute_control_output_.end()) { + return absl::InvalidArgumentError( + absl::StrCat("No registered control handle for host compute Op '", + host_compute_name, "'")); + } else { + *handle = iter->second; + } + return absl::OkStatus(); +} + +absl::Status XlaCompiler::SetHostComputeControlDependency( + const std::string& host_compute_name, const xla::XlaOp handle) { + if (host_compute_control_output_.find(host_compute_name) != + host_compute_control_output_.end()) { + return absl::InvalidArgumentError(absl::StrCat( + "Duplicate control handles registered for host compute Op ", + host_compute_name)); + } + host_compute_control_output_[host_compute_name] = handle; + return absl::OkStatus(); +} + +void XlaCompiler::PushNodeTokenMapping() { + node_token_mapping_stack_.emplace(std::map{}); +} + +absl::Status XlaCompiler::PopNodeTokenMapping() { + if (node_token_mapping_stack_.empty()) { + return absl::FailedPreconditionError( + "Calling PopNodeTokenMapping() when node_token_mapping_stack_ is " + "empty."); + } + node_token_mapping_stack_.pop(); + return absl::OkStatus(); +} + +absl::Status XlaCompiler::SetNodeToken(const std::string& node_name, + const xla::XlaOp op) { + if (node_token_mapping_stack_.empty()) { + return absl::FailedPreconditionError( + "Calling SetNodeToken() when node_token_mapping_stack_ is " + "empty."); + } + auto insert_result = node_token_mapping_stack_.top().insert({node_name, op}); + if (!insert_result.second) { + return absl::FailedPreconditionError( + absl::StrCat("Token mapping already exists for node ", node_name)); + } + return absl::OkStatus(); +} + +absl::StatusOr XlaCompiler::GetNodeToken( + const std::string& node_name) { + if (node_token_mapping_stack_.empty()) { + return absl::FailedPreconditionError( + "Calling GetNodeToken() when node_token_mapping_stack_ is " + "empty."); + } + auto iter = node_token_mapping_stack_.top().find(node_name); + if (iter == node_token_mapping_stack_.top().end()) { + return absl::FailedPreconditionError( + absl::StrCat("Cannot find token mapping for node ", node_name)); + } + return iter->second; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler.h new file mode 100644 index 0000000000000000000000000000000000000000..bf2466d1957d1d7e38f582d26398fb59a81ed972 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler.h @@ -0,0 +1,443 @@ +/* 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_XLA_COMPILER_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILER_H_ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/base/thread_annotations.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/synchronization/mutex.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/host_compute_metadata.pb.h" +#include "tensorflow/compiler/tf2xla/layout_util.h" +#include "tensorflow/compiler/tf2xla/xla_argument.h" +#include "tensorflow/compiler/tf2xla/xla_compilation_device.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/client/client.h" +#include "xla/client/local_client.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/shape.h" +#include "xla/status_macros.h" +#include "xla/stream_executor/device_memory_allocator.h" +#include "tensorflow/core/common_runtime/device.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/errors.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/notification.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/protobuf/config.pb.h" +#include "tensorflow/core/public/version.h" + +namespace tensorflow { + +class XlaContext; + +// The XlaCompiler class is responsible for compilation of a self-contained +// subgraph of a TensorFlow computation using the XLA linear algebra runtime. +// It does a symbolic execution of the graph starting from specific input +// shapes, using a JIT device to convert operators into XLA computations. +// +// XlaCompiler is typically invoked from an `XlaLaunch` operator once the +// shapes of all input parameters to the computation are known. This is +// because the symbolic execution requires known shapes for all operations. +// +// XlaCompiler compiles Tensorflow graphs that received inputs via _Arg nodes, +// and return outputs via _Retval nodes. +// +// The XlaCompiler requires one Argument struct for each _Arg index, that +// describes each argument. Arguments can be compile-time constants +// (kind kConstant), run-time parameters (kind kParameter), or resources +// (kind kResource). +// +// Only kParameter and initialized kResource arguments become runtime parameters +// to the generated XLA computation. +// +// The run-time outputs of the XLA computation are arranged in the following +// order: +// +------------------+-----------------------------------------+ +// | _Retval values | Updated values of kResource arguments | +// +------------------+-----------------------------------------+ +// _Retval values are ordered by _Retval index, whereas kResource values are +// ordered by the original _Arg position of the variable. +// +// If a shape representation function is provided as part of +// XlaCompiler::CompileOptions, kParameter arguments and return values to an +// entry computation will be reshaped in accordance to the shape function. +// Arguments and return values to a non-entry computation are not reshaped. +// Variable resource arguments are passed and returned in reshaped form, even +// for non-entry computations. This feature allows TensorFlow to keep on-device +// tensors with a different shape to their representation inside the XLA +// computation. +// +// In computation outputs, updated kResource values are placed the end. When +// emitting While loop bodies, we must ensure that the loop body has +// identical input and output signatures. By passing variable values +// at the end of the argument list and using the +// `return_updated_values_for_all_variables` option, we can ensure that the +// input and output values of resources appear at the same positions. +// +// Resources are passed as parameters or returned as resource updates in +// "packed" form. +// kStack resources are packed as (array, size of stack) XLA tuples. +// kTensorArray resources without gradients are packed as the array that +// backs the TensorArray. If gradients are present (`tensor_array_gradients`), +// the packed representation is a (array, gradient0, gradient1, ...) tuple, +// where gradient_k is the value of the k-th gradient in the +// `tensor_array_gradients` ordered set. +class XlaCompiler { + public: + // TODO(b/255826209): Remove this alias. Depending on XlaCompiler just to use + // XlaArgument seeems weird and can cause circular dependencies. + using Argument = ::tensorflow::XlaArgument; + + // Options pertaining to an individual call to CompileGraph() or + // CompileFunction(). + struct CompileOptions { + // If `use_tuple_arg` is true, a single tuple parameter will be used for all + // arguments; if false, each argument gets its own parameter. + bool use_tuple_arg = false; + + // If 'return_updated_values_for_all_resources' is true, then updated + // values of all resource arguments will be included in the + // 'resource_updates' of the computation, even if the resource was not + // modified by the computation. Used when compiling loop bodies to ensure + // the input and output signatures match. + bool return_updated_values_for_all_resources = false; + + // If 'always_return_tuple' is true, then the output of a computation will + // always be a tuple. Otherwise, a single-element output will not be wrapped + // in a tuple. + bool always_return_tuple = true; + + // True when compiling the entry computation, false for subcomputations + // (while, call, etc.) + bool is_entry_computation = true; + + // True when we should add XLA input & output to the graph/function. + bool add_token_input_output = false; + + // Resource updates are converted into input / output of xla. The two + // buffers are aliased with other if this option is true. + bool alias_resource_update = false; + + std::string DebugString() const { + return absl::StrCat("use_tuple_arg=", use_tuple_arg, + " return_updated_values_for_all_resources=", + return_updated_values_for_all_resources, + " always_return_tuple=", always_return_tuple, + " is_entry_computation=", is_entry_computation, + " add_token_input_output=", add_token_input_output, + " alias_resource_update=", alias_resource_update); + } + }; + + using OutputDescription = ::tensorflow::XlaOutputDescription; + + using ResourceUpdate = ::tensorflow::XlaResourceUpdate; + + using CompilationResult = ::tensorflow::XlaCompilationResult; + + struct Options { + // Name of the compilation device to use. It must be set by the caller. + // The default empty value is invalid. + DeviceType device_type = DeviceType(""); + + // The device to use during compilation to execute instructions on, for + // example for auto-tuning. + // Valid values are defined by `xla::Backend::devices_ordinal_supported()`. + // -1 indicates the default device should be used. + int device_ordinal = -1; + + xla::Client* client = nullptr; + + // Function library in which to find function definitions. Must be non-null. + const FunctionLibraryDefinition* flib_def = nullptr; + + // The graph def version to be compiled. + int graph_def_version = TF_GRAPH_DEF_VERSION; + + // If 'allow_cpu_custom_calls' is true, kernels may make use of CustomCall() + // for CPU. + bool allow_cpu_custom_calls = false; + + // A ShapeDeterminationFns (i.e., a bundle of LayoutSelectionFn and + // ShapeRepresentationFn). Each bundle describes the XLA representation of + // arguments represented to XLA as the shape given by this shape function. + // Arguments are input activations or weights to an XLA entry computation. + // Variables are reshaped to this shape on write, and reshaped to their + // original shape on read. + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + + // If not nullptr, populate_resource_manager is called with the + // compilation device's resource manager when the compilation + // device is created, and can be used to create metadata objects + // that can be accessed by XLA op kernels. + std::function* populate_resource_manager = + nullptr; + + // If not nullptr, this memory allocator can be used by the compiler for + // temporary allocations it might want to make during compilation. + // + // For example, the compiler may want to try out different algorithms and + // choose the fastest one, and it might run those algorithms over buffers + // created using this allocator. + // + // The compiler can function correctly without an explicit allocator given + // here, but on some devices (notably, GPUs), TensorFlow tends to eagerly + // allocate most or all available memory on the device, leaving none for the + // compiler to access, unless it can use TensorFlow's allocator. + // This must be a shared_ptr, as this is passed all the way down to the + // cluster compilation. This allows asynchronous compilation to hold a + // reference until the compilation is finished. + std::shared_ptr device_allocator; + + // Alias input and output buffers for parameters that are passed-through XLA + // modules without being changed. + bool alias_passthrough_params = false; + + // Enable detailed logging of compilation metadata. + bool detailed_logging = true; + + // If true, use Shardy (go/shardy) partitioner. If false, use GSPMD. + bool use_shardy_partitioner = false; + }; + + // Argument for compiling a single op. + struct SingleOpCompileArgument { + // Data type of the output tensors. This is used to create _Retval node. + std::vector output_dtypes; + + // The NodeDef representing the op. + NodeDef node_def; + + // This is currently only used to obtain MLIR TPU bridge rollout state. + // Can be removed once full rollout is complete. + ConfigProto config_proto; + + SingleOpCompileArgument() = default; + + explicit SingleOpCompileArgument(const OpKernelContext& ctx); + }; + + explicit XlaCompiler(Options options); + + ~XlaCompiler(); + + // Helper function to populate an XlaCompiler::Argument from XlaResource. + static void PopulateArgumentFromResource(const XlaResource& resource, + Argument* arg); + + absl::Status CompileFunction(const CompileOptions& options, + const NameAttrList& fn_name_attrs, + absl::Span args, + CompilationResult* result); + + absl::Status CompileSingleOp( + const CompileOptions& options, + const SingleOpCompileArgument& single_op_compile_argument, + absl::Span args, CompilationResult* result); + + // Compiles a tensorflow::Graph into an xla::XlaComputation. + // Similar to CompileFunction, but takes a Graph as input rather than a + // function. + absl::Status CompileGraph(const CompileOptions& options, + const std::string& name, + std::unique_ptr graph, + absl::Span args, + CompilationResult* result); + + // Returns the shape of the XLA parameter for an argument 'arg'. + // See the class comment for more details about the argument passing + // convention. + absl::Status XLAShapeForArgument( + const Argument& arg, bool is_entry_computation, + const std::optional& arg_sharding, + xla::Shape* xla_shape) const; + + // Retrieves the channel handle associated with `key`. Allocates + // a new channel handle if none exists. + // Channel handles can be used to communicate between different + // computations. Computations that communicate should be compiled with the + // same XlaCompiler. + absl::Status GetChannelHandle(const std::string& key, + xla::ChannelHandle* channel); + + // Retrieves the host-to-device channel handle associated with `key`. + // Allocates a new channel handle if none exists. + absl::Status GetHostToDeviceChannelHandle(const std::string& key, + xla::ChannelHandle* channel); + + // Retrieves the device-to-host channel handle associated with `key`. + // Allocates a new channel handle if none exists. + absl::Status GetDeviceToHostChannelHandle(const std::string& key, + xla::ChannelHandle* channel); + + // Sets the shapes and types for the device to host transfer associated with + // 'key'. + absl::Status SetDeviceToHostMetadata(const std::string& key, + absl::Span types, + absl::Span shapes); + + // Gets the shapes the device to host transfer associated with 'key'. + absl::Status GetDeviceToHostShapes(const std::string& key, + std::vector* shapes) const; + + // Sets the shapes and types for the host to device transfer associated with + // 'key'. + absl::Status SetHostToDeviceMetadata(const std::string& key, + absl::Span types, + absl::Span shapes); + + // In order to avoid deadlocks from dependencies in host computations, it can + // be necessary to enforce a partial order on the execution of HostCompute + // Ops. In particular it may be necessary to constrain the SendToHost for one + // HostCompute to run before blocking on the RecvAtHost for another + // HostCompute. The compiler maintains a mapping from 'host_compute_name' to + // handle, where the handle is an 'output' of the HostCompute Op corresponding + // to 'host_compute_name'. Another HostCompute Op that needs to be sequenced + // later can add the handle as an 'input' to enforce the constraints. + // 'host_compute_name' can be any string the client wishes to use to identify + // a given HostCompute Op as long as the names are unique within the + // compilation. + absl::Status GetHostComputeControlDependency( + const std::string& host_compute_name, xla::XlaOp* handle); + absl::Status SetHostComputeControlDependency( + const std::string& host_compute_name, xla::XlaOp handle); + + const Options& options() const { return options_; } + xla::Client* client() const { return options_.client; } + FunctionLibraryRuntime* flib_runtime() const { return flib_runtime_; } + + void PushNodeTokenMapping(); + absl::Status PopNodeTokenMapping(); + absl::Status SetNodeToken(const std::string& node_name, xla::XlaOp op); + absl::StatusOr GetNodeToken(const std::string& node_name); + + // Sets the function body `fbody` to the one registered as `function`. + absl::Status FindFunctionBody(const NameAttrList& function, + const FunctionBody** fbody, + const ConfigProto** config_proto = nullptr); + + private: + absl::Mutex channel_mutex_; + // Returns the optimized graph object in this function body. + std::unique_ptr GetGraph(const FunctionBody* fbody); + + // Builds XLA computations for each of the arguments to the computation. + // `args` are the arguments to the computation. Populates + // `args_tuple_sdy_sharding` with corresponding shardy sharding if + // `use_tuple_arg` is true. + absl::Status BuildArguments( + const Graph& graph, const std::vector& args, + bool use_tuple_arg, xla::XlaBuilder* builder, XlaContext* context, + const std::map& arg_shardings, + std::vector* arg_expressions, + std::vector* input_to_args, std::vector* input_shapes, + std::string& args_tuple_sdy_sharding, bool is_entry_computation); + + xla::ChannelHandle NewChannel(xla::ChannelHandle::ChannelType type); + + // Graph compiler needs to know how to get an optimized graph from a function + // body. + friend class GraphCompiler; + friend class XlaCompilerTest; + + Options options_; + + // Status set to non-OK in the constructor if initialization fails. + absl::Status initialization_status_; + + // Returns the next step sequence number. + int64_t NextStepId(); + + // Internal sequence number for steps executed on the compilation device. + int64_t next_step_id_; + + XlaCompilationDevice* device_; // Owned by device_mgr_ + StaticDeviceMgr device_mgr_; + + // The next sequence number to assign to a channel. + int64_t next_channel_ ABSL_GUARDED_BY(channel_mutex_) = 1; + + // To avoid copying the client's function library, use a local function + // library and runtime for functions created as part of the functionalize + // control flow transformation. + std::unique_ptr local_flib_def_; + std::unique_ptr pflr_; + std::unique_ptr local_pflr_; + + FunctionLibraryRuntime* local_flib_runtime_; // owned by local_pflr_. + FunctionLibraryRuntime* flib_runtime_; // owned by pflr_. + + struct SignatureHash { + uint64_t operator()( + const std::pair>& signature) const; + }; + + std::unordered_map>, + CompilationResult, SignatureHash> + cache_; + + std::unordered_map channels_; + + std::unordered_map + host_compute_sends_; + std::unordered_map + host_compute_recvs_; + + std::unordered_map host_compute_control_output_; + + // This is used to store mapping. Side-effecting + // ops call SetNodeToken() to record its token output, so later side-effecting + // ops can use GetNodeToken() to get it and use it as token input. + // + // It's a stack because we need a mapping like this for each level of nested + // CompileGraph() call. In CompileGraph(), we will push a new mapping to the + // stack, and pop the mapping before returning. + std::stack> node_token_mapping_stack_; + + XlaCompiler(const XlaCompiler&) = delete; + void operator=(const XlaCompiler&) = delete; +}; + + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_COMPILER_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..e7decd99d02fe2c6e88d57654f83f1ae7c6e4439 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_compiler_test.cc @@ -0,0 +1,2316 @@ +/* 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/xla_compiler.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/match.h" +#include "absl/strings/str_cat.h" +#include "tensorflow/cc/framework/ops.h" +#include "tensorflow/cc/framework/scope.h" +#include "tensorflow/cc/ops/array_ops.h" +#include "tensorflow/cc/ops/const_op.h" +#include "tensorflow/cc/ops/data_flow_ops.h" +#include "tensorflow/cc/ops/function_ops.h" +#include "tensorflow/cc/ops/functional_ops.h" +#include "tensorflow/cc/ops/list_ops.h" +#include "tensorflow/cc/ops/math_ops.h" +#include "tensorflow/cc/ops/resource_variable_ops.h" +#include "tensorflow/cc/ops/standard_ops.h" +#include "tensorflow/compiler/tf2xla/layout_util.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/side_effect_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/array.h" +#include "xla/client/client.h" +#include "xla/client/client_library.h" +#include "xla/client/local_client.h" +#include "xla/debug_options_flags.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/ir/hlo_module.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/hlo/testlib/filecheck.h" +#include "xla/layout_util.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/service/hlo.pb.h" +#include "xla/service/hlo_module_util.h" +#include "xla/service/hlo_proto_util.h" +#include "xla/service/service.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tests/literal_test_util.h" +#include "xla/tsl/lib/core/status_test_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/tsl/platform/statusor.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/common_runtime/function.h" +#include "tensorflow/core/common_runtime/graph_constructor.h" +#include "tensorflow/core/framework/common_shape_fns.h" +#include "tensorflow/core/framework/fake_input.h" +#include "tensorflow/core/framework/function.h" +#include "tensorflow/core/framework/function.pb.h" +#include "tensorflow/core/framework/function_testlib.h" +#include "tensorflow/core/framework/graph_to_functiondef.h" +#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/op_requires.h" +#include "tensorflow/core/framework/resource_base.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.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/algorithm.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/graph/node_builder.h" +#include "tensorflow/core/kernels/ops_testutil.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/version.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { + +class XlaCompilerTest : public ::testing::Test { + protected: + void SetUp() override { + client_ = xla::ClientLibrary::LocalClientOrDie(); + + XlaOpRegistry::RegisterCompilationKernels(); + + FunctionDefLibrary flib; + flib_def_.reset(new FunctionLibraryDefinition(OpRegistry::Global(), flib)); + } + + XlaCompiler::Options DefaultOptions() { + XlaCompiler::Options options; + options.device_type = DeviceType(DEVICE_CPU_XLA_JIT); + options.client = client_; + options.flib_def = flib_def_.get(); + return options; + } + + FunctionLibraryDefinition* LocalFlibDef(XlaCompiler* compiler) { + return compiler->local_flib_def_.get(); + } + + xla::Client* client_; + std::unique_ptr flib_def_; +}; + +namespace { + +// Helper class to test the ability to pass resources through to XLA +// compiled kernels. +class DummyResourceForTest : public ResourceBase { + public: + std::string DebugString() const override { return "dummy"; } + void Increment() { ++value_; } + int Get() { return value_; } + + private: + int value_ = 0; +}; + +class DummyReadResourceOp : public XlaOpKernel { + public: + explicit DummyReadResourceOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + ResourceMgr* rm = ctx->op_kernel_context()->resource_manager(); + OP_REQUIRES(ctx, rm, absl::InternalError("No resource manager.")); + DummyResourceForTest* dummy; + OP_REQUIRES_OK(ctx, rm->Lookup( + rm->default_container(), "dummy", &dummy)); + dummy->Increment(); + dummy->Unref(); + + ctx->SetOutput(0, ctx->Input(0)); + ctx->SetOutput(1, ctx->Input(0)); + } +}; + +class DummyReadResourceCC { + public: + DummyReadResourceCC(const Scope& scope, const Input& value) { + if (!scope.ok()) return; + auto _value = ops::AsNodeOut(scope, value); + if (!scope.ok()) return; + Node* ret; + const auto unique_name = scope.GetUniqueNameForOp("DummyReadResource"); + auto builder = NodeBuilder(unique_name, "DummyReadResource").Input(_value); + scope.UpdateBuilder(&builder); + scope.UpdateStatus(builder.Finalize(scope.graph(), &ret)); + if (!scope.ok()) return; + scope.UpdateStatus(scope.DoShapeInference(ret)); + if (!scope.ok()) return; + this->output1_ = Output(ret, 0); + this->output2_ = Output(ret, 1); + } + + Output output1_; + Output output2_; +}; + +REGISTER_OP("DummyReadResource") + .Input("input: int32") + .Output("output1: int32") + .Output("output2: int32") + .SetShapeFn(shape_inference::UnknownShape) + .Doc(R"doc( +A dummy Op. + +input: dummy input. +output1: dummy output. +output2: dummy output. +)doc"); + +REGISTER_XLA_OP(Name("DummyReadResource"), DummyReadResourceOp); + +// DummyDuplicateOp is present purely to test multiple REGISTER_XLA_OP calls +// on the same Op name below. +class DummyDuplicateOp : public XlaOpKernel { + public: + explicit DummyDuplicateOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + ctx->SetOutput(0, ctx->Input(0)); + } +}; + +REGISTER_OP("DummyDuplicateOp") + .Input("input: int32") + .Output("output: int32") + .Doc(R"doc( +A dummy Op. + +input: dummy input. +output: dummy output. +)doc"); + +REGISTER_XLA_OP(Name("DummyDuplicateOp").Device(DEVICE_CPU_XLA_JIT), + DummyDuplicateOp); +REGISTER_XLA_OP(Name("DummyDuplicateOp").Device(DEVICE_GPU_XLA_JIT), + DummyDuplicateOp); + +// Tests compilation and execution of an empty graph. +TEST_F(XlaCompilerTest, EmptyReturnValues) { + XlaCompiler compiler(DefaultOptions()); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), + /*args=*/{}, &result)); + + TF_ASSERT_OK(client_->Execute(*result.computation, {}).status()); +} + +// Tests compilation and execution of a graph that adds two tensors. +TEST_F(XlaCompilerTest, Simple) { + // Builds a graph that adds two Tensors. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); + auto c = ops::Add(scope.WithOpName("C"), a, b); + auto d = ops::_Retval(scope.WithOpName("D"), c, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[1].kind = XlaCompiler::Argument::kParameter; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + + // Tests that the generated computation works. + xla::Literal param0_literal = xla::LiteralUtil::CreateR1({7, 42}); + xla::Literal param1_literal = xla::LiteralUtil::CreateR1({-3, 101}); + std::unique_ptr param0_data = + client_->TransferToServer(param0_literal).value(); + std::unique_ptr param1_data = + client_->TransferToServer(param1_literal).value(); + + std::unique_ptr actual = + client_ + ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) + .value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal expected0 = xla::LiteralUtil::CreateR1({4, 143}); + xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +absl::StatusOr> LoadModuleFromHloProto( + const xla::HloModuleProto& module_proto) { + TF_ASSIGN_OR_RETURN(auto module_config, + xla::HloModule::CreateModuleConfigFromProto( + module_proto, xla::GetDebugOptionsFromFlags())); + return xla::CreateModuleFromProto(module_proto, module_config); +} + +// Tests compilation and execution of a graph that adds two tensors with dynamic +// shape parameters. +TEST_F(XlaCompilerTest, SimpleDynamicShapeParameter) { + // Builds a graph that adds two Tensors. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); + auto c = ops::Add(scope.WithOpName("C"), a, b); + auto d = ops::_Retval(scope.WithOpName("D"), c, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = + xla::ShapeUtil::MakeShape(/*element_type=*/xla::S32, /*dimensions=*/{2}, + /*dynamic_dimensions=*/{true}); + args[1].kind = XlaCompiler::Argument::kParameter; + args[1].type = DT_INT32; + args[1].shape = TensorShape(/*dimensions=*/{2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + + auto hlo = result.computation->proto(); + TF_ASSERT_OK_AND_ASSIGN(auto module, LoadModuleFromHloProto(hlo)); + EXPECT_EQ(module->computation_count(), 1); + EXPECT_TRUE((*module->computations().begin()) + ->parameter_instruction(0) + ->shape() + .is_dynamic()); +} + +// Tests compilation of a graph where the _Retval node is not necessarily last +// amongst the graph nodes in construction order, and always_return_tuple is +// false. Regression test for bug where the wrong value was returned. +TEST_F(XlaCompilerTest, OutOfOrderGraph) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); + // The _Retval node is not last in construction order. + auto d = ops::_Retval(scope.WithOpName("D"), a, 0); + auto c = ops::Add(scope.WithOpName("C"), a, b); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[1].kind = XlaCompiler::Argument::kParameter; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompileOptions compile_options; + compile_options.always_return_tuple = false; + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + + // Tests that the generated computation works. + xla::Literal param0_literal = xla::LiteralUtil::CreateR1({7, 42}); + xla::Literal param1_literal = xla::LiteralUtil::CreateR1({-3, 101}); + std::unique_ptr param0_data = + client_->TransferToServer(param0_literal).value(); + std::unique_ptr param1_data = + client_->TransferToServer(param1_literal).value(); + + std::unique_ptr actual = + client_ + ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) + .value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + EXPECT_TRUE(xla::LiteralTestUtil::Equal(param0_literal, actual_literal)); +} + +// Tests that the compiler can correctly propagate the layout assigned by +// shape_representation_fn_ to resource returns that have not been written to. +TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForUnwrittenResource) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0); + auto d = ops::_Retval(scope.WithOpName("D"), var, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kVariable; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 3}); + + auto options = DefaultOptions(); + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [](const TensorShape& shape, DataType dt, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape)); + *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); + return xla_shape; + }; + options.shape_determination_fns = shape_determination_fns; + // Compiles the graph. + XlaCompiler compiler(options); + + XlaCompiler::CompilationResult result; + XlaCompiler::CompileOptions compile_options; + compile_options.return_updated_values_for_all_resources = true; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + xla::Shape transposed = + xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1}); + // Check that the return shapes are correctly tranposed. + EXPECT_EQ(result.xla_output_shape, + xla::ShapeUtil::MakeTupleShape({transposed})); +} + +// Tests that the compiler can correctly propagate fast mem attribute for input +// resource variable. +TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForFastMemVar) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0); + auto d = ops::_Retval(scope.WithOpName("D"), var, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kVariable; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 3}); + args[0].fast_mem = true; + + auto options = DefaultOptions(); + int fast_mem_arg_count = 0; + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [&fast_mem_arg_count]( + const TensorShape& shape, DataType dt, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape)); + *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); + if (use_fast_memory) { + fast_mem_arg_count++; + } + return xla_shape; + }; + options.shape_determination_fns = shape_determination_fns; + // Compiles the graph. + XlaCompiler compiler(options); + + XlaCompiler::CompilationResult result; + XlaCompiler::CompileOptions compile_options; + compile_options.return_updated_values_for_all_resources = true; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + // Count 2: one for argument, one for the return value. + EXPECT_EQ(fast_mem_arg_count, 2); +} + +// Tests that the compiler can correctly propagate the layout assigned by +// shape_representation_fn_ to return types. +TEST_F(XlaCompilerTest, HonorShapeRepresentationFnForRetVal) { + 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); + // 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{write}), var, + DT_INT32); + auto read_plus_one = ops::Add(scope, read, ops::Const(scope, 1)); + auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 3}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2, 3}); + + auto options = DefaultOptions(); + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [](const TensorShape& shape, DataType dt, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dt, shape, &xla_shape)); + *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); + return xla_shape; + }; + options.shape_determination_fns = shape_determination_fns; + // Compiles the graph. + XlaCompiler compiler(options); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + xla::Shape transposed = + xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1}); + // Check that the return shapes are correctly tranposed. + EXPECT_EQ(result.xla_output_shape, + xla::ShapeUtil::MakeTupleShape({transposed, transposed})); + EXPECT_EQ(result.computation->GetProgramShape().value().result(), + xla::ShapeUtil::MakeTupleShape({transposed, transposed})); +} + +// The layout of resource variable shouldn't change after transpose +TEST_F(XlaCompilerTest, TransposeVariables) { + 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); + // 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{write}), var, + DT_INT32); + auto transposed_read = ops::Transpose(scope, read, {1, 0}); + auto reshape = ops::Reshape(scope, transposed_read, {2, 3}); + auto d = ops::_Retval(scope.WithOpName("D"), reshape, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 3}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2, 3}); + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "transpose", + std::move(graph), args, &result)); + xla::Shape transposed = + xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {1, 0}); + // Check that the return shapes are correctly tranposed. + EXPECT_EQ(result.xla_output_shape, + xla::ShapeUtil::MakeTupleShape({transposed, transposed})); +} + +// Unranked fake param returns a 0 shaped tensor. +TEST_F(XlaCompilerTest, UnrankedFakeParam) { + Scope scope = Scope::NewRootScope().ExitOnError(); + PartialTensorShape shape; + auto a = ops::FakeParam(scope, DT_INT32, shape); + auto ret = ops::_Retval(scope.WithOpName("D"), a, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "compile", + std::move(graph), {}, &result)); + // Check that the return shapes are correctly tranposed. + EXPECT_EQ(result.xla_output_shape, + xla::ShapeUtil::MakeTupleShape( + {xla::ShapeUtil::MakeShape(xla::S32, {0})})); +} + +// Tests that the compiler doesn't reorder the parameters. +TEST_F(XlaCompilerTest, MixedOrderArguments) { + for (bool swap_order : {false, true}) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto var = + ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, swap_order ? 0 : 1); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, swap_order ? 1 : 0); + // 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{write}), var, + DT_INT32); + auto read_plus_one = ops::Add(scope, read, ops::Const(scope, 1)); + auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + if (swap_order) { + // Even after swapping arguments, the compiler should maintain the new + // ordering of parameters. + std::swap(args[0], args[1]); + } + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompileOptions compile_options; + compile_options.always_return_tuple = false; + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + + EXPECT_THAT(result.input_mapping, ::testing::ElementsAre(0, 1)); + } +} + +TEST_F(XlaCompilerTest, HasSaneErrorOnNonCompileTimeConstantInputToReshape) { + // Builds a graph that adds reshapes a tensor, but with the shape not + // statically known. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); + auto c = ops::Reshape(scope.WithOpName("C"), a, b); + auto d = ops::_Retval(scope.WithOpName("D"), c, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[1].kind = XlaCompiler::Argument::kParameter; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + absl::Status status = + compiler.CompileGraph(XlaCompiler::CompileOptions(), "reshape", + std::move(graph), args, &result); + EXPECT_FALSE(status.ok()); + EXPECT_TRUE(absl::StrContains(status.message(), "depends on a parameter")) + << status.message(); + EXPECT_TRUE(absl::StrContains(status.message(), "{{node C}}")) + << status.message(); + EXPECT_TRUE( + absl::StrContains(status.message(), "must be a compile-time constant")) + << status.message(); +} + +// Tests handling of compile-time constant outputs. +TEST_F(XlaCompilerTest, ConstantOutputs) { + // Builds a graph with one compile-time constant output and one data-dependent + // output, i.e., + // func(a) { b=7; c=-a; return b, c; } + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::Const(scope.WithOpName("B"), 7); + auto c = ops::Neg(scope.WithOpName("C"), a); + auto d = ops::_Retval(scope.WithOpName("D"), b, 0); + auto e = ops::_Retval(scope.WithOpName("E"), c, 1); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + + XlaCompiler::Options options = DefaultOptions(); + XlaCompiler compiler(options); + + { + std::unique_ptr graph_copy(new Graph(OpRegistry::Global())); + CopyGraph(*graph, graph_copy.get()); + + XlaCompiler::CompileOptions compile_options; + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants", + std::move(graph_copy), args, &result)); + + ASSERT_EQ(2, result.outputs.size()); + EXPECT_FALSE(result.outputs[0].is_constant); + EXPECT_FALSE(result.outputs[1].is_constant); + + // Tests that the generated computation works. + xla::Literal param0_literal = xla::LiteralUtil::CreateR1({7, 42}); + std::unique_ptr param0_data = + client_->TransferToServer(param0_literal).value(); + + std::unique_ptr actual = + client_->Execute(*result.computation, {param0_data.get()}).value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal expected0 = xla::LiteralUtil::CreateR0(7); + xla::Literal expected1 = xla::LiteralUtil::CreateR1({-7, -42}); + xla::Literal expected = + xla::LiteralUtil::MakeTuple({&expected0, &expected1}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected, actual_literal)); + } +} + +TEST_F(XlaCompilerTest, ConstantOutputsOfFunctionalNode) { + // Define a function with one compile-time constant output and one + // data-dependent output. + // @function.Defun(noinline=True) + // foo(a) {b=7; return b, a; } + const Tensor seven = test::AsScalar(7); + FunctionDef fdef = FunctionDefHelper::Create( + "foo", {"a_0:int32"}, {"const:int32", "a:int32"}, {}, + { + {{"Const"}, "Const", {}, {{"dtype", DT_INT32}, {"value", seven}}}, + }, + {{"a", "a_0"}, {"const", "Const:output:0"}}); + (*fdef.mutable_attr())["_noinline"].set_b(true); + FunctionDefLibrary fdef_lib; + *(fdef_lib.add_function()) = fdef; + std::unique_ptr graph(new Graph(OpRegistry::Global())); + { + Scope scope = Scope::NewRootScope().ExitOnError(); + TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(fdef_lib)); + auto arg = ops::_Arg(scope.WithOpName("input_arg"), DT_INT32, 0); + NodeDef foo; + foo.set_name("foo"); + foo.set_op("foo"); + *foo.add_input() = "input_arg"; + absl::Status status; + scope.graph()->AddNode(foo, &status); + TF_ASSERT_OK(status); + NodeDef retval_1; + retval_1.set_name("retval_0"); + retval_1.set_op(FunctionLibraryDefinition::kRetOp); + *retval_1.add_input() = "foo"; + (*retval_1.mutable_attr())["T"].set_type(DT_INT32); + (*retval_1.mutable_attr())["index"].set_i(0); + scope.graph()->AddNode(retval_1, &status); + TF_ASSERT_OK(status); + NodeDef retval_2; + retval_2.set_name("retval_1"); + retval_2.set_op(FunctionLibraryDefinition::kRetOp); + *retval_2.add_input() = "foo:1"; + (*retval_2.mutable_attr())["T"].set_type(DT_INT32); + (*retval_2.mutable_attr())["index"].set_i(1); + scope.graph()->AddNode(retval_2, &status); + TF_ASSERT_OK(status); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + } + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({1}); + + XlaCompiler::Options options = DefaultOptions(); + FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); + options.flib_def = &flib_def; + XlaCompiler compiler(options); + + XlaCompiler::CompileOptions compile_options; + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "constants", + std::move(graph), args, &result)); + + ASSERT_EQ(2, result.outputs.size()); + EXPECT_FALSE(result.outputs[1].is_constant); +} + +// Tests compilation and execution of a graph that adds two tensors. +TEST_F(XlaCompilerTest, ResourceManager) { + // Builds a graph that calls the dummy resource Op. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = DummyReadResourceCC(scope.WithOpName("B"), a); + auto c = ops::Add(scope.WithOpName("C"), b.output2_, b.output1_); + auto d = ops::_Retval(scope.WithOpName("D"), c, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the argument. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + + DummyResourceForTest* resource = new DummyResourceForTest(); + + // Compiles the graph. + auto options = DefaultOptions(); + std::function populate_function = + [resource](ResourceMgr* rm) { + resource->Ref(); + return rm->Create(rm->default_container(), "dummy", resource); + }; + options.populate_resource_manager = &populate_function; + XlaCompiler compiler(options); + + EXPECT_EQ(0, resource->Get()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "dummy", + std::move(graph), args, &result)); + + EXPECT_EQ(1, resource->Get()); + + resource->Unref(); +} + +// Tests compilation and execution of a graph that adds two tensors. +TEST_F(XlaCompilerTest, DeterministicCompilation) { + // Builds a graph that contains a node with two output edges. The compiler + // should always traverse them in the same order. + const int64_t test_count = 2; + + std::vector results(test_count); + + for (int64_t i = 0; i < test_count; ++i) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::Neg(scope.WithOpName("B"), a); + auto c = ops::Neg(scope.WithOpName("C"), a); + auto d = ops::Add(scope.WithOpName("D"), b, c); + auto e = ops::_Retval(scope.WithOpName("E"), d, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the argument. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + + // Compiles the graph. + auto options = DefaultOptions(); + XlaCompiler compiler(options); + + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "dummy", + std::move(graph), args, &results[i])); + } + + for (int64_t i = 1; i < test_count; ++i) { + const auto& m1 = results[i - 1].computation->proto(); + const auto& m2 = results[i].computation->proto(); + ASSERT_EQ(m1.computations_size(), m2.computations_size()); + // Check if every hlo computation is the same. + for (int k = 0; k < m1.computations_size(); k++) { + const auto& c1 = m1.computations(k); + const auto& c2 = m2.computations(k); + ASSERT_EQ(c1.instructions_size(), c2.instructions_size()); + for (int j = 0; j < c1.instructions_size(); j++) { + auto instr1 = c1.instructions(j); + auto instr2 = c2.instructions(j); + instr1.clear_name(); + instr1.clear_id(); + instr1.clear_operand_ids(); + instr2.clear_name(); + instr2.clear_id(); + instr2.clear_operand_ids(); + // The names of instructions were uniquified by the XlaBuilder and the + // unique ids may be different, the rest of the fields should be + // identical. + std::string str1, str2; + LOG(INFO) << "instr1 = " << instr1.DebugString(); + LOG(INFO) << "instr2 = " << instr2.DebugString(); + instr1.AppendPartialToString(&str1); + instr2.AppendPartialToString(&str2); + EXPECT_EQ(str1, str2); + } + } + } +} + +// Tests a computation that receives a TensorArray resource as input and +// updates it. +TEST_F(XlaCompilerTest, CanPassTensorArraysToAndFromComputation) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0); + auto flow = ops::Const(scope, {}); + auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad1"); + auto grad2 = ops::TensorArrayGrad(scope, arg, grad1.flow_out, "grad2"); + auto index = ops::Const(scope, 1); + auto write = ops::TensorArrayWrite(scope, grad1.grad_handle, index, index, + grad2.flow_out); + auto read = ops::TensorArrayRead(scope, arg, index, write.flow_out, DT_INT32); + auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kTensorArray; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({}); + args[0].max_array_size = 2; + args[0].tensor_array_gradients = {"grad2"}; + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + + ASSERT_EQ(1, result.resource_updates.size()); + const XlaCompiler::ResourceUpdate& update = result.resource_updates[0]; + EXPECT_EQ(0, update.input_index); + EXPECT_EQ(DT_INT32, update.type); + EXPECT_EQ((std::set{"grad1", "grad2"}), + update.tensor_array_gradients_accessed); + + // Tests that the generated computation works. + xla::Literal input_base = xla::LiteralUtil::CreateR1({7, 42}); + xla::Literal input_grad2 = xla::LiteralUtil::CreateR1({-3, 101}); + xla::Literal input = xla::LiteralUtil::MakeTuple({&input_base, &input_grad2}); + std::unique_ptr param0_data = + client_->TransferToServer(input).value(); + + std::unique_ptr actual = + client_->Execute(*result.computation, {param0_data.get()}).value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal output_read = xla::LiteralUtil::CreateR0(42); + xla::Literal output_base = xla::LiteralUtil::CreateR1({7, 42}); + xla::Literal output_grad1 = xla::LiteralUtil::CreateR1({0, 1}); + xla::Literal output_grad2 = xla::LiteralUtil::CreateR1({-3, 101}); + xla::Literal output_resource = + xla::LiteralUtil::MakeTuple({&output_base, &output_grad1, &output_grad2}); + xla::Literal expected_literal = + xla::LiteralUtil::MakeTuple({&output_read, &output_resource}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +// Tests compilation and execution of a graph that adds two tensors. +TEST_F(XlaCompilerTest, UnwrittenTensorArrayGradientsAreNotComputationOutputs) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0); + auto flow = ops::Const(scope, {}); + auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad1"); + auto index = ops::Const(scope, 1); + auto read = ops::TensorArrayRead(scope, arg, index, grad1.flow_out, DT_INT32); + auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kTensorArray; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({}); + args[0].max_array_size = 2; + args[0].tensor_array_gradients = {"grad1"}; + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + + EXPECT_EQ(0, result.resource_updates.size()); +} + +// Tests compilation and execution of a graph that adds two tensors. +TEST_F(XlaCompilerTest, NewTensorArrayGradientsAreComputationOutputs) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg = ops::_Arg(scope.WithOpName("arg"), DT_RESOURCE, 0); + auto flow = ops::Const(scope, {}); + auto grad1 = ops::TensorArrayGrad(scope, arg, flow, "grad2"); + auto index = ops::Const(scope, 1); + auto read = ops::TensorArrayRead(scope, arg, index, grad1.flow_out, DT_INT32); + auto retval = ops::_Retval(scope.WithOpName("retval"), read, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kTensorArray; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({}); + args[0].max_array_size = 2; + args[0].tensor_array_gradients = {"grad1"}; + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + + EXPECT_EQ(1, result.resource_updates.size()); +} + +// Tests CompileFunction with undefined function fails. +TEST_F(XlaCompilerTest, UndefinedFunctionFails) { + XlaCompiler compiler(DefaultOptions()); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + XlaCompiler::CompilationResult result; + NameAttrList name_attr; + name_attr.set_name("Function_NotDefined_"); + absl::Status status = + compiler.CompileFunction(XlaCompiler::CompileOptions(), name_attr, + /*args=*/{}, &result); + EXPECT_FALSE(status.ok()); + EXPECT_TRUE(absl::StrContains(status.message(), "is not defined.")) + << status.message(); +} + +FunctionDef FillFn() { + return FunctionDefHelper::Define( + // Name + "FillFn", + // Args + {"x: T", "dims: int32"}, + // Return values + {"y: T"}, + // Attr def + {"T: {float, double, int32, int64}"}, + // Nodes + {{{"y"}, "Fill", {"dims", "x"}, {{"T", "$T"}}}}); +} + +TEST_F(XlaCompilerTest, FunctionCallWithConstants) { + // Certain operations in a function, "Fill" for example, requires the + // operator's argument to be a compile-time constant instead of a parameter. + // This testcase tests if XlaCompiler can handle such operators inside + // function calls. + XlaCompiler compiler(DefaultOptions()); + + FunctionDefLibrary flib; + *flib.add_function() = FillFn(); + + TF_ASSERT_OK(flib_def_->AddFunctionDef(FillFn())); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + + Scope scope = Scope::NewRootScope().ExitOnError(); + auto value = ops::Const(scope.WithOpName("value"), 1, {}); + auto shape = ops::Const(scope.WithOpName("shape"), {5}, {1}); + TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(flib)); + + NodeDef def; + TF_ASSERT_OK(NodeDefBuilder("fill", "FillFn", flib_def_.get()) + .Input(value.name(), 0, DT_INT32) + .Input(shape.name(), 1, DT_INT32) + .Finalize(&def)); + absl::Status status; + Node* fill = scope.graph()->AddNode(def, &status); + TF_ASSERT_OK(status); + TF_ASSERT_OK(scope.DoShapeInference(fill)); + scope.graph()->AddEdge(value.node(), 0, fill, 0); + scope.graph()->AddEdge(shape.node(), 0, fill, 1); + + auto retval = ops::_Retval(scope.WithOpName("retval"), Output(fill), 0); + + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the argument. + std::vector args; + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "fill", + std::move(graph), args, &result)); +} + +// Tests CompileFunction with a local function lookup failing, fails with +// informative error about both lookups. +TEST_F(XlaCompilerTest, LocalFunctionWithWrongArgumentsFail) { + XlaCompiler compiler(DefaultOptions()); + + auto local_flib_def = LocalFlibDef(&compiler); + TF_ASSERT_OK(local_flib_def->AddFunctionDef(test::function::XTimesTwo())); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + XlaCompiler::CompilationResult result; + NameAttrList name_attr; + name_attr.set_name("XTimesTwo"); + absl::Status status = + compiler.CompileFunction(XlaCompiler::CompileOptions(), name_attr, + /*args=*/{}, &result); + + ASSERT_FALSE(status.ok()); + // Flib lookup failure. + EXPECT_TRUE(absl::StrContains(status.message(), "is not defined.")) + << status.message(); + // Local flib lookup failure. + EXPECT_TRUE(absl::StrContains(status.message(), "Attr T is not found")) + << status.message(); +} + +FunctionDef SliceFn() { + return FunctionDefHelper::Define( + // Name + "SliceFn", + // Args + {"x: T", "begin: Index", "size: Index"}, + // Return values + {"y: T"}, + // Attr def + {"T: {float, double, int32, int64}", "Index: {int32,int64}"}, + // Nodes + {{{"y"}, + "Slice", + {"x", "begin", "size"}, + {{"T", "$T"}, {"Index", "$Index"}}}}); +} + +TEST_F(XlaCompilerTest, SliceWithDynamicBegins) { + // Certain operations in a function, "Slice" for example, support both dynamic + // inputs and static inputs. This test checks that dynamic inputs can also + // be supported in a function call. + XlaCompiler compiler(DefaultOptions()); + + FunctionDefLibrary flib; + *flib.add_function() = SliceFn(); + + TF_ASSERT_OK(flib_def_->AddFunctionDef(SliceFn())); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + + Scope scope = Scope::NewRootScope().ExitOnError(); + auto value = ops::Const(scope.WithOpName("shape"), {5}, {1}); + auto begin = ops::_Arg(scope.WithOpName("arg"), DT_INT32, 0); + auto size = ops::Const(scope.WithOpName("value"), {1}, {1}); + + TF_EXPECT_OK(scope.graph()->AddFunctionLibrary(flib)); + + NodeDef def; + TF_ASSERT_OK(NodeDefBuilder("slice", "SliceFn", flib_def_.get()) + .Input(value.name(), 0, DT_INT32) + .Input(begin.node()->name(), 1, DT_INT32) + .Input(size.name(), 2, DT_INT32) + .Finalize(&def)); + absl::Status status; + Node* slice = scope.graph()->AddNode(def, &status); + TF_ASSERT_OK(status); + TF_ASSERT_OK(scope.DoShapeInference(slice)); + scope.graph()->AddEdge(value.node(), 0, slice, 0); + scope.graph()->AddEdge(begin.node(), 0, slice, 1); + scope.graph()->AddEdge(size.node(), 0, slice, 2); + + auto retval = ops::_Retval(scope.WithOpName("retval"), Output(slice), 0); + + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the argument. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({1}); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "slice", + std::move(graph), args, &result)); +} + +void RunAndCheckVariablesComputation( + xla::Client* client, const XlaCompiler::CompilationResult& result) { + xla::Literal param0_literal = xla::LiteralUtil::CreateR1({7, 42}); + xla::Literal param1_literal = xla::LiteralUtil::CreateR1({-3, 101}); + std::unique_ptr param0_data = + client->TransferToServer(param0_literal).value(); + std::unique_ptr param1_data = + client->TransferToServer(param1_literal).value(); + + std::unique_ptr actual = + client + ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) + .value(); + xla::Literal actual_literal = client->Transfer(*actual).value(); + + xla::Literal expected0 = xla::LiteralUtil::CreateR1({5, 144}); + xla::Literal expected1 = xla::LiteralUtil::CreateR1({4, 143}); + xla::Literal expected_literal = + xla::LiteralUtil::MakeTuple({&expected0, &expected1}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +// Tests a simple graph that reads and writes a variable. +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); + // 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{write}), var, + DT_INT32); + auto read_plus_one = ops::Add(scope, read, ops::Const(scope, 1)); + auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + RunAndCheckVariablesComputation(client_, result); +} + +TEST_F(XlaCompilerTest, ResultLayoutSingle) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Retval(scope.WithOpName("RET"), a, 0); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 3}); + + auto options = DefaultOptions(); + // Sets the representation function to return a non-default layout. + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [](const TensorShape& shape, DataType type, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape)); + *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); + return xla_shape; + }; + options.shape_determination_fns = shape_determination_fns; + + // Compiles the graph. + XlaCompiler compiler(options); + + XlaCompiler::CompilationResult result; + auto compile_options = XlaCompiler::CompileOptions(); + compile_options.always_return_tuple = false; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "id", std::move(graph), + args, &result)); + EXPECT_TRUE(xla::ShapeUtil::Equal( + result.xla_output_shape, + xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1}))); + EXPECT_EQ(result.computation->GetProgramShape().value().result(), + result.xla_output_shape); +} + +TEST_F(XlaCompilerTest, ResultLayoutMultiple) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Retval(scope.WithOpName("RET1"), a, 0); + auto c = ops::_Retval(scope.WithOpName("RET2"), a, 1); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 3}); + + auto options = DefaultOptions(); + // Sets the representation function to return a non-default layout. + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [](const TensorShape& shape, DataType type, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape)); + *xla_shape.mutable_layout() = xla::LayoutUtil::MakeLayout({0, 1}); + return xla_shape; + }; + shape_determination_fns.layout_preference_fn = UseNoPreferenceLayoutFn(); + options.shape_determination_fns = shape_determination_fns; + + // Compiles the graph. + XlaCompiler compiler(options); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "id", + std::move(graph), args, &result)); + xla::Shape result_shape = + xla::ShapeUtil::MakeShapeWithDenseLayout(xla::S32, {2, 3}, {0, 1}); + + EXPECT_TRUE(xla::ShapeUtil::Equal( + result.xla_output_shape, + xla::ShapeUtil::MakeTupleShape({result_shape, result_shape}))); + EXPECT_EQ(result.computation->GetProgramShape().value().result(), + result.xla_output_shape); +} + +// Tests a simple graph that reads and writes a variable. +TEST_F(XlaCompilerTest, ReturnResourceHandleOnly) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 0); + auto d = ops::_Retval(scope.WithOpName("D"), var, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kVariable; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + + // Tests that the generated computation works. + xla::Literal param1_literal = xla::LiteralUtil::CreateR1({-3, 101}); + std::unique_ptr param1_data = + client_->TransferToServer(param1_literal).value(); + + std::unique_ptr actual = + client_->Execute(*result.computation, {param1_data.get()}).value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +TEST_F(XlaCompilerTest, ReturnResourceHandle) { + 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); + // 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{write}), var, + DT_INT32); + auto read_plus_one = ops::Add(scope, read, ops::Const(scope, 1)); + auto r = ops::_Retval(scope.WithOpName("R"), var, 0); + auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 1); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + RunAndCheckVariablesComputation(client_, result); +} + +absl::StatusOr> BuildTestGraph() { + 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); + auto read = ops::ReadVariableOp( + scope.WithControlDependencies(std::vector{write}), var, + DT_INT32); + auto read_plus_one = ops::Add(scope, read, ops::Const(scope, 1)); + auto d = ops::_Retval(scope.WithOpName("D"), read_plus_one, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_RETURN_IF_ERROR(scope.ToGraph(graph.get())); + return std::move(graph); +} + +// Tests a simple graph that reads and writes a variable, with a +// shape_representation_fn passed to the compiler that flattens all +// variable tensors to vectors. +TEST_F(XlaCompilerTest, VariableRepresentationShapeFunction) { + TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr graph, BuildTestGraph()); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 2}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2, 2}); + + // Compiles the graph. + XlaCompiler::Options options = DefaultOptions(); + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [](const TensorShape& shape, DataType type, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::PrimitiveType ptype; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(type, &ptype)); + return xla::ShapeUtil::MakeShape(ptype, {shape.num_elements()}); + }; + options.shape_determination_fns = shape_determination_fns; + XlaCompiler compiler(options); + + XlaCompiler::CompileOptions compile_options; + compile_options.is_entry_computation = false; // Only reshape variables. + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + + TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr program_shape, + client_->GetComputationShape(*result.computation)); + + ASSERT_EQ(program_shape->parameters_size(), 2); + EXPECT_TRUE( + xla::ShapeUtil::Compatible(program_shape->parameters(0), + xla::ShapeUtil::MakeShape(xla::S32, {2, 2}))); + EXPECT_TRUE(xla::ShapeUtil::Compatible( + program_shape->parameters(1), xla::ShapeUtil::MakeShape(xla::S32, {4}))); + EXPECT_TRUE(xla::ShapeUtil::Compatible( + program_shape->result(), + xla::ShapeUtil::MakeTupleShape( + {xla::ShapeUtil::MakeShape(xla::S32, {2, 2}), + xla::ShapeUtil::MakeShape(xla::S32, {4})}))); + + // Tests that the generated computation works. + xla::Literal param0_literal = + xla::LiteralUtil::CreateR2({{4, 55}, {1, -3}}); + xla::Literal param1_literal = + xla::LiteralUtil::CreateR1({22, 11, 33, 404}); + std::unique_ptr param0_data = + client_->TransferToServer(param0_literal).value(); + std::unique_ptr param1_data = + client_->TransferToServer(param1_literal).value(); + + std::unique_ptr actual = + client_ + ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) + .value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal expected0 = + xla::LiteralUtil::CreateR2({{27, 67}, {35, 402}}); + xla::Literal expected1 = + xla::LiteralUtil::CreateR1({26, 66, 34, 401}); + xla::Literal expected_literal = + xla::LiteralUtil::MakeTuple({&expected0, &expected1}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +TEST_F(XlaCompilerTest, ArgRetvalShapeRepresentationFunction) { + TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr graph, BuildTestGraph()); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 2}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2, 2}); + + // Compiles the graph. + XlaCompiler::Options options = DefaultOptions(); + XlaShapeLayoutHelpers::ShapeDeterminationFns shape_determination_fns; + shape_determination_fns.shape_representation_fn = + [](const TensorShape& shape, DataType type, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::PrimitiveType ptype; + TF_RETURN_IF_ERROR(DataTypeToPrimitiveType(type, &ptype)); + return xla::ShapeUtil::MakeShape(ptype, {shape.num_elements()}); + }; + options.shape_determination_fns = shape_determination_fns; + XlaCompiler compiler(options); + + XlaCompiler::CompileOptions compile_options; + compile_options.is_entry_computation = true; // Reshape args and retvals. + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + + TF_ASSERT_OK_AND_ASSIGN(std::unique_ptr program_shape, + client_->GetComputationShape(*result.computation)); + + ASSERT_EQ(program_shape->parameters_size(), 2); + EXPECT_TRUE(xla::ShapeUtil::Compatible( + program_shape->parameters(0), xla::ShapeUtil::MakeShape(xla::S32, {4}))); + EXPECT_TRUE(xla::ShapeUtil::Compatible( + program_shape->parameters(1), xla::ShapeUtil::MakeShape(xla::S32, {4}))); + EXPECT_TRUE(xla::ShapeUtil::Compatible( + program_shape->result(), + xla::ShapeUtil::MakeTupleShape( + {xla::ShapeUtil::MakeShape(xla::S32, {4}), + xla::ShapeUtil::MakeShape(xla::S32, {4})}))); + + // Tests that the generated computation works. + xla::Literal param0_literal = + xla::LiteralUtil::CreateR1({4, 55, 1, -3}); + xla::Literal param1_literal = + xla::LiteralUtil::CreateR1({22, 11, 33, 404}); + std::unique_ptr param0_data = + client_->TransferToServer(param0_literal).value(); + std::unique_ptr param1_data = + client_->TransferToServer(param1_literal).value(); + + std::unique_ptr actual = + client_ + ->Execute(*result.computation, {param0_data.get(), param1_data.get()}) + .value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal expected0 = + xla::LiteralUtil::CreateR1({27, 67, 35, 402}); + xla::Literal expected1 = + xla::LiteralUtil::CreateR1({26, 66, 34, 401}); + xla::Literal expected_literal = + xla::LiteralUtil::MakeTuple({&expected0, &expected1}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +// Tests a graph which has a function with an invalid op. +TEST_F(XlaCompilerTest, FunctionWithInvalidOp) { + XlaCompiler compiler(DefaultOptions()); + + FunctionDefLibrary flib; + FunctionDef fn = FillFn(); + NodeDef* node = fn.add_node_def(); + node->set_name("Invalid"); + node->set_op("InvalidOp"); /* unsupported op */ + node = fn.add_node_def(); + node->set_name("Switch"); + node->set_op("Switch"); /* control flow node */ + *flib.add_function() = fn; + + TF_ASSERT_OK(flib_def_->AddFunctionDef(fn)); + + std::unique_ptr graph(new Graph(OpRegistry::Global())); + + Scope scope = Scope::NewRootScope().ExitOnError(); + auto value = ops::Const(scope.WithOpName("value"), 1, {}); + auto shape = ops::Const(scope.WithOpName("shape"), {5}, {1}); + TF_ASSERT_OK(scope.graph()->AddFunctionLibrary(flib)); + + NodeDef def; + TF_ASSERT_OK(NodeDefBuilder("fill_fn", "FillFn", flib_def_.get()) + .Input(value.name(), 0, DT_INT32) + .Input(shape.name(), 1, DT_INT32) + .Finalize(&def)); + absl::Status status; + Node* fill = scope.graph()->AddNode(def, &status); + TF_ASSERT_OK(status); + TF_ASSERT_OK(scope.DoShapeInference(fill)); + scope.graph()->AddEdge(value.node(), 0, fill, 0); + scope.graph()->AddEdge(shape.node(), 0, fill, 1); + + auto retval = ops::_Retval(scope.WithOpName("retval"), Output(fill), 0); + + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + std::vector args; + XlaCompiler::CompilationResult result; + status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "fill", + std::move(graph), args, &result); + ASSERT_FALSE(status.ok()); + EXPECT_TRUE(absl::StrContains(status.message(), "InvalidOp")) + << status.message(); + EXPECT_TRUE(absl::StrContains(status.message(), "{{node fill_fn}}")) + << status.message(); +} + +// Tests a graph which has a node with invalid data type. +TEST_F(XlaCompilerTest, NodeWithInvalidDataType) { + std::unique_ptr graph(new Graph(OpRegistry::Global())); + NodeDef shape; + shape.set_name("Shape"); + shape.set_op("Shape"); + (*shape.mutable_attr())["T"].set_type(DT_INT32); + (*shape.mutable_attr())["out_type"].set_type(DT_BOOL); /* invalid type */ + absl::Status status; + Node* shape_node = graph->AddNode(shape, &status); + TF_ASSERT_OK(status); + graph->AddControlEdge(graph->source_node(), shape_node); + + std::vector args; + XlaCompiler::CompilationResult result; + XlaCompiler compiler(DefaultOptions()); + status = compiler.CompileGraph(XlaCompiler::CompileOptions(), "invalid_type", + std::move(graph), args, &result); + ASSERT_FALSE(status.ok()); + EXPECT_TRUE(absl::StrContains(status.message(), + "is not in the list of allowed values")) + << status.message(); + EXPECT_TRUE(absl::StrContains(status.message(), "{{node Shape}}")) + << status.message(); +} + +TEST_F(XlaCompilerTest, SingleOpWithoutInputs) { + std::unique_ptr graph(new Graph(OpRegistry::Global())); + NodeDef no_op; + no_op.set_name("NoOp"); + no_op.set_op("NoOp"); + absl::Status status; + graph->AddNode(no_op, &status); + TF_ASSERT_OK(status); + + std::vector args; + XlaCompiler compiler(DefaultOptions()); + // No control edge linking NoOp with source/sink. + { + std::unique_ptr graph_copy(new Graph(OpRegistry::Global())); + CopyGraph(*graph, graph_copy.get()); + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "NoOp", + std::move(graph_copy), args, &result)); + } +} + +class DummySideEffectingOp : public XlaOpKernel { + public: + explicit DummySideEffectingOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + OP_REQUIRES_OK(ctx, ctx->compiler()->SetNodeToken( + name(), xla::CreateToken(ctx->builder()))); + } +}; + +REGISTER_OP("DummySideEffectingOp"); + +REGISTER_XLA_OP(Name("DummySideEffectingOp"), DummySideEffectingOp); + +TEST_F(XlaCompilerTest, TokenInputAndOutput) { + std::unique_ptr graph(new Graph(OpRegistry::Global())); + NodeDef side_effecting_op; + side_effecting_op.set_name("DummySideEffectingOp"); + side_effecting_op.set_op("DummySideEffectingOp"); + AddNodeAttr(kXlaTokenInputNodesAttrName, + std::vector{kXlaTokenArgNodeName}, + &side_effecting_op); + AddNodeAttr(kXlaOriginalOutsideCompilationNodeName, side_effecting_op.name(), + &side_effecting_op); + absl::Status status; + graph->AddNode(side_effecting_op, &status); + TF_ASSERT_OK(status); + EXPECT_TRUE(FixupSourceAndSinkEdges(graph.get())); + + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kResource; + args[0].resource_kind = XlaResource::kVariable; + args[0].initialized = true; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 2}); + + { + // The case for entry computation: we don't add token input/output. Instead, + // we use CreateToken HLO to create the entry token. + XlaCompiler::CompileOptions options; + options.is_entry_computation = true; + options.add_token_input_output = false; + options.return_updated_values_for_all_resources = true; + XlaCompiler compiler(DefaultOptions()); + + std::unique_ptr graph_copy(new Graph(OpRegistry::Global())); + CopyGraph(*graph, graph_copy.get()); + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(options, "NoOp", std::move(graph_copy), + args, &result)); + EXPECT_EQ(result.xla_input_shapes.size(), 1); + EXPECT_TRUE(result.xla_output_shape.IsTuple()); + EXPECT_EQ(xla::ShapeUtil::TupleElementCount(result.xla_output_shape), 1); + } + { + // The case for non-entry computation (e.g. while loop body). We add token + // input/output. + XlaCompiler::CompileOptions options; + options.is_entry_computation = false; + options.add_token_input_output = true; + options.return_updated_values_for_all_resources = true; + XlaCompiler compiler(DefaultOptions()); + + std::unique_ptr graph_copy(new Graph(OpRegistry::Global())); + CopyGraph(*graph, graph_copy.get()); + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(options, "NoOp", std::move(graph_copy), + args, &result)); + EXPECT_EQ(result.xla_input_shapes.size(), 2); + EXPECT_TRUE(result.xla_input_shapes[1].IsToken()); + EXPECT_TRUE(result.xla_output_shape.IsTuple()); + EXPECT_EQ(xla::ShapeUtil::TupleElementCount(result.xla_output_shape), 2); + EXPECT_TRUE(xla::ShapeUtil::GetTupleElementShape(result.xla_output_shape, 1) + .IsToken()); + } +} + +TEST_F(XlaCompilerTest, OpsWithTensorListInput) { + FunctionDefLibrary fdef_lib; + FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); + // Build cond fn for While. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); + auto result = ops::Const(scope, {true}, {}); + ops::_Retval(scope.WithOpName("ret"), result, 0); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(*graph, "cond", &fdef)); + TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); + } + // Build body fn for While. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + auto arg = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); + ops::_Retval(scope.WithOpName("ret"), arg, 0); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(*graph, "body", &fdef)); + TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); + } + + Scope scope = Scope::NewRootScope().ExitOnError(); + auto element_shape = ops::Const(scope, {1}, {1}); + auto max_elements = ops::Const(scope, {10}, {}); + auto arg = ops::_Arg(scope.WithOpName("arg"), DT_VARIANT, 0); + std::initializer_list out = {arg, arg}; + auto add_n = ops::AddN(scope, out); + NameAttrList cond_fn, body_fn; + cond_fn.set_name("cond"); + body_fn.set_name("body"); + auto while_op = + ops::While(scope, std::initializer_list{arg}, cond_fn, body_fn); + auto ret0 = ops::_Retval(scope.WithOpName("ret0"), add_n, 0); + auto ret1 = ops::_Retval(scope.WithOpName("ret1"), while_op.output[0], 1); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kTensorList; + xla::Shape tensor_list_element_shape; + TF_ASSERT_OK(TensorShapeToXLAShape(DT_INT32, TensorShape{1}, + &tensor_list_element_shape)); + xla::Shape index_shape; + TF_ASSERT_OK(TensorShapeToXLAShape(DT_INT32, TensorShape{}, &index_shape)); + std::vector shapes{tensor_list_element_shape, index_shape}; + xla::Shape arg_shape = xla::ShapeUtil::MakeTupleShape(shapes); + args[0].shape = arg_shape; + + // Compiles the graph. + XlaCompiler::Options options = DefaultOptions(); + options.flib_def = &flib_def; + XlaCompiler compiler(options); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "add", + std::move(graph), args, &result)); + ASSERT_EQ(result.outputs.size(), 2); + const XlaCompiler::OutputDescription& output0 = result.outputs[0]; + ASSERT_TRUE(output0.is_tensor_list); + const XlaCompiler::OutputDescription& output1 = result.outputs[1]; + ASSERT_TRUE(output1.is_tensor_list); +} + +// Test the compiler supports WhileOp with a loop body where DT_RESOURCE +// variables are both inputs and outputs. +TEST_F(XlaCompilerTest, WhileWithResources) { + FunctionDefLibrary fdef_lib; + FunctionLibraryDefinition flib_def(OpRegistry::Global(), fdef_lib); + // Build cond fn for While. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2); + auto less = ops::Less(scope, arg0, ops::Const(scope, 10)); + (void)ops::_Retval(scope.WithOpName("ret"), less, 0); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(*graph, "cond", &fdef)); + TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); + } + // Build body fn for While. + { + Scope scope = Scope::NewRootScope().ExitOnError(); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2); + auto read1 = ops::ReadVariableOp(scope.WithOpName("read1"), arg1, DT_INT32); + auto plus_read1 = ops::Add(scope, arg0, read1); + auto read2 = ops::ReadVariableOp(scope.WithOpName("read2"), arg2, DT_INT32); + auto minus_read2 = ops::Sub(scope, plus_read1, read2); + (void)ops::_Retval(scope.WithOpName("ret0"), minus_read2, 0); + (void)ops::_Retval(scope.WithOpName("ret1"), arg1, 1); + (void)ops::_Retval(scope.WithOpName("ret2"), arg2, 2); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + FunctionDef fdef; + TF_ASSERT_OK(GraphToFunctionDef(*graph, "body", &fdef)); + TF_ASSERT_OK(flib_def.AddFunctionDef(fdef)); + } + + Scope scope = Scope::NewRootScope().ExitOnError(); + auto arg0 = ops::_Arg(scope.WithOpName("arg0"), DT_INT32, 0); + auto arg1 = ops::_Arg(scope.WithOpName("arg1"), DT_RESOURCE, 1); + auto arg2 = ops::_Arg(scope.WithOpName("arg2"), DT_RESOURCE, 2); + + NameAttrList cond_fn, body_fn; + cond_fn.set_name("cond"); + body_fn.set_name("body"); + auto while_op = ops::While( + scope, std::initializer_list{arg0, arg1, arg2}, cond_fn, body_fn); + + (void)ops::_Retval(scope.WithOpName("ret0"), while_op.output[0], 0); + (void)ops::_Retval(scope.WithOpName("ret1"), while_op.output[1], 1); + (void)ops::_Retval(scope.WithOpName("ret2"), while_op.output[2], 2); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(3); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({}); + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({}); + args[2].kind = XlaCompiler::Argument::kResource; + args[2].resource_kind = XlaResource::kVariable; + args[2].initialized = true; + args[2].type = DT_INT32; + args[2].shape = TensorShape({}); + + // Compiles the graph. + XlaCompiler::Options options = DefaultOptions(); + options.flib_def = &flib_def; + XlaCompiler compiler(options); + + XlaCompiler::CompileOptions compile_options = XlaCompiler::CompileOptions(); + compile_options.return_updated_values_for_all_resources = true; + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "tested_while_with_vars", + std::move(graph), args, &result)); + ASSERT_EQ(result.outputs.size(), 3); + const XlaCompiler::OutputDescription& output1 = result.outputs[1]; + ASSERT_EQ(output1.input_index, 1); + const XlaCompiler::OutputDescription& output2 = result.outputs[2]; + ASSERT_EQ(output2.input_index, 2); + + // Tests that the generated computation works. + xla::Literal literal0 = xla::LiteralUtil::CreateR0(0); + xla::Literal literal1 = xla::LiteralUtil::CreateR0(2); + xla::Literal literal2 = xla::LiteralUtil::CreateR0(1); + std::unique_ptr data0 = + client_->TransferToServer(literal0).value(); + std::unique_ptr data1 = + client_->TransferToServer(literal1).value(); + std::unique_ptr data2 = + client_->TransferToServer(literal2).value(); + + std::unique_ptr actual = + client_ + ->Execute(*result.computation, + {data0.get(), data1.get(), data2.get()}) + .value(); + xla::Literal actual_literal = client_->Transfer(*actual).value(); + + xla::Literal expected0 = xla::LiteralUtil::CreateR0(10); + xla::Literal expected1 = xla::LiteralUtil::CreateR0(2); + xla::Literal expected2 = xla::LiteralUtil::CreateR0(1); + xla::Literal expected_literal = + xla::LiteralUtil::MakeTuple({&expected0, &expected1, &expected2}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +TEST_F(XlaCompilerTest, SetShardingForReturnedTuple) { + // Builds a graph that returns its only argument. + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Retval(scope.WithOpName("B"), a, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Sets _XlaSharding attribute for the _Retval node. + auto node_name_index = graph->BuildNodeNameIndex(); + Node* ret_node = node_name_index["B"]; + ASSERT_NE(ret_node, nullptr); + xla::Array tile_assignment({2}); + tile_assignment.FillIota(0); + xla::HloSharding sharding = xla::HloSharding::Tile(tile_assignment); + ret_node->AddAttr("_XlaSharding", sharding.ToProto().SerializeAsString()); + + // Builds a description of the arguments. + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + + // Compiles the graph. + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "test", + std::move(graph), args, &result)); + + // Tests that we set sharding on the root TUPLE instruction. + const auto& hlo_module_proto = result.computation->proto(); + ASSERT_EQ(hlo_module_proto.computations_size(), 1); + const auto& hlo_computation_proto = hlo_module_proto.computations(0); + std::optional root_instruction_proto; + for (const auto& inst : hlo_computation_proto.instructions()) { + if (xla::HloInstruction::CalculateLocalId(inst.id()) == + xla::HloInstruction::CalculateLocalId( + hlo_computation_proto.root_id())) { + root_instruction_proto = inst; + break; + } + } + ASSERT_TRUE(root_instruction_proto); + xla::Shape tuple_shape = xla::ShapeUtil::MakeTupleShape( + {xla::ShapeUtil::MakeShape(xla::S32, {2})}); + xla::HloSharding tuple_sharding = xla::HloSharding::Tuple( + tuple_shape, std::vector{sharding}); + EXPECT_EQ(root_instruction_proto->sharding().SerializeAsString(), + tuple_sharding.ToProto().SerializeAsString()); +} + +TEST_F(XlaCompilerTest, AliasResourceUpdates) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::Const(scope.WithOpName("A"), {1, 2}); + auto var = ops::_Arg(scope.WithOpName("V"), DT_RESOURCE, 1); + auto write = ops::AssignAddVariableOp(scope, var, a); + auto read = ops::ReadVariableOp( + scope.WithControlDependencies(std::vector{write}), var, + DT_INT32); + auto d = ops::_Retval(scope.WithOpName("D"), read, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + // Builds a description of the arguments. + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kConstant; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2}); + args[0].constant_value = Tensor(DT_INT32, {1, 1}); + args[0].initialized = true; + + args[1].kind = XlaCompiler::Argument::kResource; + args[1].resource_kind = XlaResource::kVariable; + args[1].initialized = true; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2}); + + XlaCompiler compiler(DefaultOptions()); + + XlaCompiler::CompileOptions compile_options; + compile_options.alias_resource_update = true; + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "add", std::move(graph), + args, &result)); + + const xla::HloInputOutputAliasProto& alias = + result.computation->proto().input_output_alias(); + EXPECT_EQ(alias.entries_size(), 1); + EXPECT_EQ(alias.entries(0).parameter_number(), 0); +} + +// Tests that passing in an exact duplicate input to SetDeviceToHostMetadata +// is not an error. +TEST_F(XlaCompilerTest, SetDeviceToHostMetadataExactDuplicate) { + XlaCompiler compiler(DefaultOptions()); + + const std::string& key = "comm_key"; + std::vector types{DT_INT32}; + std::vector shapes{TensorShape({2})}; + + TF_ASSERT_OK(compiler.SetDeviceToHostMetadata(key, types, shapes)); + TF_ASSERT_OK(compiler.SetDeviceToHostMetadata(key, types, shapes)); +} + +// Tests that passing in a mismatched duplicate input to +// SetDeviceToHostMeatadata is not an error. +TEST_F(XlaCompilerTest, SetDeviceToHostMetadataMismatchedDuplicate) { + XlaCompiler compiler(DefaultOptions()); + + const std::string& key = "comm_key"; + std::vector types{DT_INT32}; + std::vector shapes{TensorShape({2})}; + std::vector types2{DT_FLOAT}; + std::vector shapes2{TensorShape({1})}; + + TF_ASSERT_OK(compiler.SetDeviceToHostMetadata(key, types, shapes)); + absl::Status status = compiler.SetDeviceToHostMetadata(key, types2, shapes2); + EXPECT_EQ(status.code(), error::Code::INVALID_ARGUMENT); +} + +// Tests that passing in an exact duplicate input to SetHostToDeviceMetadata +// is not an error. +TEST_F(XlaCompilerTest, SetHostToDeviceMetadataExactDuplicate) { + XlaCompiler compiler(DefaultOptions()); + + const std::string& key = "comm_key"; + std::vector types{DT_INT32}; + std::vector shapes{TensorShape({2})}; + + TF_ASSERT_OK(compiler.SetHostToDeviceMetadata(key, types, shapes)); + TF_ASSERT_OK(compiler.SetHostToDeviceMetadata(key, types, shapes)); +} + +// Tests that passing in a mismatched duplicate input to +// SetHostToDeviceMeatadata is not an error. +TEST_F(XlaCompilerTest, SetHostToDeviceMetadataMismatchedDuplicate) { + XlaCompiler compiler(DefaultOptions()); + + const std::string& key = "comm_key"; + std::vector types{DT_INT32}; + std::vector shapes{TensorShape({2})}; + std::vector types2{DT_FLOAT}; + std::vector shapes2{TensorShape({1})}; + + TF_ASSERT_OK(compiler.SetHostToDeviceMetadata(key, types, shapes)); + absl::Status status = compiler.SetHostToDeviceMetadata(key, types2, shapes2); + EXPECT_EQ(status.code(), error::Code::INVALID_ARGUMENT); +} + +TEST_F(XlaCompilerTest, GetChannelHandleIndependently) { + XlaCompiler compiler1(DefaultOptions()); + XlaCompiler compiler2(DefaultOptions()); + int num_channels = 3; + std::vector channel_ids1, channel_ids2; + for (int j = 0; j < num_channels; ++j) { + xla::ChannelHandle channel_handle; + TF_ASSERT_OK( + compiler1.GetChannelHandle(/*key=*/absl::StrCat(j), &channel_handle)); + channel_ids1.push_back(channel_handle.handle()); + } + for (int j = 0; j < num_channels; ++j) { + xla::ChannelHandle channel_handle; + TF_ASSERT_OK( + compiler2.GetChannelHandle(/*key=*/absl::StrCat(j), &channel_handle)); + channel_ids2.push_back(channel_handle.handle()); + } + EXPECT_THAT(channel_ids1, ::testing::UnorderedElementsAreArray({1, 2, 3})); + EXPECT_THAT(channel_ids2, ::testing::UnorderedElementsAreArray({1, 2, 3})); +} + +TEST_F(OpsTestBase, BuildSingleOpCompileArgument) { + TF_EXPECT_OK(NodeDefBuilder("identity_op", "Identity") + .Input(FakeInput(DT_FLOAT)) + .Attr("T", DT_FLOAT) + .Finalize(node_def())); + TF_EXPECT_OK(InitOp()); + AddInputFromArray(TensorShape({1, 2}), {0, 1}); + TF_EXPECT_OK(RunOpKernel()); + + XlaCompiler::SingleOpCompileArgument arg(*context_); + + EXPECT_THAT(arg.output_dtypes, ::testing::ElementsAreArray({DT_FLOAT})); + EXPECT_EQ(arg.node_def.SerializeAsString(), + context_->op_kernel().def().SerializeAsString()); + EXPECT_EQ(arg.config_proto.ByteSizeLong(), 0); +} + +TEST_F(OpsTestBase, CompileSingleOp) { + TF_EXPECT_OK(NodeDefBuilder("identity_op", "Identity") + .Input(FakeInput(DT_FLOAT)) + .Attr("T", DT_FLOAT) + .Finalize(node_def())); + TF_EXPECT_OK(InitOp()); + AddInputFromArray(TensorShape({1, 2}), {6.9, 4.2}); + TF_EXPECT_OK(RunOpKernel()); + + XlaCompiler::SingleOpCompileArgument single_op_arg(*context_); + + xla::Client* client = xla::ClientLibrary::LocalClientOrDie(); + XlaOpRegistry::RegisterCompilationKernels(); + FunctionDefLibrary flib; + std::unique_ptr flib_def( + new FunctionLibraryDefinition(OpRegistry::Global(), flib)); + + XlaCompiler::Options options; + options.device_type = DeviceType(DEVICE_CPU_XLA_JIT); + options.client = client; + options.flib_def = flib_def.get(); + + XlaCompiler compiler(options); + + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kConstant; + args[0].type = DT_FLOAT; + args[0].shape = TensorShape({1, 2}); + args[0].constant_value = GetInput(0); + args[0].initialized = true; + + XlaCompiler::CompilationResult result; + TF_EXPECT_OK(compiler.CompileSingleOp(XlaCompiler::CompileOptions(), + single_op_arg, args, &result)); + + // Tests that the generated computation works. + std::unique_ptr actual = + client->Execute(*result.computation, {}).value(); + xla::Literal actual_literal = client->Transfer(*actual).value(); + + xla::Literal expected0 = xla::LiteralUtil::CreateR2({{6.9, 4.2}}); + xla::Literal expected_literal = xla::LiteralUtil::MakeTuple({&expected0}); + EXPECT_TRUE(xla::LiteralTestUtil::Equal(expected_literal, actual_literal)); +} + +TEST_F(XlaCompilerTest, SetShardingForParametersAndReturnValues) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Retval(scope.WithOpName("B"), a, 0); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + auto node_name_index = graph->BuildNodeNameIndex(); + Node* arg_node = node_name_index["A"]; + ASSERT_NE(arg_node, nullptr); + Node* ret_node = node_name_index["B"]; + ASSERT_NE(ret_node, nullptr); + + std::vector args(1); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 2}); + + xla::OpSharding sharding; + sharding.set_type(xla::OpSharding::OTHER); + int rank = 2; + int shard_dim = 1; + int num_shards = 2; + for (int i = 0; i < rank; i++) { + sharding.add_tile_assignment_dimensions(i == shard_dim ? num_shards : 1); + } + xla::OpSharding sharding_v2(sharding); + for (int i = 0; i < num_shards; ++i) { + sharding.add_tile_assignment_devices(i); + } + sharding_v2.add_iota_reshape_dims(num_shards); + sharding_v2.add_iota_transpose_perm(0); + + arg_node->AddAttr("_XlaSharding", sharding.SerializeAsString()); + arg_node->AddAttr("_XlaShardingV2", sharding_v2.SerializeAsString()); + ret_node->AddAttr("_XlaSharding", sharding.SerializeAsString()); + ret_node->AddAttr("_XlaShardingV2", sharding_v2.SerializeAsString()); + + // Expected HLO module with Shardy attributes + const char* const expected = R"( + // CHECK: HloModule test.1, entry_computation_layout={{.*}}, frontend_attributes= + // CHECK-SAME: {xla.sdy.tuple_results_shardings="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>]>"} + // + // CHECK: ENTRY %test.1 (arg0.1: s32[2,2]) -> (s32[2,2]) { + // CHECK-NEXT: %arg0.1 = s32[2,2]{1,0} parameter(0), parameter_replication={false}, sharding={devices=[1,2]<=[2]}, frontend_attributes={xla.sdy.sharding="#sdy.sharding, [{}, {\"_axis_0\"}]>"}, metadata={op_name="XLA_Args"} + // CHECK-NEXT: %reshape.1 = s32[2,2]{1,0} reshape(%arg0.1) + // CHECK-NEXT: %XLA_Retvals.3 = s32[2,2]{1,0} reshape(%reshape.1), metadata={op_name="XLA_Retvals"} + // CHECK-NEXT: %XLA_Retvals.4 = s32[2,2]{1,0} copy(%XLA_Retvals.3), sharding={devices=[1,2]<=[2]}, frontend_attributes={xla.sdy.sharding="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>]>"}, metadata={op_name="XLA_Retvals"} + // CHECK-NEXT{LITERAL}: ROOT %XLA_Retvals.5 = (s32[2,2]{1,0}) tuple(%XLA_Retvals.4), sharding={{devices=[1,2]<=[2]}}, metadata={op_name="XLA_Retvals"} + })"; + XlaCompiler::Options compiler_options = DefaultOptions(); + compiler_options.use_shardy_partitioner = true; + XlaCompiler compiler(compiler_options); + + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(XlaCompiler::CompileOptions(), "test", + std::move(graph), args, &result)); + TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, + LoadModuleFromHloProto(result.computation->proto())); + EXPECT_TRUE(*xla::RunFileCheck(hlo_module->ToString(xla::HloPrintOptions{}), + expected)); +} + +TEST_F(XlaCompilerTest, SetShardingForTupleArguments) { + Scope scope = Scope::NewRootScope().ExitOnError(); + auto a = ops::_Arg(scope.WithOpName("A"), DT_INT32, 0); + auto b = ops::_Arg(scope.WithOpName("B"), DT_INT32, 1); + auto c = ops::_Retval(scope.WithOpName("C"), a, 0); + auto d = ops::_Retval(scope.WithOpName("D"), b, 1); + std::unique_ptr graph(new Graph(OpRegistry::Global())); + TF_ASSERT_OK(scope.ToGraph(graph.get())); + + auto node_name_index = graph->BuildNodeNameIndex(); + Node* arg_node_a = node_name_index["A"]; + ASSERT_NE(arg_node_a, nullptr); + Node* arg_node_b = node_name_index["B"]; + ASSERT_NE(arg_node_b, nullptr); + Node* ret_node_c = node_name_index["C"]; + ASSERT_NE(ret_node_c, nullptr); + Node* ret_node_d = node_name_index["D"]; + ASSERT_NE(ret_node_d, nullptr); + + std::vector args(2); + args[0].kind = XlaCompiler::Argument::kParameter; + args[0].type = DT_INT32; + args[0].shape = TensorShape({2, 2}); + args[1].kind = XlaCompiler::Argument::kParameter; + args[1].type = DT_INT32; + args[1].shape = TensorShape({2, 2}); + + xla::OpSharding sharding; + sharding.set_type(xla::OpSharding::OTHER); + int rank = 2; + int shard_dim = 1; + int num_shards = 2; + for (int i = 0; i < rank; i++) { + sharding.add_tile_assignment_dimensions(i == shard_dim ? num_shards : 1); + } + xla::OpSharding sharding_v2(sharding); + for (int i = 0; i < num_shards; ++i) { + sharding.add_tile_assignment_devices(i); + } + + sharding_v2.add_iota_reshape_dims(num_shards); + sharding_v2.add_iota_transpose_perm(0); + + arg_node_a->AddAttr("_XlaSharding", sharding.SerializeAsString()); + arg_node_a->AddAttr("_XlaShardingV2", sharding_v2.SerializeAsString()); + arg_node_b->AddAttr("_XlaSharding", sharding.SerializeAsString()); + arg_node_b->AddAttr("_XlaShardingV2", sharding_v2.SerializeAsString()); + ret_node_c->AddAttr("_XlaSharding", sharding.SerializeAsString()); + ret_node_c->AddAttr("_XlaShardingV2", sharding_v2.SerializeAsString()); + ret_node_d->AddAttr("_XlaSharding", sharding.SerializeAsString()); + ret_node_d->AddAttr("_XlaShardingV2", sharding_v2.SerializeAsString()); + + // Expected HLO module with Shardy attributes + const char* const expected = R"( + // CHECK: HloModule test.1, entry_computation_layout={{.*}}, frontend_attributes={ + // CHECK-SAME: xla.sdy.tuple_args_shardings="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>, , [{}, {\"_axis_0\"}]>]>", + // CHECK-SAME: xla.sdy.tuple_results_shardings="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>, , [{}, {\"_axis_0\"}]>]>", + // CHECK-SAME: xla.sdy.use_tuple_args="True"} + // + // CHECK: ENTRY %test.1 (arg_tuple.1: (s32[2,2], s32[2,2])) -> (s32[2,2], s32[2,2]) { + // CHECK-NEXT{LITERAL}: %arg_tuple.1 = (s32[2,2]{1,0}, s32[2,2]{1,0}) parameter(0), parameter_replication={false,false}, sharding={{devices=[1,2]<=[2]}, {devices=[1,2]<=[2]}}, metadata={op_name="XLA_Args"} + // CHECK-NEXT: %get-tuple-element.2 = s32[2,2]{1,0} get-tuple-element(%arg_tuple.1), index=0, sharding={devices=[1,2]<=[2]}, frontend_attributes={xla.sdy.sharding="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>]>"} + // CHECK-NEXT: %reshape.2 = s32[2,2]{1,0} reshape(%get-tuple-element.2) + // CHECK-NEXT: %XLA_Retvals.5 = s32[2,2]{1,0} reshape(%reshape.2), metadata={op_name="XLA_Retvals"} + // CHECK-NEXT: %XLA_Retvals.6 = s32[2,2]{1,0} copy(%XLA_Retvals.5), sharding={devices=[1,2]<=[2]}, frontend_attributes={xla.sdy.sharding="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>]>"}, metadata={op_name="XLA_Retvals"} + // CHECK-NEXT: %get-tuple-element.3 = s32[2,2]{1,0} get-tuple-element(%arg_tuple.1), index=1, sharding={devices=[1,2]<=[2]}, frontend_attributes={xla.sdy.sharding="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>]>"} + // CHECK-NEXT: %reshape.3 = s32[2,2]{1,0} reshape(%get-tuple-element.3) + // CHECK-NEXT: %XLA_Retvals.7 = s32[2,2]{1,0} reshape(%reshape.3), metadata={op_name="XLA_Retvals"} + // CHECK-NEXT: %XLA_Retvals.8 = s32[2,2]{1,0} copy(%XLA_Retvals.7), sharding={devices=[1,2]<=[2]}, frontend_attributes={xla.sdy.sharding="#sdy.sharding_per_value<[, [{}, {\"_axis_0\"}]>]>"}, metadata={op_name="XLA_Retvals"} + // CHECK-NEXT{LITERAL}: ROOT %XLA_Retvals.9 = (s32[2,2]{1,0}, s32[2,2]{1,0}) tuple(%XLA_Retvals.6, %XLA_Retvals.8), sharding={{devices=[1,2]<=[2]}, {devices=[1,2]<=[2]}}, metadata={op_name="XLA_Retvals"} + })"; + + XlaCompiler::Options compiler_options = DefaultOptions(); + compiler_options.use_shardy_partitioner = true; + XlaCompiler compiler(compiler_options); + + XlaCompiler::CompileOptions compile_options; + compile_options.use_tuple_arg = true; + XlaCompiler::CompilationResult result; + TF_ASSERT_OK(compiler.CompileGraph(compile_options, "test", std::move(graph), + args, &result)); + TF_ASSERT_OK_AND_ASSIGN(auto hlo_module, + LoadModuleFromHloProto(result.computation->proto())); + EXPECT_TRUE(*xla::RunFileCheck(hlo_module->ToString(xla::HloPrintOptions{}), + expected)); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_context.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_context.cc new file mode 100644 index 0000000000000000000000000000000000000000..ef94681ecd24b653ec4c2f3da4217856bfd4caa3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_context.cc @@ -0,0 +1,226 @@ +/* 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/xla_context.h" + +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/shape_util.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/errors.h" + +namespace tensorflow { + +const char XlaContext::kXlaContextResourceName[] = "_xla_context"; + +// Looks up the context associated with the current step. It is stored +// in a resource container managed by the device. +/* static */ XlaContext& XlaContext::Get(const OpKernelContext* ctx) { + // When an Op kernel wants to use an XLA JIT context, the + // per-step context is looked up in the resource manager. The + // JIT will prepopulate the JITContext. + XlaContext* context; + CHECK_OK(ctx->step_container()->Lookup(ctx->resource_manager(), + kXlaContextResourceName, &context)); + // The resource manager handed us a fresh reference to 'context', but retains + // a reference itself so the context won't be freed. The resource manager will + // outlive the JIT compilation. + context->Unref(); + return *context; +} + +void XlaContext::set_args(std::vector args) { + args_ = std::move(args); +} + +XlaContext::XlaContext(XlaCompiler* compiler, xla::XlaBuilder* builder, + const Graph* graph) + : compiler_(compiler), builder_(builder) { + if (graph) { + for (const Node* node : graph->nodes()) { + stack_traces_[node->name()] = node->GetStackTrace(); + } + } +} + +std::string XlaContext::DebugString() const { return "XLA JIT context"; } + +void XlaContext::SetRetval(int index, const XlaExpression& expression) { + const int64_t retvals_size = retvals_.size(); + if (retvals_size <= index) { + retvals_.resize(index + 1); + } + retvals_[index] = expression; +} + +XlaResource* XlaContext::AddResource(std::unique_ptr resource) { + resources_.push_back(std::move(resource)); + return resources_.back().get(); +} + +const xla::XlaComputation* XlaContext::GetOrCreateMax(const DataType type) { + return LookupOrCreate(type, &max_func_, [type] { + const std::string type_string = DataTypeString(type); + VLOG(1) << "Building Max() for " << type_string; + xla::XlaBuilder b("max<" + type_string + ">"); + xla::PrimitiveType xla_type; + CHECK_OK(DataTypeToPrimitiveType(type, &xla_type)); + auto x = + xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x"); + auto y = + xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y"); + xla::Max(x, y); + return b.Build().value(); + }); +} + +const xla::XlaComputation* XlaContext::GetOrCreateMin(const DataType type) { + return LookupOrCreate(type, &min_func_, [type] { + const std::string type_string = DataTypeString(type); + VLOG(1) << "Building Min() for " << type_string; + xla::XlaBuilder b("min<" + type_string + ">"); + xla::PrimitiveType xla_type; + CHECK_OK(DataTypeToPrimitiveType(type, &xla_type)); + auto x = + xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x"); + auto y = + xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y"); + xla::Min(x, y); + return b.Build().value(); + }); +} + +const xla::XlaComputation* XlaContext::GetOrCreateAdd(const DataType type) { + return LookupOrCreate(type, &add_func_, [type] { + const std::string type_string = DataTypeString(type); + VLOG(1) << "Building Add() for " << type_string; + xla::XlaBuilder b("add<" + type_string + ">"); + xla::PrimitiveType xla_type; + CHECK_OK(DataTypeToPrimitiveType(type, &xla_type)); + auto x = + xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x"); + auto y = + xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y"); + xla::Add(x, y); + return b.Build().value(); + }); +} + +const xla::XlaComputation* XlaContext::GetOrCreateLogAddExp( + const DataType type) { + return LookupOrCreate(type, &log_add_exp_func_, [type] { + const std::string type_string = DataTypeString(type); + VLOG(1) << "Building LogAddExp() for " << type_string; + xla::XlaBuilder b("log_add_exp<" + type_string + ">"); + xla::PrimitiveType xla_type; + CHECK_OK(DataTypeToPrimitiveType(type, &xla_type)); + auto x = + xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x"); + auto y = + xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y"); + auto max = xla::Max(x, y); + auto min = xla::Min(x, y); + auto inner = xla::Select(xla::Not(xla::IsFinite(max)), + xla::Neg(xla::Abs(max)), xla::Sub(min, max)); + + xla::Add(max, xla::Log1p(xla::Exp(inner))); + return b.Build().value(); + }); +} + +const xla::XlaComputation* XlaContext::GetOrCreateMul(const DataType type) { + return LookupOrCreate(type, &mul_func_, [type] { + const std::string type_string = DataTypeString(type); + VLOG(1) << "Building Mul() for " << type_string; + xla::XlaBuilder b("mul<" + type_string + ">"); + xla::PrimitiveType xla_type; + CHECK_OK(DataTypeToPrimitiveType(type, &xla_type)); + auto x = + xla::Parameter(&b, 0, xla::ShapeUtil::MakeShape(xla_type, {}), "x"); + auto y = + xla::Parameter(&b, 1, xla::ShapeUtil::MakeShape(xla_type, {}), "y"); + xla::Mul(x, y); + return b.Build().value(); + }); +} + +const xla::XlaComputation* XlaContext::LookupOrCreate( + DataType type, ComputationMap* out, + const std::function& create) { + { + const auto& entry = (*out)[type]; + if (!entry.IsNull()) { + return &entry; + } + } + auto new_entry = create(); + { + // Somebody else might have made one concurrently. + auto& entry = (*out)[type]; + if (entry.IsNull()) { + entry = std::move(new_entry); + } + return &entry; + } +} + +absl::Status XlaContext::RecordCollectiveInfoFromNestedCompilationResult( + const XlaCompilationResult& result) { + if (result.collective_info) { + return RecordCollectiveInfo(result.collective_info->group_key, + result.collective_info->group_size) + .status(); + } + return absl::OkStatus(); +} + +absl::StatusOr XlaContext::RecordCollectiveInfo(int group_key, + int group_size) { + if (!collective_info_) { + collective_info_ = {group_key, group_size, 0}; + } else if (collective_info_->group_key != group_key || + collective_info_->group_size != group_size) { + return absl::InvalidArgumentError( + absl::StrCat("Only single configuration of CollectiveReduceV2Op is ", + "supported in a given cluster. Recorded group_key=", + collective_info_->group_key, + " attempting to insert group_key=", group_key)); + } + + // Create the channel_id to be used for the collective. Avoid having the + // same channel_id to be used for 2 or more collectives since XLA attempts + // to "gang schedule" all collectives with the same channel_id. + return (static_cast(group_key) << 32) | collective_info_->next_id++; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_context.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_context.h new file mode 100644 index 0000000000000000000000000000000000000000..5934172ba9d4af956f499f768736a16140b3869b --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_context.h @@ -0,0 +1,184 @@ +/* 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. +==============================================================================*/ + +// This file defines the contexts used during XLA compilation. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_XLA_CONTEXT_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_CONTEXT_H_ + +#include + +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/status_macros.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/resource_mgr.h" +#include "tensorflow/core/graph/graph.h" +#include "tensorflow/core/platform/macros.h" + +namespace tensorflow { + +class XlaOpKernelContext; +class XlaCompiler; + +// The XlaContext is the data structure that holds the state of an XLA +// compilation, that is accessible from OpKernelContexts when compiling a +// subgraph of Ops using XLA. +class XlaContext : public ResourceBase { + public: + // Retrieves the XlaContext of the current compilation. + static XlaContext& Get(const OpKernelContext* ctx); + + // Creates a new XlaContext. See the documentation on the class data fields + // for descriptions of the arguments. + XlaContext(XlaCompiler* compiler, xla::XlaBuilder* builder, + const Graph* graph); + + // Virtual method defined by ResourceBase. + std::string DebugString() const override; + + XlaCompiler* compiler() const { return compiler_; } + + const AbstractStackTrace* StackTraceForNodeName(const std::string& name) { + const auto& it = stack_traces_.find(name); + if (it != stack_traces_.end()) { + return it->second.get(); + } + return nullptr; + } + + // Returns the XlaBuilder that Ops use for compiling new expressions. + xla::XlaBuilder* builder() { return builder_; } + + const std::vector& args() const { return args_; } + void set_args(std::vector args); + + const std::vector& retvals() { return retvals_; } + + // Sets a return value. + // Since we do not always know in advance how many return values there are, + // grows the return values vector to size index+1 if it is smaller. + void SetRetval(int index, const XlaExpression& expression); + + // Adds 'resource' to the set of resources owned by the context. + XlaResource* AddResource(std::unique_ptr resource); + + const std::vector>& resources() { + return resources_; + } + + // Get an XLA lambda to compute Max. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateMax(const DataType type); + + // Get an XLA lambda to compute Min. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateMin(const DataType type); + + // Get an XLA lambda to compute Add. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateAdd(const DataType type); + + // Get an XLA lambda to compute LogAddExp. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateLogAddExp(const DataType type); + + // Get an XLA lambda to compute Mul. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateMul(const DataType type); + + // The name of the XlaContext resource during symbolic graph execution. + static const char kXlaContextResourceName[]; + + // Records the collective information from the nested compilation `result`. + absl::Status RecordCollectiveInfoFromNestedCompilationResult( + const XlaCompilationResult& result); + + // Records the collective configurations for all the collectives in the XLA + // cluster and returns the channel_id to be used for the next collective. + absl::StatusOr RecordCollectiveInfo(int group_key, int group_size); + + const std::optional& + GetCollectiveInfo() { + return collective_info_; + } + + private: + XlaCompiler* const compiler_; + + // The XlaBuilder used to construct the subgraph's compiled representation. + xla::XlaBuilder* builder_; + + // Stack traces for the graph used for compilation. + StackTracesMap stack_traces_; + + // Arguments to the Tensorflow graph, indexed by _Arg index. + // Includes both compile-time constant arguments and runtime parameters. + std::vector args_; + + // Return values of the Tensorflow graph, indexed by _Retval index. + std::vector retvals_; + + // Holds ownership of resources. The resources are not ordered. + std::vector> resources_; + + // Information about encountered collective ops. We allow only a + // single configuration per cluster. + std::optional collective_info_; + + // Cache of prebuilt computations indexed by their type. + using ComputationMap = std::map; + + // Finds the value for the given type in out map if it already + // exists or makes a new value with create function and keeps it the + // map. The returned value != nullptr and is owned by the map. + const xla::XlaComputation* LookupOrCreate( + DataType type, ComputationMap* out, + const std::function& create); + + // Cached computation to compute Max of two elements, specialized by type. + ComputationMap max_func_; + + // Cached computation to compute Min of two elements, specialized by type. + ComputationMap min_func_; + + // Cached computation to compute Sum of two elements, specialized by type. + ComputationMap add_func_; + + // Cached computation to compute Mul of two elements, specialized by type. + ComputationMap mul_func_; + + // Cached computation to compute Log(Add(Exp())) of two elements, specialized + // by type. + ComputationMap log_add_exp_func_; + + // Cached computation to compute Sigmoid of an element, specialized by type. + ComputationMap sigmoid_func_; + + XlaContext(const XlaContext&) = delete; + void operator=(const XlaContext&) = delete; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_CONTEXT_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_cpu_backend.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_cpu_backend.cc new file mode 100644 index 0000000000000000000000000000000000000000..873e07c6ddf6ab2dff0913387518f5ed1cc42b1a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_cpu_backend.cc @@ -0,0 +1,34 @@ +/* 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/tf2xla_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/kernel_def.pb.h" + +namespace tensorflow { + +bool CpuOpFilter(KernelDef* kdef) { + if (kdef->op() == "Const") { + AddDtypeToKernelDefConstraint("dtype", DT_STRING, kdef); + } + if (kdef->op() == "Assert") { + AddDtypeToKernelDefConstraint("T", DT_STRING, kdef); + } + return true; +} + +REGISTER_XLA_BACKEND(DEVICE_CPU_XLA_JIT, kCpuAllTypes, CpuOpFilter); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression.cc new file mode 100644 index 0000000000000000000000000000000000000000..19fe2c4a1b26437cf06c3dc05f94284e79bb94a8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression.cc @@ -0,0 +1,259 @@ +/* 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/xla_expression.h" + +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "xla/hlo/builder/value_inference.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/errors.h" + +namespace tensorflow { + +XlaExpression::XlaExpression() = default; + +XlaExpression XlaExpression::Invalid() { + XlaExpression e; + e.kind_ = Kind::kInvalid; + return e; +} + +XlaExpression XlaExpression::Constant(Tensor value) { + XlaExpression e; + e.kind_ = Kind::kConstant; + e.dtype_ = value.dtype(); + e.constant_value_ = value; + return e; +} + +XlaExpression XlaExpression::ConstantResource(Tensor value, + XlaResource* resource) { + XlaExpression e; + e.kind_ = Kind::kResource; + e.dtype_ = DT_RESOURCE; + e.resource_ = resource; + e.constant_value_ = value; + return e; +} + +XlaExpression XlaExpression::XlaOp(xla::XlaOp value, DataType dtype) { + XlaExpression e; + e.kind_ = Kind::kXlaOp; + e.dtype_ = dtype; + e.handle_ = value; + return e; +} + +XlaExpression XlaExpression::TensorList(xla::XlaOp tensor_list) { + XlaExpression e; + e.kind_ = Kind::kTensorList; + e.dtype_ = DT_VARIANT; + e.handle_ = tensor_list; + return e; +} + +XlaExpression XlaExpression::Resource(XlaResource* resource) { + XlaExpression e; + e.kind_ = Kind::kResource; + e.dtype_ = DT_RESOURCE; + e.resource_ = resource; + return e; +} + +std::string XlaExpression::HumanString() const { + switch (kind_) { + case Kind::kInvalid: + return "invalid"; + case Kind::kConstant: + return "constant"; + case Kind::kXlaOp: + return "xla_op"; + case Kind::kResource: + return "resource"; + case Kind::kTensorList: + return "tensor_list"; + } +} + +xla::XlaOp XlaExpression::AsXlaOp(xla::XlaBuilder* builder) const { + return builder->ReportErrorOrReturn([&]() -> absl::StatusOr { + switch (kind_) { + case Kind::kConstant: { + xla::BorrowingLiteral literal; + TF_RETURN_IF_ERROR( + HostTensorToBorrowingLiteral(*constant_value_, &literal)); + return xla::ConstantLiteral(builder, literal); + } + case Kind::kTensorList: + TF_FALLTHROUGH_INTENDED; + case Kind::kXlaOp: + if (builder != handle_.builder()) { + return absl::InvalidArgumentError( + "Mismatched builders in XlaExpression::AsXlaOp"); + } + return handle_; + default: + return absl::InvalidArgumentError( + absl::StrCat("AsXlaOp called on XlaExpression: ", HumanString())); + } + }); +} + +absl::StatusOr XlaExpression::ResolveDynamism() const { + switch (kind()) { + case Kind::kConstant: { + // Constant values are considered static. + Tensor constant_false(DT_BOOL, constant_value()->shape()); + auto flat = constant_false.flat(); + for (int64_t i = 0; i < flat.size(); ++i) flat(i) = false; + return constant_false; + } + case Kind::kXlaOp: + break; + case Kind::kTensorList: + TF_FALLTHROUGH_INTENDED; + case Kind::kResource: + TF_FALLTHROUGH_INTENDED; + case Kind::kInvalid: + return absl::InvalidArgumentError( + absl::StrCat("ResolveDynamism called on unsupported XlaExpression: ", + HumanString())); + } + + TF_ASSIGN_OR_RETURN(TensorShape shape, GetShape()); + + // The XLA layout is specified minor to major, and TensorFlow uses a major to + // minor order. + std::vector layout_indices(shape.dims()); + std::iota(layout_indices.rbegin(), layout_indices.rend(), 0); + xla::ValueInference value_inference(handle().builder()); + TF_ASSIGN_OR_RETURN(xla::LiteralSlice literal, + value_inference.AnalyzeIsDynamic(handle())); + Tensor tensor(DT_BOOL); + TF_RETURN_IF_ERROR(LiteralToHostTensor(literal, DT_BOOL, &tensor)); + return tensor; +} + +absl::StatusOr> XlaExpression::ResolveConstant( + xla::Client* client, bool dynamic_dimension_is_minus_one, + xla::ValueInferenceMode mode) const { + switch (kind()) { + case Kind::kConstant: + case Kind::kResource: + return constant_value(); + case Kind::kXlaOp: + break; + case Kind::kTensorList: + TF_FALLTHROUGH_INTENDED; + case Kind::kInvalid: + return absl::InvalidArgumentError(absl::StrCat( + "ResolveConstant called on XlaExpression: ", HumanString())); + } + TF_ASSIGN_OR_RETURN(TensorShape shape, GetShape()); + // The XLA layout is specified minor to major, and TensorFlow uses a major to + // minor order. + std::vector layout_indices(shape.dims()); + std::iota(layout_indices.rbegin(), layout_indices.rend(), 0); + xla::Layout layout = xla::LayoutUtil::MakeLayout(layout_indices); + if (mode == xla::ValueInferenceMode::kLowerBound || + mode == xla::ValueInferenceMode::kUpperBound || + mode == xla::ValueInferenceMode::kValue) { + std::vector layout_indices(shape.dims()); + std::iota(layout_indices.rbegin(), layout_indices.rend(), 0); + xla::ValueInference value_inference(handle().builder()); + TF_ASSIGN_OR_RETURN(xla::OptionalLiteral literal, + value_inference.AnalyzeConstant(handle(), mode)); + if (!literal.GetValue().has_value()) { + return {std::nullopt}; + } + Tensor tensor; + TF_RETURN_IF_ERROR(LiteralToHostTensor( + literal.GetValue().value().Relayout(layout), dtype(), &tensor)); + return {tensor}; + } + + TF_ASSIGN_OR_RETURN(bool is_constant, + handle().builder()->IsConstant(handle())); + if (!is_constant) { + return {std::nullopt}; + } + + if (!client) + return absl::InvalidArgumentError("client is required to resolve constant"); + + TF_ASSIGN_OR_RETURN(xla::XlaComputation constant_graph, + handle().builder()->BuildConstantSubGraph( + handle(), dynamic_dimension_is_minus_one)); + + TF_ASSIGN_OR_RETURN(xla::Literal literal, + client->ComputeConstant(constant_graph, &layout)); + Tensor tensor; + TF_RETURN_IF_ERROR(LiteralToHostTensor(literal, dtype(), &tensor)); + return {tensor}; +} + +absl::StatusOr XlaExpression::GetShape() const { + switch (kind_) { + case Kind::kConstant: + return constant_value()->shape(); + case Kind::kResource: + if (constant_value()) { + return constant_value()->shape(); + } + return TensorShape({}); + case Kind::kXlaOp: { + TF_ASSIGN_OR_RETURN(xla::Shape xla_shape, + handle().builder()->GetShape(handle())); + TensorShape shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(xla_shape, &shape)); + return shape; + } + case Kind::kTensorList: + return TensorShape({}); + case Kind::kInvalid: + return absl::InvalidArgumentError( + "GetShape() called on invalid XlaExpression"); + } +} + +absl::StatusOr XlaExpression::GetXlaShape() const { + if (kind_ == Kind::kXlaOp) { + return handle().builder()->GetShape(handle()); + } + TF_ASSIGN_OR_RETURN(TensorShape shape, GetShape()); + return TensorShapeToXLAShape(dtype_, shape); +} + +const XlaExpression* XlaExpression::CastExpressionFromTensor( + const Tensor& tensor) { + const XlaExpression* expression = + reinterpret_cast(tensor.tensor_data().data()); + CHECK(expression->kind() != XlaExpression::Kind::kInvalid) + << expression->HumanString(); + return expression; +} + +// Assigns an XlaExpression to a tensor on an XLA compilation device. +void XlaExpression::AssignExpressionToTensor(const XlaExpression& value, + Tensor* tensor) { + const XlaExpression* expression = + reinterpret_cast(tensor->tensor_data().data()); + CHECK(expression->kind() == XlaExpression::Kind::kInvalid) + << expression->HumanString(); + *const_cast(expression) = value; +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression.h new file mode 100644 index 0000000000000000000000000000000000000000..7e2072f1b00143ffe4e62eb7653795065d39aa5c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression.h @@ -0,0 +1,173 @@ +/* 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_XLA_EXPRESSION_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_EXPRESSION_H_ + +#include "absl/types/optional.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/client/client.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/statusor.h" + +namespace tensorflow { + +// A XlaExpression represents a symbolic TensorFlow value in a TF->XLA +// compilation. +// An expression is one of: +// * a constant tensor. +// * an xla::XlaOp, representing a symbolic XLA value. +// * a resource, e.g., a variable, represented as an XlaResource pointer. +// * a tensor list, represented by a tuple of tensors and the list length. +// +// Constant tensors are mostly an optimization to avoid passing large constants +// to XLA, but are also sometimes used to represent tensors that have no XLA +// representation, for example, DT_STRING tensors. A canonical use case might be +// an error message string. +// +// Tensor lists are very similar to xla::XlaOp, however they require some +// specific logic around shape management since the tuples are not supported by +// TensorFlow. +class XlaExpression { + public: + enum class Kind { + kInvalid, + kConstant, + kXlaOp, + kResource, + kTensorList, + }; + + XlaExpression(); + XlaExpression(const XlaExpression&) = default; + XlaExpression& operator=(const XlaExpression&) = default; + + // Builds an invalid expression. (Same as the default constructor, but makes + // the intent clearer.) + static XlaExpression Invalid(); + + // Builds a constant XLA expression. + static XlaExpression Constant(Tensor value); + + // Builds a XlaOp expression. Since the mapping from TF data types to XLA + // types is not 1-1, the TF type must also be provided; in general it cannot + // be derived from the XLA type. + static XlaExpression XlaOp(xla::XlaOp value, DataType dtype); + + // Builds a tensor list expression. + static XlaExpression TensorList(xla::XlaOp tensor_list); + + // Builds a resource expression. + static XlaExpression Resource(XlaResource* resource); + + // Builds a resource whose value is known at a compile time. + static XlaExpression ConstantResource(Tensor value, XlaResource* resource); + + Kind kind() const { return kind_; } + + DataType dtype() const { return dtype_; } + + // handle() returns the XlaOp that backs a kXlaOp expression. + const xla::XlaOp& handle() const { return handle_; } + + // Return a constant value associated with this expression. Always set for + // constants, might be set for resources. + std::optional constant_value() const { + if (kind_ == Kind::kResource && resource_->IsOverwritten()) { + // The constant is no longer available if the value was overwritten. + return std::nullopt; + } + return constant_value_; + } + + // Set the bound of the expression. + void set_value_bound(Tensor tensor) { + value_bound_.emplace(std::move(tensor)); + } + + // Return the bound of the expression, if available. + std::optional value_bound() const { return value_bound_; } + + // Set the dynamism of the expression, indicating whether or not each value in + // this expression is dynamic. + void set_value_dynamism(Tensor tensor) { + value_dynamism_.emplace(std::move(tensor)); + } + + // Return the dynamism of the expression, if available. + std::optional value_dynamism() const { return value_dynamism_; } + + XlaResource* resource() const { return resource_; } + + // Returns a human-readable summary of the expression. + std::string HumanString() const; + + // Returns the value of a kValue or kXlaOp as an xla::XlaOp. Returns + // an erroneous XlaOp if the expression is not a constant or an expression. + xla::XlaOp AsXlaOp(xla::XlaBuilder* builder) const; + + // If a kXlaOp or kValue expression can be resolved to a compile-time + // constant, returns the value as a host-memory Tensor. Returns an empty + // optional if it cannot be resolved. Returns an error if passed a resource + // expression. + absl::StatusOr> ResolveConstant( + xla::Client* client, bool dynamic_dimension_is_minus_one = false, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue) const; + + // ResolveDynamism computes where a value inside this op is dynamic or can be + // inferred at compile time. + absl::StatusOr ResolveDynamism() const; + + // Returns the shape of the tensor. + // The shape of a resource is the shape of a resource handle (i.e., a scalar), + // not the shape of the resource's value. + absl::StatusOr GetShape() const; + absl::StatusOr GetXlaShape() const; + + // Retrieves an XlaExpression that was allocated by a previous Op. + static const XlaExpression* CastExpressionFromTensor(const Tensor& tensor); + + // Assigns an XlaExpression to a tensor on an XLA compilation device. + static void AssignExpressionToTensor(const XlaExpression& value, + Tensor* tensor); + + private: + Kind kind_ = Kind::kInvalid; + + DataType dtype_ = DT_INVALID; + + // The XLA handle of the expression's computation, if kind_ == kXlaOp or + // a tuple expression if kind_ == kTensorList. + xla::XlaOp handle_; + + // The value of the constant, if available. + std::optional constant_value_; + + // The bound of the expression, if available. + std::optional value_bound_; + + // Indicate whether each value inside a tensor is dynamic or not. + std::optional value_dynamism_; + + // The resource, if kind_ == kResource. Not owned. + XlaResource* resource_ = nullptr; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_EXPRESSION_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..6e55f46fbf9b1b194abb1a0b68e959d1ca6f4059 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_expression_test.cc @@ -0,0 +1,151 @@ +/* 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/tf2xla/xla_expression.h" + +#include + +#include "absl/memory/memory.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/client/client_library.h" +#include "xla/client/local_client.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/literal.h" +#include "xla/shape_util.h" +#include "xla/status_macros.h" +#include "xla/tests/literal_test_util.h" +#include "tensorflow/core/framework/tensor_testutil.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { + +class XlaExpressionTest : public ::testing::Test { + protected: + void SetUp() override { + client_ = xla::ClientLibrary::LocalClientOrDie(); + builder_ = std::make_unique("acomputation"); + constant_ = test::AsScalar(42); + op_ = xla::ConstantR0(builder_.get(), 7); + non_constant_op_ = xla::Parameter( + builder_.get(), 0, xla::ShapeUtil::MakeShape(xla::F32, {}), "x"); + resource_ = std::make_unique( + XlaResource::kVariable, /*arg_num=*/0, + /*name=*/std::string("avariable"), DT_INT32, TensorShape({17, 3}), op_, + /*tensor_array_size=*/-1, + /*tensor_array_gradients=*/std::set(), + /*tensor_array_multiple_writes_aggregate=*/false); + } + + xla::Client* client_; + std::unique_ptr builder_; + Tensor constant_; + xla::XlaOp op_; + xla::XlaOp non_constant_op_; + std::unique_ptr resource_; +}; + +TEST_F(XlaExpressionTest, Kind) { + EXPECT_TRUE(XlaExpression::Kind::kInvalid == XlaExpression().kind()); + EXPECT_TRUE(XlaExpression::Kind::kInvalid == XlaExpression::Invalid().kind()); + EXPECT_TRUE(XlaExpression::Kind::kConstant == + XlaExpression::Constant(constant_).kind()); + EXPECT_TRUE(XlaExpression::Kind::kXlaOp == + XlaExpression::XlaOp(op_, DT_INT32).kind()); + EXPECT_TRUE(XlaExpression::Kind::kResource == + XlaExpression::Resource(resource_.get()).kind()); +} + +TEST_F(XlaExpressionTest, HumanString) { + EXPECT_EQ("invalid", XlaExpression().HumanString()); + EXPECT_EQ("invalid", XlaExpression::Invalid().HumanString()); + EXPECT_EQ("constant", XlaExpression::Constant(constant_).HumanString()); + EXPECT_EQ("xla_op", XlaExpression::XlaOp(op_, DT_INT32).HumanString()); + EXPECT_EQ("resource", XlaExpression::Resource(resource_.get()).HumanString()); +} + +TEST_F(XlaExpressionTest, AsXlaOp) { + xla::XlaOp op_as_op = + XlaExpression::XlaOp(op_, DT_INT32).AsXlaOp(builder_.get()); + EXPECT_TRUE(op_.IsIdenticalTo(op_as_op)); + + xla::XlaOp const_as_op = + XlaExpression::Constant(constant_).AsXlaOp(builder_.get()); + TF_ASSERT_OK_AND_ASSIGN(xla::XlaComputation computation, + builder_->BuildConstantSubGraph(const_as_op)); + TF_ASSERT_OK_AND_ASSIGN(xla::Literal value, + client_->ComputeConstant(computation)); + EXPECT_TRUE(xla::LiteralTestUtil::Equal( + xla::LiteralUtil::CreateR0(42), value)); +} + +TEST_F(XlaExpressionTest, GetShape) { + EXPECT_FALSE(XlaExpression().GetShape().ok()); + EXPECT_FALSE(XlaExpression::Invalid().GetShape().ok()); + + TF_ASSERT_OK_AND_ASSIGN(TensorShape resource_shape, + XlaExpression::Resource(resource_.get()).GetShape()); + EXPECT_EQ(TensorShape({}), resource_shape); + + TF_ASSERT_OK_AND_ASSIGN(TensorShape op_shape, + XlaExpression::XlaOp(op_, DT_INT32).GetShape()); + EXPECT_EQ(TensorShape({}), op_shape); + + TF_ASSERT_OK_AND_ASSIGN(TensorShape constant_shape, + XlaExpression::Constant(constant_).GetShape()); + EXPECT_EQ(TensorShape({}), constant_shape); +} + +TEST_F(XlaExpressionTest, ResolveConstant) { + EXPECT_FALSE(XlaExpression().ResolveConstant(client_).ok()); + EXPECT_FALSE(XlaExpression::Invalid().ResolveConstant(client_).ok()); + + EXPECT_FALSE(XlaExpression::Resource(resource_.get()) + .ResolveConstant(client_) + ->has_value()); + + TF_ASSERT_OK_AND_ASSIGN( + std::optional op_constant, + XlaExpression::XlaOp(op_, DT_INT32).ResolveConstant(client_)); + ASSERT_TRUE(op_constant.has_value()); + test::ExpectTensorEqual(test::AsScalar(7), *op_constant); + + TF_ASSERT_OK_AND_ASSIGN(std::optional op_nonconstant, + XlaExpression::XlaOp(non_constant_op_, DT_FLOAT) + .ResolveConstant(client_)); + EXPECT_FALSE(op_nonconstant.has_value()); + + TF_ASSERT_OK_AND_ASSIGN( + std::optional constant_constant, + XlaExpression::Constant(constant_).ResolveConstant(client_)); + ASSERT_TRUE(constant_constant.has_value()); + test::ExpectTensorEqual(constant_, *constant_constant); +} + +TEST_F(XlaExpressionTest, ResolveConstantOnResource) { + XlaExpression constant_resource = + XlaExpression::ConstantResource(constant_, resource_.get()); + EXPECT_TRUE(constant_resource.ResolveConstant(client_).ok()); + EXPECT_TRUE(resource_->SetZeroValue(builder_.get()).ok()); + LOG(ERROR) << "Resource is overwritten: " << resource_->IsOverwritten(); + absl::StatusOr> resolved_constant = + constant_resource.ResolveConstant(client_); + EXPECT_TRUE(resolved_constant.ok()); + EXPECT_FALSE(resolved_constant->has_value()); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_gpu_backend.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_gpu_backend.cc new file mode 100644 index 0000000000000000000000000000000000000000..04c26d01f8bf9b1a415d7843b202a532b2da33c8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_gpu_backend.cc @@ -0,0 +1,34 @@ +/* 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/tf2xla_util.h" +#include "tensorflow/compiler/tf2xla/xla_op_registry.h" +#include "tensorflow/core/framework/kernel_def.pb.h" + +namespace tensorflow { + +bool GpuOpFilter(KernelDef* kdef) { + if (kdef->op() == "Const") { + AddDtypeToKernelDefConstraint("dtype", DT_STRING, kdef); + } + if (kdef->op() == "Assert") { + AddDtypeToKernelDefConstraint("T", DT_STRING, kdef); + } + return true; +} + +REGISTER_XLA_BACKEND(DEVICE_GPU_XLA_JIT, kGpuAllTypes, GpuOpFilter); + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_helpers.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_helpers.cc new file mode 100644 index 0000000000000000000000000000000000000000..5022d7abc0180f4e3bb01c1dc34c611f4800b43d --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_helpers.cc @@ -0,0 +1,283 @@ +/* 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. +==============================================================================*/ + +// This file defines helper routines for XLA compilation. + +#include "tensorflow/compiler/tf2xla/xla_helpers.h" + +#include +#include +#include +#include +#include + +#include "absl/container/btree_map.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/str_cat.h" +#include "absl/synchronization/notification.h" +#include "absl/time/time.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/lib/util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "xla/core/collectives/clique_id.h" +#include "xla/core/collectives/clique_key.h" +#include "xla/executable_run_options.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/literal.h" +#include "xla/literal_util.h" +#include "xla/service/computation_placer.h" +#include "xla/service/gpu/gpu_executable_run_options.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/stream_executor/stream.h" +#include "xla/stream_executor/stream_executor.h" +#include "xla/tsl/platform/errors.h" +#include "tensorflow/core/common_runtime/device_mgr.h" +#include "tensorflow/core/framework/collective.h" +#include "tensorflow/core/framework/device.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/refcount.h" + +namespace tensorflow { + +xla::XlaOp XlaHelpers::Zero(xla::XlaBuilder* b, DataType data_type) { + xla::PrimitiveType type; + CHECK_OK(DataTypeToPrimitiveType(data_type, &type)); + return xla::ConstantLiteral(b, xla::LiteralUtil::Zero(type)); +} + +xla::XlaOp XlaHelpers::One(xla::XlaBuilder* b, DataType data_type) { + xla::PrimitiveType type; + CHECK_OK(DataTypeToPrimitiveType(data_type, &type)); + return xla::ConstantLiteral(b, xla::LiteralUtil::One(type)); +} + +xla::XlaOp XlaHelpers::IntegerLiteral(xla::XlaBuilder* b, DataType data_type, + int64_t value) { + xla::PrimitiveType type; + CHECK_OK(DataTypeToPrimitiveType(data_type, &type)); + return ::tensorflow::IntegerLiteral(b, type, value); +} + +xla::XlaOp XlaHelpers::FloatLiteral(xla::XlaBuilder* b, DataType data_type, + double value) { + xla::PrimitiveType type; + CHECK_OK(DataTypeToPrimitiveType(data_type, &type)); + return ::tensorflow::FloatLiteral(b, type, value); +} + +/* static */ absl::Status XlaHelpers::ReshapeLiteral( + const xla::Literal& input, absl::Span dimensions, + xla::Literal* output) { + if (input.shape().IsTuple()) { + return absl::InvalidArgumentError( + "ReshapeLiteral does not support tuples."); + } + xla::Shape shape = + xla::ShapeUtil::MakeShape(input.shape().element_type(), dimensions); + int64_t elements_before = xla::ShapeUtil::ElementsIn(input.shape()); + int64_t elements_after = xla::ShapeUtil::ElementsIn(shape); + if (elements_before != elements_after) { + return absl::InvalidArgumentError( + "Shapes before and after ReshapeLiteral have different numbers of " + "elements."); + } + + *output = input.Clone(); + std::swap(*output->mutable_shape_do_not_use(), shape); + return absl::OkStatus(); +} + +absl::Status XlaHelpers::OneHot(xla::XlaBuilder* builder, int64_t depth, + int axis, DataType index_type, + const TensorShape& indices_shape, + const xla::XlaOp indices, + const xla::XlaOp on_value, + const xla::XlaOp off_value, + xla::XlaOp* one_hot) { + // Broadcast the linspace constant across the indices along the new axis, + // and test equality at each position. + std::vector broadcast_dims(indices_shape.dims()); + std::iota(broadcast_dims.begin(), broadcast_dims.begin() + axis, 0); + std::iota(broadcast_dims.begin() + axis, broadcast_dims.end(), axis + 1); + + TensorShape output_shape = indices_shape; + output_shape.InsertDim(axis, depth); + xla::Shape iota_shape; + TF_RETURN_IF_ERROR( + TensorShapeToXLAShape(index_type, output_shape, &iota_shape)); + + // Selects the user-provided off_value and on_value values. + *one_hot = xla::Select( + xla::Eq(indices, xla::Iota(builder, iota_shape, axis), broadcast_dims), + xla::Broadcast(on_value, output_shape.dim_sizes()), + xla::Broadcast(off_value, output_shape.dim_sizes())); + return absl::OkStatus(); +} + +DataType XlaHelpers::SumAccumulationType(const DataType& dtype) { + // Upcast 16 bit sum reductions to 32 bit to reduce the precision loss from + // repeated floating point additions. + if (dtype == DT_BFLOAT16 || dtype == DT_HALF) { + return DT_FLOAT; + } + // Upcast small integer types to 32 bit to avoid overflow. + if (dtype == DT_INT8 || dtype == DT_INT16) { + return DT_INT32; + } + if (dtype == DT_UINT8 || dtype == DT_UINT16) { + return DT_UINT32; + } + return dtype; +} + +xla::XlaOp XlaHelpers::ConvertElementType(const xla::XlaOp operand, + const DataType new_element_type) { + xla::PrimitiveType convert_to; + CHECK_OK(DataTypeToPrimitiveType(new_element_type, &convert_to)); + return xla::ConvertElementType(operand, convert_to); +} + +XlaHelpers::ShapeRepresentationFn IdentityShapeRepresentationFn() { + return + [](const TensorShape& shape, DataType dtype, bool use_fast_memory, + XlaLayoutPreference layout_preference) -> absl::StatusOr { + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(dtype, shape, &xla_shape)); + return xla_shape; + }; +} + +absl::Status ResolveDeviceAssignment( + OpKernelContext* ctx, + const XlaCompilationResult::CollectiveInfo& collective_info, + xla::ExecutableRunOptions& run_options, + xla::DeviceAssignment& device_assignment, + xla::gpu::GpuExecutableRunOptions& gpu_options) { + // TODO(nnigania): workaround for b/199436990 + static const int kTimeoutSeconds = 1000; + if (ctx->collective_executor() == nullptr) { + return absl::InvalidArgumentError( + "CollectiveExecutor is required but not available"); + } + + auto params = core::RefCountPtr(new CollectiveParams()); + params->name = "xla-reduction-compilation"; + params->group.device_type = + DeviceType{static_cast(ctx->device())->device_type()}; + params->group.group_size = collective_info.group_size; + params->group.group_key = collective_info.group_key; + params->instance.type = REDUCTION_COLLECTIVE; + params->instance.impl_details.communication_hint = "nccl"; + params->instance.impl_details.timeout_seconds = kTimeoutSeconds; + params->instance.impl_details.collective_name = "NcclReduce"; + // TODO(cheshire): Avoid passing a dummy shape, TF runtime does not resolve + // devices otherwise. + params->instance.shape = TensorShape({1}); + + VLOG(5) << "Using collective params to resolve device assignment: " + << params->ToString(); + + absl::Status st; + absl::Notification n; + ctx->collective_executor()->CompleteParamsAsync( + ctx->device()->attributes(), params.get(), ctx->cancellation_manager(), + [&](const absl::Status& s) { + st = s; + n.Notify(); + }); + if (!n.WaitForNotificationWithTimeout(absl::Seconds(kTimeoutSeconds))) { + return absl::InvalidArgumentError("Timeout reached"); + } + TF_RETURN_IF_ERROR(st); + VLOG(5) << "Collective params completed: " << params->ToString(); + + // Identify the physical device associated with each replica. + device_assignment = xla::DeviceAssignment(params->group.group_size, 1); + for (int device_idx = 0; device_idx < params->group.group_size; + device_idx++) { + const DeviceAttributes& device = params->group.members[device_idx].device; + if (device.xla_global_id() == -1) { + if (params->group.device_type == DEVICE_TPU) { + return absl::InvalidArgumentError( + absl::StrCat("No global ID was set for TPU device ", device.name(), + ". Try initializing the TPU system, e.g. " + "`tf.tpu.experimental.initialize_tpu_system()`.")); + } else if (params->group.device_type == DEVICE_GPU) { + return absl::InternalError( + absl::StrCat("No global ID was set for ", device.name(), + ". This is unexpected, please file a bug.")); + } else { + // TODO(b/194942685): Implement CPU collectives. + return absl::UnimplementedError( + absl::StrCat("Collectives are not yet implemented for ", + params->group.device_type.type_string(), + " devices when compiling with XLA. Attempted to " + "compile a collective running on", + device.name(), + ". Please comment on b/194942685 or " + "file a new bug if you don't have access.")); + } + } + VLOG(2) << "Assigning physical id " << device.xla_global_id() + << " for replica " << device_idx << " (" << device.name() << ")"; + device_assignment(device_idx, 0) = device.xla_global_id(); + } + VLOG(5) << "Generated device assignment: " << device_assignment.ToString(); + if (params->group.device_type == DEVICE_GPU) { + // For GPU collectives, `xla_global_id`s are arbitrary integers, and XLA + // requires a mapping from local device IDs to global device IDs. + const DeviceMgr* device_mgr = ctx->function_library()->device_mgr(); + absl::btree_map global_device_ids; + + for (int device_idx = 0; device_idx < params->group.group_size; + device_idx++) { + const DeviceAttributes& device_attributes = + params->group.members[device_idx].device; + Device* resolved_device = nullptr; + absl::Status lookup_status = + device_mgr->LookupDevice(device_attributes.name(), &resolved_device); + if (lookup_status.ok()) { + // This is a local device, so include it in the mapping. + const DeviceBase::AcceleratorDeviceInfo* accelerator_device_info = + resolved_device->tensorflow_accelerator_device_info(); + global_device_ids[xla::LocalDeviceId( + accelerator_device_info->stream->parent()->device_ordinal())] = + device_attributes.xla_global_id(); + } + } + gpu_options.set_gpu_global_device_ids(global_device_ids); + } + const std::string& communicator_key = + params->group.runtime_details.communicator_key; + gpu_options.set_clique_id_callback([=](const xla::CliqueKey& key) { + return xla::CliqueIds(xla::CliqueId(communicator_key)); + }); + run_options.set_device_assignment(&device_assignment); + run_options.set_gpu_executable_run_options(&gpu_options); + return absl::OkStatus(); +} + +} // end namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_helpers.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_helpers.h new file mode 100644 index 0000000000000000000000000000000000000000..5e45812ddbf5429364a357390ea45c373f01771e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_helpers.h @@ -0,0 +1,214 @@ +/* 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. +==============================================================================*/ + +// This file defines helper routines for the XLA device. + +#ifndef TENSORFLOW_COMPILER_TF2XLA_XLA_HELPERS_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_HELPERS_H_ + +#include + +#include "absl/types/optional.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/host_compute_metadata.pb.h" +#include "xla/executable_run_options.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/ir/hlo_sharding.h" +#include "xla/hlo/translate/mhlo_to_hlo/layout_util.h" +#include "xla/service/computation_placer.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" + +namespace tensorflow { + +using XlaLayoutPreference = mlir::XlaLayoutPreference; + +inline std::string GetDeviceToHostChannelName(absl::string_view channel_key, + int index) { + return absl::StrCat(channel_key, "_dtoh_", index); +} +inline std::string GetHostToDeviceChannelName(absl::string_view channel_key, + int index) { + return absl::StrCat(channel_key, "_htod_", index); +} + +// Helper methods for building XLA computations. +class XlaHelpers { + public: + // Returns a handle representing the zero value of a scalar + // element of data_type. + static xla::XlaOp Zero(xla::XlaBuilder* b, DataType data_type); + + // Returns a handle representing the one value of a scalar + // element of data_type. + static xla::XlaOp One(xla::XlaBuilder* b, DataType data_type); + + // Returns a handle representing the given value of an integer scalar + // element of data_type. + // Note that unlike One and Zero, does not work on boolean types. + static xla::XlaOp IntegerLiteral(xla::XlaBuilder* b, DataType data_type, + int64_t value); + + // Returns a handle representing the given value of a floating-point scalar + // element of data_type. + static xla::XlaOp FloatLiteral(xla::XlaBuilder* b, DataType data_type, + double value); + + // Reshapes literal 'input' to have 'shape'. Both the original shape and + // 'shape' must contain the same number of elements. + static absl::Status ReshapeLiteral(const xla::Literal& input, + absl::Span shape, + xla::Literal* output); + + // Converts `indices` into a one-hot representation. `depth` is the size + // of the new axis to add. `axis` is the position at which to add the new + // axis. `indices_shape` is the shape of `indices`. `on_value` and + // `off_value` represent the values to use for the on and off positions, + // respectively. + static absl::Status OneHot(xla::XlaBuilder* builder, int64_t depth, int axis, + DataType index_type, + const TensorShape& indices_shape, + xla::XlaOp indices, xla::XlaOp on_value, + xla::XlaOp off_value, xla::XlaOp* one_hot); + + // Certain DataTypes should use increased precision DataTypes when performing + // reductions. This function remaps a given DataType to a higher precision + // DataType if needed. + static DataType SumAccumulationType(const DataType& dtype); + + // A helper for creating a ConvertElementType xla op given a DataType rather + // than the xla::PrimitiveType. + static xla::XlaOp ConvertElementType(xla::XlaOp operand, + const DataType new_element_type); + + typedef std::function(const TensorShape&, DataType, + bool, XlaLayoutPreference)> + ShapeRepresentationFn; +}; + +// Creates an identity shape representation function. +XlaHelpers::ShapeRepresentationFn IdentityShapeRepresentationFn(); + +struct XlaOutputDescription { + // Type and shape of the output. The shape is the unflattened shape. + // When `type` is DT_RESOURCE, `shape` is the shape of the resource + // variable's value. + DataType type; + TensorShape shape; + + // Constant output value, if known to be constant at JIT compilation time. + // 'Tensor' is in host memory. + bool is_constant = false; + Tensor constant_value; + + // When this output is a resource, i.e. `type == DT_RESOURCE`, this is + // the index of the input that contains the resource. + int input_index; + + // Whether this output is a TensorList. + bool is_tensor_list = false; +}; + +// Describes a variable write side effect of the computation. +struct XlaResourceUpdate { + // Index of the input that contains the variable resource to write to. + int input_index; + + // Type and shape of the tensor to be written back. + // The `shape` field has the same meaning as the Argument::shape field. + DataType type; + TensorShape shape; + + // Was the value of the variable modified by the computation? + // (Always true, unless `return_updated_values_for_all_resources` is true.) + bool modified; + + // If the resource is a TensorArray, the set of gradients read or written. + std::set tensor_array_gradients_accessed; +}; + +struct XlaCompilationResult { + // Vector that maps from the parameters of the XLA computation to their + // original argument positions. To handle compile-time constant inputs, the + // parameters to the XLA computation may be a subset of the original + // arguments. The relative ordering of parameters are maintained. + std::vector input_mapping; + + // Input shapes of the computation. If we are flattening inputs, these are + // the flattened shapes. + std::vector xla_input_shapes; + + // Output shape in XLA format. The output shape is always a tuple. If we + // are flattening outputs, these are the flattened shapes. + xla::Shape xla_output_shape; + + // TensorFlow shapes of outputs, together with the values of any + // constant arguments. Vector indexed by Tensorflow _Retval number, + // containing both constant and non-constant results. + std::vector outputs; + + // TensorFlow shapes and types of sends/recvs from HostCompute Ops to their + // matching RecvAtHost/SendFromHost Ops in the outer graph. + tf2xla::HostComputeMetadata host_compute_metadata; + + // Resources whose values were updated by the computation, ordered + // by return value position (which is the same as the order the resources + // were passed as arguments). Resource updates follow the non-constant + // results in the outputs of XLA computation. + std::vector resource_updates; + + // The XLA computation built from the tensorflow subgraph. + std::shared_ptr computation; + + // Meta-info about encountered collective ops. + struct CollectiveInfo { + int group_key; + int group_size; + int next_id; + + template + friend H AbslHashValue(H h, const CollectiveInfo& info) { + return H::combine(std::move(h), info.group_key, info.group_size, + info.next_id); + } + + friend bool operator==(const CollectiveInfo& lhs, + const CollectiveInfo& rhs) { + return lhs.group_key == rhs.group_key && + lhs.group_size == rhs.group_size && lhs.next_id == rhs.next_id; + } + }; + + // Information of the collectives encountered during the translation. + std::optional collective_info; +}; + +// Resolves the device assignment based on CollectiveInfo. +// CollectiveInfo records collective ops in the cluster. Note that +// this relies on a rendezvous and blocks until all replicas are there. +// +// Takes several extra configuration objects by reference since +// xla::ExecutableRunOptions does not take ownership; these are configured and +// bundled into `run_options` if applicable. +absl::Status ResolveDeviceAssignment( + OpKernelContext* ctx, + const XlaCompilationResult::CollectiveInfo& collective_info, + xla::ExecutableRunOptions& run_options, + xla::DeviceAssignment& device_assignment, + xla::gpu::GpuExecutableRunOptions& gpu_options); + +} // end namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_HELPERS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc new file mode 100644 index 0000000000000000000000000000000000000000..e2e0003ca185e6e9ec3da7ae7749d7a2ec3e46fb --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.cc @@ -0,0 +1,272 @@ +/* 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/xla_jit_compiled_cpu_function.h" + +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/tf2xla.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function.h" +#include "xla/backends/cpu/buffer_allocation_info.h" +#include "xla/backends/cpu/buffer_allocation_info_util.h" +#include "xla/backends/cpu/codegen/compiled_function_library.h" +#include "xla/client/client_library.h" +#include "xla/client/executable_build_options.h" +#include "xla/client/local_client.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/service/cpu/cpu_aot_compilation_result.h" +#include "xla/service/cpu/cpu_executable.h" +#include "xla/service/platform_util.h" +#include "xla/shape_util.h" +#include "xla/stream_executor/platform.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/types.h" +#include "tsl/platform/casts.h" +#include "tsl/platform/statusor.h" + +namespace tensorflow { + +namespace { +constexpr char kHostPlatform[] = "Host"; + +// Returns the index of the result in the temp buffers. +absl::StatusOr ComputeResultIndex( + const xla::BufferAssignment& buffer_assignment) { + TF_ASSIGN_OR_RETURN(const xla::BufferAllocation::Slice result_slice, + buffer_assignment.GetUniqueTopLevelOutputSlice()); + return result_slice.index(); +} + +// Returns the number of results. +int CountResults( + absl::Span buffer_infos) { + int num_results = 0; + for (const auto& info : buffer_infos) { + if (info.is_result()) { + ++num_results; + } + } + return num_results; +} + +// Collect names from `entries`, where T is one of +// tf2xla::{Feed,Fetch,Variable}. We hold the actual strings in nonempty_names, +// and hold arrays of pointers in name_ptrs, terminated by a nullptr entry. +template +void CollectNames(const T& entries, std::vector* nonempty_names, + std::vector* name_ptrs) { + // First collect `nonempty_names`, to ensure the underlying strings won't + // change out from under us. + for (const auto& entry : entries) { + const std::string& name = entry.name(); + if (!name.empty()) { + nonempty_names->push_back(name); + } + } + // Now set `name_ptrs` pointing to the strings in `nonempty_names`. + name_ptrs->reserve(entries.size() + 1); // +1 for nullptr array terminator + size_t nonempty_index = 0; + for (const auto& entry : entries) { + const std::string& name = entry.name(); + if (!name.empty()) { + name_ptrs->push_back(nonempty_names->at(nonempty_index).c_str()); + ++nonempty_index; + } else { + name_ptrs->push_back(""); + } + } + name_ptrs->push_back(nullptr); // array terminator +} + +} // namespace + +/*static*/ absl::StatusOr> +XlaJitCompiledCpuFunction::Compile( + const GraphDef& graph_def, const tf2xla::Config& config, + const xla::ExecutableBuildOptions& build_options) { + // Convert the graph_def into an xla::XlaComputation. + TF_ASSIGN_OR_RETURN(se::Platform * platform, + xla::PlatformUtil::GetPlatform(kHostPlatform)); + TF_ASSIGN_OR_RETURN(xla::LocalClient * client, + xla::ClientLibrary::GetOrCreateLocalClient(platform)); + xla::XlaComputation computation; + TF_RETURN_IF_ERROR(tensorflow::ConvertGraphDefToXla(graph_def, config, client, + &computation)); + + // Get and verify the program shape. + TF_ASSIGN_OR_RETURN(std::unique_ptr program_shape, + client->GetComputationShape(computation)); + if (program_shape->result().element_type() != xla::TUPLE) { + // The XlaCompiler we use to build the xla computation always generates a + // tuple result, and XlaCompiledCpuFunction relies on this for simpler + // calling semantics. + return absl::InternalError( + "XlaJitCompiledCpuFunction requires the XLA result to be a tuple"); + } + // The parameter names are currently meaningless, and redundant with the rest + // of our metadata, so clear them out to avoid confusion and save space. + program_shape->clear_parameter_names(); + + // Compute arg shapes, needed to compile the executable. + std::vector arg_shapes; + arg_shapes.reserve(program_shape->parameters_size()); + for (int i = 0; i < program_shape->parameters_size(); ++i) { + arg_shapes.push_back(&program_shape->parameters(i)); + } + + // Compile the executable. The static_cast to the CpuExecutable subclass is + // necessary since the raw function and buffer assignments are only available + // there. + TF_ASSIGN_OR_RETURN(auto executables, + client->Compile(computation, arg_shapes, build_options)); + TF_RET_CHECK(executables.size() == 1); + std::unique_ptr executable = std::move(executables[0]); + xla::cpu::CpuExecutable* cpu_executable = + static_cast(executable->executable()); + const xla::BufferAssignment& buffer_assignment = + cpu_executable->buffer_assignment(); + + // Compute buffer infos and the result index, needed to run the raw function. + std::vector buffer_infos = + xla::cpu::CreateBufferAllocationInfos(cpu_executable->module(), + buffer_assignment); + + std::vector buffer_allocation_infos = + xla::cpu::CreateBufferAllocationInfos(cpu_executable->module(), + buffer_assignment); + + std::vector arg_index_table = + xla::cpu::CreateArgIndexTable(buffer_infos); + std::vector result_index_table = + xla::cpu::CreateResultIndexTable(buffer_infos); + TF_ASSIGN_OR_RETURN(size_t result_index, + ComputeResultIndex(buffer_assignment)); + const int num_results = CountResults(buffer_infos); + + std::unique_ptr jit_unique_ptr( + new XlaJitCompiledCpuFunction); + + XlaJitCompiledCpuFunction* jit = jit_unique_ptr.get(); + + if (!cpu_executable->has_thunks()) { + return absl::InternalError( + "JIT compilation supports only thunk execution."); + } + + { + // This is here for simplicity, effectively just used to get the thunk + // information to the XlaCompiledCpuFunction. + TF_ASSIGN_OR_RETURN( + auto compilation_result, + xla::cpu::CpuAotCompilationResult::Create( + &cpu_executable->module(), &cpu_executable->buffer_assignment(), + cpu_executable->module_name(), + // Symbols and object files are not needed since the function + // library will be backed by the one in the executable which is + // owned by XlaJitCompiledCpuFunction. + /*obj_files=*/{}, /*symbols=*/{}, + cpu_executable->thunks().thunk_sequence(), + /*function_library=*/nullptr)); + + const std::optional temp_allocation_index = + compilation_result->temp_allocation_index(); + + XlaCompiledCpuFunction::set_static_data_temp_allocation_index( + &jit->static_data_, temp_allocation_index); + + jit->compilation_result_proto_ = + std::make_unique( + compilation_result->proto()); + + auto compiled_function_library = + absl::down_cast( + cpu_executable->function_library()); + + if (!compiled_function_library) { + return absl::InternalError( + "Could not downcast FunctionLibrary to CompiledFunctionLibrary"); + } + + // NOTE: This will work because the function library is by the + // executable and keeps the function pointers alive. + jit->function_library_symbol_map_ = + compiled_function_library->GetTypelessSymbolsMap(); + } + + jit->executable_ = std::move(executable); + jit->buffer_infos_ = std::move(buffer_infos); + jit->arg_index_table_ = std::move(arg_index_table); + jit->result_index_table_ = std::move(result_index_table); + jit->program_shape_ = + std::make_unique(program_shape->ToProto()); + XlaCompiledCpuFunction::set_static_data_compilation_result_proto( + &jit->static_data_, jit->compilation_result_proto_.get()); + XlaCompiledCpuFunction::set_static_data_function_library_symbol_map( + &jit->static_data_, jit->function_library_symbol_map_); + + XlaCompiledCpuFunction::set_static_data_buffer_infos( + &jit->static_data_, jit->buffer_infos_.data()); + XlaCompiledCpuFunction::set_static_data_num_buffers( + &jit->static_data_, jit->buffer_infos_.size()); + XlaCompiledCpuFunction::set_static_data_arg_index_table( + &jit->static_data_, jit->arg_index_table_.data()); + XlaCompiledCpuFunction::set_static_data_result_index_table( + &jit->static_data_, jit->result_index_table_.data()); + XlaCompiledCpuFunction::set_static_data_num_args( + &jit->static_data_, jit->arg_index_table_.size()); + XlaCompiledCpuFunction::set_static_data_num_variables(&jit->static_data_, + config.variable_size()); + XlaCompiledCpuFunction::set_static_data_num_results(&jit->static_data_, + num_results); + XlaCompiledCpuFunction::set_static_data_result_index(&jit->static_data_, + result_index); + // Optional metadata is collected and set below. + CollectNames(config.feed(), &jit->nonempty_arg_names_, &jit->arg_names_); + + auto variable_copy = config.variable(); + for (auto& var : variable_copy) { + if (var.name().empty()) { + var.set_name(var.node_name()); + } + } + CollectNames(variable_copy, &jit->nonempty_variable_names_, + &jit->variable_names_); + + CollectNames(config.fetch(), &jit->nonempty_result_names_, + &jit->result_names_); + XlaCompiledCpuFunction::set_static_data_arg_names(&jit->static_data_, + jit->arg_names_.data()); + XlaCompiledCpuFunction::set_static_data_variable_names( + &jit->static_data_, jit->variable_names_.data()); + XlaCompiledCpuFunction::set_static_data_result_names( + &jit->static_data_, jit->result_names_.data()); + XlaCompiledCpuFunction::set_static_data_program_shape( + &jit->static_data_, jit->program_shape_.get()); + + return std::move(jit_unique_ptr); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h new file mode 100644 index 0000000000000000000000000000000000000000..8e9924e88d19866b2ece300d95094da55f4631ff --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function.h @@ -0,0 +1,112 @@ +/* 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_XLA_JIT_COMPILED_CPU_FUNCTION_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_JIT_COMPILED_CPU_FUNCTION_H_ + +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "absl/log/check.h" +#include "tensorflow/compiler/tf2xla/encoded_buffer_allocation_info.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.h" +#include "xla/backends/cpu/buffer_allocation_info.h" +#include "xla/client/local_client.h" +#include "xla/service/cpu/executable.pb.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { + +// Represents the result of JIT compilation by XLA down to a function. This +// class holds the state necessary to create XlaCompiledCpuFunction instances, +// which are used to actually invoke the compiled computation. +// +// XlaJitCompiledCpuFunction must outlive the XlaCompiledCpuFunctions that are +// created from it. It holds state shared by all of the functions, including the +// JIT-compiled function itself, along with buffer sizes and other metadata +// necessary for execution. +class XlaJitCompiledCpuFunction { + public: + // Compile a tensorflow::GraphDef into an XlaJitCompiledCpuFunction. The given + // `config` specifies the portion of the graph to compile, via feeds and + // fetches. Each feed is a positional input argument for the compiled + // function, while each fetch is a positional output argument. + static absl::StatusOr> Compile( + const GraphDef& graph_def, const tf2xla::Config& config, + const xla::ExecutableBuildOptions& build_options); + + XlaJitCompiledCpuFunction(const XlaJitCompiledCpuFunction&) = delete; + XlaJitCompiledCpuFunction& operator=(const XlaJitCompiledCpuFunction&) = + delete; + + // Returns static data used to create an XlaCompiledCpuFunction instance, + // which represents the JIT-compiled function. The static data is unchanging + // across each instance. + const XlaCompiledCpuFunction::StaticData& StaticData() const { + return static_data_; + } + + const xla::LocalExecutable& LocalExecutable() const { + CHECK(executable_); // Crash ok + return *executable_; + } + + private: + XlaJitCompiledCpuFunction() : compilation_result_proto_(nullptr) {} + + // The executable holds the underlying function. + std::unique_ptr executable_; + + // The compilation result proto. + std::unique_ptr compilation_result_proto_; + + // Function library symbol map used to construct AotCompiledFunctionLibrary + absl::flat_hash_map function_library_symbol_map_; + + // The static data is backed by the rest of the state in this class. + XlaCompiledCpuFunction::StaticData static_data_; + + // The backing array for buffer infos. + std::vector buffer_infos_; + + // The backing array for the arg index table. + std::vector arg_index_table_; + + // The backing array for the result index table. + std::vector result_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 + // data to refer to. + std::vector nonempty_arg_names_; + std::vector nonempty_variable_names_; + std::vector nonempty_result_names_; + std::vector arg_names_; + std::vector variable_names_; + std::vector result_names_; + + // The backing data for the program shape. The proto form of program shape is + // used because the program shape is serialized and embedded in the object + // file. + std::unique_ptr program_shape_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_JIT_COMPILED_CPU_FUNCTION_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..2abb82fe8cde62d24f228d62af59ffce9696e4ab --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_jit_compiled_cpu_function_test.cc @@ -0,0 +1,362 @@ +/* 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/xla_jit_compiled_cpu_function.h" + +#include +#include + +#include "absl/log/check.h" +#include "absl/status/statusor.h" +#include "tensorflow/compiler/tf2xla/tf2xla.pb.h" +#include "tensorflow/compiler/tf2xla/xla_compiled_cpu_function_thunks.h" +#include "xla/client/executable_build_options.h" +#include "xla/hlo/testlib/test.h" +#include "xla/service/compiler.h" +#include "xla/service/platform_util.h" +#include "xla/shape.h" +#include "xla/shape_util.h" +#include "xla/stream_executor/platform.h" +#include "xla/stream_executor/platform_manager.h" +#include "xla/tsl/lib/core/status_test_util.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/attr_value.pb.h" +#include "tensorflow/core/framework/attr_value_util.h" +#include "tensorflow/core/framework/graph.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +using ::testing::HasSubstr; + +PLATFORM_DEFINE_ID(kFakePlatformId, FakePlatform); + +AttrValue TypeAttrValue(DataType type) { + AttrValue attr_value; + SetAttrValue(type, &attr_value); + return attr_value; +} + +GraphDef SumGraph() { + GraphDef graph_def; + NodeDef* x = graph_def.add_node(); + x->set_name("x"); + x->set_op("Placeholder"); + (*x->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32); + NodeDef* y = graph_def.add_node(); + y->set_name("y"); + y->set_op("Placeholder"); + (*y->mutable_attr())["dtype"] = TypeAttrValue(DT_INT32); + NodeDef* sum = graph_def.add_node(); + sum->set_name("sum"); + sum->set_op("Add"); + sum->add_input("x"); + sum->add_input("y"); + (*sum->mutable_attr())["T"] = TypeAttrValue(DT_INT32); + return graph_def; +} + +tf2xla::Config SumConfig() { + tf2xla::Config config; + tf2xla::Feed* x = config.add_feed(); + x->mutable_id()->set_node_name("x"); + x->set_name("x_name"); + tf2xla::Feed* y = config.add_feed(); + y->mutable_id()->set_node_name("y"); + y->set_name("y_name"); + tf2xla::Fetch* sum = config.add_fetch(); + sum->mutable_id()->set_node_name("sum"); + sum->set_name("sum_name"); + return config; +} + +GraphDef SumGraphVariable() { + constexpr char text_proto[] = R"pb( + node { + name: "x" + op: "VarHandleOp" + attr { + key: "dtype" + value { type: DT_INT32 } + } + attr { + key: "shared_name" + value { s: "myvar" } + } + attr { + key: "shape" + value { shape { dim { size: 1 } } } + } + } + node { + name: "read" + op: "ReadVariableOp" + input: "x" + attr { + key: "dtype" + value { type: DT_INT32 } + } + } + node { + name: "y" + op: "Placeholder" + attr { + key: "dtype" + value { type: DT_INT32 } + } + } + node { + name: "sum" + op: "Add" + input: "read" + input: "y" + attr { + key: "T" + value { type: DT_INT32 } + } + } + node { + name: "assign" + op: "AssignVariableOp" + input: "x" + input: "sum" + attr { + key: "dtype" + value { type: DT_INT32 } + } + } + # We use this identity op to make sure assign doesn't get pruned away. + node { + name: "out" + op: "Identity" + input: "y" + input: "^assign" + attr { + key: "T" + value { type: DT_INT32 } + } + })pb"; + GraphDef graph; + CHECK(protobuf::TextFormat::ParseFromString(text_proto, &graph)); + return graph; +} + +tf2xla::Config SumConfigVariable() { + constexpr char text_proto[] = R"pb(feed { id { node_name: "y" } } + variable { + node_name: "myvar" + shape { dim { size: 1 } } + type: DT_INT32 + } + fetch { id { node_name: "out" } })pb"; + tf2xla::Config config; + CHECK(protobuf::TextFormat::ParseFromString(text_proto, &config)); + return config; +} + +TEST(XlaJitCompiledCpuFunction, Sum) { + GraphDef graph_def = SumGraph(); + tf2xla::Config config = SumConfig(); + + TF_ASSERT_OK_AND_ASSIGN( + std::unique_ptr jit, + XlaJitCompiledCpuFunction::Compile(graph_def, config, + xla::ExecutableBuildOptions())); + XlaCompiledCpuFunctionThunks function(jit->StaticData()); + ASSERT_EQ(function.num_args(), 2); + ASSERT_EQ(function.num_results(), 1); + + // Run the function and check results. + *static_cast(function.arg_data(0)) = 10; + *static_cast(function.arg_data(1)) = 32; + EXPECT_TRUE(function.Run()); + EXPECT_EQ(function.error_msg(), ""); + EXPECT_EQ(*static_cast(function.result_data(0)), 42); + + // Run the function again. + *static_cast(function.arg_data(0)) = 100; + *static_cast(function.arg_data(1)) = 320; + EXPECT_TRUE(function.Run()); + EXPECT_EQ(function.error_msg(), ""); + EXPECT_EQ(*static_cast(function.result_data(0)), 420); + + // Check name to index lookups. + EXPECT_TRUE(function.HasNameIndices()); + + EXPECT_EQ(function.LookupArgIndex("x_name"), 0); + EXPECT_EQ(function.LookupArgIndex("y_name"), 1); + EXPECT_EQ(function.LookupArgIndex(""), -1); + EXPECT_EQ(function.LookupArgIndex("x"), -1); + EXPECT_EQ(function.LookupArgIndex("y"), -1); + EXPECT_EQ(function.LookupArgIndex("sum"), -1); + EXPECT_EQ(function.LookupArgIndex("sum_name"), -1); + + EXPECT_EQ(function.LookupResultIndex("sum_name"), 0); + EXPECT_EQ(function.LookupResultIndex(""), -1); + EXPECT_EQ(function.LookupResultIndex("x"), -1); + EXPECT_EQ(function.LookupResultIndex("y"), -1); + EXPECT_EQ(function.LookupResultIndex("sum"), -1); + EXPECT_EQ(function.LookupResultIndex("x_name"), -1); + EXPECT_EQ(function.LookupResultIndex("y_name"), -1); + + EXPECT_EQ(0, function.num_variables()); + EXPECT_EQ(function.LookupVariableIndex("x"), -1); + + // Expect that name and index lookups match. + for (int i = 0; i < function.num_args(); ++i) { + const char* name = function.GetArgName(i); + ASSERT_NE(name, nullptr); + const int roundtrip_i = function.LookupArgIndex(name); + EXPECT_EQ(roundtrip_i, i) << " name= " << name; + } + for (int i = 0; i < function.num_results(); ++i) { + const char* name = function.GetResultName(i); + ASSERT_NE(name, nullptr); + const int roundtrip_i = function.LookupResultIndex(name); + EXPECT_EQ(roundtrip_i, i) << " name= " << name; + } + // Expect correct handling of invalid indices. + EXPECT_EQ(function.GetArgName(-1), nullptr); + EXPECT_EQ(function.GetArgName(function.num_args()), nullptr); + EXPECT_EQ(function.GetResultName(-1), nullptr); + EXPECT_EQ(function.GetResultName(function.num_results()), nullptr); + EXPECT_EQ(function.GetVariableName(0), nullptr); + + // Check program shape. + using xla::ShapeUtil; + const xla::Shape s32 = ShapeUtil::MakeShape(xla::S32, {}); + ASSERT_TRUE(function.ProgramShape() != nullptr); + TF_ASSERT_OK_AND_ASSIGN( + xla::ProgramShape program_shape, + xla::ProgramShape::FromProto(*function.ProgramShape())); + ASSERT_EQ(program_shape.parameters_size(), 2); + EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(0), s32)); + EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(1), s32)); + + const xla::Shape& result = program_shape.result(); + ASSERT_EQ(result.element_type(), xla::TUPLE); + ASSERT_EQ(ShapeUtil::TupleElementCount(result), 1); + const xla::Shape& result0 = ShapeUtil::GetTupleElementShape(result, 0); + EXPECT_TRUE(ShapeUtil::Compatible(result0, s32)); +} + +TEST(XlaJitCompiledCpuFunction, SumVariable) { + GraphDef graph_def = SumGraphVariable(); + tf2xla::Config config = SumConfigVariable(); + + TF_ASSERT_OK_AND_ASSIGN( + std::unique_ptr jit, + XlaJitCompiledCpuFunction::Compile(graph_def, config, + xla::ExecutableBuildOptions())); + XlaCompiledCpuFunctionThunks function(jit->StaticData()); + ASSERT_EQ(function.num_args(), 2); + ASSERT_EQ(function.num_results(), 2); + + // Run the function and check results. + *static_cast(function.arg_data(0)) = 10; + *static_cast(function.arg_data(1)) = 32; + EXPECT_TRUE(function.Run()); + EXPECT_EQ(function.error_msg(), ""); + EXPECT_EQ(*static_cast(function.result_data(0)), 10); + EXPECT_EQ(*static_cast(function.result_data(1)), 42); + + // Run the function again. + *static_cast(function.arg_data(0)) = 100; + *static_cast(function.arg_data(1)) = 320; + EXPECT_TRUE(function.Run()); + EXPECT_EQ(function.error_msg(), ""); + EXPECT_EQ(*static_cast(function.result_data(0)), 100); + EXPECT_EQ(*static_cast(function.result_data(1)), 420); + + // Check name to index lookups. + EXPECT_TRUE(function.HasNameIndices()); + + EXPECT_EQ(2, function.num_args()); + + EXPECT_EQ(1, function.num_variables()); + EXPECT_EQ(function.LookupVariableIndex("myvar"), 1); + + const char* name = function.GetVariableName(0); + EXPECT_EQ(std::string(name), "myvar"); + EXPECT_EQ(function.GetVariableName(1), nullptr); + EXPECT_EQ(function.GetVariableName(-1), nullptr); + + // Check program shape. + using xla::ShapeUtil; + const xla::Shape s32 = ShapeUtil::MakeShape(xla::S32, {}); + const xla::Shape s32_1 = ShapeUtil::MakeShape(xla::S32, {1}); + ASSERT_TRUE(function.ProgramShape() != nullptr); + TF_ASSERT_OK_AND_ASSIGN( + xla::ProgramShape program_shape, + xla::ProgramShape::FromProto(*function.ProgramShape())); + ASSERT_EQ(program_shape.parameters_size(), 2); + EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(0), s32)); + EXPECT_TRUE(ShapeUtil::Compatible(program_shape.parameters(1), s32_1)); + + const xla::Shape& result = program_shape.result(); + ASSERT_EQ(result.element_type(), xla::TUPLE); + ASSERT_EQ(ShapeUtil::TupleElementCount(result), 2); + const xla::Shape& result0 = ShapeUtil::GetTupleElementShape(result, 0); + EXPECT_TRUE(ShapeUtil::Compatible(result0, s32)); +} + +TEST(XlaJitCompiledCpuFunction, CanCompileWithAdditionalPlatform) { + class FakePlatform : public se::Platform { + public: + FakePlatform() : name_(kFakePlatformId->ToName()) {} + ~FakePlatform() override {} + + se::Platform::Id id() const override { return kFakePlatformId; } + + int VisibleDeviceCount() const override { return 0; } + + const std::string& Name() const override { return name_; } + + absl::StatusOr> DescriptionForDevice( + int ordinal) const override { + return std::unique_ptr(nullptr); + } + + absl::StatusOr ExecutorForDevice( + int ordinal) override { + return nullptr; + } + + private: + std::string name_; + }; + + TF_EXPECT_OK( + se::PlatformManager::RegisterPlatform(std::make_unique())); + xla::Compiler::RegisterCompilerFactory(kFakePlatformId, []() { + return std::unique_ptr(nullptr); + }); + + EXPECT_THAT(xla::PlatformUtil::GetDefaultPlatform().status().message(), + HasSubstr(kFakePlatformId->ToName())); + + GraphDef graph_def = SumGraph(); + tf2xla::Config config = SumConfig(); + TF_ASSERT_OK_AND_ASSIGN( + std::unique_ptr jit, + XlaJitCompiledCpuFunction::Compile(graph_def, config, + xla::ExecutableBuildOptions())); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_kernel.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_kernel.cc new file mode 100644 index 0000000000000000000000000000000000000000..439d488b8a951084659df43634132d334788f318 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_kernel.cc @@ -0,0 +1,840 @@ +/* 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/xla_op_kernel.h" + +#include + +#include "absl/memory/memory.h" +#include "tensorflow/compiler/tf2xla/literal_util.h" +#include "tensorflow/compiler/tf2xla/shape_util.h" +#include "tensorflow/compiler/tf2xla/type_util.h" +#include "tensorflow/compiler/tf2xla/xla_compilation_device.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/status_macros.h" +#include "tensorflow/core/common_runtime/dma_helper.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/util/overflow.h" + +namespace tensorflow { + +XlaOpKernelContext::XlaOpKernelContext(OpKernelContext* context) + : context_(context), + dynamic_dimension_is_minus_one_(false), + value_inference_(xla_context()->builder()) {} + +bool XlaOpKernelContext::ValidateInputsAreSameShape(OpKernel* op) { + return context_->ValidateInputsAreSameShape(op); +} + +XlaContext* XlaOpKernelContext::xla_context() const { + return &XlaContext::Get(context_); +} + +xla::XlaBuilder* XlaOpKernelContext::builder() const { + return xla_context()->builder(); +} + +xla::ValueInference& XlaOpKernelContext::value_inference() { + return value_inference_; +} + +XlaCompiler* XlaOpKernelContext::compiler() const { + return xla_context()->compiler(); +} + +const XlaExpression& XlaOpKernelContext::InputExpression(int index) { + return *XlaExpression::CastExpressionFromTensor(context_->input(index)); +} + +const XlaExpression& XlaOpKernelContext::InputExpression( + absl::string_view name) { + return *XlaExpression::CastExpressionFromTensor(GetInputTensorByName(name)); +} + +xla::XlaOp XlaOpKernelContext::Input(int index) { + return InputExpression(index).AsXlaOp(builder()); +} + +xla::XlaOp XlaOpKernelContext::Input(absl::string_view name) { + return InputExpression(name).AsXlaOp(builder()); +} + +TensorShape XlaOpKernelContext::InputShape(int index) { + return context_->input(index).shape(); +} + +TensorShape XlaOpKernelContext::InputShape(absl::string_view name) { + return GetInputTensorByName(name).shape(); +} + +absl::StatusOr XlaOpKernelContext::InputXlaShape(int index) { + return InputExpression(index).GetXlaShape(); +} + +absl::StatusOr XlaOpKernelContext::InputXlaShape( + absl::string_view name) { + return InputExpression(name).GetXlaShape(); +} + +DataType XlaOpKernelContext::input_type(int index) const { + DataType type = context_->input_dtype(index); + if (type == DT_UINT8) { + // Masqueraded XlaExpression could have different type. See + // XlaOpKernelContext::SetOutputExpression for details. + auto expression = + XlaExpression::CastExpressionFromTensor(context_->input(index)); + type = expression->dtype(); + } + return type; +} + +DataType XlaOpKernelContext::InputType(absl::string_view name) { + const Tensor& tensor = GetInputTensorByName(name); + DataType type = tensor.dtype(); + if (type == DT_UINT8) { + // Masqueraded XlaExpression could have different type. See + // XlaOpKernelContext::SetOutputExpression for details. + auto expression = XlaExpression::CastExpressionFromTensor(tensor); + type = expression->dtype(); + } + return type; +} + +xla::PrimitiveType XlaOpKernelContext::input_xla_type(int index) { + xla::PrimitiveType type; + absl::Status status = DataTypeToPrimitiveType(input_type(index), &type); + if (!status.ok()) { + SetStatus(status); + return xla::PRIMITIVE_TYPE_INVALID; + } + return type; +} + +xla::PrimitiveType XlaOpKernelContext::InputXlaType(absl::string_view name) { + xla::PrimitiveType type; + absl::Status status = DataTypeToPrimitiveType(InputType(name), &type); + if (!status.ok()) { + SetStatus(status); + return xla::PRIMITIVE_TYPE_INVALID; + } + return type; +} + +absl::Status XlaOpKernelContext::ConstantInput(int index, + xla::Literal* constant_literal, + xla::ValueInferenceMode mode) { + if (this->InputXlaShape(index)->is_dynamic()) { + return absl::InvalidArgumentError(absl::StrCat( + "Reading input as constant from a dynamic tensor is not yet supported. " + "Xla shape: ", + this->InputXlaShape(index)->ToString())); + } + return ConstantInputReshaped(index, + context_->input(index).shape().dim_sizes(), + constant_literal, mode); +} + +static absl::StatusOr InputIndex(XlaOpKernelContext* context, + absl::string_view name) { + int start, stop; + TF_RETURN_IF_ERROR(context->op_kernel().InputRange(name, &start, &stop)); + if (stop != start + 1) { + return absl::InvalidArgumentError( + absl::StrCat("OpKernel used list-valued input name '", name, + "' when single-valued input was " + "expected")); + } + return start; +} + +absl::Status XlaOpKernelContext::ResolveInputDynamism( + int index, xla::Literal* dynamism_literal) { + return ResolveInputDynamismReshaped( + index, context_->input(index).shape().dim_sizes(), dynamism_literal); +} + +absl::Status XlaOpKernelContext::ResolveInputDynamism( + absl::string_view name, xla::Literal* dynamism_literal) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ResolveInputDynamism(index, dynamism_literal); +} + +absl::Status XlaOpKernelContext::ConstantInput(absl::string_view name, + xla::Literal* constant_literal, + xla::ValueInferenceMode mode) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ConstantInput(index, constant_literal, mode); +} + +absl::Status XlaOpKernelContext::ConstantInputReshaped( + int index, absl::Span new_dims, + xla::Literal* constant_literal, xla::ValueInferenceMode mode) { + TF_ASSIGN_OR_RETURN(Tensor constant, ConstantInputTensor(index, mode)); + Tensor temp(constant.dtype()); + if (!temp.CopyFrom(constant, TensorShape(new_dims))) { + return absl::InvalidArgumentError( + absl::StrCat(context_->op_kernel().name(), " input ", index, + " has shape ", constant.shape().DebugString(), + " but was asked to be reshaped to incompatible shape ", + TensorShape(new_dims).DebugString())); + } + + TF_ASSIGN_OR_RETURN(*constant_literal, HostTensorToLiteral(temp)); + return absl::OkStatus(); +} + +// Converts an int16, int32 or int64 scalar literal to an int64. +static absl::Status LiteralToInt64Scalar(const xla::LiteralSlice& literal, + int64_t* out) { + if (!literal.shape().dimensions().empty()) { + return absl::InvalidArgumentError("value is not a scalar"); + } + if (literal.shape().element_type() == xla::S16) { + *out = literal.Get({}); + } else if (literal.shape().element_type() == xla::S32) { + *out = literal.Get({}); + } else if (literal.shape().element_type() == xla::S64) { + *out = literal.Get({}); + } else { + return absl::InvalidArgumentError("value must be int16, int32, or int64"); + } + return absl::OkStatus(); +} + +// Converts an float32 or float64 scalar literal to a float64. +static absl::Status LiteralToFloat64Scalar(const xla::LiteralSlice& literal, + double* out) { + if (!literal.shape().dimensions().empty()) { + return absl::InvalidArgumentError("value is not a scalar"); + } + if (literal.shape().element_type() == xla::F32) { + *out = literal.Get({}); + } else if (literal.shape().element_type() == xla::F64) { + *out = literal.Get({}); + } else { + return absl::InvalidArgumentError( + "value must be either float32 or float64"); + } + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ConstantInputAsIntScalar( + int index, int64_t* out, xla::ValueInferenceMode mode) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInput(index, &literal, mode)); + return LiteralToInt64Scalar(literal, out); +} + +absl::Status XlaOpKernelContext::ConstantInputAsIntScalar( + absl::string_view name, int64_t* out, xla::ValueInferenceMode mode) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ConstantInputAsIntScalar(index, out, mode); +} + +absl::StatusOr XlaOpKernelContext::ConstantInputAsIntScalar( + absl::string_view name, xla::ValueInferenceMode mode) { + int64_t out; + TF_RETURN_IF_ERROR(ConstantInputAsIntScalar(name, &out, mode)); + return out; +} + +absl::Status XlaOpKernelContext::ConstantInputAsFloatScalar( + int index, double* out, xla::ValueInferenceMode mode) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInput(index, &literal, mode)); + return LiteralToFloat64Scalar(literal, out); +} + +static absl::Status LiteralToPredVector(const xla::LiteralSlice& literal, + std::vector* out) { + if (literal.shape().dimensions().size() != 1) { + return absl::InvalidArgumentError(absl::StrCat( + "output_shape must be rank 1, got shape ", literal.shape().ToString())); + } + int64_t size = xla::ShapeUtil::ElementsIn(literal.shape()); + if (literal.shape().element_type() != xla::PRED) { + return absl::InvalidArgumentError("value is not PRED"); + } + for (int64_t i = 0; i < size; ++i) { + out->push_back(literal.Get({i})); + } + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ResolveInputDynamismIntoPred(int index, + bool* out) { + xla::Literal literal; + XlaExpression e = InputExpression(index); + absl::StatusOr dynamism_or_status = e.ResolveDynamism(); + if (!dynamism_or_status.ok()) { + // When failed to resolve dynamism, conservatively consider the value + // dynamic. This could happen if the input depends on some ops like + // custom-call that is not supported generally for dynamism computation. + // + // TODO(b/176993339): Support resolving dynamism across computations so + // resolving dynamism will not fail in those cases. + *out = true; + return absl::OkStatus(); + } + Tensor dynamism = dynamism_or_status.value(); + + Tensor temp(dynamism.dtype()); + TensorShape tensor_shape({}); + if (!temp.CopyFrom(dynamism, tensor_shape)) { + return errors::InvalidArgument( + context_->op_kernel().name(), " input ", index, " has shape ", + dynamism.shape().DebugString(), " which is not a R0 ", tensor_shape); + } + + TF_ASSIGN_OR_RETURN(literal, HostTensorToLiteral(temp)); + *out = literal.Get({}); + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ResolveInputDynamismIntoPredVector( + absl::string_view name, std::vector* out) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ResolveInputDynamismIntoPredVector(index, out); +} + +absl::Status XlaOpKernelContext::ResolveInputDynamismIntoPred( + absl::string_view name, bool* out) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ResolveInputDynamismIntoPred(index, out); +} + +absl::Status XlaOpKernelContext::ResolveInputDynamismReshaped( + int index, absl::Span new_dims, + xla::Literal* dynamism_literal) { + XlaExpression e = InputExpression(index); + absl::StatusOr dynamism_or_status = e.ResolveDynamism(); + if (!dynamism_or_status.ok()) { + xla::Literal true_literal = xla::LiteralUtil::CreateR0(true); + // When failed to resolve dynamism, conservatively consider the value + // dynamic. This could happen if the input depends on some ops like + // custom-call that is not supported generally for dynamism computation. + *dynamism_literal = + true_literal + .Broadcast(xla::ShapeUtil::MakeShape(xla::PRED, new_dims), {}) + .value(); + + return absl::OkStatus(); + } + Tensor dynamism = dynamism_or_status.value(); + + Tensor temp(dynamism.dtype()); + if (!temp.CopyFrom(dynamism, TensorShape(new_dims))) { + return absl::InvalidArgumentError( + absl::StrCat(context_->op_kernel().name(), " input ", index, + " has shape ", dynamism.shape().DebugString(), + " but was asked to be reshaped to incompatible shape ", + TensorShape(new_dims).DebugString())); + } + + TF_ASSIGN_OR_RETURN(*dynamism_literal, HostTensorToLiteral(temp)); + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ResolveInputDynamismIntoPredVector( + int index, std::vector* out) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ResolveInputDynamismReshaped( + index, {InputShape(index).num_elements()}, &literal)); + + return LiteralToPredVector(literal, out); +} + +// Converts an int32 or int64 1D literal to an int64 vector. +static absl::Status LiteralToInt64Vector(const xla::LiteralSlice& literal, + std::vector* out) { + if (literal.shape().dimensions().size() != 1) { + return absl::InvalidArgumentError(absl::StrCat( + "output_shape must be rank 1, got shape ", literal.shape().ToString())); + } + int64_t size = xla::ShapeUtil::ElementsIn(literal.shape()); + if (literal.shape().element_type() == xla::S32) { + for (int64_t i = 0; i < size; ++i) { + out->push_back(literal.Get({i})); + } + } else if (literal.shape().element_type() == xla::S64) { + for (int64_t i = 0; i < size; ++i) { + out->push_back(literal.Get({i})); + } + } else { + return absl::InvalidArgumentError("value must be either int32 or int64"); + } + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ConstantInputAsIntVector( + int index, std::vector* out, xla::ValueInferenceMode mode) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInput(index, &literal, mode)); + return LiteralToInt64Vector(literal, out); +} + +absl::Status XlaOpKernelContext::ConstantInputAsIntVector( + absl::string_view name, std::vector* out, + xla::ValueInferenceMode mode) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ConstantInputAsIntVector(index, out, mode); +} + +absl::Status XlaOpKernelContext::ConstantInputReshapedToIntVector( + int index, std::vector* out, xla::ValueInferenceMode mode) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInputReshaped( + index, {InputShape(index).num_elements()}, &literal, mode)); + return LiteralToInt64Vector(literal, out); +} + +absl::Status XlaOpKernelContext::ConstantInputReshapedToIntVector( + absl::string_view name, std::vector* out, + xla::ValueInferenceMode mode) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInputReshaped( + index, {InputShape(index).num_elements()}, &literal, mode)); + return LiteralToInt64Vector(literal, out); +} + +absl::Status XlaOpKernelContext::ConstantInputAsInt64Literal( + int index, xla::Literal* out, xla::ValueInferenceMode mode) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInput(index, &literal, mode)); + switch (literal.shape().element_type()) { + case xla::S32: { + *out = xla::Literal( + xla::ShapeUtil::ChangeElementType(literal.shape(), xla::S64)); + auto src_data = literal.data(); + for (int64_t i = 0; i < src_data.size(); ++i) { + out->data()[i] = src_data[i]; + } + return absl::OkStatus(); + } + case xla::S64: + *out = std::move(literal); + return absl::OkStatus(); + + default: + return absl::InvalidArgumentError( + absl::StrCat("Invalid argument to ConstantInputAsInt64Literal: ", + xla::ShapeUtil::HumanString(literal.shape()))); + } +} + +absl::Status XlaOpKernelContext::ConstantInputAsInt64Literal( + absl::string_view name, xla::Literal* out, xla::ValueInferenceMode mode) { + TF_ASSIGN_OR_RETURN(int index, InputIndex(this, name)); + return ConstantInputAsInt64Literal(index, out, mode); +} + +// TODO(phawkins): validate that the dimensions form a valid shape, fail +// gracefully if they do not. +absl::Status XlaOpKernelContext::ConstantInputAsShape( + int index, TensorShape* shape, xla::ValueInferenceMode mode) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInput(index, &literal, mode)); + std::vector dims; + TF_RETURN_IF_ERROR(LiteralToInt64Vector(literal, &dims)); + + int64_t num_elements = 1; + for (auto i = dims.begin(); i != dims.end(); ++i) { + num_elements = MultiplyWithoutOverflow(num_elements, *i); + if (num_elements < 0) + return absl::InvalidArgumentError(absl::StrCat( + "The total elements specified by orig_input_shape is too large.", + "Encountered overflow after multiplying", *i, + ", result: ", num_elements)); + } + *shape = TensorShape(dims); + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ConstantInputAsPartialShape( + int index, PartialTensorShape* shape) { + xla::Literal literal; + TF_RETURN_IF_ERROR(ConstantInput(index, &literal)); + // If `literal` is a scalar it's value must be -1. + if (literal.shape().dimensions().empty()) { + int64_t shape_val; + TF_RETURN_IF_ERROR(LiteralToInt64Scalar(literal, &shape_val)); + if (shape_val != -1) { + return absl::InvalidArgumentError(absl::StrCat( + "Cannot convert value to PartialTensorShape: ", shape_val)); + } + *shape = PartialTensorShape(); // Shape with unknown rank. + return absl::OkStatus(); + } + std::vector dims; + TF_RETURN_IF_ERROR(LiteralToInt64Vector(literal, &dims)); + *shape = PartialTensorShape(dims); + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::InputList(absl::string_view name, + std::vector* handles, + std::vector* shapes) { + OpInputList inputs; + TF_RETURN_IF_ERROR(context_->input_list(name, &inputs)); + handles->clear(); + shapes->clear(); + for (const Tensor& input : inputs) { + handles->push_back( + XlaExpression::CastExpressionFromTensor(input)->AsXlaOp(builder())); + shapes->push_back(input.shape()); + } + return absl::OkStatus(); +} + +absl::Status XlaOpKernelContext::ConstantInputList( + absl::string_view name, std::vector* outputs, + xla::ValueInferenceMode mode) { + int start, stop; + TF_RETURN_IF_ERROR(op_kernel().InputRange(name, &start, &stop)); + outputs->resize(stop - start); + for (int i = start; i < stop; ++i) { + TF_RETURN_IF_ERROR(ConstantInput(i, &(*outputs)[i], mode)); + } + return absl::OkStatus(); +} + +absl::StatusOr XlaOpKernelContext::ConstantInputTensor( + int index, xla::ValueInferenceMode mode) { + XlaExpression e = InputExpression(index); + auto* client = compiler() ? compiler()->client() : nullptr; + absl::StatusOr> constant_or_status = + e.ResolveConstant(client, dynamic_dimension_is_minus_one_, mode); + if (!constant_or_status.ok()) { + absl::Status status = constant_or_status.status(); + errors::AppendToMessage(&status, "while evaluating input ", index, " of ", + context_->op_kernel().type_string(), + " operator as a compile-time constant."); + return status; + } + std::optional constant = constant_or_status.value(); + if (!constant.has_value()) { + return absl::InvalidArgumentError(absl::StrCat( + "Input ", index, " to node `", context_->op_kernel().name(), + "` with op ", context_->op_kernel().type_string(), + " must be a compile-time constant.\n\n" + "XLA compilation requires that operator arguments that represent " + "shapes or dimensions be evaluated to concrete values at compile time. " + "This error means that a shape or dimension argument could not be " + "evaluated at compile time, usually because the value of the argument " + "depends on a parameter to the computation, on a variable, or on a " + "stateful operation such as a random number generator.")); + } + return *constant; +} + +namespace { + +absl::Status ReadVariableInputTensor(const Tensor& tensor, DataType type, + const XlaOpKernelContext* ctx, + TensorShape* shape, xla::XlaOp* value) { + const XlaExpression* expression = + XlaExpression::CastExpressionFromTensor(tensor); + XlaResource* variable = expression->resource(); + TF_RET_CHECK(variable != nullptr); + TF_RET_CHECK(variable->kind() == XlaResource::kVariable); + if (!variable->initialized()) { + return absl::FailedPreconditionError(absl::StrCat( + "Read variable failure ", variable->name(), + ". It could mean the variable is uninitialized or the variable is on " + "another device ")); + } + if (variable->type() != type) { + return absl::InvalidArgumentError(absl::StrCat( + "Trying to read variable with wrong dtype. Expected ", + DataTypeString(type), " got ", DataTypeString(variable->type()))); + } + if (shape) { + *shape = variable->shape(); + } + + if (!variable->IsOverwritten() && expression->constant_value()) { + TF_ASSIGN_OR_RETURN(xla::Literal literal, + HostTensorToLiteral(*expression->constant_value())); + *value = xla::ConstantLiteral(ctx->builder(), literal); + return absl::OkStatus(); + } + auto shape_determination_fns = + ctx->compiler()->options().shape_determination_fns; + XlaLayoutPreference layout_preference = + shape_determination_fns.layout_preference_fn( + variable->shape(), variable->type(), std::nullopt); + TF_ASSIGN_OR_RETURN(xla::Shape representation_shape, + shape_determination_fns.shape_representation_fn( + variable->shape(), variable->type(), + /*use_fast_memory=*/false, layout_preference)); + xla::Shape xla_shape; + TF_RETURN_IF_ERROR( + TensorShapeToXLAShape(variable->type(), variable->shape(), &xla_shape)); + if (xla::ShapeUtil::Compatible(xla_shape, representation_shape)) { + *value = variable->value(); + } else { + *value = xla::Reshape(variable->value(), variable->shape().dim_sizes()); + } + return absl::OkStatus(); +} + +} // namespace + +absl::Status XlaOpKernelContext::ReadVariableInput(int index, DataType type, + TensorShape* shape, + xla::XlaOp* value) { + return ReadVariableInputTensor(context_->input(index), type, this, shape, + value); +} + +absl::Status XlaOpKernelContext::ReadVariableInput(absl::string_view name, + DataType type, + TensorShape* shape, + xla::XlaOp* value) { + return ReadVariableInputTensor(GetInputTensorByName(name), type, this, shape, + value); +} + +absl::Status XlaOpKernelContext::GetVariableTypeAndShape( + int index, DataType* type, TensorShape* shape) const { + const Tensor& tensor = context_->input(index); + const XlaExpression* expression = + XlaExpression::CastExpressionFromTensor(tensor); + XlaResource* variable = expression->resource(); + TF_RET_CHECK(variable != nullptr); + TF_RET_CHECK(variable->kind() == XlaResource::kVariable); + if (!variable->initialized()) { + return absl::InvalidArgumentError(absl::StrCat( + "Read variable failure ", variable->name(), + ". It could mean the variable is uninitialized or the variable is on " + "another device ")); + } + *type = variable->type(); + *shape = variable->shape(); + return absl::OkStatus(); +} + +void XlaOpKernelContext::SetOutputExpression(int index, + const XlaExpression& expression) { + absl::Status status = [&] { + // The step's default allocator is the dummy XlaCompilationAllocator which + // simply allocates a metadata buffer to hold the expression to which it + // corresponds. + // Provides a special behavior for DT_VARIANT and other types that are not + // trivially copyable. In those cases, allocate a tensor of type DT_UINT8. + if (!DataTypeCanUseMemcpy(expression.dtype())) { + // tensor_data() is not supported for tensors that cannot be copied via + // memcpy, as the copy logic might try to inspect the stored data (e.g. + // a std::string). This is likely to fail, as the data is invalid given + // that it actually encodes an XlaExpression. Using a uint8 tensor is + // always safe, so simply do that. + // TODO(jpienaar): This should be refactored to stop masquerading + // XlaExpressions as Tensors. + Tensor output; + TensorShape tensor_shape; + TF_RETURN_IF_ERROR( + context_->allocate_temp(DT_UINT8, tensor_shape, &output)); + context_->set_output(index, output); + } else { + Tensor* output = nullptr; + TF_ASSIGN_OR_RETURN(TensorShape shape, expression.GetShape()); + TF_RETURN_IF_ERROR(context_->allocate_output(index, shape, &output)); + } + XlaExpression::AssignExpressionToTensor(expression, + context_->mutable_output(index)); + return absl::OkStatus(); + }(); + if (!status.ok()) { + SetStatus(status); + } +} + +xla::PrimitiveType XlaOpKernelContext::output_xla_type(int index) { + xla::PrimitiveType type; + absl::Status status = + DataTypeToPrimitiveType(expected_output_dtype(index), &type); + if (!status.ok()) { + SetStatus(status); + return xla::PRIMITIVE_TYPE_INVALID; + } + return type; +} + +void XlaOpKernelContext::SetOutput(int index, const xla::XlaOp handle) { + SetOutputExpression( + index, + XlaExpression::XlaOp(handle, context_->expected_output_dtype(index))); +} + +void XlaOpKernelContext::SetConstantOutput(int index, const Tensor& constant) { + SetOutputExpression(index, XlaExpression::Constant(constant)); +} + +void XlaOpKernelContext::SetTensorListOutput(int index, + const xla::XlaOp handle) { + SetOutputExpression(index, XlaExpression::TensorList(handle)); +} + +void XlaOpKernelContext::SetResourceOutput(int index, XlaResource* resource) { + SetOutputExpression(index, XlaExpression::Resource(resource)); +} + +absl::Status XlaOpKernelContext::GetResourceInput(int index, + XlaResource** resource) { + const XlaExpression* expression = + XlaExpression::CastExpressionFromTensor(context_->input(index)); + TF_RET_CHECK(expression->resource() != nullptr); + *resource = expression->resource(); + return absl::OkStatus(); +} + +namespace { + +absl::Status AssignVariableTensor(const Tensor& tensor, DataType type, + const XlaOpKernelContext* ctx, + xla::XlaOp handle, xla::XlaBuilder* builder) { + const XlaExpression* expression = + XlaExpression::CastExpressionFromTensor(tensor); + XlaResource* variable = expression->resource(); + TF_RET_CHECK(variable != nullptr); + TF_RET_CHECK(variable->kind() == XlaResource::kVariable); + + auto shape_or_status = builder->GetShape(handle); + if (!shape_or_status.ok()) { + return shape_or_status.status(); + } + TensorShape shape; + TF_RETURN_IF_ERROR(XLAShapeToTensorShape(shape_or_status.value(), &shape)); + + TF_RETURN_IF_ERROR(variable->SetTypeAndShape(type, shape)); + + auto shape_determination_fns = + ctx->compiler()->options().shape_determination_fns; + XlaLayoutPreference layout_preference = + shape_determination_fns.layout_preference_fn(shape, type, std::nullopt); + TF_ASSIGN_OR_RETURN(xla::Shape representation_shape, + shape_determination_fns.shape_representation_fn( + shape, type, + /*use_fast_memory=*/false, layout_preference)); + xla::Shape xla_shape; + TF_RETURN_IF_ERROR(TensorShapeToXLAShape(type, shape, &xla_shape)); + if (!xla::ShapeUtil::Compatible(xla_shape, representation_shape)) { + handle = xla::Reshape(handle, representation_shape.dimensions()); + } + variable->SetRepresentationShape(representation_shape); + return variable->SetValue(handle); +} + +} // namespace + +absl::Status XlaOpKernelContext::AssignVariable(int input_index, DataType type, + xla::XlaOp handle) { + TF_RET_CHECK(handle.valid()); + return AssignVariableTensor(context_->input(input_index), type, this, handle, + builder()); +} + +absl::Status XlaOpKernelContext::AssignVariable(absl::string_view name, + DataType type, + xla::XlaOp handle) { + TF_RET_CHECK(handle.valid()); + return AssignVariableTensor(GetInputTensorByName(name), type, this, handle, + builder()); +} + +static absl::Status GetStatusWithStackTrace(const absl::Status& s, + const XlaOpKernelContext* ctx) { + if (s.code() == error::INVALID_ARGUMENT) { + return absl::Status{s.code(), + absl::StrCat(s.message(), "\n", ctx->StackTrace())}; + } + return s; +} + +void XlaOpKernelContext::CtxFailure(const absl::Status& s) { + context_->CtxFailure(GetStatusWithStackTrace(s, this)); +} +void XlaOpKernelContext::CtxFailureWithWarning(const absl::Status& s) { + context_->CtxFailureWithWarning(GetStatusWithStackTrace(s, this)); +} + +void XlaOpKernelContext::CtxFailure(const char* file, int line, + const absl::Status& s) { + context_->CtxFailure(file, line, GetStatusWithStackTrace(s, this)); +} +void XlaOpKernelContext::CtxFailureWithWarning(const char* file, int line, + const absl::Status& s) { + context_->CtxFailureWithWarning(file, line, GetStatusWithStackTrace(s, this)); +} + +const xla::XlaComputation* XlaOpKernelContext::GetOrCreateMax( + const DataType type) { + return xla_context()->GetOrCreateMax(type); +} + +const xla::XlaComputation* XlaOpKernelContext::GetOrCreateMin( + const DataType type) { + return xla_context()->GetOrCreateMin(type); +} + +const xla::XlaComputation* XlaOpKernelContext::GetOrCreateAdd( + const DataType type) { + return xla_context()->GetOrCreateAdd(type); +} + +const xla::XlaComputation* XlaOpKernelContext::GetOrCreateLogAddExp( + const DataType type) { + return xla_context()->GetOrCreateLogAddExp(type); +} + +const xla::XlaComputation* XlaOpKernelContext::GetOrCreateMul( + const DataType type) { + return xla_context()->GetOrCreateMul(type); +} + +const Tensor& XlaOpKernelContext::GetInputTensorByName(absl::string_view name) { + const Tensor* tensor; + CHECK_OK(context_->input(name, &tensor)); + return *tensor; +} + +XlaOpKernel::XlaOpKernel(OpKernelConstruction* context) : OpKernel(context) {} + +void XlaOpKernel::Compute(OpKernelContext* context) { + XlaOpKernelContext xla_context(context); + Compile(&xla_context); +} + +std::string XlaOpKernelContext::StackTrace() const { + if (const AbstractStackTrace* stack_trace = + xla_context()->StackTraceForNodeName(op_kernel().name())) { + AbstractStackTrace::TracePrintingOptions opts; + opts.show_line_contents = true; + opts.filter_common_prefix = true; + opts.drop_internal_frames = true; + return absl::StrCat("\nStack trace for op definition: \n", + stack_trace->ToString(opts), "\n"); + } else { + return ""; + } +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_kernel.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_kernel.h new file mode 100644 index 0000000000000000000000000000000000000000..4c8b5bc2bb490759aff42a5d71b72f959af16c72 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_kernel.h @@ -0,0 +1,391 @@ +/* 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_XLA_OP_KERNEL_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_OP_KERNEL_H_ + +#include "absl/base/attributes.h" +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/tf2xla/xla_compiler.h" +#include "tensorflow/compiler/tf2xla/xla_context.h" +#include "tensorflow/compiler/tf2xla/xla_expression.h" +#include "tensorflow/compiler/tf2xla/xla_resource.h" +#include "xla/hlo/builder/value_inference.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/hlo/builder/xla_computation.h" +#include "xla/literal.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/macros.h" +#include "tensorflow/core/platform/status.h" + +namespace tensorflow { + +class XlaOpKernelContext; + +// Implementations of operators that generate XLA code should usually subclass +// XlaOpKernel and implement the Compile() method. Unlike a regular OpKernel, +// an XlaOpKernel produces and consumes symbolic values during compilation. +// +// See the comments in xla_context.h for more details. +class XlaOpKernel : public OpKernel { + public: + explicit XlaOpKernel(OpKernelConstruction* construction); + + // Subclasses should implement Compile(), much as standard OpKernels implement + // Compute(). + virtual void Compile(XlaOpKernelContext* context) = 0; + + private: + void Compute(OpKernelContext* context) final; +}; + +// The context passed to the Compile() method of XlaOpKernel. An +// XlaOpKernelContext is a variant of the standard OpKernel class, tailored for +// implementing operators that perform symbolic execution as part of the XLA +// compiler. The key difference is that XlaOpKernelContext produces and consumes +// data as XLA computations, rather than as standard Tensors. +// +// Under the hood, symbolic execution communicates using special Tensors that +// wrap XlaExpression objects, however this is an implementation detail that +// this class hides. The *only* correct way to allocate a Tensor during +// compilation is using the XlaOpKernelContext methods, since they ensure there +// is a valid XlaExpression backing the tensor. No Op should ever call +// allocate_output or allocate_temp directly on the underlying OpKernelContext. +class XlaOpKernelContext { + public: + explicit XlaOpKernelContext(OpKernelContext* context); + + XlaContext* xla_context() const; + + // Returns the XLA XlaBuilder containing the output of compilation. + xla::XlaBuilder* builder() const; + + xla::ValueInference& value_inference(); + + // Inputs + + // Returns the number of inputs to the operator. + int num_inputs() const { return context_->num_inputs(); } + + // Returns the type of input `index`. + DataType input_type(int index) const; + + // Returns the type of input `name`. + DataType InputType(absl::string_view name); + + // Returns the type of input `index` as an xla::PrimitiveType. If the type + // is not representable as an XLA type, sets an error status and returns + // xla::PRIMITIVE_TYPE_INVALID. + xla::PrimitiveType input_xla_type(int index); + + // Returns the type of input `name` as an xla::PrimitiveType. If the type + // is not representable as an XLA type, sets an error status and returns + // xla::PRIMITIVE_TYPE_INVALID. + xla::PrimitiveType InputXlaType(absl::string_view name); + + // Returns the shape of input at `index` or input the given `name`. Note that + // in case the shape of the input is not static, then the returned shape has + // bounds as the dimension size instead of having unknown dimensions. Use + // InputXlaShape instead that provides shapes with dynamism information. + // + ABSL_DEPRECATED( + "Prefer InputXlaShape which handles dynamic shapes accurately.") + TensorShape InputShape(int index); + ABSL_DEPRECATED( + "Prefer InputXlaShape which handles dynamic shapes accurately.") + TensorShape InputShape(absl::string_view name); + + // Returns input `index` as a XlaOp. Unlike + // OpKernelContext::Input returns a symbolic value rather than a concrete + // Tensor. + xla::XlaOp Input(int index); + // Returns input `name` as a XlaOp. + xla::XlaOp Input(absl::string_view name); + + // Returns the xla input shape for a given index. + absl::StatusOr InputXlaShape(int index); + absl::StatusOr InputXlaShape(absl::string_view name); + + // Returns true if all inputs are the same shape, otherwise sets the + // status to a non-OK value and returns false. + // Usage: if (!context->ValidateInputsAreSameShape(this)) return; + bool ValidateInputsAreSameShape(OpKernel* op) TF_MUST_USE_RESULT; + + // Returns the named list-valued immutable input in "list", as + // defined in the OpDef. If the named output is not list-valued, + // returns a one-element list. + absl::Status InputList(absl::string_view name, + std::vector* handles, + std::vector* shapes); + // Evaluates input and returns their dynamism vector in a vector of + // predicates. + absl::Status ResolveInputDynamismIntoPredVector(int index, + std::vector* out); + absl::Status ResolveInputDynamismIntoPred(int index, bool* out); + absl::Status ResolveInputDynamismIntoPredVector(absl::string_view name, + std::vector* out); + absl::Status ResolveInputDynamismIntoPred(absl::string_view name, bool* out); + + absl::Status ResolveInputDynamism(int index, xla::Literal* dynamism_literal); + absl::Status ResolveInputDynamism(absl::string_view name, + xla::Literal* dynamism_literal); + + absl::Status ResolveInputDynamismReshaped(int index, + absl::Span new_dims, + xla::Literal* dynamism_literal); + // Helper methods for constant inputs. + + // Evaluates input `index` and stores it in `*constant_literal`. If the + // expression cannot be evaluated, e.g., because it depends on unbound + // parameters, returns a non-OK status. This function can also be used to + // infer constant input upper or lower bounds, by changing the `mode` + // parameter. + absl::Status ConstantInput( + int index, xla::Literal* constant_literal, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + absl::Status ConstantInput( + absl::string_view name, xla::Literal* constant_literal, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Converts a constant scalar int32 or int64 tensor into an int64. + absl::Status ConstantInputAsIntScalar( + int index, int64_t* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + absl::Status ConstantInputAsIntScalar( + absl::string_view name, int64_t* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + absl::StatusOr ConstantInputAsIntScalar( + absl::string_view name, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Converts a constant scalar float32 or float64 tensor into a float64. + absl::Status ConstantInputAsFloatScalar( + int index, double* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Converts a constant 1D int32 or int64 tensor into a vector of int64s. + absl::Status ConstantInputAsIntVector( + int index, std::vector* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + absl::Status ConstantInputAsIntVector( + absl::string_view name, std::vector* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Reshapes and converts a constant int32 or int64 tensor into a vector of + // int64s. + absl::Status ConstantInputReshapedToIntVector( + int index, std::vector* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + absl::Status ConstantInputReshapedToIntVector( + absl::string_view name, std::vector* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Converts a constant int32 or int64 Tensor into an xla int64 Literal. + absl::Status ConstantInputAsInt64Literal( + int index, xla::Literal* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + absl::Status ConstantInputAsInt64Literal( + absl::string_view name, xla::Literal* out, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Converts a constant 1D int32 or int64 tensor into a TensorShape. + absl::Status ConstantInputAsShape( + int index, TensorShape* shape, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Converts a constant 1D int32 or int64 tensor, or a scalar with value -1 + // into a PartialTensorShape. + absl::Status ConstantInputAsPartialShape(int index, + PartialTensorShape* shape); + + // Returns the named list-valued immutable input in "list", as + // defined in the OpDef. If the named output is not list-valued, + // returns a one-element list. + absl::Status ConstantInputList( + absl::string_view name, std::vector* outputs, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Returns the Tensor representation of the constant input. + absl::StatusOr ConstantInputTensor( + int index, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + // Returns an XlaExpression describing the value of 'index'. + const XlaExpression& InputExpression(int index); + const XlaExpression& InputExpression(absl::string_view name); + + // Outputs + + int num_outputs() const { return context_->num_outputs(); } + DataType expected_output_dtype(int index) const { + return context_->expected_output_dtype(index); + } + + // Returns the type of output `index` as an xla::PrimitiveType. If the type + // is not representable as an XLA type, sets an error status and returns + // xla::PRIMITIVE_TYPE_INVALID. + xla::PrimitiveType output_xla_type(int index); + + // Sets output `index` to the XlaOp `handle`. + // All outputs should be set using SetOutput and SetConstantOutput, not + // via the underlying OpKernelContext. + void SetOutput(int index, xla::XlaOp handle); + + // Sets output `index` to compile-time constant `host_tensor`, where + // `host_tensor` is a tensor in host memory. It is preferable to use + // SetConstantOutput where possible. + void SetConstantOutput(int index, const Tensor& host_tensor); + + // Returns an XlaExpression describing the value of 'index'. + void SetOutputExpression(int index, const XlaExpression& expression); + + // Sets output `index` to the Tensor List `handle`. + void SetTensorListOutput(int index, xla::XlaOp handle); + + // Status handling. + void SetStatus(const absl::Status& status) { context_->SetStatus(status); } + absl::Status status() { return context_->status(); } + + // Variables + + // Sets `*resource` to the resource associated with input `index`. + absl::Status GetResourceInput(int index, XlaResource** resource); + + // Sets output `index` to be a reference to resource `resource`. + void SetResourceOutput(int index, XlaResource* resource); + + // Sets `*type` and `*shape` to the current type and shape of a variable's + // value. + absl::Status GetVariableTypeAndShape(int index, DataType* type, + TensorShape* shape) const; + + // When dynamic_dimension_is_minus_one is set, querying a dynamic dimension + // returns "-1", this is useful when the underlying ops expect explicit + // dynamic index like reshape. + void set_dynamic_dimension_is_minus_one(bool value) { + dynamic_dimension_is_minus_one_ = value; + } + + bool dynamic_dimension_is_minus_one() const { + return dynamic_dimension_is_minus_one_; + } + + bool is_dynamic_dimension(int64_t dim_size) { return dim_size == -1; } + + // Reads the current value of the resource variable referred to by input + // `index`. If `shape` is not nullptr, sets `*shape` to the shape of the + // variable. Returns an error if the variable has not been initialized, or if + // its type does not match `type`. + absl::Status ReadVariableInput(int index, DataType type, TensorShape* shape, + xla::XlaOp* value); + // Reads the current value of the resource variable referred to by input + // `name`. + absl::Status ReadVariableInput(absl::string_view name, DataType type, + TensorShape* shape, xla::XlaOp* value); + + // Assigns the value `handle` to the variable referenced by input + // `input_index`. The variable must be of `type`. Returns an error if the + // variable has been initialized with a different type or with a + // different shape. + absl::Status AssignVariable(int input_index, DataType type, + xla::XlaOp handle); + // Assigns the value `handle` to the variable referenced by input `name`. + absl::Status AssignVariable(absl::string_view name, DataType type, + xla::XlaOp handle); + + // Helper routines for the OP_REQUIRES macros + void CtxFailure(const absl::Status& s); + void CtxFailureWithWarning(const absl::Status& s); + void CtxFailure(const char* file, int line, const absl::Status& s); + void CtxFailureWithWarning(const char* file, int line, const absl::Status& s); + + // If this kernel invocation is within a function execution, + // call_frame() returns the call frame for the function call. + CallFrameInterface* call_frame() const { return context_->call_frame(); } + + FunctionLibraryRuntime* function_library() const { + return context_->function_library(); + } + + const OpKernel& op_kernel() const { return context_->op_kernel(); } + + // Returns the underlying OpKernelContext. Use rarely. + OpKernelContext* op_kernel_context() const { return context_; } + + // Returns the XlaCompiler that is performing the compilation. Used for, e.g., + // While to compile nested computations. + XlaCompiler* compiler() const; + + // TODO(phawkins): find a better home for these helpers. + + // Gets an XLA lambda to compute Max. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateMax(DataType type); + + // Gets an XLA lambda to compute Min. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateMin(DataType type); + + // Gets an XLA lambda to compute Add. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateAdd(DataType type); + + // Gets an XLA lambda to compute LogAddExp. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateLogAddExp(DataType type); + + // Gets an XLA lambda to compute Mul. This is cached in the + // XlaContext since it may be used by multiple Ops. There is a + // separate specialization of the computation for each DataType. + const xla::XlaComputation* GetOrCreateMul(DataType type); + + // Returns stack trace encoded as a string at a given module, or an empty + // string if none found. + std::string StackTrace() const; + + private: + // Returns the tensor of input `name`. + const Tensor& GetInputTensorByName(absl::string_view name); + // Evaluates input `index`, reshapes it to `new_shape` if new_shape != + // InputShape(index), and stores it in `*constant_literal`. If the input + // cannot be evaluated, e.g., because it depends on unbound parameters, + // returns a non-Ok status. If InputShape(index).num_elements() != + // new_shape.num_elements(), returns an error status. + absl::Status ConstantInputReshaped( + int index, absl::Span new_dims, + xla::Literal* constant_literal, + xla::ValueInferenceMode mode = xla::ValueInferenceMode::kValue); + + OpKernelContext* const context_; + bool dynamic_dimension_is_minus_one_; + xla::ValueInference value_inference_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_OP_KERNEL_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry.cc new file mode 100644 index 0000000000000000000000000000000000000000..b745e958d2d950c2a228f68fd21179b80f8542ee --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry.cc @@ -0,0 +1,638 @@ +/* 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/xla_op_registry.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "absl/algorithm/container.h" +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_join.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/compiler/jit/flags.h" +#include "tensorflow/compiler/jit/xla_cluster_util.h" +#include "xla/tsl/platform/errors.h" +#include "xla/util.h" +#include "tensorflow/core/common_runtime/next_pluggable_device/next_pluggable_device_factory.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/device_factory.h" +#include "tensorflow/core/framework/kernel_def.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/node_def_util.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_def.pb.h" +#include "tensorflow/core/framework/op_def_util.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/tfrt/common/pjrt_util.h" + +namespace tensorflow { + +const char* const DEVICE_CPU_XLA_JIT = "XLA_CPU_JIT"; +const char* const DEVICE_GPU_XLA_JIT = "XLA_GPU_JIT"; +const char* const DEVICE_XLA_CPU = "XLA_CPU"; +const char* const DEVICE_XLA_GPU = "XLA_GPU"; + +static absl::Status LaunchOpHasKernelForDevice(const DeviceType& device_type) { + const OpDef* op_def; + TF_RETURN_IF_ERROR(OpRegistry::Global()->LookUpOpDef("XlaLaunch", &op_def)); + NodeDef node_def; + node_def.set_name("_XlaLaunch-op"); + node_def.set_op("XlaLaunch"); + std::string kernel_class_name; + TF_RETURN_IF_ERROR(FindKernelDef(device_type, node_def, /*KernelDef*/ nullptr, + &kernel_class_name)); + VLOG(1) << "LaunchOpHasKernelForDevice" + << " kernel_class_name: " << kernel_class_name; + return absl::OkStatus(); +} + +XlaOpRegistry::XlaOpRegistry() = default; +XlaOpRegistry::~XlaOpRegistry() = default; + +// TODO(b/64575122) consider adding more sophisticated definitions of +// compatibility if needed by future use cases. +/* static */ bool XlaOpRegistry::IsCompatible(const OpRegistration& x, + const OpRegistration& y) { + if (x.name != y.name) return true; + if (x.label != y.label) return true; + // The registrations refer to the same Op: ensures they are compatible and + // are restricted to different device allowlists. + if (x.compilation_only != y.compilation_only) { + LOG(WARNING) << "Registrations of " << x.name + << " have incompatible compilation_only settings."; + return false; + } + if (x.allow_resource_types != y.allow_resource_types) { + LOG(WARNING) << "Registrations of " << x.name + << " have incompatible allow_resource_types settings."; + return false; + } + if (x.allow_variant_types != y.allow_variant_types) { + LOG(WARNING) << "Registrations of " << x.name + << " have incompatible allow_variant_types settings."; + return false; + } + if (x.allow_string_type != y.allow_string_type) { + LOG(WARNING) << "Registrations of " << x.name + << " have incompatible allow_string_type settings."; + return false; + } + if (!x.has_device_allowlist && !y.has_device_allowlist) { + LOG(WARNING) << "Duplicate registrations of " << x.name + << " with no device allowlists."; + return false; + } + if (x.has_device_allowlist && y.has_device_allowlist) { + for (const auto& device : x.device_allowlist) { + if (y.device_allowlist.count(device) != 0) { + LOG(WARNING) << "Multiple registrations of " << x.name << " on device " + << device; + return false; + } + } + } + if (x.compile_time_constant_inputs != y.compile_time_constant_inputs) { + LOG(WARNING) << "Registrations of " << x.name + << " have incompatible compile time constant inputs."; + return false; + } + if (x.is_metadata_op != y.is_metadata_op) { + LOG(WARNING) << "Registrations of " << x.name + << " have incompatible values for is_metadata_op."; + return false; + } + return true; +} + +/* static */ void XlaOpRegistry::RegisterCompilationDevice( + const std::string& device_name, const DeviceRegistration& registration) { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + auto result = + registry.compilation_devices_.emplace(device_name, registration); + CHECK(result.second || result.first->second.compilation_device_name == + registration.compilation_device_name); +} + +/* static */ void XlaOpRegistry::RegisterBackend( + const std::string& compilation_device_name, + absl::Span supported_types, BackendOpFilter op_filter) { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + auto result = registry.backends_.emplace(compilation_device_name, Backend()); + CHECK(result.second) << "Duplicate XLA backend registration " + << compilation_device_name; + result.first->second.supported_types.insert(supported_types.begin(), + supported_types.end()); + result.first->second.op_filter = op_filter; +} + +/* static */ bool XlaOpRegistry::IsCompilationDevice( + const std::string& device_name) { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + return registry.backends_.find(device_name) != registry.backends_.end(); +} + +/* static */ bool XlaOpRegistry::GetCompilationDevice( + const std::string& device_name, const DeviceRegistration** registration) { + XlaOpRegistry& registry = Instance(); + + // Lazily register the CPU and GPU JIT devices the first time + // GetCompilationDevice is called. + static void* registration_init = [®istry]() { + MarkForCompilationPassFlags* flags = GetMarkForCompilationPassFlags(); + bool cpu_global_jit = flags->tf_xla_cpu_global_jit; + VLOG(2) << "tf_xla_cpu_global_jit = " << cpu_global_jit; + + mutex_lock lock(registry.mutex_); + if (LaunchOpHasKernelForDevice(DeviceType(DEVICE_CPU)).ok()) { + DeviceRegistration& registration = + registry.compilation_devices_[DEVICE_CPU]; + registration.compilation_device_name = DEVICE_CPU_XLA_JIT; + registration.autoclustering_policy = + cpu_global_jit + ? XlaOpRegistry::AutoclusteringPolicy::kIfEnabledGlobally + : XlaOpRegistry::AutoclusteringPolicy::kIfExplicitlyRequested; + } + if (LaunchOpHasKernelForDevice(DeviceType(DEVICE_GPU)).ok()) { + DeviceRegistration& registration = + registry.compilation_devices_[DEVICE_GPU]; + registration.compilation_device_name = DEVICE_GPU_XLA_JIT; + registration.autoclustering_policy = + XlaOpRegistry::AutoclusteringPolicy::kIfEnabledGlobally; + } + return nullptr; + }(); + (void)registration_init; + + // Register GPU JIT devices for NextPluggableDevice if its jit_device_type is + // `XLA_GPU_JIT`. + if (DeviceFactory::IsPluggableDevice(device_name) && + GetPjRtClient(DeviceType(device_name)).ok()) { + mutex_lock lock(registry.mutex_); + + NextPluggableDeviceFactory* device_factory = + static_cast( + DeviceFactory::GetFactory(device_name)); + if (device_factory != nullptr && + DeviceType(device_factory->compilation_device_name()) == + DeviceType(DEVICE_GPU_XLA_JIT) && + registry.compilation_devices_.find(device_name) == + registry.compilation_devices_.end()) { + DeviceRegistration& registration = + registry.compilation_devices_[device_name]; + registration.compilation_device_name = DEVICE_GPU_XLA_JIT; + registration.autoclustering_policy = + XlaOpRegistry::AutoclusteringPolicy::kIfEnabledGlobally; + } + } + + mutex_lock lock(registry.mutex_); + auto it = registry.compilation_devices_.find(device_name); + if (it == registry.compilation_devices_.end()) return false; + *registration = &it->second; + return true; +} + +void XlaOpRegistry::RegisterCompilationKernels() { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + + if (registry.jit_kernels_registered_) return; + registry.jit_kernels_registered_ = true; + + OpRegistryInterface* op_registry = OpRegistry::Global(); + // Order of op registration: + // The goal is to allow the co-existence of backend-specific kernels and + // generic kernels. To achieve this, we enforce the following order of + // registrations for one op: + // 1. Process op registration with device allowlists: + // this pass registers backend-specific kernels for this op. + // 2. Process op registration without device allowlists: + // this pass registers the kernels for all the other supported backends. + for (auto& ops : registry.ops_) { + const std::string& op_name = ops.first; + std::vector>& op_registrations = ops.second; + // Partition the op registration so that the ones with device allowlists + // precede the one without device allowlist. + std::partition(op_registrations.begin(), op_registrations.end(), + [](const std::unique_ptr& op_reg) { + return op_reg->has_device_allowlist; + }); + + // Collect a set of backend registered by ops with device allowlists. + // The op registration without allowlists will register a generic kernel + // for all other backends not in this set. + std::unordered_set allowlisted_backend; + for (auto& op_registration : op_registrations) { + if (op_registration->has_device_allowlist) { + allowlisted_backend.insert(op_registration->device_allowlist.begin(), + op_registration->device_allowlist.end()); + } + } + + for (auto& op_registration : op_registrations) { + const OpDef* op_def; + absl::Status lookup_status = op_registry->LookUpOpDef(op_name, &op_def); + if (!lookup_status.ok()) { + LOG(ERROR) << lookup_status.message(); + XLA_LOG_LINES( + ERROR, + "Ops registered: \n" + + dynamic_cast(op_registry)->DebugString(true)); + } + CHECK_OK(lookup_status); + + std::unordered_set type_attrs; + for (const OpDef::AttrDef& attr_def : op_def->attr()) { + if (attr_def.type() == "type" || attr_def.type() == "list(type)") { + type_attrs.insert(attr_def.name()); + } + } + + // Checks there are no type constraints referring to unknown attributes. + for (const auto& constraint : op_registration->type_constraints) { + if (type_attrs.find(constraint.first) == type_attrs.end()) { + LOG(FATAL) << "Unknown type attribute " << constraint.first + << " in XLA op registration for " << op_name; + } + } + + for (auto& backend : registry.backends_) { + // If the operator has a device allowlist, only register on allowlisted + // devices. + if (op_registration->has_device_allowlist && + op_registration->device_allowlist.find(backend.first) == + op_registration->device_allowlist.end()) { + continue; + } + + // If the operator does NOT has a device allowlist, skip all devices + // that has already been registered. + if (!op_registration->has_device_allowlist && + allowlisted_backend.find(backend.first) != + allowlisted_backend.end()) { + continue; + } + + std::unique_ptr kdef(new KernelDef); + kdef->set_op(op_registration->name); + kdef->set_device_type(backend.first); + kdef->set_label(op_registration->label); + + // Constrain each type attribute to the intersection of: + // a) the types supported by the backend, and + // b) the types allowed by the OpDef, and + // c) the type constraints. + bool unsatisfiable_type_constraint = false; + for (const std::string& type_attr : type_attrs) { + KernelDef::AttrConstraint* attr_constraint = kdef->add_constraint(); + attr_constraint->set_name(type_attr); + auto* allowed_values = + attr_constraint->mutable_allowed_values()->mutable_list(); + + const OpDef::AttrDef& op_def_attr = *FindAttr(type_attr, *op_def); + const auto* op_def_allowed_types = + op_def_attr.has_allowed_values() + ? &op_def_attr.allowed_values().list().type() + : nullptr; + auto constraint_it = + op_registration->type_constraints.find(type_attr); + const std::set* type_constraints = + constraint_it != op_registration->type_constraints.end() + ? &constraint_it->second + : nullptr; + for (DataType dtype : backend.second.supported_types) { + // Filter out types that aren't allowed by the OpDef. + if (op_def_allowed_types != nullptr && + std::find(op_def_allowed_types->begin(), + op_def_allowed_types->end(), + dtype) == op_def_allowed_types->end()) { + continue; + } + // Filter out types based on the type constraints. + if (type_constraints != nullptr && + type_constraints->find(dtype) == type_constraints->end()) { + continue; + } + // Passed all the filters, this type is allowed. + allowed_values->add_type(dtype); + } + if (op_registration->allow_resource_types) { + allowed_values->add_type(DT_RESOURCE); + } + if (op_registration->allow_variant_types) { + allowed_values->add_type(DT_VARIANT); + } + if (op_registration->allow_string_type) { + allowed_values->add_type(DT_STRING); + } + // Don't build KernelDefs that have unsatisfiable type constraints. + if (allowed_values->type().empty()) { + unsatisfiable_type_constraint = true; + break; + } + } + if (unsatisfiable_type_constraint) continue; + + if (backend.second.op_filter != nullptr && + !backend.second.op_filter(kdef.get())) { + continue; + } + VLOG(2) << "XLA op registration: device: " << backend.first + << " op: " << op_name; + registry.kernel_registrars_.emplace_back( + new kernel_factory::OpKernelRegistrar( + new KernelDef(*kdef), "XlaJitOp", op_registration->factory)); + backend.second.kernel_defs.push_back(std::move(kdef)); + } + } + } +} + +std::vector XlaOpRegistry::DeviceKernels( + const std::string& compilation_device_name, + bool include_compilation_only_kernels) { + // Ensure compilation kernels registered. + RegisterCompilationKernels(); + std::vector kernels; + XlaOpRegistry& registry = Instance(); + std::string registered_backends = + absl::StrJoin(registry.BackendNames(), ", "); + mutex_lock lock(registry.mutex_); + auto it = registry.backends_.find(compilation_device_name); + + CHECK(it != registry.backends_.end()) + << "Unknown backend " << compilation_device_name + << "; Known backends are: " << registered_backends; + for (const std::unique_ptr& k : it->second.kernel_defs) { + auto op_iter = registry.ops_.find(k->op()); + CHECK(op_iter != registry.ops_.end() && !op_iter->second.empty()); + // The test in IsCompatible ensures that if there are multiple matching + // registrations for this op name, they all have the same value of + // compilation_only, so only the first match needs to be tested. + if (include_compilation_only_kernels || + !op_iter->second.front()->compilation_only) { + kernels.push_back(k.get()); + } + } + return kernels; +} + +/*static*/ std::vector XlaOpRegistry::GetAllRegisteredOps() { + std::vector ops; + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + ops.reserve(registry.ops_.size()); + for (const auto& pair : registry.ops_) { + ops.push_back(pair.first); + } + std::sort(ops.begin(), ops.end()); + return ops; +} + +/*static*/ const std::unordered_set* +XlaOpRegistry::CompileTimeConstantInputArgNames(const std::string& op) { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + auto it = registry.ops_.find(op); + static auto empty_set = new std::unordered_set; + if (it == registry.ops_.end() || it->second.empty()) { + return empty_set; + } else { + return &it->second.front()->compile_time_constant_inputs; + } +} + +/* static */ absl::Status XlaOpRegistry::CompileTimeConstantInputs( + const NodeDef& node_def, const OpKernel* op_kernel, const OpDef* op_def, + std::vector* result) { + result->clear(); + + DCHECK(op_def != nullptr || op_kernel != nullptr); + + std::unordered_set compile_time_constant_inputs_from_attr; + std::vector compile_time_constant_inputs_vect_from_attr; + + const std::unordered_set* compile_time_constant_inputs; + + if (TryGetNodeAttr(node_def, kXlaCompileTimeConstantInputsAttr, + &compile_time_constant_inputs_vect_from_attr)) { + absl::c_copy(compile_time_constant_inputs_vect_from_attr, + std::inserter(compile_time_constant_inputs_from_attr, + compile_time_constant_inputs_from_attr.end())); + compile_time_constant_inputs = &compile_time_constant_inputs_from_attr; + } else { + compile_time_constant_inputs = + CompileTimeConstantInputArgNames(node_def.op()); + if (compile_time_constant_inputs->empty()) { + return absl::OkStatus(); + } + } + + VLOG(3) << "For operation " + << (op_def != nullptr ? op_def->name() : op_kernel->name()) + << " required constants are: " + << absl::StrJoin(*compile_time_constant_inputs, ", "); + + for (const std::string& input : *compile_time_constant_inputs) { + if (op_def) { + NameRangeMap input_name_ranges; + TF_RETURN_IF_ERROR( + NameRangesForNode(node_def, *op_def, &input_name_ranges, nullptr)); + auto name_range = input_name_ranges.find(input); + if (name_range == input_name_ranges.end()) { + continue; + } + + for (int i = name_range->second.first; i < name_range->second.second; + i++) { + result->push_back(i); + } + } else { + int start, stop; + CHECK_OK(op_kernel->InputRange(input, &start, &stop)); + for (int i = start; i < stop; ++i) { + result->push_back(i); + } + } + } + + absl::c_sort(*result); + return absl::OkStatus(); +} + +/*static*/ bool XlaOpRegistry::IsMetadataOp(const std::string& op) { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + auto it = registry.ops_.find(op); + if (it == registry.ops_.end() || it->second.empty()) { + return false; + } + + // The test in IsCompatible ensures that if there are multiple matching + // registrations for this op name, they all have the same value of + // is_metadata_op, so only the first match is returned. + return it->second.front()->is_metadata_op; +} + +std::vector XlaOpRegistry::BackendNames() { + std::vector names; + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + names.reserve(registry.backends_.size()); + for (const auto& backend_pair : registry.backends_) { + names.push_back(backend_pair.first); + } + return names; +} + +bool XlaOpRegistry::IsBackendRegistered(const std::string& name) { + XlaOpRegistry& registry = Instance(); + mutex_lock lock(registry.mutex_); + return registry.backends_.find(name) != registry.backends_.end(); +} + +XlaOpRegistry& XlaOpRegistry::Instance() { + static XlaOpRegistry* r = new XlaOpRegistry; + return *r; +} + +XlaOpRegistrationBuilder::XlaOpRegistrationBuilder(absl::string_view name) { + registration_.reset(new XlaOpRegistry::OpRegistration); + registration_->name = std::string(name); +} + +XlaOpRegistrationBuilder XlaOpRegistrationBuilder::Name( + absl::string_view name) { + XlaOpRegistrationBuilder registration(name); + return registration; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::Device( + absl::Span devices) { + registration_->has_device_allowlist = true; + for (absl::string_view device : devices) { + registration_->device_allowlist.emplace(device); + } + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::Device( + absl::string_view device) { + registration_->has_device_allowlist = true; + registration_->device_allowlist.emplace(device); + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::CompilationOnly() { + registration_->compilation_only = true; + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::AllowResourceTypes() { + registration_->allow_resource_types = true; + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::AllowVariantTypes() { + registration_->allow_variant_types = true; + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::AllowStringType() { + registration_->allow_string_type = true; + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::TypeConstraint( + absl::string_view attr_name, DataType allowed) { + std::set& types = + registration_->type_constraints[std::string(attr_name)]; + types.insert(allowed); + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::TypeConstraint( + absl::string_view attr_name, absl::Span allowed) { + std::set& types = + registration_->type_constraints[std::string(attr_name)]; + for (DataType t : allowed) { + types.insert(t); + } + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::CompileTimeConstantInput( + absl::string_view input_name) { + registration_->compile_time_constant_inputs.emplace(input_name); + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::IsMetadataOp() { + registration_->is_metadata_op = true; + return *this; +} + +XlaOpRegistrationBuilder& XlaOpRegistrationBuilder::Label(std::string label) { + registration_->label = label; + return *this; +} + +std::unique_ptr XlaOpRegistrationBuilder::Build( + XlaOpRegistry::Factory factory) { + registration_->factory = factory; + return std::move(registration_); +} + +XlaOpRegistrar::XlaOpRegistrar( + std::unique_ptr registration) { + XlaOpRegistry& registry = XlaOpRegistry::Instance(); + mutex_lock lock(registry.mutex_); + auto& existing_ops = registry.ops_[registration->name]; + for (auto& existing : existing_ops) { + if (!XlaOpRegistry::IsCompatible(*existing, *registration)) { + LOG(FATAL) + << "XLA op registration " << registration->name + << " is incompatible with existing registration of the same name."; + } + } + existing_ops.emplace_back(std::move(registration)); +} + +XlaBackendRegistrar::XlaBackendRegistrar( + absl::string_view name, absl::Span types, + XlaOpRegistry::BackendOpFilter op_filter) { + XlaOpRegistry& registry = XlaOpRegistry::Instance(); + registry.RegisterBackend(std::string(name), types, op_filter); + + AddSymbolicExecutionDevice(name); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry.h new file mode 100644 index 0000000000000000000000000000000000000000..b0f280560da461811a5685850ccd98a3b457b0c1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry.h @@ -0,0 +1,479 @@ +/* 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_XLA_OP_REGISTRY_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_OP_REGISTRY_H_ + +#include +#include +#include +#include +#include + +#include "absl/status/status.h" +#include "absl/status/statusor.h" +#include "absl/strings/string_view.h" +#include "absl/types/span.h" +#include "tensorflow/core/common_runtime/device_factory.h" +#include "tensorflow/core/common_runtime/local_device.h" +#include "tensorflow/core/framework/device_base.h" +#include "tensorflow/core/framework/kernel_def.pb.h" +#include "tensorflow/core/framework/node_def.pb.h" +#include "tensorflow/core/framework/op_def.pb.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/tensor.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/mem.h" +#include "tensorflow/core/platform/mutex.h" +#include "tensorflow/core/platform/thread_annotations.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/public/session_options.h" +#include "tsl/platform/errors.h" + +namespace tensorflow { + +// Names of the XLA compilation devices. These are not user-visible, and are +// used internally by the Tensorflow/XLA bridge to perform symbolic execution of +// a Tensorflow graph. + +extern const char* const DEVICE_CPU_XLA_JIT; // "CPU_XLA_JIT" +extern const char* const DEVICE_GPU_XLA_JIT; // "GPU_XLA_JIT" + +extern const char* const DEVICE_XLA_CPU; +extern const char* const DEVICE_XLA_GPU; + +// Do not include DT_FLOAT8_* as float or numeric types since they are only +// supported in a very limited set of ops. +constexpr std::array kFloatTypes = { + {DT_HALF, DT_FLOAT, DT_DOUBLE, DT_BFLOAT16}}; +constexpr std::array kFloatAndComplexTypes = { + {DT_HALF, DT_FLOAT, DT_DOUBLE, DT_BFLOAT16, DT_COMPLEX64, DT_COMPLEX128}}; +constexpr std::array kNumericTypes = { + {DT_UINT8, DT_UINT16, DT_UINT32, DT_UINT64, DT_INT8, DT_INT16, DT_INT32, + DT_INT64, DT_HALF, DT_FLOAT, DT_DOUBLE, DT_COMPLEX64, DT_COMPLEX128, + DT_BFLOAT16}}; + +constexpr std::array kCpuAllTypes = {{DT_UINT8, + DT_QUINT8, + DT_UINT16, + DT_UINT32, + DT_UINT64, + DT_INT8, + DT_QINT8, + DT_INT16, + DT_INT32, + DT_QINT32, + DT_INT64, + DT_HALF, + DT_FLOAT, + DT_DOUBLE, + DT_COMPLEX64, + DT_COMPLEX128, + DT_BOOL, + DT_BFLOAT16, + DT_FLOAT8_E5M2, + DT_FLOAT8_E4M3FN, + DT_FLOAT8_E4M3FNUZ, + DT_FLOAT8_E4M3B11FNUZ, + DT_FLOAT8_E5M2FNUZ, + DT_INT4, + DT_UINT4}}; + +constexpr std::array kGpuAllTypes = {{DT_UINT8, + DT_QUINT8, + DT_UINT16, + DT_UINT32, + DT_UINT64, + DT_INT8, + DT_QINT8, + DT_INT16, + DT_INT32, + DT_QINT32, + DT_INT64, + DT_HALF, + DT_FLOAT, + DT_DOUBLE, + DT_COMPLEX64, + DT_COMPLEX128, + DT_BOOL, + DT_BFLOAT16, + DT_FLOAT8_E5M2, + DT_FLOAT8_E4M3FN, + DT_FLOAT8_E4M3FNUZ, + DT_FLOAT8_E4M3B11FNUZ, + DT_FLOAT8_E5M2FNUZ, + DT_INT4, + DT_UINT4}}; + +// Class that manages registrations of operators and devices for the XLA JIT. +// Not thread-safe. +class XlaOpRegistry { + public: + typedef OpKernel* (*Factory)(OpKernelConstruction*); + + enum class AutoclusteringPolicy { + // Enable autoclustering if the user requests it, e.g., via + // experimental_jit_scope. Does not autocluster if the JIT is enabled + // globally (e.g., via the OptimizerOptions in the TF session + // configuration.) + kIfExplicitlyRequested, + // Enable autoclustering if explicitly requested, or if the JIT is enabled + // globally in the session options, or via TF_XLA_FLAGS=--tf_xla_auto_jit=N. + kIfEnabledGlobally, + // Always try to autocluster ops placed on this device. + kAlways, + }; + + // Describes how to compile operators assigned to a device. + struct DeviceRegistration { + // The name of the an XLA compilation device to use to compile code. + std::string compilation_device_name; + + // When should we autocluster operators assigned to this device? + AutoclusteringPolicy autoclustering_policy; + + // If we should ignore the resource variable memory model when clustering + // resource variable reads and writes placed on this device. + bool cluster_resource_variable_ops_unsafely = false; + + // If we should auto-cluster Stack operations placed on this device. + bool cluster_stack_ops = false; + + // If we should auto-cluster TensorArray operations placed on this device. + bool cluster_tensor_array_ops = false; + + // If we should auto-cluster stateful RNG operations placed on this device. + // Stateful RNG semantics are not properly supported by XLA so it is not + // necessarily correct to auto-cluster stateful RNG ops in general. + bool cluster_stateful_rng_ops = false; + + // If we should auto-cluster ControlTrigger operations placed on this + // device. ControlTrigger operations are not necessarily safe to cluster + // since they affect deadness (a dead ControlTrigger produces a live + // output). + bool cluster_control_trigger = false; + + // If we should cluster Assert and CheckNumerics by eliding them (XLA does + // not natively support Assert or CheckNumerics). + bool elide_assert_and_checknumerics = false; + + // If we should cluster operations returning DT_VARIANT. + bool cluster_variant_ops = false; + + // Whether ops known to be slow should be auto-clustered. + bool cluster_slow_ops = false; + + // Whether ops known to have numerical accuracy issues should be + // auto-clustered. + bool cluster_inaccurate_ops = false; + }; + + // Registers an XLA backend. `compilation_device_name` is the name of the + // device used for symbolic execution during compilation. `supported_types` + // is the list of non-resource types supported by the device. Each operators + // will be registered for the intersection of the operator's supported types + // and the device's supported types. `backend_op_filter` is a function used + // to exclude or modify operator registrations on the device; it may be + // nullptr, in which case all ops are included. + // `backend_op_filter` should return true if the op should be registered on + // the device; it may optionally modify the KernelDef. + typedef bool (*BackendOpFilter)(KernelDef* kdef); + static void RegisterBackend(const std::string& compilation_device_name, + absl::Span supported_types, + BackendOpFilter op_filter); + + // Returns the names of the registered backends. + static std::vector BackendNames(); + + // Returns true iff a backend with the given name is registered. + static bool IsBackendRegistered(const std::string& name); + + // Registers `device_name` for XLA compilation, using information from + // `registration`. + // Does nothing if a registration for `device_name` already exists. + static void RegisterCompilationDevice(const std::string& device_name, + const DeviceRegistration& registration); + + // Returns whether the device name is for the JIT device used exclusively for + // TF2XLA conversion. + static bool IsCompilationDevice(const std::string& device_name); + + // Returns the JIT device name associated with 'device_name', setting + // 'jit_device_name', 'requires_jit', and 'enabled_jit_by_default', if they + // are not null. Returns false and leaves the outputs unchanged if no matching + // JIT device is registered. + // '*enable_jit_by_default' is set to true if we should try to JIT using this + // device when the JIT is enabled via the Session OptimizerOptions. + static bool GetCompilationDevice(const std::string& device_name, + const DeviceRegistration** registration); + + // Registers all JIT kernels on JIT devices, if not already registered. + // Does nothing otherwise. + static void RegisterCompilationKernels(); + + // Returns KernelDefs for compilation ops registered on + // 'compilation_device_name'. Does not include kernels registered as + // CompilationOnly, iff include_compilation_only_kernels=false. + static std::vector DeviceKernels( + const std::string& compilation_device_name, + bool include_compilation_only_kernels); + + // Returns all operations for which there are XLA kernels on any device. + static std::vector GetAllRegisteredOps(); + + // Returns (via `result`) the indices of inputs to `node_def` that must be + // compile-time constants. Returns an empty vector if the op is not + // registered. + // + // `result` is sorted. + static absl::Status CompileTimeConstantInputs(const NodeDef& node_def, + const OpDef& op_def, + std::vector* result) { + return CompileTimeConstantInputs(node_def, /*op_kernel=*/nullptr, &op_def, + result); + } + + static absl::StatusOr> CompileTimeConstantInputs( + const NodeDef& node_def, const OpDef& op_def) { + std::vector out; + TF_RETURN_IF_ERROR(CompileTimeConstantInputs(node_def, op_def, &out)); + return out; + } + + // Returns (via `result`) the indices of inputs to `op_kernel` that must be + // compile-time constants. + // + // `result` is sorted. + static absl::Status CompileTimeConstantInputs(const OpKernel& op_kernel, + std::vector* result) { + return CompileTimeConstantInputs(op_kernel.def(), /*op_kernel=*/&op_kernel, + /*op_def=*/nullptr, result); + } + + // Return names of arguments for a given op which are supposed to be + // constants. + static const std::unordered_set* + CompileTimeConstantInputArgNames(const std::string& op); + + // Returns true if `op` is a "metadata" op, one that only looks at the shapes + // of its operands and not their values. + static bool IsMetadataOp(const std::string& op); + + private: + friend class XlaBackendRegistrar; + friend class XlaOpRegistrar; + friend class XlaOpRegistrationBuilder; + + static XlaOpRegistry& Instance(); + + XlaOpRegistry(); + ~XlaOpRegistry(); + + mutex mutex_; + + // Describes an XLA backend. + struct Backend { + // Which types are supported by this device? + std::set supported_types; + + // The per-backend operator filter function. See the comment on + // RegisterBackend() for details. + BackendOpFilter op_filter; + + // KernelDefs built by RegisterCompilationKernels() for each op supported + // by the device. + std::vector> kernel_defs; + }; + + // Map from compilation device names to a description of the backend. + std::unordered_map backends_ TF_GUARDED_BY(mutex_); + + // Map from Tensorflow device names to the corresponding JIT device metadata. + std::unordered_map compilation_devices_ + TF_GUARDED_BY(mutex_); + + // A description of a Tensorflow operator that can be compiled to XLA. + struct OpRegistration { + std::string name; + + // Should this operator be registered only on compilation devices, without a + // dummy kernel registered on the corresponding XLA device? + bool compilation_only = false; + + // Should we allow resource types for type attributes? Used by _Arg to + // allow DT_RESOURCE. + bool allow_resource_types = false; + + // Should we allow variant types for type attributes? Used by While to + // allow TensorList which is of type DT_VARIANT. + bool allow_variant_types = false; + + // Should we allow string type for type attributes? Used by PartitionedCall + // to allow DT_STRING. + bool allow_string_type = false; + + // Mapping from attribute name to a list of supported types. + std::unordered_map> type_constraints; + + // An optional allowlist of devices. If there is no allowlist, all devices + // are permitted. + bool has_device_allowlist = false; + std::unordered_set device_allowlist; + + // Names of arguments that must be compile-time constants. + std::unordered_set compile_time_constant_inputs; + + // True if this is a "metadata" op, one that only looks at the shapes of its + // operands and not their values. + bool is_metadata_op = false; + + std::string label; + + // Factory used to build OpKernels that perform symbolic execution. + Factory factory; + }; + + // Returns true if registrations x and y can both be added to the registry. + // This is always the case if they refer to different ops. If they refer to + // the same op name, they must: have the same values for compilation_only, + // allow_resource_types and allow_variant_types; use a device_allowlist; and + // their allowlists must not intersect. + static bool IsCompatible(const OpRegistration& x, const OpRegistration& y); + + static absl::Status CompileTimeConstantInputs(const NodeDef& node_def, + const OpKernel* op_kernel, + const OpDef* op_def, + std::vector* result); + + // Map from operator name to OpRegistrations, populated by REGISTER_XLA_OP. + // Registrations present under the same key must satisfy IsCompatible above, + // and this is checked during registration. + std::unordered_map>> + ops_ TF_GUARDED_BY(mutex_); + + // Have we already registered the JIT kernels on the JIT devices? + bool jit_kernels_registered_ = false; + + // Holds ownership of OpKernelRegistrars that represent the Tensorflow kernel + // registrations created by RegisterCompilationKernels() and + // RegisterDeviceKernels(). + std::vector> + kernel_registrars_ TF_GUARDED_BY(mutex_); +}; + +// REGISTER_XLA_OP() registers an XLA OpKernel by name, for example: +// REGISTER_XLA_OP(Name("Add"), AddOp); +// where 'AddOp' is the name of a JIT OpKernel class that implements "Add". +// +// We don't use a variadic macro here because we don't expect JIT operators to +// be templated. + +#define REGISTER_XLA_OP(NAME, OP) \ + REGISTER_XLA_OP_UNIQ_HELPER(__COUNTER__, NAME, OP) + +#define REGISTER_XLA_CONV_OP(BUILDER, OP) \ + REGISTER_XLA_OP(BUILDER.TypeConstraint("T", GetXlaConvTypesForNonGpu()), OP) \ + REGISTER_XLA_OP(BUILDER.TypeConstraint("T", GetXlaConvTypesForGpu()) \ + .Device(DEVICE_GPU_XLA_JIT), \ + OP) + +class XlaOpRegistrationBuilder { + public: + // Starts an operator registration chain. + static XlaOpRegistrationBuilder Name(absl::string_view name); + + // Specifies a allowlist of devices on which the operator may run. + XlaOpRegistrationBuilder& Device(absl::string_view devices); + XlaOpRegistrationBuilder& Device(absl::Span devices); + + // Specifies a type constraint for a type variable attribute. Each constraint + // specifies the set of types that the type variable may assume. + XlaOpRegistrationBuilder& TypeConstraint(absl::string_view attr_name, + DataType allowed); + + XlaOpRegistrationBuilder& TypeConstraint(absl::string_view attr_name, + absl::Span allowed); + + // Specifies that a dummy copy of this operator should not be registered on + // XLA_* devices, but may be used during compilation. + XlaOpRegistrationBuilder& CompilationOnly(); + + // Allow DT_RESOURCE types for type parameters. + XlaOpRegistrationBuilder& AllowResourceTypes(); + + // Allow DT_VARIANT types for type parameters. + XlaOpRegistrationBuilder& AllowVariantTypes(); + + // Allow DT_STRING type for type parameters. + XlaOpRegistrationBuilder& AllowStringType(); + + // Mark 'input_name' as an argument whose value must be known at compile-time. + XlaOpRegistrationBuilder& CompileTimeConstantInput( + absl::string_view input_name); + + // Mark this op as a "metadata" op, one that only looks at the shapes of its + // operands and not their values. + XlaOpRegistrationBuilder& IsMetadataOp(); + + // Specifies a particular value for the "_kernel" attr. + XlaOpRegistrationBuilder& Label(std::string label); + + std::unique_ptr Build( + XlaOpRegistry::Factory factory); + + private: + XlaOpRegistrationBuilder(absl::string_view name); + + std::unique_ptr registration_; +}; + +// REGISTER_XLA_BACKEND() registers an XLA backend. Example usage: +// REGISTER_XLA_BACKEND(DEVICE_GPU_XLA_JIT, kGpuAllTypes, GpuOpFilter); +#define REGISTER_XLA_BACKEND(NAME, ...) \ + REGISTER_XLA_BACKEND_UNIQ_HELPER(__COUNTER__, NAME, __VA_ARGS__) + +// Implementation details. + +class XlaOpRegistrar { + public: + XlaOpRegistrar(std::unique_ptr registration); +}; + +#define REGISTER_XLA_OP_UNIQ_HELPER(COUNTER, BUILDER, OP) \ + REGISTER_XLA_OP_UNIQ(COUNTER, BUILDER, OP) + +#define REGISTER_XLA_OP_UNIQ(CTR, BUILDER, OP) \ + static ::tensorflow::XlaOpRegistrar xla_op_registrar__body__##CTR##__object( \ + ::tensorflow::XlaOpRegistrationBuilder::BUILDER.Build( \ + [](::tensorflow::OpKernelConstruction* context) \ + -> ::tensorflow::OpKernel* { return new OP(context); })); + +class XlaBackendRegistrar { + public: + XlaBackendRegistrar(absl::string_view name, absl::Span types, + XlaOpRegistry::BackendOpFilter op_filter = nullptr); +}; + +#define REGISTER_XLA_BACKEND_UNIQ_HELPER(COUNTER, NAME, ...) \ + REGISTER_XLA_BACKEND_UNIQ(COUNTER, NAME, __VA_ARGS__) + +#define REGISTER_XLA_BACKEND_UNIQ(CTR, NAME, ...) \ + static ::tensorflow::XlaBackendRegistrar \ + xla_backend_registrar__body__##CTR##__object(NAME, __VA_ARGS__); + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_OP_REGISTRY_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry_test.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..ee8345296c1d56839b813a46cf6b88fa74c51ee4 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_op_registry_test.cc @@ -0,0 +1,143 @@ +/* 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/tf2xla/xla_op_registry.h" + +#include "absl/log/log.h" +#include "tensorflow/compiler/tf2xla/xla_op_kernel.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_kernel.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/test.h" + +namespace tensorflow { +namespace { + +// This test is to verify the correctness of XLA op registration with specific +// backend overrides. + +// A dummy backend-specific OpKernel for CPU. +class DummyCPUOp : public XlaOpKernel { + public: + explicit DummyCPUOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + ctx->SetOutput(0, ctx->Input(0)); + } +}; + +// A dummy generic OpKernel for all backends. +class DummyGenericOp : public XlaOpKernel { + public: + explicit DummyGenericOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + ctx->SetOutput(0, ctx->Input(0)); + } +}; + +REGISTER_OP("DummyDuplicateOp") + .Attr("T: {float, int32}") + .Input("input: int32") + .Output("output: int32") + .Doc(R"doc( +A dummy Op. + +input: dummy input. +output: dummy output. +)doc"); + +// Register the DummyCPUOp kernel for CPU with type INT32. +REGISTER_XLA_OP(Name("DummyDuplicateOp") + .Device(DEVICE_CPU_XLA_JIT) + .TypeConstraint("T", DT_INT32), + DummyCPUOp); +// Register the DummyGeneric kernel for all registered device (except CPU since +// it is already registered), with type FLOAT. +REGISTER_XLA_OP(Name("DummyDuplicateOp").TypeConstraint("T", DT_FLOAT), + DummyGenericOp); + +// Test the correctness of registered kernels. The kernel registered for CPU +// should have type INT32 while all other kernels should have type FLOAT. +TEST(XlaOpRegistryTest, XlaOpRegistrationWithOverride) { + XlaOpRegistry::RegisterCompilationKernels(); + auto registered_kernels = GetAllRegisteredKernels().kernel(); + for (const auto& kernels : registered_kernels) { + if (kernels.op() == "DummyDuplicateOp") { + EXPECT_EQ(kernels.constraint_size(), 1); + EXPECT_EQ(kernels.constraint(0).name(), "T"); + if (kernels.device_type() == "XLA_CPU_JIT") { + EXPECT_EQ(kernels.constraint(0).allowed_values().list().type(0), + DT_INT32); + } else { + EXPECT_EQ(kernels.constraint(0).allowed_values().list().type(0), + DT_FLOAT); + } + } + } +} + +TEST(XlaOpReigstryTest, XlaOpRegistrationDeviceKernels) { + XlaOpRegistry::RegisterCompilationKernels(); + auto registered_devices = XlaOpRegistry::BackendNames(); + for (const auto& resgistered_device : registered_devices) { + auto kernels = XlaOpRegistry::DeviceKernels(resgistered_device, true); + for (const auto& kernel : kernels) { + if (kernel->op() == "DummyDuplicateOp") { + if (resgistered_device == DEVICE_CPU_XLA_JIT) { + EXPECT_EQ(kernel->constraint(0).allowed_values().list().type(0), + DT_INT32); + } else { + EXPECT_EQ(kernel->constraint(0).allowed_values().list().type(0), + DT_FLOAT); + } + } + } + } +} + +// A dummy generic OpKernel for all backends. +class DummyInfeasibleTypeConstraintOp : public XlaOpKernel { + public: + explicit DummyInfeasibleTypeConstraintOp(OpKernelConstruction* ctx) + : XlaOpKernel(ctx) {} + void Compile(XlaOpKernelContext* ctx) override { + LOG(FATAL) << "unreachable"; + } +}; + +REGISTER_OP("DummyInfeasibleTypeConstraintOp") + .Attr("T: {float, string}") + .Input("input: T") + .Output("output: T") + .Doc(R"doc( +A dummy Op. + +input: dummy input. +output: dummy output. +)doc"); +REGISTER_XLA_OP( + Name("DummyInfeasibleTypeConstraintOp").TypeConstraint("T", DT_STRING), + DummyInfeasibleTypeConstraintOp); + +TEST(XlaOpRegistryTest, OpWithInfeasibleTypeConstraintIsNotRegistered) { + XlaOpRegistry::RegisterCompilationKernels(); + auto registered_kernels = GetAllRegisteredKernels().kernel(); + for (const auto& kernels : registered_kernels) { + // The operator should not be registered. + EXPECT_NE(kernels.op(), "DummyInfeasibleTypeConstraintOp"); + } +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_resource.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_resource.cc new file mode 100644 index 0000000000000000000000000000000000000000..4d813dd5eb27c6de391c701e7a48911f0bbf020a --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_resource.cc @@ -0,0 +1,253 @@ +/* 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/xla_resource.h" + +#include +#include +#include +#include +#include +#include +#include + +#include "absl/log/check.h" +#include "absl/log/log.h" +#include "absl/status/status.h" +#include "absl/strings/str_cat.h" +#include "absl/strings/string_view.h" +#include "tensorflow/compiler/tf2xla/xla_helpers.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/status_macros.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/platform/errors.h" +#include "tensorflow/core/platform/status.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/managed_stack_trace.h" +#include "tsl/platform/errors.h" + +namespace tensorflow { + +/*static*/ absl::string_view XlaResource::KindToString(XlaResource::Kind kind) { + switch (kind) { + case XlaResource::kInvalid: + return "invalid"; + case XlaResource::kVariable: + return "variable"; + case XlaResource::kStack: + return "stack"; + case XlaResource::kTensorArray: + return "tensorarray"; + } +} + +/*static*/ std::unique_ptr XlaResource::CreateStack( + std::string name, DataType type, int64_t max_size) { + return std::make_unique( + XlaResource::kStack, /*arg_num=*/-1, std::move(name), type, TensorShape(), + /*initial_value=*/xla::XlaOp(), + /*max_array_size=*/max_size, + /*tensor_array_gradients=*/std::set{}, + /*tensor_array_multiple_writes_aggregate=*/false); +} + +/*static*/ std::unique_ptr XlaResource::CreateTensorArray( + std::string name, DataType type, TensorShape shape, + xla::XlaOp initial_value, int64_t max_array_size) { + return std::make_unique( + XlaResource::kTensorArray, /*arg_num=*/-1, std::move(name), type, shape, + initial_value, max_array_size, + /*tensor_array_gradients=*/std::set{}, + /*tensor_array_multiple_writes_aggregate=*/false); +} + +XlaResource::XlaResource( + Kind kind, int arg_num, std::string name, DataType type, TensorShape shape, + xla::XlaOp initial_value, int64_t max_array_size, + const std::set& tensor_array_gradients, + bool tensor_array_multiple_writes_aggregate, + const std::optional& definition_stack_trace) + : kind_(kind), + arg_num_(arg_num), + name_(std::move(name)), + type_(type), + shape_(std::move(shape)), + value_(initial_value), + initial_value_(initial_value), + max_array_size_(max_array_size), + tensor_array_multiple_writes_aggregate_( + tensor_array_multiple_writes_aggregate), + definition_stack_trace_(definition_stack_trace) { + CHECK(kind_ != kInvalid); + + for (const std::string& gradient : tensor_array_gradients) { + tensor_array_gradients_[gradient].reset(new XlaResource( + /*kind=*/kTensorArray, /*arg_num=*/-1, + /*name=*/absl::StrCat("TensorArrayGrad: ", name_), type_, shape_, + xla::XlaOp(), max_array_size_, /*tensor_array_gradients=*/{}, + /*tensor_array_multiple_writes_aggregate=*/true)); + } +} + +absl::Status XlaResource::SetTypeAndShape(DataType type, + const TensorShape& shape) { + if (type == DT_INVALID) { + return absl::InvalidArgumentError(absl::StrCat( + "Attempted to set type of resource '", name_, "'' to an invalid type", + DefinitionLocationMsg(definition_stack_trace_))); + } + if (initialized() && type_ != type) { + return absl::InvalidArgumentError( + absl::StrCat("Trying to assign variable with wrong dtype. Expected ", + DataTypeString(type_), " got ", DataTypeString(type), + DefinitionLocationMsg(definition_stack_trace_))); + } + if (initialized() && shape_ != shape) { + return absl::InvalidArgumentError(absl::StrCat( + "Shape of resource ", name_, + " cannot be changed after initialization: " + "old shape was ", + shape_.DebugString(), ", new shape is ", shape.DebugString(), + DefinitionLocationMsg(definition_stack_trace_))); + } + type_ = type; + shape_ = shape; + return absl::OkStatus(); +} + +absl::Status XlaResource::SetValue(const xla::XlaOp value) { + if (type_ == DT_INVALID) { + return absl::InvalidArgumentError( + absl::StrCat("Resource '", name_, + "' must be initialized with a valid type before use.")); + } + value_ = value; + is_overwritten_ = true; + return absl::OkStatus(); +} + +absl::Status XlaResource::SetZeroValue(xla::XlaBuilder* builder) { + is_overwritten_ = true; + if (type_ == DT_INVALID) { + return absl::InvalidArgumentError( + absl::StrCat("Resource '", name_, + "' must be initialized with a valid type before use.")); + } + switch (kind_) { + case kVariable: { + value_ = + xla::Broadcast(XlaHelpers::Zero(builder, type_), shape_.dim_sizes()); + break; + } + case kTensorArray: { + TensorShape ta_shape; + TF_RETURN_IF_ERROR(ta_shape.AddDimWithStatus(max_array_size_)); + ta_shape.AppendShape(shape_); + value_ = xla::Broadcast(XlaHelpers::Zero(builder, type_), + ta_shape.dim_sizes()); + break; + } + case kStack: { + TensorShape ta_shape; + TF_RETURN_IF_ERROR(ta_shape.AddDimWithStatus(max_array_size_)); + ta_shape.AppendShape(shape_); + value_ = + xla::Tuple(builder, {xla::Broadcast(XlaHelpers::Zero(builder, type_), + ta_shape.dim_sizes()), + xla::ConstantR0(builder, 0)}); + break; + } + + case kInvalid: + default: + LOG(FATAL) << "Invalid resource type"; + } + return absl::OkStatus(); +} + +absl::Status XlaResource::GetOrCreateTensorArrayGradient( + const std::string& source, xla::XlaBuilder* builder, + XlaResource** gradient_out) { + VLOG(2) << "Gradient lookup for resource: " << name_ + << " gradient: " << source; + TF_RET_CHECK(kind_ == kTensorArray); + std::unique_ptr& gradient = tensor_array_gradients_[source]; + if (!gradient) { + TensorShape ta_shape; + TF_RETURN_IF_ERROR(ta_shape.AddDimWithStatus(max_array_size_)); + ta_shape.AppendShape(shape_); + xla::XlaOp gradient_value = + xla::Broadcast(XlaHelpers::Zero(builder, type_), ta_shape.dim_sizes()); + gradient.reset( + new XlaResource(/*kind=*/kTensorArray, /*arg_num=*/-1, + /*name=*/absl::StrCat("TensorArrayGrad: ", name_), + type_, shape_, gradient_value, max_array_size_, + /*tensor_array_gradients=*/{}, + /*tensor_array_multiple_writes_aggregate=*/true)); + } + *gradient_out = gradient.get(); + return absl::OkStatus(); +} + +absl::Status XlaResource::Pack(xla::XlaOp* pack, + xla::XlaBuilder* builder) const { + if (tensor_array_gradients_.empty()) { + *pack = value_; + } else { + TF_RET_CHECK(kind_ == kTensorArray); + std::vector elems; + elems.push_back(value_); + for (const auto& gradient : tensor_array_gradients_) { + elems.push_back(gradient.second->value_); + } + *pack = xla::Tuple(builder, elems); + } + return absl::OkStatus(); +} + +absl::Status XlaResource::SetFromPack( + const std::set& gradient_sources, const xla::XlaOp pack, + xla::XlaBuilder* builder) { + if (gradient_sources.empty()) { + if (!initialized()) { + initial_value_ = pack; + } + value_ = pack; + } else { + TF_RET_CHECK(kind_ == kTensorArray); + int pos = 0; + auto v = xla::GetTupleElement(pack, pos++); + if (!initialized()) { + initial_value_ = v; + } + value_ = v; + + for (const auto& source : gradient_sources) { + XlaResource* gradient; + TF_RETURN_IF_ERROR( + GetOrCreateTensorArrayGradient(source, builder, &gradient)); + auto v = xla::GetTupleElement(pack, pos++); + if (!gradient->initialized()) { + gradient->initial_value_ = v; + } + gradient->value_ = v; + } + } + return absl::OkStatus(); +} + +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_resource.h b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_resource.h new file mode 100644 index 0000000000000000000000000000000000000000..b3707788be5fdf381c271f89519b6be5a4ccc9d1 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_resource.h @@ -0,0 +1,199 @@ +/* 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_XLA_RESOURCE_H_ +#define TENSORFLOW_COMPILER_TF2XLA_XLA_RESOURCE_H_ + +#include + +#include "absl/status/status.h" +#include "absl/strings/string_view.h" +#include "absl/types/optional.h" +#include "xla/hlo/builder/xla_builder.h" +#include "xla/shape.h" +#include "xla/xla_data.pb.h" +#include "tensorflow/core/framework/tensor_shape.h" +#include "tensorflow/core/framework/types.pb.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/platform/types.h" +#include "tensorflow/core/util/managed_stack_trace.h" + +namespace tensorflow { + +// Represents a resource, such as a Variable or TensorArray. +class XlaResource { + public: + enum Kind { + kInvalid, + kVariable, + kTensorArray, + kStack, + }; + static absl::string_view KindToString(Kind kind); + + // Creates a new Stack resource. + static std::unique_ptr CreateStack(std::string name, + DataType type, + int64_t max_size); + + // Creates a new TensorArray resource. + static std::unique_ptr CreateTensorArray( + std::string name, DataType type, TensorShape shape, + xla::XlaOp initial_value, int64_t max_array_size); + + XlaResource(Kind kind, int arg_num, std::string name, DataType type, + TensorShape shape, xla::XlaOp initial_value, + int64_t max_array_size, + const std::set& tensor_array_gradients, + bool tensor_array_multiple_writes_aggregate, + const std::optional& definition_stack_trace = + std::nullopt); + + XlaResource(const XlaResource&) = delete; + XlaResource(XlaResource&&) = delete; + XlaResource& operator=(const XlaResource&) = delete; + XlaResource& operator=(XlaResource&&) = delete; + + Kind kind() const { return kind_; } + + // If this resource is visible externally to the computation, what was its + // argument number? + // < 0 means "not visible externally". + int arg_num() const { return arg_num_; } + + // A descriptive name for the resource, used in error messages. + const std::string& name() const { return name_; } + + // Current type and value of the resource. Uninitialized resources are + // represented by a default (zero) handle and type DT_INVALID. + // While the type of a resource is notionally fixed during execution, when + // a resource is first initialized we do not yet know its type, so we keep + // track of its type dynamically. + DataType type() const { return type_; } + + // Shape of the resource. For an uninitialized resource, this is ignored. + // For a Variable, this is the shape of the value. For a TensorArray or Stack + // this is the shape of each entry in the TensorArray/Stack. + const TensorShape& shape() const { return shape_; } + + const xla::XlaOp& value() const { return value_; } + + // Value of the resource at computation entry. Used to detect which + // variables have new values that need to be written back. + const xla::XlaOp& initial_value() const { return initial_value_; } + + // An xla shape that indicates how this resource variable is represented on + // device. + const std::optional& representation_shape() const { + return representation_shape_; + } + + // A variable is initialized if it has a value. + bool initialized() const { return value_.valid(); } + + // Sets the type and shape of the resource. The type and shape of a resource + // must not change once the variable has been initialized. + absl::Status SetTypeAndShape(DataType type, const TensorShape& shape); + + // Sets the current value of the resource. Returns an error if the type is not + // set to a valid value. + absl::Status SetValue(xla::XlaOp value); + + // Sets the current value of the resource to an all-zero value. + absl::Status SetZeroValue(xla::XlaBuilder* builder); + + // Sets the representational shape of the resource on device. + void SetRepresentationShape(const xla::Shape& shape) { + representation_shape_ = std::make_optional(shape); + } + + // Looks up the gradient for `source`, or creates it if it does not already + // exist. The call target must be an initialized TensorArray resource. A + // TensorArray can have multiple named gradients; see the operator + // documentation for TensorArrayGradV3 for details. + absl::Status GetOrCreateTensorArrayGradient(const std::string& source, + xla::XlaBuilder* builder, + XlaResource** gradient_out); + + // Packs a resource into a single XLA value `pack`, suitable for use as + // an XlaCompiler::Argument. For non-TensorArrays or TensorArrays without + // gradients, sets `*pack` to `value`. + // For TensorArrays with gradients, packs the value and its gradient values in + // a tuple; the gradients values are packed in order by source name. + absl::Status Pack(xla::XlaOp* pack, xla::XlaBuilder* builder) const; + + // Updates the resource with values from `pack`. If `gradient_sources` is + // non-empty, treats `pack` as a tuple that represents a TensorArray and + // its gradients, and unpacks and updates the gradient resources. + // If `reset_initial_values` is true, sets the initial_values as well as the + // values. + // Opposite of Pack(). + absl::Status SetFromPack(const std::set& gradient_sources, + xla::XlaOp pack, xla::XlaBuilder* builder); + + bool IsOverwritten() { return is_overwritten_; } + + // TensorArray and Stack specific fields + // TODO(phawkins): refactor this code to use subclasses, rather than putting + // kind-specific fields in XlaResource. + + // 'max_array_size' stores the expected size of the TensorArray or Stack. + // We need to store this since sometimes TensorArrays must be initialized + // lazily since we do not know the element shape at construction time. + // Used by both TensorArrays and Stacks. + int64_t max_array_size() const { return max_array_size_; } + void set_max_array_size(int64_t size) { max_array_size_ = size; } + + bool tensor_array_multiple_writes_aggregate() const { + return tensor_array_multiple_writes_aggregate_; + } + + // 'tensor_array_gradient' is a map from TensorArrayGradV3 'source' attributes + // to an XlaResource containing the gradient TensorArrays. We store a pointer + // here since there should only be one gradient TensorArray per 'source' + // string, irrespective of the number of calls to TensorArrayGrad. The map + // is ordered since values are packed into tuples by Pack() sorted by name + // order. + const std::map>& + tensor_array_gradients() const { + return tensor_array_gradients_; + } + + private: + const Kind kind_; + const int arg_num_; + const std::string name_; + + DataType type_; + TensorShape shape_; + xla::XlaOp value_; + xla::XlaOp initial_value_; + + // An xla shape that indicates how this resource variable is represented on + // device. + std::optional representation_shape_; + + int64_t max_array_size_ = -1; + bool tensor_array_multiple_writes_aggregate_ = false; + + std::map> tensor_array_gradients_; + bool is_overwritten_ = false; + + std::optional definition_stack_trace_; +}; + +} // namespace tensorflow + +#endif // TENSORFLOW_COMPILER_TF2XLA_XLA_RESOURCE_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_tpu_backend.cc b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_tpu_backend.cc new file mode 100644 index 0000000000000000000000000000000000000000..03b6dcc0f30486809f754a11ad33aaafe7078954 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/compiler/tf2xla/xla_tpu_backend.cc @@ -0,0 +1,31 @@ +/* Copyright 2020 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/xla_op_registry.h" +#include "tensorflow/core/tpu/tpu_defs.h" +#include "tensorflow/core/tpu/tpu_node_device_util.h" + +namespace tensorflow { +namespace { + +bool RegisterTpuXlaBackend() { + REGISTER_XLA_BACKEND(DEVICE_TPU_XLA_JIT, kTpuAllTypes, TpuOpFilter); + return true; +} + +static bool tpu_xla_backend_registered = RegisterTpuXlaBackend(); + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/BUILD b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/BUILD new file mode 100644 index 0000000000000000000000000000000000000000..8b01e659950d4bc4c6fb1e0a531cbdf773dde9c2 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/BUILD @@ -0,0 +1,58 @@ +load("//tensorflow:tensorflow.bzl", "if_not_mobile") +load("//tensorflow/core/platform:rules_cc.bzl", "cc_library") + +package( + # copybara:uncomment default_applicable_licenses = ["//tensorflow:license"], + default_visibility = ["//tensorflow:internal"], + licenses = ["notice"], +) + +filegroup( + name = "activity_watcher_headers", + srcs = [ + "activity.h", + "activity_utils.h", + ], + visibility = ["//visibility:public"], +) + +cc_library( + name = "activity_watcher", + hdrs = ["activity.h"], + defines = if_not_mobile(["TF_ENABLE_ACTIVITY_WATCHER"]), + deps = [ + "//tensorflow/core:lib", + "@com_google_absl//absl/container:flat_hash_map", + "@xla//xla/tsl/platform:types", + ] + if_not_mobile([ + ":activity_watcher_impl", + ]), + alwayslink = True, +) + +cc_library( + name = "activity_watcher_impl", + srcs = [ + "activity.cc", + ], + hdrs = ["activity.h"], + deps = [ + "//tensorflow/core:lib", + "@com_google_absl//absl/base:core_headers", + "@com_google_absl//absl/container:flat_hash_map", + "@xla//xla/tsl/platform:types", + ], + alwayslink = True, +) + +cc_library( + name = "activity_watcher_utils", + srcs = ["activity_utils.cc"], + hdrs = ["activity_utils.h"], + deps = [ + ":activity_watcher", + "//tensorflow/core:framework", + "@com_google_absl//absl/strings", + "@xla//xla/tsl/platform:types", + ], +) diff --git a/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity.cc b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity.cc new file mode 100644 index 0000000000000000000000000000000000000000..7d8ee7236c812086b62bae5b85ecd3b2095ba2d8 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity.cc @@ -0,0 +1,39 @@ +/* Copyright 2021 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/activity_watcher/activity.h" + +#include +#include + +#include "absl/base/attributes.h" + +namespace tensorflow { +namespace activity_watcher { +ABSL_ATTRIBUTE_WEAK void MaybeEnableMultiWorkersWatching( + tsl::CoordinationServiceAgent* agent) {} + +namespace tfw_internal { + +ABSL_ATTRIBUTE_WEAK std::atomic g_watcher_level(kWatcherDisabled); +ABSL_ATTRIBUTE_WEAK ActivityId RecordActivityStart(std::unique_ptr) { + return kActivityNotRecorded; +} +ABSL_ATTRIBUTE_WEAK void RecordActivityEnd(ActivityId id) {} + +} // namespace tfw_internal + +} // namespace activity_watcher +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity.h b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity.h new file mode 100644 index 0000000000000000000000000000000000000000..124b118cdd7a9a6b3afc5ffc8c65fac19cf15a2e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity.h @@ -0,0 +1,187 @@ +/* Copyright 2021 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_ACTIVITY_WATCHER_ACTIVITY_H_ +#define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ + +#include +#include +#include +#include + +#include "absl/container/flat_hash_map.h" +#include "xla/tsl/platform/macros.h" +#include "xla/tsl/platform/types.h" + +namespace tsl { +class CoordinationServiceAgent; +} + +namespace tensorflow { + +namespace activity_watcher { + +using ActivityId = uint64_t; +constexpr ActivityId kActivityNotRecorded = 0; +constexpr int kWatcherDisabled = 0; + +enum ActivityCategory { + kCollective = 0, + kRemoteFunction = 1, + kMisc = 2, + kDatasetOp = 3, + kTpuOp = 4, + kRendezvous = 5, +}; + +static std::string ToString(ActivityCategory category) { + switch (category) { + case ActivityCategory::kCollective: + return "Collective"; + case ActivityCategory::kRemoteFunction: + return "Remote Function"; + case ActivityCategory::kMisc: + return "Miscellaneous"; + case ActivityCategory::kDatasetOp: + return "Dataset Op"; + case ActivityCategory::kTpuOp: + return "TPU Op"; + case ActivityCategory::kRendezvous: + return "Rendezvous"; + } + return "Unknown"; +} + +// An activity to be recorded. +struct Activity { + using Attributes = absl::flat_hash_map; + // A human readable title of the activity. + std::string title; + // The category of the activity. + ActivityCategory category = ActivityCategory::kMisc; + // Key/value pairs that are attached to the activity. + Attributes attributes; + Activity() = default; + Activity(std::string title, ActivityCategory category) + : title(std::move(title)), category(category) {} + Activity(std::string title, ActivityCategory category, Attributes attributes) + : title(std::move(title)), + category(category), + attributes(std::move(attributes)) {} +}; + +// Enable activity wathcer to send own workers activities to coordination +// service and also fetch all workers' activities. +void MaybeEnableMultiWorkersWatching(tsl::CoordinationServiceAgent* agent); + +namespace tfw_internal { + +#if defined(TF_ENABLE_ACTIVITY_WATCHER) + +// Records an activity start without checking whether the watcher is enabled. +ActivityId RecordActivityStart(std::unique_ptr activity); +// Records an activity end without checking whether the activity_id is valid. +void RecordActivityEnd(ActivityId activity_id); + +TF_EXPORT extern std::atomic g_watcher_level; + +// Returns whether the activitity watcher is enabled. +inline bool WatcherEnabled(int level = 1) { + return g_watcher_level.load(std::memory_order_acquire) >= level; +} + +#endif + +// NOTE: Borrowed from boost C++ libraries because std::is_invocable_r is not +// available in Android NDK. +template +struct is_invocable_r + : std::is_constructible< + std::function, + std::reference_wrapper::type>> {}; + +} // namespace tfw_internal + +template +constexpr bool is_activity_generator = + tfw_internal::is_invocable_r, F>::value; + +// Records an activity explicitly. Useful when the start and end of an activity +// happen in different threads. Generates the Activity only if activity +// watching is enabled, useful for avoiding expensive operations when activity +// watching is disabled. +// Example Usage: +// auto aid = ActivityStart([&]() { +// return std::make_unique( +// op_name, category, +// Activity::Attributes{{"key1", value1}, {"key2", value2}}); +// }, /*level=*/2); +// DoSomething(); +// ActivityEnd(aid); +template < + typename ActivityGenerator, + std::enable_if_t, bool> = true> +inline ActivityId ActivityStart(ActivityGenerator&& gen, int level = 1) { +#if defined(TF_ENABLE_ACTIVITY_WATCHER) + if (TF_PREDICT_FALSE(tfw_internal::WatcherEnabled(level))) { + return tfw_internal::RecordActivityStart( + std::forward(gen)()); + } +#endif + return kActivityNotRecorded; +} + +inline void ActivityEnd(ActivityId id) { +#if defined(TF_ENABLE_ACTIVITY_WATCHER) + if (TF_PREDICT_FALSE(id != kActivityNotRecorded)) { + tfw_internal::RecordActivityEnd(id); + } +#endif +} + +// ActivityScope marks a scope as an activity and record it with a global +// ActivityRecorder. +// Example Usage: +// { +// ActivityScope activity_scope([&]() { +// return std::make_unique( +// op_name, ActivityCategory::kMisc, +// Activity::Attributes{{"key1", value1}, {"key2", value2}}); +// }, /*level=*/2); +// DoSomething(); +// } +class ActivityScope { + public: + template < + typename ActivityGenerator, + std::enable_if_t, bool> = true> + explicit ActivityScope(ActivityGenerator&& gen, int level = 1) { + activity_id_ = ActivityStart(std::forward(gen), level); + } + ActivityScope(ActivityScope&& activity) { + activity_id_ = activity.activity_id_; + activity.activity_id_ = kActivityNotRecorded; + } + ~ActivityScope() { ActivityEnd(activity_id_); } + + private: + ActivityId activity_id_; + ActivityScope(const ActivityScope&) = delete; + void operator=(const ActivityScope&) = delete; +}; + +} // namespace activity_watcher +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity_utils.cc b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity_utils.cc new file mode 100644 index 0000000000000000000000000000000000000000..228b0fe4eae4bc4ed9eb7b88f73a2e7851e0ece3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity_utils.cc @@ -0,0 +1,60 @@ +/* Copyright 2022 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/activity_watcher/activity_utils.h" + +#include +#include +#include + +#include "absl/strings/str_cat.h" +#include "absl/strings/str_join.h" +#include "xla/tsl/platform/types.h" +#include "tensorflow/core/activity_watcher/activity.h" +#include "tensorflow/core/framework/op_kernel.h" + +namespace tensorflow { +namespace activity_watcher { + +std::unique_ptr ActivityFromContext( + OpKernelContext* context, std::string name, ActivityCategory category, + Activity::Attributes additional_attributes) { + Activity::Attributes attributes(std::move(additional_attributes)); + if (context) { + attributes.merge(Activity::Attributes({ + {"node_name", context->op_kernel().def().name()}, + {"step_id", absl::StrCat(context->step_id())}, + {"device", context->device()->name()}, + {"op", context->op_kernel().def().op()}, + {"iter_num", absl::StrCat(context->frame_iter().iter_id)}, + {"inputs", absl::StrJoin(context->op_kernel().def().input(), "; ")}, + {"original_node_names ", absl::StrJoin(context->op_kernel() + .def() + .experimental_debug_info() + .original_node_names(), + "; ")}, + {"original_func_names", absl::StrJoin(context->op_kernel() + .def() + .experimental_debug_info() + .original_func_names(), + "; ")}, + })); + } + + return std::make_unique(name, category, std::move(attributes)); +} + +} // namespace activity_watcher +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity_utils.h b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity_utils.h new file mode 100644 index 0000000000000000000000000000000000000000..db31cc305adeb7d06c9725fb5a009e5ce457f36e --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/activity_watcher/activity_utils.h @@ -0,0 +1,38 @@ +/* Copyright 2022 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_ACTIVITY_WATCHER_ACTIVITY_UTILS_H_ +#define TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_UTILS_H_ + +#include + +#include "xla/tsl/platform/types.h" +#include "tensorflow/core/activity_watcher/activity.h" + +namespace tensorflow { + +class OpKernelContext; + +namespace activity_watcher { + +// A convenient way to create an activity. Writes OpKernelContext information +// and given attributes to a new activity and returns. +std::unique_ptr ActivityFromContext( + OpKernelContext* context, std::string name, ActivityCategory category, + Activity::Attributes additional_attributes = Activity::Attributes()); + +} // namespace activity_watcher +} // namespace tensorflow + +#endif // TENSORFLOW_CORE_ACTIVITY_WATCHER_ACTIVITY_UTILS_H_ diff --git a/western_ai/usa/tensorflow/tensorflow/core/api_def/api_test.cc b/western_ai/usa/tensorflow/tensorflow/core/api_def/api_test.cc new file mode 100644 index 0000000000000000000000000000000000000000..fa5caaa323b0e970b8d69d21ba7bd519c78bc9c3 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/api_def/api_test.cc @@ -0,0 +1,353 @@ +/* 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. +==============================================================================*/ + +// Test that validates tensorflow/core/api_def/base_api/api_def*.pbtxt files. + +#include + +#include +#include +#include +#include + +#include "tensorflow/core/api_def/excluded_ops.h" +#include "tensorflow/core/framework/api_def.pb.h" +#include "tensorflow/core/framework/op.h" +#include "tensorflow/core/framework/op_def.pb.h" +#include "tensorflow/core/framework/op_gen_lib.h" +#include "tensorflow/core/lib/core/status.h" +#include "tensorflow/core/lib/core/status_test_util.h" +#include "tensorflow/core/lib/io/path.h" +#include "tensorflow/core/lib/strings/stringprintf.h" +#include "tensorflow/core/platform/env.h" +#include "tensorflow/core/platform/init_main.h" +#include "tensorflow/core/platform/protobuf.h" +#include "tensorflow/core/platform/resource_loader.h" +#include "tensorflow/core/platform/test.h" +#include "tensorflow/core/platform/types.h" + +namespace tensorflow { +namespace { + +constexpr char kApiDefFilePattern[] = "api_def_*.pbtxt"; + +std::string DefaultApiDefDir() { + return GetDataDependencyFilepath( + io::JoinPath("tensorflow", "core", "api_def", "base_api")); +} + +std::string PythonApiDefDir() { + return GetDataDependencyFilepath( + io::JoinPath("tensorflow", "core", "api_def", "python_api")); +} + +// Reads golden ApiDef files and returns a map from file name to ApiDef file +// contents. +void GetGoldenApiDefs( + Env* env, const std::string& api_files_dir, + std::unordered_map* name_to_api_def) { + std::vector matching_paths; + TF_CHECK_OK(env->GetMatchingPaths( + io::JoinPath(api_files_dir, kApiDefFilePattern), &matching_paths)); + + for (auto& file_path : matching_paths) { + std::string file_contents; + TF_CHECK_OK(ReadFileToString(env, file_path, &file_contents)); + file_contents = PBTxtFromMultiline(file_contents); + + ApiDefs 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); + } +} + +void TestAllApiDefsHaveCorrespondingOp( + const OpList& ops, + const std::unordered_map& api_defs_map) { + std::unordered_set op_names; + for (const auto& op : ops.op()) { + op_names.insert(op.name()); + } + for (const auto& name_and_api_def : api_defs_map) { + ASSERT_TRUE(op_names.find(name_and_api_def.first) != op_names.end()) + << name_and_api_def.first << " op has ApiDef but missing from ops. " + << "Does api_def_" << name_and_api_def.first << " need to be deleted?"; + } +} + +void TestAllApiDefInputArgsAreValid( + const OpList& ops, + const std::unordered_map& api_defs_map) { + for (const auto& op : ops.op()) { + const auto api_def_iter = api_defs_map.find(op.name()); + if (api_def_iter == api_defs_map.end()) { + continue; + } + const auto& api_def = api_def_iter->second; + for (const auto& api_def_arg : api_def.in_arg()) { + bool found_arg = false; + for (const auto& op_arg : op.input_arg()) { + if (api_def_arg.name() == op_arg.name()) { + found_arg = true; + break; + } + } + ASSERT_TRUE(found_arg) + << "Input argument " << api_def_arg.name() + << " (overwritten in api_def_" << op.name() + << ".pbtxt) is not defined in OpDef for " << op.name(); + } + } +} + +void TestAllApiDefOutputArgsAreValid( + const OpList& ops, + const std::unordered_map& api_defs_map) { + for (const auto& op : ops.op()) { + const auto api_def_iter = api_defs_map.find(op.name()); + if (api_def_iter == api_defs_map.end()) { + continue; + } + const auto& api_def = api_def_iter->second; + for (const auto& api_def_arg : api_def.out_arg()) { + bool found_arg = false; + for (const auto& op_arg : op.output_arg()) { + if (api_def_arg.name() == op_arg.name()) { + found_arg = true; + break; + } + } + ASSERT_TRUE(found_arg) + << "Output argument " << api_def_arg.name() + << " (overwritten in api_def_" << op.name() + << ".pbtxt) is not defined in OpDef for " << op.name(); + } + } +} + +void TestAllApiDefAttributeNamesAreValid( + const OpList& ops, + const std::unordered_map& api_defs_map) { + for (const auto& op : ops.op()) { + const auto api_def_iter = api_defs_map.find(op.name()); + if (api_def_iter == api_defs_map.end()) { + continue; + } + const auto& api_def = api_def_iter->second; + for (const auto& api_def_attr : api_def.attr()) { + bool found_attr = false; + for (const auto& op_attr : op.attr()) { + if (api_def_attr.name() == op_attr.name()) { + found_attr = true; + } + } + ASSERT_TRUE(found_attr) + << "Attribute " << api_def_attr.name() << " (overwritten in api_def_" + << op.name() << ".pbtxt) is not defined in OpDef for " << op.name(); + } + } +} + +void TestDeprecatedAttributesSetCorrectly( + const std::unordered_map& api_defs_map) { + for (const auto& name_and_api_def : api_defs_map) { + int num_deprecated_endpoints = 0; + const auto& api_def = name_and_api_def.second; + for (const auto& endpoint : api_def.endpoint()) { + if (endpoint.deprecated()) { + ++num_deprecated_endpoints; + } + } + + const auto& name = name_and_api_def.first; + ASSERT_TRUE(api_def.deprecation_message().empty() || + num_deprecated_endpoints == 0) + << "Endpoints are set to 'deprecated' for deprecated op " << name + << ". If an op is deprecated (i.e. deprecation_message is set), " + << "all the endpoints are deprecated implicitly and 'deprecated' " + << "field should not be set."; + if (num_deprecated_endpoints > 0) { + ASSERT_NE(num_deprecated_endpoints, api_def.endpoint_size()) + << "All " << name << " endpoints are deprecated. Please, set " + << "deprecation_message in api_def_" << name << ".pbtxt instead. " + << "to indicate that the op is deprecated."; + } + } +} + +void TestDeprecationVersionSetCorrectly( + const std::unordered_map& api_defs_map) { + for (const auto& name_and_api_def : api_defs_map) { + const auto& name = name_and_api_def.first; + const auto& api_def = name_and_api_def.second; + if (api_def.deprecation_version() != 0) { + ASSERT_TRUE(api_def.deprecation_version() > 0) + << "Found ApiDef with negative deprecation_version"; + ASSERT_FALSE(api_def.deprecation_message().empty()) + << "ApiDef that includes deprecation_version > 0 must also specify " + << "a deprecation_message. Op " << name + << " has deprecation_version > 0 but deprecation_message is not set."; + } + } +} + +class BaseApiTest : public ::testing::Test { + protected: + BaseApiTest() { + OpRegistry::Global()->Export(false, &ops_); + const std::vector multi_line_fields = {"description"}; + + Env* env = Env::Default(); + GetGoldenApiDefs(env, DefaultApiDefDir(), &api_defs_map_); + } + OpList ops_; + std::unordered_map api_defs_map_; +}; + +// Check that all ops have an ApiDef. +TEST_F(BaseApiTest, AllOpsAreInApiDef) { + auto* excluded_ops = GetExcludedOps(); + for (const auto& op : ops_.op()) { + if (excluded_ops->find(op.name()) != excluded_ops->end()) { + continue; + } + EXPECT_TRUE(api_defs_map_.find(op.name()) != api_defs_map_.end()) + << op.name() << " op does not have api_def_*.pbtxt file. " + << "Please add api_def_" << op.name() << ".pbtxt file " + << "under tensorflow/core/api_def/base_api/ directory."; + } +} + +// Check that ApiDefs have a corresponding op. +TEST_F(BaseApiTest, AllApiDefsHaveCorrespondingOp) { + TestAllApiDefsHaveCorrespondingOp(ops_, api_defs_map_); +} + +std::string GetOpDefHasDocStringError(const std::string& op_name) { + return absl::StrFormat( + "OpDef for %s has a doc string. " + "Doc strings must be defined in ApiDef instead of OpDef. " + "Please, add summary and descriptions in api_def_%s" + ".pbtxt file instead", + op_name.c_str(), op_name.c_str()); +} + +// Check that OpDef's do not have descriptions and summaries. +// Descriptions and summaries must be in corresponding ApiDefs. +TEST_F(BaseApiTest, OpDefsShouldNotHaveDocs) { + auto* excluded_ops = GetExcludedOps(); + for (const auto& op : ops_.op()) { + if (excluded_ops->find(op.name()) != excluded_ops->end()) { + continue; + } + ASSERT_TRUE(op.summary().empty()) << GetOpDefHasDocStringError(op.name()); + ASSERT_TRUE(op.description().empty()) + << GetOpDefHasDocStringError(op.name()); + for (const auto& arg : op.input_arg()) { + ASSERT_TRUE(arg.description().empty()) + << GetOpDefHasDocStringError(op.name()); + } + for (const auto& arg : op.output_arg()) { + ASSERT_TRUE(arg.description().empty()) + << GetOpDefHasDocStringError(op.name()); + } + for (const auto& attr : op.attr()) { + ASSERT_TRUE(attr.description().empty()) + << GetOpDefHasDocStringError(op.name()); + } + } +} + +// Checks that input arg names in an ApiDef match input +// arg names in corresponding OpDef. +TEST_F(BaseApiTest, AllApiDefInputArgsAreValid) { + TestAllApiDefInputArgsAreValid(ops_, api_defs_map_); +} + +// Checks that output arg names in an ApiDef match output +// arg names in corresponding OpDef. +TEST_F(BaseApiTest, AllApiDefOutputArgsAreValid) { + TestAllApiDefOutputArgsAreValid(ops_, api_defs_map_); +} + +// Checks that attribute names in an ApiDef match attribute +// names in corresponding OpDef. +TEST_F(BaseApiTest, AllApiDefAttributeNamesAreValid) { + TestAllApiDefAttributeNamesAreValid(ops_, api_defs_map_); +} + +// Checks that deprecation is set correctly. +TEST_F(BaseApiTest, DeprecationSetCorrectly) { + TestDeprecatedAttributesSetCorrectly(api_defs_map_); +} + +// Checks that deprecation_version is set for entire op only if +// deprecation_message is set. +TEST_F(BaseApiTest, DeprecationVersionSetCorrectly) { + TestDeprecationVersionSetCorrectly(api_defs_map_); +} + +class PythonApiTest : public ::testing::Test { + protected: + PythonApiTest() { + OpRegistry::Global()->Export(false, &ops_); + const std::vector multi_line_fields = {"description"}; + + Env* env = Env::Default(); + GetGoldenApiDefs(env, PythonApiDefDir(), &api_defs_map_); + } + OpList ops_; + std::unordered_map api_defs_map_; +}; + +// Check that ApiDefs have a corresponding op. +TEST_F(PythonApiTest, AllApiDefsHaveCorrespondingOp) { + TestAllApiDefsHaveCorrespondingOp(ops_, api_defs_map_); +} + +// Checks that input arg names in an ApiDef match input +// arg names in corresponding OpDef. +TEST_F(PythonApiTest, AllApiDefInputArgsAreValid) { + TestAllApiDefInputArgsAreValid(ops_, api_defs_map_); +} + +// Checks that output arg names in an ApiDef match output +// arg names in corresponding OpDef. +TEST_F(PythonApiTest, AllApiDefOutputArgsAreValid) { + TestAllApiDefOutputArgsAreValid(ops_, api_defs_map_); +} + +// Checks that attribute names in an ApiDef match attribute +// names in corresponding OpDef. +TEST_F(PythonApiTest, AllApiDefAttributeNamesAreValid) { + TestAllApiDefAttributeNamesAreValid(ops_, api_defs_map_); +} + +// Checks that deprecation is set correctly. +TEST_F(PythonApiTest, DeprecationSetCorrectly) { + TestDeprecatedAttributesSetCorrectly(api_defs_map_); +} + +// Checks that deprecation_version is set for entire op only if +// deprecation_message is set. +TEST_F(PythonApiTest, DeprecationVersionSetCorrectly) { + TestDeprecationVersionSetCorrectly(api_defs_map_); +} + +} // namespace +} // namespace tensorflow diff --git a/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_Abort.pbtxt b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_Abort.pbtxt new file mode 100644 index 0000000000000000000000000000000000000000..cc489230c4d6d1eb898298324e3a1e2450aeb3cd --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_Abort.pbtxt @@ -0,0 +1,16 @@ +op { + graph_op_name: "Abort" + attr { + name: "error_msg" + description: < [nan nan 0. 0.62236255 5.9914584 9.903487 inf] +``` +END +} diff --git a/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_Add.pbtxt b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_Add.pbtxt new file mode 100644 index 0000000000000000000000000000000000000000..0a39832393580fc4fadc45bd1054e57b91ef62ea --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_Add.pbtxt @@ -0,0 +1,13 @@ +op { + graph_op_name: "Add" + summary: "Returns x + y element-wise." + description: < 26 + ``` +END +} diff --git a/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_AddSparseToTensorsMap.pbtxt b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_AddSparseToTensorsMap.pbtxt new file mode 100644 index 0000000000000000000000000000000000000000..5096e13e3408cc892750a069a4e2adf565748c97 --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_AddSparseToTensorsMap.pbtxt @@ -0,0 +1,58 @@ +op { + graph_op_name: "AddSparseToTensorsMap" + in_arg { + name: "sparse_indices" + description: <= 2." +} diff --git a/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_AdjustContrastv2.pbtxt b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_AdjustContrastv2.pbtxt new file mode 100644 index 0000000000000000000000000000000000000000..8db5cfb3cb0cdfa1c5dd7f5d51fa534638cc482c --- /dev/null +++ b/western_ai/usa/tensorflow/tensorflow/core/api_def/base_api/api_def_AdjustContrastv2.pbtxt @@ -0,0 +1,36 @@ +op { + graph_op_name: "AdjustContrastv2" + endpoint { + name: "AdjustContrast" + } + in_arg { + name: "images" + description: <