xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/tf2xla/lib/broadcast.cc (revision b6fb3261f9314811a0f4371741dbb8839866f948)
1 /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
2 
3 Licensed under the Apache License, Version 2.0 (the "License");
4 you may not use this file except in compliance with the License.
5 You may obtain a copy of the License at
6 
7     http://www.apache.org/licenses/LICENSE-2.0
8 
9 Unless required by applicable law or agreed to in writing, software
10 distributed under the License is distributed on an "AS IS" BASIS,
11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 See the License for the specific language governing permissions and
13 limitations under the License.
14 ==============================================================================*/
15 
16 #include "tensorflow/compiler/tf2xla/lib/broadcast.h"
17 
18 #include <vector>
19 
20 #include "absl/algorithm/container.h"
21 #include "absl/strings/str_join.h"
22 #include "tensorflow/compiler/tf2xla/shape_util.h"
23 #include "tensorflow/compiler/xla/client/lib/broadcast.h"
24 #include "tensorflow/compiler/xla/shape_util.h"
25 #include "tensorflow/compiler/xla/status_macros.h"
26 #include "tensorflow/compiler/xla/util.h"
27 #include "tensorflow/core/framework/tensor_shape.h"
28 #include "tensorflow/core/util/bcast.h"
29 
30 namespace tensorflow {
31 
BroadcastTo(xla::XlaOp input,absl::Span<int64_t const> output_dims)32 StatusOr<xla::XlaOp> BroadcastTo(xla::XlaOp input,
33                                  absl::Span<int64_t const> output_dims) {
34   return xla::BroadcastTo(input, output_dims);
35 }
36 
BroadcastOpsToSame(xla::XlaOp * lhs,xla::XlaOp * rhs)37 Status BroadcastOpsToSame(xla::XlaOp* lhs, xla::XlaOp* rhs) {
38   TF_ASSIGN_OR_RETURN(auto lhs_xla_shape, lhs->builder()->GetShape(*lhs));
39   TF_ASSIGN_OR_RETURN(auto rhs_xla_shape, rhs->builder()->GetShape(*rhs));
40   tensorflow::TensorShape lhs_tf_shape;
41   tensorflow::TensorShape rhs_tf_shape;
42   TF_RETURN_IF_ERROR(XLAShapeToTensorShape(lhs_xla_shape, &lhs_tf_shape));
43   TF_RETURN_IF_ERROR(XLAShapeToTensorShape(rhs_xla_shape, &rhs_tf_shape));
44   if (!lhs_tf_shape.IsSameSize(rhs_tf_shape)) {
45     tensorflow::BCast bcast(tensorflow::BCast::FromShape(lhs_tf_shape),
46                             tensorflow::BCast::FromShape(rhs_tf_shape));
47     if (!bcast.IsValid()) {
48       return tensorflow::errors::InvalidArgument(
49           "Dimensions cannot be made to match through broadcasting");
50     }
51     TF_ASSIGN_OR_RETURN(*lhs, xla::BroadcastTo(*lhs, bcast.output_shape()));
52     TF_ASSIGN_OR_RETURN(*rhs, xla::BroadcastTo(*rhs, bcast.output_shape()));
53   }
54   return OkStatus();
55 }
56 
57 }  // namespace tensorflow
58