1 /* Copyright 2019 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/xla_op_kernel.h" 17 #include "tensorflow/compiler/xla/client/lib/matrix.h" 18 #include "tensorflow/compiler/xla/client/lib/qr.h" 19 #include "tensorflow/compiler/xla/client/xla_builder.h" 20 #include "tensorflow/compiler/xla/xla_data.pb.h" 21 22 namespace tensorflow { 23 namespace { 24 25 class MatrixSolveOp : public XlaOpKernel { 26 public: MatrixSolveOp(OpKernelConstruction * ctx)27 explicit MatrixSolveOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) { 28 OP_REQUIRES_OK(ctx, ctx->GetAttr("adjoint", &adjoint_)); 29 } 30 Compile(XlaOpKernelContext * ctx)31 void Compile(XlaOpKernelContext* ctx) override { 32 const TensorShape matrix_shape = ctx->InputShape(0); 33 int64_t matrix_ndims = matrix_shape.dims(); 34 OP_REQUIRES(ctx, matrix_ndims >= 2, 35 errors::InvalidArgument( 36 "Input matrix must have rank >= 2, got ", matrix_ndims)); 37 OP_REQUIRES(ctx, 38 matrix_shape.dim_size(matrix_ndims - 2) == 39 matrix_shape.dim_size(matrix_ndims - 1), 40 errors::InvalidArgument( 41 "Input matrices must be square, got", 42 matrix_shape.dim_size(matrix_ndims - 2), 43 " != ", matrix_shape.dim_size(matrix_ndims - 1))); 44 45 xla::XlaOp matrix = ctx->Input(0); 46 xla::XlaOp rhs = ctx->Input(1); 47 48 // TODO(b/111271662): Using LU decomposition instead of QR should be faster. 49 xla::XlaOp q, r; 50 xla::QrExplicit(matrix, /*full_matrices=*/false, q, r); 51 52 xla::XlaOp inv = 53 xla::TriangularSolve(r, xla::TransposeInMinorDims(q), 54 /*left_side=*/true, 55 /*lower=*/false, /*unit_diagonal=*/false, 56 /*transpose_a=*/ 57 xla::TriangularSolveOptions::NO_TRANSPOSE); 58 59 xla::XlaOp output = 60 xla::BatchDot(inv, adjoint_, rhs, 61 /*transpose_y=*/false, xla::PrecisionConfig::HIGHEST); 62 ctx->SetOutput(0, output); 63 } 64 65 private: 66 bool adjoint_; 67 68 TF_DISALLOW_COPY_AND_ASSIGN(MatrixSolveOp); 69 }; 70 71 // TODO(b/111271662): Support integer and complex types. 72 REGISTER_XLA_OP(Name("MatrixSolve").TypeConstraint("T", kFloatTypes), 73 MatrixSolveOp); 74 75 } // namespace 76 } // namespace tensorflow 77