1 /* Copyright 2020 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/xla/client/lib/lu_decomposition.h"
17
18 #include <vector>
19
20 #include "tensorflow/compiler/xla/shape_util.h"
21 #include "tensorflow/compiler/xla/statusor.h"
22 #include "tensorflow/compiler/xla/types.h"
23
24 namespace xla {
25
LuDecomposition(XlaOp a)26 LuDecompositionResult LuDecomposition(XlaOp a) {
27 XlaBuilder* builder = a.builder();
28 XlaOp result = builder->ReportErrorOrReturn([&]() -> StatusOr<XlaOp> {
29 TF_ASSIGN_OR_RETURN(Shape a_shape, builder->GetShape(a));
30 const int ndims = a_shape.rank();
31 TF_RET_CHECK(ndims >= 2);
32 const int64 m = ShapeUtil::GetDimension(a_shape, -2);
33 const int64 n = ShapeUtil::GetDimension(a_shape, -1);
34 const int num_batch_dims = a_shape.dimensions().size() - 2;
35 const std::vector<int64> batch_dims(
36 a_shape.dimensions().begin(),
37 a_shape.dimensions().begin() + num_batch_dims);
38
39 std::vector<int64> pivot_dims = batch_dims;
40 pivot_dims.push_back(std::min(m, n));
41 std::vector<int64> perm_dims = batch_dims;
42 perm_dims.push_back(m);
43 Shape lu_shape = ShapeUtil::MakeTupleShape(
44 {a_shape, ShapeUtil::MakeShape(S32, pivot_dims),
45 ShapeUtil::MakeShape(S32, perm_dims)});
46 // The TPU compiler has a rewrite pass that lowers an LuDecomposition
47 // CustomCall.
48 // TODO(phawkins): upgrade LU decomposition to a first-class HLO operator
49 // and implement it on other backends.
50 return CustomCall(a.builder(), "LuDecomposition", {a}, lu_shape);
51 });
52 return LuDecompositionResult{GetTupleElement(result, 0),
53 GetTupleElement(result, 1),
54 GetTupleElement(result, 2)};
55 }
56
57 } // namespace xla
58