xref: /aosp_15_r20/external/tensorflow/tensorflow/compiler/xla/service/topk_rewriter.h (revision b6fb3261f9314811a0f4371741dbb8839866f948)
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 #ifndef TENSORFLOW_COMPILER_XLA_SERVICE_TOPK_REWRITER_H_
17 #define TENSORFLOW_COMPILER_XLA_SERVICE_TOPK_REWRITER_H_
18 
19 #include "tensorflow/compiler/xla/service/hlo_instruction.h"
20 #include "tensorflow/compiler/xla/service/hlo_instructions.h"
21 #include "tensorflow/compiler/xla/service/hlo_module.h"
22 #include "tensorflow/compiler/xla/service/hlo_pass_interface.h"
23 
24 namespace xla {
25 // This pass pattern-matches soups of HLOs executing a TopK operation and
26 // replaces them with a TopK CustomCall when the given values are supported by
27 // the CustomCall and it is more efficient to use that implementation.
28 class TopkRewriter : public HloModulePass {
29  public:
TopkRewriter(std::function<bool (const HloSortInstruction *,int64_t)> is_profitable_to_convert)30   explicit TopkRewriter(std::function<bool(const HloSortInstruction*, int64_t)>
31                             is_profitable_to_convert)
32       : is_profitable_to_convert_(std::move(is_profitable_to_convert)) {}
33 
name()34   absl::string_view name() const override { return "topk-rewriter"; }
35 
36   using HloPassInterface::Run;
37   StatusOr<bool> Run(
38       HloModule* module,
39       const absl::flat_hash_set<absl::string_view>& execution_threads) override;
40 
41  protected:
42   // Check if the sort instruction is in TopK.
43   std::optional<int64_t> SortIsInTopK(HloInstruction* inst);
44 
45   // Transform to CustomCall.
46   StatusOr<bool> TransformToCustomCall(
47       HloModule* module,
48       const absl::flat_hash_set<absl::string_view>& execution_threads);
49 
50  protected:
51   // Check if the sort instruction is in TopK.
52   absl::optional<int64> SortIsInTopK(HloInstruction* inst);
53 
54   // Transform to CustomCall.
55   StatusOr<bool> TransformToCustomCall(HloModule* module);
56 
57  private:
58   // Predicate that returns true if a sort instruction is profitable to be
59   // converted into a custom call.
60   std::function<bool(const HloSortInstruction*, int64_t)>
61       is_profitable_to_convert_;
62 };
63 }  // namespace xla
64 
65 #endif  // TENSORFLOW_COMPILER_XLA_SERVICE_TOPK_REWRITER_H_
66