jasonfan commited on
Commit
046e18f
·
verified ·
1 Parent(s): 6a9874a

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/cpu_event.h +31 -0
  2. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call.h +1893 -0
  3. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call_registry.h +76 -0
  4. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/async_values_cache.h +113 -0
  5. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/memory_mapper.h +38 -0
  6. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/diagnostics.h +174 -0
  7. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/errors.h +42 -0
  8. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/executable.h +439 -0
  9. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/execution_engine.h +187 -0
  10. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi.h +97 -0
  11. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_abi.h +62 -0
  12. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_api.h +1270 -0
  13. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_c_api.h +276 -0
  14. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/jit_executable.h +240 -0
  15. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/logical_result.h +36 -0
  16. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/map_by_type.h +110 -0
  17. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memory_mapper.h +65 -0
  18. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memref_view.h +56 -0
  19. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module.h +185 -0
  20. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module_registry.h +75 -0
  21. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/results.h +186 -0
  22. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/runtime.h +66 -0
  23. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/state.h +218 -0
  24. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/symbolic_shape.h +117 -0
  25. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/tracing.h +44 -0
  26. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/type_id.h +173 -0
  27. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/types.h +326 -0
  28. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/algebraic_simplifier.h +617 -0
  29. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_broadcast_reorder.h +41 -0
  30. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_combiner.h +56 -0
  31. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_decomposer.h +50 -0
  32. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_combiner.h +54 -0
  33. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_contiguous.h +39 -0
  34. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_folder.h +48 -0
  35. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_key.h +43 -0
  36. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_promotion.h +40 -0
  37. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_reassociate.h +53 -0
  38. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_to_all_decomposer.h +46 -0
  39. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/allocation_tracker.h +154 -0
  40. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/async_collective_creator.h +60 -0
  41. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/backend.h +208 -0
  42. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batch_dot_simplification.h +42 -0
  43. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batchnorm_expander.h +56 -0
  44. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/bitcast_dtypes_expander.h +45 -0
  45. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/broadcast_canonicalizer.h +40 -0
  46. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.h +793 -0
  47. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.pb.h +416 -0
  48. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value.h +183 -0
  49. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value_containers.h +55 -0
  50. miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_graph.h +386 -0
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/cpu_event.h ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_CPU_EVENT_H_
17
+ #define XLA_RUNTIME_CPU_EVENT_H_
18
+
19
+ namespace xla {
20
+ namespace runtime {
21
+
22
+ // Typical use case: AsyncValueRef<CpuEvent> is used to indicate the
23
+ // completion of a CPU operation, e.g., data transfer or running a program.
24
+ struct CpuEvent {
25
+ CpuEvent() = default;
26
+ };
27
+
28
+ } // namespace runtime
29
+ } // namespace xla
30
+
31
+ #endif // XLA_RUNTIME_CPU_EVENT_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call.h ADDED
@@ -0,0 +1,1893 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_CUSTOM_CALL_H_
17
+ #define XLA_RUNTIME_CUSTOM_CALL_H_
18
+
19
+ #include <algorithm>
20
+ #include <any>
21
+ #include <cstddef>
22
+ #include <cstdint>
23
+ #include <functional>
24
+ #include <iterator>
25
+ #include <optional>
26
+ #include <string>
27
+ #include <string_view>
28
+ #include <tuple>
29
+ #include <type_traits>
30
+ #include <utility>
31
+ #include <vector>
32
+
33
+ #include "absl/base/dynamic_annotations.h"
34
+ #include "absl/status/status.h"
35
+ #include "absl/status/statusor.h"
36
+ #include "absl/types/span.h"
37
+ #include "Eigen/Core" // from @eigen_archive
38
+ #include "llvm/ADT/STLExtras.h"
39
+ #include "llvm/ADT/StringExtras.h"
40
+ #include "xla/primitive_util.h"
41
+ #include "xla/runtime/async_runtime.h"
42
+ #include "xla/runtime/diagnostics.h"
43
+ #include "xla/runtime/errors.h"
44
+ #include "xla/runtime/ffi/ffi_abi.h"
45
+ #include "xla/runtime/logical_result.h"
46
+ #include "xla/runtime/map_by_type.h"
47
+ #include "xla/runtime/memref_view.h"
48
+ #include "xla/runtime/state.h"
49
+ #include "xla/runtime/type_id.h"
50
+ #include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime
51
+ #include "tfrt/concurrency/chain.h" // from @tf_runtime
52
+
53
+ namespace xla {
54
+ namespace runtime {
55
+
56
+ // Forward declare.
57
+ struct ExecutionContext;
58
+
59
+ // Forward declare template defined below.
60
+ template <typename... Ts>
61
+ class CustomCallBinding;
62
+
63
+ // Registers mappings from TypeIDs supported by the custom calls to their unique
64
+ // names in the given registry.
65
+ void PopulateCustomCallTypeIdNames(TypeIDNameRegistry& registry);
66
+
67
+ // A type tag to declare MLIR TypeID specializations for types passed to the
68
+ // custom calls. We don't want to declare specializations for scalar types
69
+ // directly in this translation unit, so we rely on a tag to wrap them.
70
+ //
71
+ // See explicit TypeID declarations at the end of this file.
72
+ template <typename T>
73
+ struct Tagged {};
74
+
75
+ class CustomCall {
76
+ public:
77
+ // Container for passing data between XLA user and the custom call handler.
78
+ using UserData = PtrMapByType<CustomCall>;
79
+
80
+ // A type for matching all remaining custom call arguments.
81
+ class RemainingArgs;
82
+
83
+ // A type for passing an argument of different types at the same position,
84
+ // and the handler will do the decoding.
85
+ class VariantArg;
86
+ class VariantAttr;
87
+
88
+ // A type for representing tensors with shapes.
89
+ template <typename T>
90
+ struct TensorRef {
91
+ absl::Span<const int64_t> shape;
92
+ absl::Span<const T> data;
93
+ };
94
+
95
+ // An ordinal of a function exported from executable.
96
+ struct FunctionOrdinal {
97
+ unsigned ordinal;
98
+ };
99
+
100
+ // Custom call handler can check arguments and attributes types and names
101
+ // at runtime, however this comes at extra cost and can be optionally
102
+ // disabled. If the version of the compiler that generated the XLA executable
103
+ // doesn't match the custom call handler, it can lead to undefined behavior.
104
+ enum class RuntimeChecks : uint8_t {
105
+ // Check arguments and attributes types, also check attribute names. It is
106
+ // safe to pass extra attributes (if `exact_attrs` is false) to the custom
107
+ // call when name checking is enabled, because it will safely skip
108
+ // irrelevant attributes.
109
+ kDefault = 0,
110
+
111
+ // Check only the types of the arguments and attributes. At this check level
112
+ // custom calls never check the names of the attributes because it can be
113
+ // too expensive, however type checking should prevent catastrophic
114
+ // segfaults. This is the recommended checks level in optimized builds.
115
+ kLess = 1,
116
+
117
+ // Do not check the number of arguments and attributes and their types, and
118
+ // do not check that the user data was passed to the custom call. This is
119
+ // the most dangerous option, because it blindly reinterprets opaque memory
120
+ // passed to the handler, and can easily lead to segfaults if the data
121
+ // doesn't match the expected custom call signature.
122
+ kNone = 2
123
+ };
124
+
125
+ struct Options {
126
+ // Check that attributes passed at run time exactly match the attributes
127
+ // defined by the custom call binding. If `false` then custom call handler
128
+ // will happily ignore any additional attributes passed at run time. It is
129
+ // unsafe to disable run-time checks for custom calls that support non-exact
130
+ // attributes, as the custom call handler uses pre-computed attributes
131
+ // offsets based on the binding specification.
132
+ bool exact_attrs = true;
133
+ };
134
+
135
+ static constexpr bool CheckNames(RuntimeChecks checks) {
136
+ return checks == RuntimeChecks::kDefault;
137
+ }
138
+
139
+ static constexpr bool CheckTypes(RuntimeChecks checks) {
140
+ return checks != RuntimeChecks::kNone;
141
+ }
142
+
143
+ static constexpr bool CheckUserData(RuntimeChecks checks) {
144
+ return checks != RuntimeChecks::kNone;
145
+ }
146
+
147
+ template <typename T>
148
+ static bool Isa(RuntimeChecks checks, TypeID type_id) {
149
+ return !CheckTypes(checks) || type_id == TypeID::get<Tagged<T>>();
150
+ }
151
+
152
+ template <typename T, typename U, typename... Ts>
153
+ static bool Isa(RuntimeChecks checks, TypeID type_id) {
154
+ return !CheckTypes(checks) || type_id == TypeID::get<Tagged<T>>() ||
155
+ Isa<U, Ts...>(checks, type_id);
156
+ }
157
+
158
+ virtual ~CustomCall() = default;
159
+
160
+ virtual std::string_view name() const = 0;
161
+ virtual LogicalResult call(void** args, void** attrs, void** rets,
162
+ const UserData* user_data,
163
+ const DiagnosticEngine* diagnostic) const = 0;
164
+
165
+ static CustomCallBinding<> Bind(std::string callee);
166
+ static CustomCallBinding<> Bind(std::string callee, const Options& opts);
167
+
168
+ // This is a helper template that allows to convert functions pointers from
169
+ // the run time values to compile time values (template arguments) with
170
+ // automatic template arguments inference.
171
+ //
172
+ // Example:
173
+ //
174
+ // static LogicalResult Foo(int32_t arg) {... }
175
+ //
176
+ // template<typename Callable>
177
+ // void call(Callable callable) { callable(42); }
178
+ //
179
+ // call(Foo); // `Foo` passed as a runtime value
180
+ // call(FunctionWrapper<Foo>()) // `Foo` passed as a template argument
181
+ //
182
+ // In the first case compiler will not be able to inline `Foo` into the `call`
183
+ // body. However in the second case it can do that, because function pointer
184
+ // is a statically known value (template non-type argument).
185
+ template <auto fn>
186
+ struct FunctionWrapper;
187
+
188
+ template <typename Ret, typename... Args, Ret (*fn)(Args...)>
189
+ struct FunctionWrapper<fn> {
190
+ ABSL_ATTRIBUTE_ALWAYS_INLINE Ret operator()(Args... args) const {
191
+ return fn(args...);
192
+ }
193
+ };
194
+ };
195
+
196
+ // Forward declare template defined below.
197
+ template <CustomCall::RuntimeChecks checks, typename Fn, typename... Ts>
198
+ class CustomCallHandler;
199
+
200
+ namespace internal {
201
+
202
+ // A type tag to distinguish arguments tied to the attributes in the
203
+ // `CustomCallBinding` variadic template argument.
204
+ template <typename T>
205
+ struct Attr {};
206
+
207
+ // A type tag to distinguish arguments tied to the return in the
208
+ // `CustomCallBinding` variadic template argument.
209
+ template <typename T>
210
+ struct Ret {};
211
+
212
+ // A type tag to distinguish arguments tied to the user data in the
213
+ // `CustomCallBinding` variadic template argument.
214
+ template <typename T>
215
+ struct UserData {};
216
+
217
+ // A type tag to distinguish arguments tied to the state in the
218
+ // `CustomCallBinding` variadic template argument.
219
+ template <typename T>
220
+ struct StateTag {};
221
+
222
+ // A type tag to distinguish arguments tied to the constant values in the
223
+ // `CustomCallBinding` variadic template argument.
224
+ template <typename T>
225
+ struct Value {};
226
+
227
+ // A template for checking if type is a regular argument or one of the special
228
+ // arguments wrapped in a type tag (e.g. attr, user data, etc...).
229
+ template <typename>
230
+ struct IsWrapped : std::false_type {};
231
+
232
+ template <typename T>
233
+ struct IsWrapped<internal::Attr<T>> : std::true_type {};
234
+
235
+ template <typename T>
236
+ struct IsWrapped<internal::Ret<T>> : std::true_type {};
237
+
238
+ template <typename T>
239
+ struct IsWrapped<internal::UserData<T>> : std::true_type {};
240
+
241
+ template <typename T>
242
+ struct IsWrapped<internal::StateTag<T>> : std::true_type {};
243
+
244
+ template <typename T>
245
+ struct IsWrapped<internal::Value<T>> : std::true_type {};
246
+
247
+ template <typename T>
248
+ struct IsResult : std::false_type {};
249
+
250
+ template <typename T>
251
+ struct IsResult<internal::Ret<T>> : std::true_type {};
252
+
253
+ // Checks if remaining arguments are in the parameter pack.
254
+ template <typename... Ts>
255
+ using HasRemainingArgs =
256
+ std::disjunction<std::is_same<CustomCall::RemainingArgs, Ts>...>;
257
+
258
+ } // namespace internal
259
+
260
+ // Custom call binding describes the function signature of the expected custom
261
+ // call handler using its variadic template parameter.
262
+ //
263
+ // Custom call binding:
264
+ // CustomCallBinding<int32_t, MemrefView>
265
+ //
266
+ // Function signature:
267
+ // LogicalResult MyHandle(int32_t algo, MemrefView memref);
268
+ //
269
+ template <typename... Ts>
270
+ class CustomCallBinding {
271
+ public:
272
+ using Options = CustomCall::Options;
273
+ using RuntimeChecks = CustomCall::RuntimeChecks;
274
+
275
+ template <typename T>
276
+ CustomCallBinding<Ts..., T> Arg() && {
277
+ return {std::move(*this)};
278
+ }
279
+
280
+ CustomCallBinding<Ts..., CustomCall::RemainingArgs> RemainingArgs() && {
281
+ static_assert(!internal::HasRemainingArgs<Ts...>::value,
282
+ "remaining arguments can be passed just once");
283
+ return {std::move(*this)};
284
+ }
285
+
286
+ template <typename T>
287
+ CustomCallBinding<Ts..., internal::Attr<T>> Attr(std::string attr) && {
288
+ attrs_.push_back(std::move(attr));
289
+ return {std::move(*this)};
290
+ }
291
+
292
+ template <typename T>
293
+ CustomCallBinding<Ts..., internal::Ret<T>> Ret() && {
294
+ return {std::move(*this)};
295
+ }
296
+
297
+ template <typename T>
298
+ CustomCallBinding<Ts..., internal::UserData<T>> UserData() && {
299
+ static_assert(std::is_pointer<T>::value, "user data must be a pointer");
300
+ return {std::move(*this)};
301
+ }
302
+
303
+ template <typename T>
304
+ CustomCallBinding<Ts..., internal::StateTag<T>> State(std::string id) && {
305
+ attrs_.push_back(std::move(id));
306
+ return {std::move(*this)};
307
+ }
308
+
309
+ template <typename T>
310
+ CustomCallBinding<Ts..., internal::Value<T>> Value(T value) && {
311
+ values_.push_back(std::move(value));
312
+ return {std::move(*this)};
313
+ }
314
+
315
+ template <RuntimeChecks checks = RuntimeChecks::kDefault, typename Fn>
316
+ std::unique_ptr<CustomCallHandler<checks, Fn, Ts...>> To(Fn fn) {
317
+ return std::unique_ptr<CustomCallHandler<checks, Fn, Ts...>>(
318
+ new CustomCallHandler<checks, Fn, Ts...>(
319
+ std::forward<Fn>(fn), std::move(callee_), std::move(attrs_),
320
+ std::move(values_), opts_));
321
+ }
322
+
323
+ private:
324
+ template <typename...>
325
+ friend class CustomCallBinding;
326
+ friend class CustomCall;
327
+
328
+ CustomCallBinding(std::string callee, const Options& opts)
329
+ : callee_(std::move(callee)), opts_(opts) {
330
+ static_assert(sizeof...(Ts) == 0, "custom call arguments must be empty");
331
+ }
332
+
333
+ template <typename... TTs>
334
+ CustomCallBinding(CustomCallBinding<TTs...>&& other) // NOLINT
335
+ : callee_(std::move(other.callee_)),
336
+ attrs_(std::move(other.attrs_)),
337
+ values_(std::move(other.values_)),
338
+ opts_(other.opts_) {}
339
+
340
+ CustomCallBinding(CustomCallBinding&) = delete;
341
+
342
+ std::string callee_; // custom call target
343
+ std::vector<std::string> attrs_; // names of bound attributes
344
+ std::vector<std::any> values_; // values bound to arguments
345
+ Options opts_;
346
+ };
347
+
348
+ inline CustomCallBinding<> CustomCall::Bind(std::string callee) {
349
+ return Bind(std::move(callee), Options());
350
+ }
351
+
352
+ inline CustomCallBinding<> CustomCall::Bind(std::string callee,
353
+ const Options& opts) {
354
+ return CustomCallBinding<>(std::move(callee), opts);
355
+ }
356
+
357
+ // Custom calls return results to the caller through the template
358
+ // specializations of the `Result`. Each template specialization is responsible
359
+ // for definining the result encoding/decoding to/from opaque memory.
360
+ template <typename T>
361
+ class Result;
362
+
363
+ // Custom call arguments decoding must be defined by specializing this template.
364
+ //
365
+ // Example: decoding for the `MyType` arguments
366
+ //
367
+ // template <CustomCall::RuntimeChecks checks>
368
+ // struct CustomCallArgDecoding<MyType, checks> {
369
+ // static FailureOr<MyType> Decode(TypeID type_id, void* value);
370
+ // };
371
+ //
372
+ template <typename T, CustomCall::RuntimeChecks>
373
+ struct CustomCallArgDecoding;
374
+
375
+ // Custom call attribute decoding must be defined by specializing this template.
376
+ //
377
+ // Example: decoding for the `MyType` attributes
378
+ //
379
+ // template <CustomCall::RuntimeChecks checks>
380
+ // struct CustomCallAttrDecoding<MyType, checks> {
381
+ // static FailureOr<MyType> Decode(std::string_view name,
382
+ // TypeID type_id, void* value);
383
+ // }
384
+ //
385
+ template <typename T, CustomCall::RuntimeChecks>
386
+ struct CustomCallAttrDecoding;
387
+
388
+ // Custom call returns decoding must be defined by specializing this template.
389
+ //
390
+ // Example: decoding for the `MyType` arguments
391
+ //
392
+ // template <CustomCall::RuntimeChecks checks>
393
+ // struct CustomCallRetDecoding<MyType, checks> {
394
+ // static FailureOr<Result<MyType>> Decode(TypeID type_id, void* value);
395
+ // };
396
+ //
397
+ template <typename T, CustomCall::RuntimeChecks>
398
+ struct CustomCallRetDecoding;
399
+
400
+ //===----------------------------------------------------------------------===//
401
+ // Helpers for decoding opaque arguments and attributes memory.
402
+ //===----------------------------------------------------------------------===//
403
+
404
+ namespace internal {
405
+
406
+ // Decoded pair of an argument type and opaque value.
407
+ struct DecodedArg {
408
+ TypeID type_id;
409
+ void* value;
410
+ };
411
+
412
+ // Decoded triple of an attribute name, type and opaque value.
413
+ struct DecodedAttr {
414
+ std::string_view name;
415
+ TypeID type_id;
416
+ void* value;
417
+ };
418
+
419
+ // A convenience wrapper around opaque arguments memory.
420
+ class DecodedArgs {
421
+ public:
422
+ explicit DecodedArgs(void** args) {
423
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(args, sizeof(void*));
424
+ size_ = *reinterpret_cast<int64_t*>(args[0]);
425
+ if (size_) {
426
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(args + 1, sizeof(void*));
427
+ type_table_ = reinterpret_cast<void**>(args[1]);
428
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(type_table_, size_ * sizeof(void*));
429
+ values_ = args + 2;
430
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(values_, size_ * sizeof(void*));
431
+ }
432
+ }
433
+
434
+ ABSL_ATTRIBUTE_ALWAYS_INLINE int64_t size() const { return size_; }
435
+
436
+ ABSL_ATTRIBUTE_ALWAYS_INLINE DecodedArg operator[](size_t i) const {
437
+ DecodedArg arg;
438
+ arg.type_id = TypeID::getFromOpaquePointer(type_table_[i]);
439
+ arg.value = values_[i];
440
+ return arg;
441
+ }
442
+
443
+ private:
444
+ int64_t size_;
445
+ void** type_table_ = nullptr;
446
+ void** values_ = nullptr;
447
+ };
448
+
449
+ // A convenience wrapper around opaque attributes memory.
450
+ class DecodedAttrs {
451
+ public:
452
+ explicit DecodedAttrs(void** attrs) : encoded_(attrs + 1) {
453
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(attrs, sizeof(void*));
454
+ size_ = *reinterpret_cast<int64_t*>(attrs[0]);
455
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded_, 3 * size_ * sizeof(void*));
456
+ }
457
+
458
+ ABSL_ATTRIBUTE_ALWAYS_INLINE int64_t size() const { return size_; }
459
+
460
+ ABSL_ATTRIBUTE_ALWAYS_INLINE DecodedAttr operator[](size_t i) const {
461
+ void** attr_base = encoded_ + i * 3;
462
+
463
+ DecodedAttr attr;
464
+ auto* name = reinterpret_cast<internal::EncodedArray<char>*>(attr_base[0]);
465
+ attr.name = std::string_view(name->data, name->size);
466
+ attr.type_id = TypeID::getFromOpaquePointer(attr_base[1]);
467
+ attr.value = attr_base[2];
468
+
469
+ return attr;
470
+ }
471
+
472
+ private:
473
+ void** encoded_;
474
+ int64_t size_;
475
+ };
476
+
477
+ // Using the same class for decoded returns
478
+ using DecodedRet = DecodedArg;
479
+ using DecodedRets = DecodedArgs;
480
+
481
+ } // namespace internal
482
+
483
+ //===----------------------------------------------------------------------===//
484
+ // CustomCall remaining arguments wraps the type-erased `DecodedArg` container,
485
+ // and provides a type-safe API for accessing individual arguments.
486
+ //===----------------------------------------------------------------------===//
487
+
488
+ class CustomCall::RemainingArgs {
489
+ public:
490
+ using RuntimeChecks = CustomCall::RuntimeChecks;
491
+
492
+ RemainingArgs(internal::DecodedArgs args, size_t offset)
493
+ : args_(args), offset_(offset) {
494
+ assert(offset <= args_.size() && "illegal remaining args offset");
495
+ }
496
+
497
+ size_t size() const { return args_.size() - offset_; }
498
+ bool empty() const { return size() == 0; }
499
+
500
+ template <typename T>
501
+ bool isa(size_t index) const {
502
+ return args_[index + offset_].type_id == TypeID::get<Tagged<T>>();
503
+ }
504
+
505
+ template <typename T, RuntimeChecks checks = RuntimeChecks::kDefault>
506
+ FailureOr<T> get(size_t index) const {
507
+ internal::DecodedArg arg = args_[index + offset_];
508
+ return CustomCallArgDecoding<T, checks>::Decode(arg.type_id, arg.value);
509
+ }
510
+
511
+ private:
512
+ internal::DecodedArgs args_;
513
+ size_t offset_;
514
+ };
515
+
516
+ class CustomCall::VariantArg {
517
+ public:
518
+ using RuntimeChecks = CustomCall::RuntimeChecks;
519
+
520
+ VariantArg(internal::DecodedArgs args, size_t offset)
521
+ : args_(args), offset_(offset) {
522
+ assert(offset <= args_.size() && "illegal remaining args offset");
523
+ }
524
+
525
+ template <typename T>
526
+ bool isa() const {
527
+ return args_[offset_].type_id == TypeID::get<Tagged<T>>();
528
+ }
529
+
530
+ template <typename T, RuntimeChecks checks = RuntimeChecks::kDefault>
531
+ FailureOr<T> get() const {
532
+ internal::DecodedArg arg = args_[offset_];
533
+ return CustomCallArgDecoding<T, checks>::Decode(arg.type_id, arg.value);
534
+ }
535
+
536
+ private:
537
+ internal::DecodedArgs args_;
538
+ size_t offset_;
539
+ };
540
+
541
+ class CustomCall::VariantAttr {
542
+ public:
543
+ using RuntimeChecks = CustomCall::RuntimeChecks;
544
+
545
+ VariantAttr(std::string_view name, TypeID type_id, void* value)
546
+ : name_(name), type_id_(type_id), value_(value) {}
547
+
548
+ template <typename T>
549
+ bool isa() const {
550
+ return type_id_ == TypeID::get<Tagged<T>>();
551
+ }
552
+
553
+ template <typename T, RuntimeChecks checks = RuntimeChecks::kDefault>
554
+ FailureOr<T> get() const {
555
+ return CustomCallAttrDecoding<T, checks>::Decode(name_, type_id_, value_);
556
+ }
557
+
558
+ private:
559
+ std::string_view name_;
560
+ TypeID type_id_;
561
+ void* value_;
562
+ };
563
+
564
+ //===----------------------------------------------------------------------===//
565
+ // A little bit of template metaprogramming to implement type safe binding
566
+ // of custom calls to C++ functions. This is internal implementation details,
567
+ // and must not be relied on in any of the client code.
568
+ //===----------------------------------------------------------------------===//
569
+
570
+ namespace internal {
571
+
572
+ // A helper struct to extract the type of the handler argument.
573
+ template <typename T>
574
+ struct FnArgType {
575
+ using Type = T;
576
+ };
577
+
578
+ // Extracts the underlying type from the attribute type tag.
579
+ template <typename T>
580
+ struct FnArgType<internal::Attr<T>> {
581
+ using Type = T;
582
+ };
583
+
584
+ // Extracts the underlying type from the return type tag.
585
+ template <typename T>
586
+ struct FnArgType<internal::Ret<T>> {
587
+ using Type = Result<T>;
588
+ };
589
+
590
+ // Extracts the underlying type from the user data type tag.
591
+ template <typename T>
592
+ struct FnArgType<internal::UserData<T>> {
593
+ using Type = T;
594
+ };
595
+
596
+ // Extracts the underlying type from the state type tag.
597
+ template <typename T>
598
+ struct FnArgType<internal::StateTag<T>> {
599
+ using Type = State<T>;
600
+ };
601
+
602
+ // Extracts the underlying type from the value type tag.
603
+ template <typename T>
604
+ struct FnArgType<internal::Value<T>> {
605
+ using Type = T;
606
+ };
607
+
608
+ // A template for counting regular arguments in the Ts pack.
609
+ template <typename... Ts>
610
+ struct NumArgs;
611
+
612
+ template <typename T, typename... Ts>
613
+ struct NumArgs<T, Ts...> {
614
+ static constexpr int64_t value = !IsWrapped<T>::value + NumArgs<Ts...>::value;
615
+ };
616
+
617
+ template <>
618
+ struct NumArgs<> {
619
+ static constexpr int64_t value = 0;
620
+ };
621
+
622
+ // A template for counting returns in the Ts pack.
623
+ template <typename... Ts>
624
+ struct NumRets;
625
+
626
+ template <typename T, typename... Ts>
627
+ struct NumRets<T, Ts...> {
628
+ static constexpr int64_t value = IsResult<T>::value + NumRets<Ts...>::value;
629
+ };
630
+
631
+ template <>
632
+ struct NumRets<> {
633
+ static constexpr int64_t value = 0;
634
+ };
635
+
636
+ // Unwrap return type to get the type expected by result `Set` method.
637
+ //
638
+ // TODO(ezhulenev): Result template itself should define what type `T` it
639
+ // expects to see in the `Set` method, because it's not necessery the same as
640
+ // the template type of the result.
641
+ template <typename T>
642
+ struct UnwrapRet;
643
+
644
+ template <typename T>
645
+ struct UnwrapRet<Result<T>> {
646
+ using Type = T;
647
+ };
648
+
649
+ // A helper template to concatenate index + index sequence.
650
+ template <size_t, typename>
651
+ struct ConsIdx;
652
+
653
+ template <size_t idx, size_t... Is>
654
+ struct ConsIdx<idx, std::index_sequence<Is...>> {
655
+ using Type = std::index_sequence<idx, Is...>;
656
+ };
657
+
658
+ // Get indices of the variadic template type parameters corresponding to
659
+ // results. This template will produce an `std::index_sequence` type with
660
+ // indices of custom call result arguments.
661
+ template <size_t idx, typename... Ts>
662
+ struct IndexRets;
663
+
664
+ template <size_t idx>
665
+ struct IndexRets<idx> {
666
+ using Is = std::index_sequence<>;
667
+ };
668
+
669
+ template <size_t idx, typename T, typename... Ts>
670
+ struct IndexRets<idx, T, Ts...> {
671
+ using Is = std::conditional_t<
672
+ IsResult<T>::value,
673
+ typename ConsIdx<idx, typename IndexRets<idx + 1, Ts...>::Is>::Type,
674
+ typename IndexRets<idx + 1, Ts...>::Is>;
675
+ };
676
+
677
+ // Get indices of the variadic template type parameters corresponding to
678
+ // all arguments excluding results.
679
+ template <size_t idx, typename... Ts>
680
+ struct IndexArgs;
681
+
682
+ template <size_t idx>
683
+ struct IndexArgs<idx> {
684
+ using Is = std::index_sequence<>;
685
+ };
686
+
687
+ template <size_t idx, typename T, typename... Ts>
688
+ struct IndexArgs<idx, T, Ts...> {
689
+ using Is = std::conditional_t<
690
+ !IsResult<T>::value,
691
+ typename ConsIdx<idx, typename IndexArgs<idx + 1, Ts...>::Is>::Type,
692
+ typename IndexArgs<idx + 1, Ts...>::Is>;
693
+ };
694
+
695
+ template <size_t... FnArgsIs, size_t... ResultIs, typename FnArgs,
696
+ typename Result>
697
+ void SetResultsFromTuple(std::index_sequence<ResultIs...>, FnArgs fn_args,
698
+ Result tuple) {
699
+ ((*std::get<FnArgsIs>(fn_args)).Set(std::get<ResultIs>(tuple)), ...);
700
+ }
701
+
702
+ // When decoding input data we need to keep track of how many arguments,
703
+ // attributes, and returns we decoded so far to index into the correct data
704
+ // structure.
705
+ struct DecodingOffsets {
706
+ int64_t args = 0;
707
+ int64_t attrs = 0;
708
+ int64_t rets = 0;
709
+ int64_t values = 0;
710
+ };
711
+
712
+ struct DecodingContext {
713
+ internal::DecodedArgs args;
714
+ internal::DecodedRets rets;
715
+ internal::DecodedAttrs attrs;
716
+
717
+ // Attributes' names and mapping from attrs' offsets to indices in `attrs`.
718
+ absl::Span<const std::string> attrs_names;
719
+ absl::Span<const size_t> attrs_idx;
720
+
721
+ // Values bound to arguments at handler construction time.
722
+ absl::Span<const std::any> values;
723
+
724
+ // User-provided auxiliary data.
725
+ const CustomCall::UserData* user_data;
726
+
727
+ // User-provided diagnostic engine for reporting detailed errors.
728
+ const DiagnosticEngine* diagnostic;
729
+ };
730
+
731
+ template <typename T, CustomCall::RuntimeChecks checks>
732
+ ABSL_ATTRIBUTE_ALWAYS_INLINE inline FailureOr<T*> DecodeUserData(
733
+ const CustomCall::UserData* user_data) {
734
+ if (!CustomCall::CheckUserData(checks)) return user_data->get<T>();
735
+
736
+ // TODO(ezhulenev): Add an option to request nullable user data, because
737
+ // right now we do not distinguish between a user data pointer that doesn't
738
+ // exist, and a null pointer passed by the user.
739
+
740
+ // Get the requested value if user data was passed to the custom call.
741
+ auto* ptr = user_data ? user_data->getIfExists<T>() : nullptr;
742
+ if (LLVM_UNLIKELY(!ptr)) return failure();
743
+ return ptr;
744
+ }
745
+
746
+ template <typename T, CustomCall::RuntimeChecks checks>
747
+ ABSL_ATTRIBUTE_ALWAYS_INLINE inline FailureOr<T> DecodeAttr(
748
+ DecodingOffsets& offsets, absl::Span<const std::string> attrs_names,
749
+ absl::Span<const size_t> attrs_idx, internal::DecodedAttrs attrs) {
750
+ // Find decoded attribute corresponding for the given attribute index.
751
+ int64_t idx = offsets.attrs++;
752
+
753
+ // Do not check the attribute name, and decode attribute at the given index.
754
+ if (!CustomCall::CheckNames(checks)) {
755
+ size_t i = attrs_idx[idx];
756
+ return CustomCallAttrDecoding<T, checks>::Decode(
757
+ attrs[i].name, attrs[i].type_id, attrs[i].value);
758
+ }
759
+
760
+ std::string_view attr_name = attrs_names[idx];
761
+
762
+ // Given that attributes are passed to the custom call handler
763
+ // lexicographically sorted by name, we can find the attribute we are
764
+ // looking for only between the `attrs_idx` offset and the end of the
765
+ // attributes array.
766
+ for (size_t i = attrs_idx[idx]; i < attrs.size(); ++i) {
767
+ if (LLVM_LIKELY(attrs[i].name == attr_name))
768
+ return CustomCallAttrDecoding<T, checks>::Decode(
769
+ attrs[i].name, attrs[i].type_id, attrs[i].value);
770
+ }
771
+
772
+ // Attribute we were looking for was not passed as an argument.
773
+ return failure();
774
+ }
775
+
776
+ template <typename T, CustomCall::RuntimeChecks checks>
777
+ struct Decode {
778
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> call(
779
+ DecodingOffsets& offsets, DecodingContext& ctx) {
780
+ internal::DecodedArg arg = ctx.args[offsets.args++];
781
+ return CustomCallArgDecoding<T, checks>::Decode(arg.type_id, arg.value);
782
+ }
783
+ };
784
+
785
+ template <typename T, CustomCall::RuntimeChecks checks>
786
+ struct Decode<internal::Ret<T>, checks> {
787
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<Result<T>> call(
788
+ DecodingOffsets& offsets, DecodingContext& ctx) {
789
+ internal::DecodedRet ret = ctx.rets[offsets.rets++];
790
+ return CustomCallRetDecoding<T, checks>::Decode(ret.type_id, ret.value);
791
+ }
792
+ };
793
+
794
+ template <typename T, CustomCall::RuntimeChecks checks>
795
+ struct Decode<internal::Attr<T>, checks> {
796
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> call(
797
+ DecodingOffsets& offsets, DecodingContext& ctx) {
798
+ return DecodeAttr<T, checks>(offsets, ctx.attrs_names, ctx.attrs_idx,
799
+ ctx.attrs);
800
+ }
801
+ };
802
+
803
+ template <typename T, CustomCall::RuntimeChecks checks>
804
+ struct Decode<internal::UserData<T>, checks> {
805
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> call(
806
+ DecodingOffsets& offsets, DecodingContext& ctx) {
807
+ using UserDataT = std::remove_pointer_t<T>;
808
+ if (auto decoded = DecodeUserData<UserDataT, checks>(ctx.user_data);
809
+ LLVM_LIKELY(succeeded(decoded)))
810
+ return decoded;
811
+ return ctx.diagnostic->EmitError(InternalError(
812
+ "failed to decode UserData of type %s", typeid(T).name()));
813
+ }
814
+ };
815
+
816
+ template <typename T, CustomCall::RuntimeChecks checks>
817
+ struct Decode<internal::StateTag<T>, checks> {
818
+ using Snapshot = typename StateVector<T>::Snapshot;
819
+
820
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<runtime::State<T>> call(
821
+ DecodingOffsets& offsets, DecodingContext& ctx) {
822
+ // Get the state snapshot and state id from user data and attributes.
823
+ FailureOr<Snapshot*> snapshot =
824
+ DecodeUserData<Snapshot, checks>(ctx.user_data);
825
+ FailureOr<int64_t> id = DecodeAttr<int64_t, checks>(
826
+ offsets, ctx.attrs_names, ctx.attrs_idx, ctx.attrs);
827
+ if (LLVM_UNLIKELY(failed(snapshot) || failed(id))) return failure();
828
+
829
+ return (*snapshot)->state(*id);
830
+ }
831
+ };
832
+
833
+ template <typename T, CustomCall::RuntimeChecks checks>
834
+ struct Decode<internal::Value<T>, checks> {
835
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> call(
836
+ DecodingOffsets& offsets, DecodingContext& ctx) {
837
+ return std::any_cast<T>(ctx.values[offsets.values++]);
838
+ }
839
+ };
840
+
841
+ template <CustomCall::RuntimeChecks checks>
842
+ struct Decode<CustomCall::RemainingArgs, checks> {
843
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<CustomCall::RemainingArgs> call(
844
+ DecodingOffsets& offsets, DecodingContext& ctx) {
845
+ return CustomCall::RemainingArgs(ctx.args, offsets.args);
846
+ }
847
+ };
848
+
849
+ template <CustomCall::RuntimeChecks checks>
850
+ struct Decode<CustomCall::VariantArg, checks> {
851
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<CustomCall::VariantArg> call(
852
+ DecodingOffsets& offsets, DecodingContext& ctx) {
853
+ return CustomCall::VariantArg(ctx.args, offsets.args++);
854
+ }
855
+ };
856
+
857
+ } // namespace internal
858
+
859
+ // Custom call handler binds concrete custom call implementation of type `Fn` to
860
+ // the custom call function signature. `Fn` can be a function pointer, or a
861
+ // lambda.
862
+ //
863
+ // Custom call handler uses the variadic template parameter `Ts` to decode the
864
+ // opaque pointers passed to the `call` function into the C++ types that are
865
+ // forwarded to the custom call implementation.
866
+ template <CustomCall::RuntimeChecks checks, typename Fn, typename... Ts>
867
+ class CustomCallHandler : public CustomCall {
868
+ static constexpr int64_t kSize = sizeof...(Ts);
869
+ static constexpr int64_t kNumArgs = internal::NumArgs<Ts...>::value;
870
+ static constexpr int64_t kNumRets = internal::NumRets<Ts...>::value;
871
+
872
+ template <typename T>
873
+ using FnArgType = typename internal::FnArgType<T>::Type;
874
+
875
+ template <typename T>
876
+ using UnwrapRet = typename internal::UnwrapRet<T>::Type;
877
+
878
+ // Custom call can signal error using a LogicalError result.
879
+ static constexpr bool kIsLogicalErr =
880
+ std::is_invocable_r_v<LogicalResult, Fn, FnArgType<Ts>...>;
881
+
882
+ // Custom call can signal error together with a detailed error message.
883
+ static constexpr bool kIsStatusErr =
884
+ std::is_invocable_r_v<absl::Status, Fn, FnArgType<Ts>...>;
885
+
886
+ // Custom call returns results as `absl::StatusOr<std::tuple<Ts...>>`
887
+ // (multiple results) or `absl::StatusOr<T>` (single result).
888
+ template <size_t... RetsIs, size_t... ArgsIs>
889
+ static constexpr bool IsStatusOrInvocable(std::index_sequence<RetsIs...>,
890
+ std::index_sequence<ArgsIs...>) {
891
+ // Define a tuple to help extracting type by index.
892
+ using ArgsTuple = std::tuple<FnArgType<Ts>...>;
893
+
894
+ // Custom call doesn't have any results.
895
+ if constexpr (sizeof...(RetsIs) == 0) return false;
896
+
897
+ // Custom call returns a single result.
898
+ if constexpr (sizeof...(RetsIs) == 1) {
899
+ using StatusOr =
900
+ absl::StatusOr<UnwrapRet<std::tuple_element_t<RetsIs, ArgsTuple>>...>;
901
+ return std::is_invocable_r_v<StatusOr, Fn,
902
+ std::tuple_element_t<ArgsIs, ArgsTuple>...>;
903
+ }
904
+
905
+ // Custom call returns multiple results as a tuple.
906
+ if constexpr (sizeof...(RetsIs) > 1) {
907
+ using StatusOr = absl::StatusOr<
908
+ std::tuple<UnwrapRet<std::tuple_element_t<RetsIs, ArgsTuple>>...>>;
909
+ return std::is_invocable_r_v<StatusOr, Fn,
910
+ std::tuple_element_t<ArgsIs, ArgsTuple>...>;
911
+ }
912
+
913
+ llvm_unreachable("unsupported result rank");
914
+ }
915
+
916
+ static constexpr bool kIsStatusOrResult =
917
+ IsStatusOrInvocable(typename internal::IndexRets<0, Ts...>::Is{},
918
+ typename internal::IndexArgs<0, Ts...>::Is{});
919
+
920
+ static_assert(kIsLogicalErr || kIsStatusErr || kIsStatusOrResult,
921
+ "incompatible custom call handler types");
922
+
923
+ public:
924
+ std::string_view name() const final { return callee_; }
925
+
926
+ ABSL_ATTRIBUTE_ALWAYS_INLINE LogicalResult
927
+ call(void** args, void** attrs, void** rets, const UserData* user_data,
928
+ const DiagnosticEngine* diagnostic) const final {
929
+ // Decode arguments and attributes from the opaque pointers.
930
+ internal::DecodedArgs decoded_args(args);
931
+ internal::DecodedAttrs decoded_attrs(attrs);
932
+ internal::DecodedRets decoded_rets(rets);
933
+
934
+ int64_t num_args = decoded_args.size();
935
+ int64_t num_attrs = decoded_attrs.size();
936
+ int64_t num_rets = decoded_rets.size();
937
+
938
+ if (LLVM_UNLIKELY(diagnostic == nullptr))
939
+ diagnostic = DiagnosticEngine::DefaultDiagnosticEngine();
940
+
941
+ // If all runtime checks are disabled we are just reinterpreting opaque
942
+ // `args`, `attrs` and `rets` memory according to the custom call handler
943
+ // signature and skip all checks (these checks will be optimized out).
944
+ auto eval = [](bool condition) {
945
+ return checks == RuntimeChecks::kNone ? false : condition;
946
+ };
947
+
948
+ // Check that the number of passed arguments matches the signature. Each
949
+ // individual argument decoding will check the actual type.
950
+ if (internal::HasRemainingArgs<Ts...>::value) {
951
+ if (LLVM_UNLIKELY(eval(num_args < kNumArgs - 1)))
952
+ return diagnostic->EmitError(InvalidArgument(
953
+ "Wrong number of arguments: expected at least %d got %d",
954
+ kNumArgs - 1, num_args));
955
+ } else {
956
+ if (LLVM_UNLIKELY(eval(num_args != kNumArgs)))
957
+ return diagnostic->EmitError(
958
+ InvalidArgument("Wrong number of arguments: expected %d got %d",
959
+ kNumArgs, num_args));
960
+ }
961
+
962
+ // Check that the number of returns matches the signature. The return
963
+ // decoding will check the actual type.
964
+ if (LLVM_UNLIKELY(eval(num_rets != kNumRets)))
965
+ return diagnostic->EmitError(InvalidArgument(
966
+ "Wrong number of returns: expected %d got %d", kNumRets, num_rets));
967
+
968
+ // Check that we have a correct number of attributes passed to the custom
969
+ // call. Each individual attribute decoding will check the name and the
970
+ // type of the attribute.
971
+ if (LLVM_UNLIKELY(eval(opts_.exact_attrs ? num_attrs != num_encoded_attrs_
972
+ : num_attrs < num_encoded_attrs_)))
973
+ return diagnostic->EmitError(InvalidArgument(
974
+ "Wrong number of attributes: expected %s%d got %d",
975
+ opts_.exact_attrs ? "" : "at least ", num_encoded_attrs_, num_attrs));
976
+
977
+ // Define index sequences to access custom call operands.
978
+ using Is = std::make_index_sequence<kSize>;
979
+ using ArgsIs = typename internal::IndexArgs<0, Ts...>::Is;
980
+ using RetsIs = typename internal::IndexRets<0, Ts...>::Is;
981
+
982
+ return call(decoded_args, decoded_attrs, decoded_rets, user_data,
983
+ diagnostic, Is{}, ArgsIs{}, RetsIs{});
984
+ }
985
+
986
+ template <size_t... Is, size_t... ArgsIs, size_t... RetsIs>
987
+ ABSL_ATTRIBUTE_ALWAYS_INLINE LogicalResult
988
+ call(internal::DecodedArgs args, internal::DecodedAttrs attrs,
989
+ internal::DecodedRets rets, const UserData* user_data,
990
+ const DiagnosticEngine* diagnostic, std::index_sequence<Is...>,
991
+ std::index_sequence<ArgsIs...>, std::index_sequence<RetsIs...>) const {
992
+ // A helper structure to allow each decoder find the correct offset in the
993
+ // arguments, attributes or results.
994
+ internal::DecodingOffsets offsets;
995
+
996
+ // Package all the data required for decoding custom call operands.
997
+ internal::DecodingContext ctx{args, rets, attrs, attrs_,
998
+ attrs_idx_, values_, user_data, diagnostic};
999
+
1000
+ // Decode all operands into FailureOr containers. It is guaranteed
1001
+ // that initializer list will be evaluated left-to-right, and we can rely
1002
+ // on correct offsets computation.
1003
+ std::tuple<FailureOr<FnArgType<Ts>>...> fn_args = {
1004
+ internal::Decode<Ts, checks>::call(offsets, ctx)...};
1005
+
1006
+ // Check if all operands and results were decoded.
1007
+ bool all_decoded = (succeeded(std::get<Is>(fn_args)) && ...);
1008
+
1009
+ if (LLVM_UNLIKELY(!all_decoded)) {
1010
+ std::array<bool, kSize> decoded = {succeeded(std::get<Is>(fn_args))...};
1011
+ auto bad_args = llvm::make_filter_range(
1012
+ llvm::enumerate(decoded), [](auto pair) { return !pair.value(); });
1013
+ auto to_str = [](auto pair) { return std::to_string(pair.index()); };
1014
+
1015
+ return diagnostic->EmitError(InvalidArgument(
1016
+ "Failed to decode all custom call operands (bad operads at: %s)",
1017
+ llvm::join(llvm::map_range(bad_args, to_str), ", ")));
1018
+ }
1019
+
1020
+ // Custom call returns logical result to signal failures.
1021
+ if constexpr (kIsLogicalErr) {
1022
+ return fn_(std::move(*std::get<Is>(fn_args))...);
1023
+ }
1024
+
1025
+ // Custom call returns detailed error to signal failures.
1026
+ if constexpr (kIsStatusErr) {
1027
+ if (auto st = fn_(std::move(*std::get<Is>(fn_args))...); !st.ok()) {
1028
+ return diagnostic->EmitError(std::move(st));
1029
+ }
1030
+ return success();
1031
+ }
1032
+
1033
+ // Custom call returns result(s) as `absl::StatusOr`.
1034
+ if constexpr (kIsStatusOrResult) {
1035
+ auto status_or = fn_(std::move(*std::get<ArgsIs>(fn_args))...);
1036
+ if (!status_or.ok()) {
1037
+ return diagnostic->EmitError(status_or.status());
1038
+ }
1039
+
1040
+ static_assert(sizeof...(RetsIs) >= 1, "unsupported number or results");
1041
+
1042
+ if constexpr (sizeof...(RetsIs) == 1) {
1043
+ (*std::get<RetsIs...>(fn_args)).Set(status_or.value());
1044
+ return success();
1045
+ }
1046
+
1047
+ if constexpr (sizeof...(RetsIs) > 1) {
1048
+ using ResultIs = std::make_index_sequence<kNumRets>;
1049
+ internal::SetResultsFromTuple<RetsIs...>(ResultIs{}, std::move(fn_args),
1050
+ std::move(status_or.value()));
1051
+ return success();
1052
+ }
1053
+ }
1054
+
1055
+ llvm_unreachable("unexpected custom call type");
1056
+ }
1057
+
1058
+ private:
1059
+ template <typename...>
1060
+ friend class CustomCallBinding;
1061
+
1062
+ CustomCallHandler(Fn fn, std::string callee, std::vector<std::string> attrs,
1063
+ std::vector<std::any> values, const Options& opts)
1064
+ : fn_(std::move(fn)),
1065
+ callee_(std::move(callee)),
1066
+ attrs_(std::move(attrs)),
1067
+ values_(std::move(values)),
1068
+ opts_(opts),
1069
+ attrs_idx_(attrs_.size()) {
1070
+ // Sort attributes names and remove duplicates. These unique attributes are
1071
+ // what we'll be looking for in the encoded custom call attributes.
1072
+ std::vector<std::string> sorted = attrs_;
1073
+ std::sort(sorted.begin(), sorted.end());
1074
+ sorted.erase(
1075
+ std::unique(sorted.begin(), sorted.end(), std::equal_to<std::string>()),
1076
+ sorted.end());
1077
+ num_encoded_attrs_ = sorted.size();
1078
+
1079
+ // Find index or every attribute in the sorted attributes vector.
1080
+ for (size_t i = 0; i < attrs_.size(); ++i) {
1081
+ std::string_view attr = attrs_[i];
1082
+ attrs_idx_[i] = std::distance(sorted.begin(), llvm::find(sorted, attr));
1083
+ }
1084
+ }
1085
+
1086
+ Fn fn_;
1087
+ std::string callee_;
1088
+ std::vector<std::string> attrs_;
1089
+ std::vector<std::any> values_;
1090
+ Options opts_;
1091
+
1092
+ // A mapping from the attribute index to its index in the lexicographically
1093
+ // sorter vector of attribute names. Attributes passed in the custom call
1094
+ // handler sorted by the name, we use this index to efficiently find the
1095
+ // decoded attribute entry.
1096
+ std::vector<size_t> attrs_idx_;
1097
+
1098
+ // The number of attributes we expect in the encoded custom call arguments.
1099
+ // This is not the same as `attrs_.size()` because of potential duplicates,
1100
+ // e.g. attribute corresponding to state id might be used multiple times.
1101
+ size_t num_encoded_attrs_;
1102
+ };
1103
+
1104
+ template <CustomCall::RuntimeChecks checks, typename Fn, typename... Ts>
1105
+ constexpr int64_t CustomCallHandler<checks, Fn, Ts...>::kSize;
1106
+
1107
+ template <CustomCall::RuntimeChecks checks, typename Fn, typename... Ts>
1108
+ constexpr int64_t CustomCallHandler<checks, Fn, Ts...>::kNumArgs;
1109
+
1110
+ template <CustomCall::RuntimeChecks checks, typename Fn, typename... Ts>
1111
+ constexpr int64_t CustomCallHandler<checks, Fn, Ts...>::kNumRets;
1112
+
1113
+ //===----------------------------------------------------------------------===//
1114
+ // Custom arguments decoding.
1115
+ //===----------------------------------------------------------------------===//
1116
+
1117
+ llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const StridedMemrefView&);
1118
+ llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const MemrefView&);
1119
+ llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const FlatMemrefView&);
1120
+
1121
+ template <CustomCall::RuntimeChecks checks>
1122
+ struct CustomCallArgDecoding<StridedMemrefView, checks> {
1123
+ using EncodedMemref = internal::EncodedMemref;
1124
+
1125
+ ABSL_ATTRIBUTE_ALWAYS_INLINE
1126
+ static FailureOr<StridedMemrefView> Decode(TypeID type_id, void* value) {
1127
+ if (!CustomCall::Isa<MemrefView, StridedMemrefView>(checks, type_id)) {
1128
+ return failure();
1129
+ }
1130
+
1131
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1132
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1133
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(
1134
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1135
+
1136
+ PrimitiveType dtype = static_cast<PrimitiveType>(encoded->dtype);
1137
+ return StridedMemrefView{dtype,
1138
+ encoded->data,
1139
+ {encoded->dims, encoded->rank},
1140
+ {encoded->dims + encoded->rank, encoded->rank}};
1141
+ }
1142
+ };
1143
+
1144
+ template <CustomCall::RuntimeChecks checks>
1145
+ struct CustomCallArgDecoding<MemrefView, checks> {
1146
+ using EncodedMemref = internal::EncodedMemref;
1147
+
1148
+ ABSL_ATTRIBUTE_ALWAYS_INLINE
1149
+ static FailureOr<MemrefView> Decode(TypeID type_id, void* value) {
1150
+ if (!CustomCall::Isa<MemrefView>(checks, type_id)) {
1151
+ return failure();
1152
+ }
1153
+
1154
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1155
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1156
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(
1157
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1158
+
1159
+ PrimitiveType dtype = static_cast<PrimitiveType>(encoded->dtype);
1160
+ return MemrefView{dtype, encoded->data, {encoded->dims, encoded->rank}};
1161
+ }
1162
+ };
1163
+
1164
+ template <CustomCall::RuntimeChecks checks>
1165
+ struct CustomCallArgDecoding<FlatMemrefView, checks> {
1166
+ using EncodedMemref = internal::EncodedMemref;
1167
+
1168
+ ABSL_ATTRIBUTE_ALWAYS_INLINE
1169
+ static FailureOr<FlatMemrefView> Decode(TypeID type_id, void* value) {
1170
+ if (!CustomCall::Isa<MemrefView>(checks, type_id)) {
1171
+ return failure();
1172
+ }
1173
+
1174
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1175
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1176
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(
1177
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1178
+
1179
+ PrimitiveType dtype = static_cast<PrimitiveType>(encoded->dtype);
1180
+ int64_t size_in_bytes = primitive_util::ByteWidth(dtype);
1181
+ for (int d = 0; d < encoded->rank; ++d) size_in_bytes *= encoded->dims[d];
1182
+ return FlatMemrefView{dtype, encoded->data, size_in_bytes};
1183
+ }
1184
+ };
1185
+
1186
+ #define XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(T) \
1187
+ template <CustomCall::RuntimeChecks checks> \
1188
+ struct CustomCallArgDecoding<T, checks> { \
1189
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode(TypeID type_id, \
1190
+ void* value) { \
1191
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1192
+ return failure(); \
1193
+ } \
1194
+ \
1195
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(T)); \
1196
+ return *reinterpret_cast<T*>(value); \
1197
+ } \
1198
+ }
1199
+
1200
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(bool);
1201
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int8_t);
1202
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int16_t);
1203
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int32_t);
1204
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(int64_t);
1205
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(float);
1206
+ XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING(double);
1207
+
1208
+ #undef XLA_RUNTIME_REGISTER_SCALAR_ARG_DECODING
1209
+
1210
+ // Register decoding for special floating point types defined in Eigen.
1211
+ #define XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING(T, STORAGE) \
1212
+ template <CustomCall::RuntimeChecks checks> \
1213
+ struct CustomCallArgDecoding<T, checks> { \
1214
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode(TypeID type_id, \
1215
+ void* value) { \
1216
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1217
+ return failure(); \
1218
+ } \
1219
+ \
1220
+ auto* src = reinterpret_cast<STORAGE*>(value); \
1221
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(STORAGE)); \
1222
+ return Eigen::numext::bit_cast<T>(*src); \
1223
+ } \
1224
+ }
1225
+
1226
+ XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING(Eigen::bfloat16, uint16_t);
1227
+ XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING(Eigen::half, uint16_t);
1228
+
1229
+ #undef XLA_RUNTIME_REGISTER_EIGEN_FP_ARG_DECODING
1230
+
1231
+ //===----------------------------------------------------------------------===//
1232
+ // Opaque arguments at run time passed as pointers and decoded by wrapping them
1233
+ // into a reference type, for example `AsyncValue *` pointer can be wrapped into
1234
+ // a typed `AsyncValuePtr<T>` pointer wrapper.
1235
+ //===----------------------------------------------------------------------===//
1236
+
1237
+ #define XLA_RUNTIME_REGISTER_OPAQUE_ARG_DECODING(T, PTR) \
1238
+ template <CustomCall::RuntimeChecks checks> \
1239
+ struct CustomCallArgDecoding<T, checks> { \
1240
+ static_assert(std::is_pointer_v<PTR>, "must be a pointer"); \
1241
+ static_assert(std::is_trivially_destructible_v<T>, \
1242
+ "must be a trivially destructible reference type"); \
1243
+ \
1244
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode(TypeID type_id, \
1245
+ void* value) { \
1246
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1247
+ return failure(); \
1248
+ } \
1249
+ \
1250
+ auto* src = reinterpret_cast<PTR*>(value); \
1251
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(PTR)); \
1252
+ T ref{*src}; \
1253
+ return std::move(ref); \
1254
+ } \
1255
+ }
1256
+
1257
+ XLA_RUNTIME_REGISTER_OPAQUE_ARG_DECODING(void*, void*);
1258
+
1259
+ //===----------------------------------------------------------------------===//
1260
+ // Custom call results decoding.
1261
+ //===----------------------------------------------------------------------===//
1262
+
1263
+ #define XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(T) \
1264
+ template <> \
1265
+ class Result<T> { \
1266
+ public: \
1267
+ explicit Result(T* storage) : storage_(storage) {} \
1268
+ void Set(T value) { *storage_ = value; } \
1269
+ \
1270
+ private: \
1271
+ T* storage_; \
1272
+ }; \
1273
+ \
1274
+ template <CustomCall::RuntimeChecks checks> \
1275
+ struct CustomCallRetDecoding<T, checks> { \
1276
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<Result<T>> Decode( \
1277
+ TypeID type_id, void* value) { \
1278
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1279
+ return failure(); \
1280
+ } \
1281
+ \
1282
+ return Result<T>(reinterpret_cast<T*>(value)); \
1283
+ } \
1284
+ };
1285
+
1286
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(bool);
1287
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int8_t);
1288
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int16_t);
1289
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int32_t);
1290
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(int64_t);
1291
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(float);
1292
+ XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING(double);
1293
+
1294
+ #undef XLA_RUNTIME_REGISTER_SCALAR_RET_DECODING
1295
+
1296
+ //===----------------------------------------------------------------------===//
1297
+ // Opaque results at run time passed as pointers, and a typed wrapper binds
1298
+ // together the reference type and the underlying pointer type.
1299
+ //===----------------------------------------------------------------------===//
1300
+
1301
+ #define XLA_RUNTIME_REGISTER_OPAQUE_RET_DECODING(T, PTR) \
1302
+ template <> \
1303
+ class Result<T> { \
1304
+ static_assert(std::is_pointer_v<PTR>, "must be a pointer type"); \
1305
+ \
1306
+ public: \
1307
+ explicit Result(PTR* storage) : storage_(storage) {} \
1308
+ void Set(PTR value) { *storage_ = value; } \
1309
+ \
1310
+ private: \
1311
+ PTR* storage_; \
1312
+ }; \
1313
+ \
1314
+ template <CustomCall::RuntimeChecks checks> \
1315
+ struct CustomCallRetDecoding<T, checks> { \
1316
+ static_assert(std::is_pointer_v<PTR>, "must be a pointer type"); \
1317
+ \
1318
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<Result<T>> Decode( \
1319
+ TypeID type_id, void* value) { \
1320
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1321
+ return failure(); \
1322
+ } \
1323
+ \
1324
+ return Result<T>(reinterpret_cast<PTR*>(value)); \
1325
+ } \
1326
+ };
1327
+
1328
+ XLA_RUNTIME_REGISTER_OPAQUE_RET_DECODING(void*, void*);
1329
+
1330
+ //===----------------------------------------------------------------------===//
1331
+
1332
+ // Custom call memref result decoding
1333
+ template <>
1334
+ class Result<MemrefView> {
1335
+ using EncodedMemref = internal::EncodedMemref;
1336
+
1337
+ public:
1338
+ explicit Result(EncodedMemref* storage) : storage_(storage) {}
1339
+ void Set(MemrefView value) {
1340
+ assert(IsCompatible(value) &&
1341
+ "Custom call return types is not compatible with types in MLIR");
1342
+ storage_->data = value.data;
1343
+ for (unsigned i = 0; i < storage_->rank; ++i) {
1344
+ storage_->dims[i] = value.sizes[i];
1345
+ }
1346
+ }
1347
+
1348
+ PrimitiveType GetDType() { return PrimitiveType{storage_->dtype}; }
1349
+ absl::Span<const int64_t> GetDims() {
1350
+ return absl::Span<const int64_t>(storage_->dims, storage_->rank);
1351
+ }
1352
+
1353
+ private:
1354
+ bool IsCompatible(MemrefView value) {
1355
+ bool is_compatible =
1356
+ storage_->dtype == value.dtype && storage_->rank == value.sizes.size();
1357
+ if (!is_compatible) return false;
1358
+
1359
+ for (unsigned i = 0; i < storage_->rank; ++i) {
1360
+ is_compatible = (storage_->dims[i] == value.sizes[i]) ||
1361
+ (storage_->dims[i] == /*MemrefType::kDynamic=*/-1);
1362
+ }
1363
+ return is_compatible;
1364
+ }
1365
+
1366
+ EncodedMemref* storage_;
1367
+ };
1368
+
1369
+ template <CustomCall::RuntimeChecks checks>
1370
+ struct CustomCallRetDecoding<MemrefView, checks> {
1371
+ using EncodedMemref = internal::EncodedMemref;
1372
+
1373
+ ABSL_ATTRIBUTE_ALWAYS_INLINE
1374
+ static FailureOr<Result<MemrefView>> Decode(TypeID type_id, void* value) {
1375
+ if (!CustomCall::Isa<MemrefView>(checks, type_id)) return failure();
1376
+
1377
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1378
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1379
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(
1380
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1381
+ return Result<MemrefView>(encoded);
1382
+ }
1383
+ };
1384
+
1385
+ //===----------------------------------------------------------------------===//
1386
+
1387
+ // Custom call AsyncValueRef result decoding
1388
+ #define XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(T) \
1389
+ template <> \
1390
+ class Result<tsl::AsyncValueRef<T>> { \
1391
+ public: \
1392
+ explicit Result(void** storage) : storage_(storage) {} \
1393
+ void Set(tsl::AsyncValueRef<T> value) { \
1394
+ auto write = [](const T* v, std::byte* store) { \
1395
+ T* store_t = reinterpret_cast<T*>(store); \
1396
+ *store_t = *v; \
1397
+ }; \
1398
+ *storage_ = runtime::AsyncRuntime::AsValue<T>( \
1399
+ value, sizeof(T), alignof(std::max_align_t), write); \
1400
+ } \
1401
+ \
1402
+ private: \
1403
+ void** storage_; \
1404
+ }; \
1405
+ \
1406
+ template <CustomCall::RuntimeChecks checks> \
1407
+ struct CustomCallRetDecoding<tsl::AsyncValueRef<T>, checks> { \
1408
+ LLVM_ATTRIBUTE_ALWAYS_INLINE \
1409
+ static FailureOr<Result<tsl::AsyncValueRef<T>>> Decode(TypeID type_id, \
1410
+ void* value) { \
1411
+ if (!CustomCall::Isa<tsl::AsyncValueRef<T>>(checks, type_id)) \
1412
+ return failure(); \
1413
+ return Result<tsl::AsyncValueRef<T>>(reinterpret_cast<void**>(value)); \
1414
+ } \
1415
+ };
1416
+
1417
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(bool);
1418
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int8_t);
1419
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int16_t);
1420
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int32_t);
1421
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(int64_t);
1422
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(float);
1423
+ XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING(double);
1424
+
1425
+ #undef XLA_RUNTIME_REGISTER_ASYNC_SCALAR_VALUE_RET_DECODING
1426
+
1427
+ template <>
1428
+ class Result<tsl::AsyncValueRef<tsl::Chain>> {
1429
+ public:
1430
+ explicit Result(void** storage) : storage_(storage) {}
1431
+ void Set(tsl::AsyncValueRef<tsl::Chain> value) {
1432
+ *storage_ = runtime::AsyncRuntime::AsToken(value);
1433
+ }
1434
+
1435
+ private:
1436
+ void** storage_;
1437
+ };
1438
+
1439
+ template <CustomCall::RuntimeChecks checks>
1440
+ struct CustomCallRetDecoding<tsl::AsyncValueRef<tsl::Chain>, checks> {
1441
+ LLVM_ATTRIBUTE_ALWAYS_INLINE
1442
+ static FailureOr<Result<tsl::AsyncValueRef<tsl::Chain>>> Decode(
1443
+ TypeID type_id, void* value) {
1444
+ if (!CustomCall::Isa<tsl::AsyncValueRef<tsl::Chain>>(checks, type_id))
1445
+ return failure();
1446
+
1447
+ return Result<tsl::AsyncValueRef<tsl::Chain>>(
1448
+ reinterpret_cast<void**>(value));
1449
+ }
1450
+ };
1451
+
1452
+ template <>
1453
+ class Result<tsl::AsyncValueRef<MemrefView>> {
1454
+ using EncodedMemref = internal::EncodedMemref;
1455
+
1456
+ struct MemrefDescriptor {
1457
+ void* allocated_ptr;
1458
+ void* aligned_ptr;
1459
+ int64_t offset;
1460
+ int64_t dims[];
1461
+ };
1462
+
1463
+ public:
1464
+ explicit Result(EncodedMemref* storage) : storage_(storage) {}
1465
+ void Set(tsl::AsyncValueRef<MemrefView> value) {
1466
+ auto write = [this](const MemrefView* view, std::byte* store) {
1467
+ assert(IsCompatible(*view) &&
1468
+ "Custom call return types is not compatible with types in MLIR");
1469
+ MemrefDescriptor* store_t = reinterpret_cast<MemrefDescriptor*>(store);
1470
+ store_t->allocated_ptr = view->data;
1471
+ store_t->aligned_ptr = view->data;
1472
+ store_t->offset = 0;
1473
+ for (unsigned i = 0; i < storage_->rank; ++i) {
1474
+ store_t->dims[i] = view->sizes[i];
1475
+ }
1476
+ };
1477
+ storage_->data = runtime::AsyncRuntime::AsValue<MemrefView>(
1478
+ value, 3 * sizeof(int64_t) + 2 * storage_->rank * sizeof(int64_t),
1479
+ alignof(std::max_align_t), write);
1480
+ }
1481
+
1482
+ PrimitiveType GetDType() { return PrimitiveType{storage_->dtype}; }
1483
+ absl::Span<const int64_t> GetDims() {
1484
+ return absl::Span<const int64_t>(storage_->dims, storage_->rank);
1485
+ }
1486
+
1487
+ private:
1488
+ bool IsCompatible(MemrefView value) {
1489
+ bool is_compatible =
1490
+ storage_->dtype == value.dtype && storage_->rank == value.sizes.size();
1491
+ if (!is_compatible) return false;
1492
+
1493
+ for (unsigned i = 0; i < storage_->rank; ++i) {
1494
+ is_compatible = (storage_->dims[i] == value.sizes[i]) ||
1495
+ (storage_->dims[i] == /*MemrefType::kDynamic=*/-1);
1496
+ }
1497
+
1498
+ return is_compatible;
1499
+ }
1500
+
1501
+ EncodedMemref* storage_;
1502
+ };
1503
+
1504
+ template <CustomCall::RuntimeChecks checks>
1505
+ struct CustomCallRetDecoding<tsl::AsyncValueRef<MemrefView>, checks> {
1506
+ using EncodedMemref = internal::EncodedMemref;
1507
+
1508
+ LLVM_ATTRIBUTE_ALWAYS_INLINE
1509
+ static FailureOr<Result<tsl::AsyncValueRef<MemrefView>>> Decode(
1510
+ TypeID type_id, void* value) {
1511
+ if (!CustomCall::Isa<tsl::AsyncValueRef<MemrefView>>(checks, type_id))
1512
+ return failure();
1513
+
1514
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1515
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1516
+ ABSL_ANNOTATE_MEMORY_IS_INITIALIZED(
1517
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1518
+
1519
+ return Result<tsl::AsyncValueRef<MemrefView>>(encoded);
1520
+ }
1521
+ };
1522
+
1523
+ // XLA_RUNTIME_REGISTER_ASYNC_VALUE_RET_DECODING(MemrefView);
1524
+
1525
+ //===----------------------------------------------------------------------===//
1526
+ // Custom call attributes decoding.
1527
+ //===----------------------------------------------------------------------===//
1528
+
1529
+ template <CustomCall::RuntimeChecks checks>
1530
+ struct CustomCallAttrDecoding<std::string_view, checks> {
1531
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<std::string_view> Decode(
1532
+ std::string_view name, TypeID type_id, void* value) {
1533
+ if (!CustomCall::Isa<std::string_view>(checks, type_id)) {
1534
+ return failure();
1535
+ }
1536
+
1537
+ auto* encoded = reinterpret_cast<internal::EncodedArray<char>*>(value);
1538
+ return std::string_view(encoded->data, encoded->size);
1539
+ }
1540
+ };
1541
+
1542
+ template <CustomCall::RuntimeChecks checks>
1543
+ struct CustomCallAttrDecoding<CustomCall::FunctionOrdinal, checks> {
1544
+ using FunctionOrdinal = CustomCall::FunctionOrdinal;
1545
+
1546
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<FunctionOrdinal> Decode(
1547
+ std::string_view name, TypeID type_id, void* value) {
1548
+ if (!CustomCall::Isa<FunctionOrdinal>(checks, type_id)) {
1549
+ return failure();
1550
+ }
1551
+
1552
+ unsigned ordinal = *reinterpret_cast<int32_t*>(value);
1553
+ return FunctionOrdinal{ordinal};
1554
+ }
1555
+ };
1556
+
1557
+ template <typename T, CustomCall::RuntimeChecks checks>
1558
+ struct CustomCallAttrDecoding<std::optional<T>, checks> {
1559
+ using ValueDecoding = CustomCallAttrDecoding<T, checks>;
1560
+
1561
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<std::optional<T>> Decode(
1562
+ std::string_view name, TypeID type_id, void* value) {
1563
+ // Convert nullptr to empty optional.
1564
+ bool is_nullopt = CustomCall::Isa<std::nullopt_t>(checks, type_id);
1565
+ if (is_nullopt && value == nullptr) return std::optional<T>();
1566
+
1567
+ // Try to decode the underlying value if it is present.
1568
+ if (auto decoded = ValueDecoding::Decode(name, type_id, value);
1569
+ succeeded(decoded)) {
1570
+ return std::optional<T>(std::move(*decoded));
1571
+ }
1572
+ return failure();
1573
+ }
1574
+ };
1575
+
1576
+ template <CustomCall::RuntimeChecks checks>
1577
+ struct CustomCallAttrDecoding<CustomCall::VariantAttr, checks> {
1578
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<CustomCall::VariantAttr> Decode(
1579
+ std::string_view name, TypeID type_id, void* value) {
1580
+ return CustomCall::VariantAttr(name, type_id, value);
1581
+ }
1582
+ };
1583
+
1584
+ #define XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(T) \
1585
+ template <CustomCall::RuntimeChecks checks> \
1586
+ struct CustomCallAttrDecoding<T, checks> { \
1587
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode( \
1588
+ std::string_view name, TypeID type_id, void* value) { \
1589
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1590
+ return failure(); \
1591
+ } \
1592
+ \
1593
+ return *reinterpret_cast<T*>(value); \
1594
+ } \
1595
+ }
1596
+
1597
+ XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(bool);
1598
+ XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(int32_t);
1599
+ XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(int64_t);
1600
+ XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(float);
1601
+ XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING(double);
1602
+
1603
+ #undef XLA_RUNTIME_REGISTER_SCALAR_ATTR_DECODING
1604
+
1605
+ // A type tag to represent empty arrays of unknown element type.
1606
+ struct EmptyArray {};
1607
+
1608
+ // Both EncodedArray and 1-D EncodedDenseElements can be decoded as an
1609
+ // absl::Span. Pointers to both EncodedArray and 1-D EncodedDenseElements
1610
+ // can be dereferenced as a pointer to EncodedArray.
1611
+ #define XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(T) \
1612
+ template <CustomCall::RuntimeChecks checks> \
1613
+ struct CustomCallAttrDecoding<absl::Span<const T>, checks> { \
1614
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<absl::Span<const T>> Decode( \
1615
+ std::string_view name, TypeID type_id, void* value) { \
1616
+ if (!CustomCall::Isa<absl::Span<const T>, CustomCall::TensorRef<T>, \
1617
+ EmptyArray>(checks, type_id)) { \
1618
+ return failure(); \
1619
+ } \
1620
+ \
1621
+ auto* encoded = reinterpret_cast<internal::EncodedArray<T>*>(value); \
1622
+ return absl::Span<const T>(encoded->data, encoded->size); \
1623
+ } \
1624
+ }
1625
+
1626
+ XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(int32_t);
1627
+ XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(int64_t);
1628
+ XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(float);
1629
+ XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING(double);
1630
+
1631
+ #undef XLA_RUNTIME_REGISTER_ARRAY_ATTR_DECODING
1632
+
1633
+ #define XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(T) \
1634
+ template <CustomCall::RuntimeChecks checks> \
1635
+ struct CustomCallAttrDecoding<CustomCall::TensorRef<T>, checks> { \
1636
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<CustomCall::TensorRef<T>> \
1637
+ Decode(std::string_view name, TypeID type_id, void* value) { \
1638
+ if (!CustomCall::Isa<CustomCall::TensorRef<T>>(checks, type_id)) { \
1639
+ return failure(); \
1640
+ } \
1641
+ \
1642
+ auto* encoded = \
1643
+ reinterpret_cast<internal::EncodedDenseElements<T>*>(value); \
1644
+ auto payload = encoded->payload; \
1645
+ absl::Span<const T> data(payload.data, payload.size); \
1646
+ absl::Span<const int64_t> shape(encoded->shape, encoded->rank); \
1647
+ return CustomCall::TensorRef<T>({shape, data}); \
1648
+ } \
1649
+ }
1650
+
1651
+ XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(int32_t);
1652
+ XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(int64_t);
1653
+ XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(float);
1654
+ XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING(double);
1655
+
1656
+ #undef XLA_RUNTIME_REGISTER_DENSE_ELEMENTS_ATTR_DECODING
1657
+
1658
+ //===----------------------------------------------------------------------===//
1659
+ // Register an XLA custom call attribute decoding for enum class. At runtime the
1660
+ // value should be passed as the underlying enum type.
1661
+ //===----------------------------------------------------------------------===//
1662
+
1663
+ // Example: register decoding for a user-defined enum class
1664
+ //
1665
+ // enum class MyEnumType { kFoo, kBar, kBaz };
1666
+ //
1667
+ // XLA_RUNTIME_REGISTER_ENUM_ATTR_DECODING(MyEnumType);
1668
+ //
1669
+ #define XLA_RUNTIME_REGISTER_ENUM_ATTR_DECODING(T) \
1670
+ template <CustomCall::RuntimeChecks checks> \
1671
+ struct CustomCallAttrDecoding<T, checks> { \
1672
+ static_assert(std::is_enum<T>::value, "expected enum class"); \
1673
+ using U = std::underlying_type_t<T>; \
1674
+ \
1675
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode( \
1676
+ std::string_view name, TypeID type_id, void* value) { \
1677
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1678
+ return failure(); \
1679
+ } \
1680
+ \
1681
+ return static_cast<T>(*reinterpret_cast<U*>(value)); \
1682
+ } \
1683
+ }
1684
+
1685
+ //===----------------------------------------------------------------------===//
1686
+ // Register an XLA custom call attribute decoding for aggregate attributes.
1687
+ //===----------------------------------------------------------------------===//
1688
+
1689
+ template <typename T>
1690
+ struct AggregateMember {
1691
+ using Type = T;
1692
+
1693
+ explicit AggregateMember(std::string_view name) : name(name) {}
1694
+ std::string_view name;
1695
+ };
1696
+
1697
+ // Example: register decoding for a user-defined struct
1698
+ //
1699
+ // struct PairOfI64 { int64_t a; int64_t b; };
1700
+ //
1701
+ // XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING(
1702
+ // PairOfI64,
1703
+ // AggregateMember<int64_t>("a"),
1704
+ // AggregateMember<int64_t>("b"));
1705
+ //
1706
+ #define XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING(T, ...) \
1707
+ template <CustomCall::RuntimeChecks checks> \
1708
+ struct CustomCallAttrDecoding<T, checks> { \
1709
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode( \
1710
+ std::string_view name, TypeID type_id, void* value) { \
1711
+ if (!CustomCall::Isa<T>(checks, type_id)) { \
1712
+ return failure(); \
1713
+ } \
1714
+ \
1715
+ auto decoder = internal::AggregateDecoder<T, checks>(__VA_ARGS__); \
1716
+ return decltype(decoder)::Decode(reinterpret_cast<void**>(value), \
1717
+ internal::AggregateNames(__VA_ARGS__)); \
1718
+ } \
1719
+ }
1720
+
1721
+ namespace internal {
1722
+ // Decodes aggregate attribute into the object of type `T` that must be
1723
+ // constructible from the `Ts` types.
1724
+ template <typename T, CustomCall::RuntimeChecks checks, typename... Ts>
1725
+ struct DecodeAggregateAttr {
1726
+ static constexpr size_t kSize = sizeof...(Ts);
1727
+
1728
+ using RuntimeChecks = CustomCall::RuntimeChecks;
1729
+
1730
+ ABSL_ATTRIBUTE_ALWAYS_INLINE
1731
+ static FailureOr<T> Decode(void** value,
1732
+ std::array<std::string_view, kSize> names) {
1733
+ internal::DecodedAttrs attrs(value);
1734
+ return Decode(attrs, names, std::make_index_sequence<kSize>{});
1735
+ }
1736
+
1737
+ template <size_t... Is>
1738
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<T> Decode(
1739
+ internal::DecodedAttrs attrs, std::array<std::string_view, kSize> names,
1740
+ std::index_sequence<Is...>) {
1741
+ // Check that the number of encoded attributes matches the signature.
1742
+ if (checks != RuntimeChecks::kNone && kSize != attrs.size())
1743
+ return failure();
1744
+
1745
+ // Check that aggregate member names match the expected names.
1746
+ if (CustomCall::CheckNames(checks)) {
1747
+ for (unsigned i = 0; i < kSize; ++i)
1748
+ if (attrs[i].name != names[i]) return failure();
1749
+ }
1750
+
1751
+ // Decode all arguments into FailureOr containers. It is guaranteed
1752
+ // that initializer list will be evaluated left-to-right, and we can rely
1753
+ // on correct offsets computation.
1754
+ std::tuple<FailureOr<Ts>...> members = {
1755
+ CustomCallAttrDecoding<Ts, checks>::Decode(
1756
+ attrs[Is].name, attrs[Is].type_id, attrs[Is].value)...};
1757
+
1758
+ bool all_decoded = (succeeded(std::get<Is>(members)) && ...);
1759
+ if (LLVM_UNLIKELY(!all_decoded)) return failure();
1760
+
1761
+ // Forward unpacked members to the type constructor.
1762
+ return T{std::move(*std::get<Is>(members))...};
1763
+ }
1764
+ };
1765
+
1766
+ template <typename... Members>
1767
+ auto AggregateNames(Members... m) {
1768
+ return std::array<std::string_view, sizeof...(Members)>{m.name...};
1769
+ }
1770
+
1771
+ template <typename T, CustomCall::RuntimeChecks checks, typename... Members>
1772
+ auto AggregateDecoder(Members... m) {
1773
+ return DecodeAggregateAttr<T, checks, typename Members::Type...>();
1774
+ }
1775
+
1776
+ } // namespace internal
1777
+
1778
+ //===----------------------------------------------------------------------===//
1779
+ // Register an XLA custom call attribute decoding for dictionary attributes.
1780
+ //===----------------------------------------------------------------------===//
1781
+
1782
+ // Dictionary attributes are encoded using the same scheme as aggregate
1783
+ // attributes and as custom call attributes: <type_id, name, data> x length.
1784
+ class Dictionary {
1785
+ using RuntimeChecks = CustomCall::RuntimeChecks;
1786
+
1787
+ public:
1788
+ explicit Dictionary(internal::DecodedAttrs attrs) : attrs_(attrs) {}
1789
+
1790
+ int64_t size() { return attrs_.size(); }
1791
+
1792
+ std::vector<std::string_view> keys() {
1793
+ std::vector<std::string_view> attr_keys(attrs_.size());
1794
+ for (int64_t i = 0; i < attrs_.size(); ++i) {
1795
+ attr_keys[i] = attrs_[i].name;
1796
+ }
1797
+ return attr_keys;
1798
+ }
1799
+
1800
+ template <typename T, RuntimeChecks checks = RuntimeChecks::kDefault>
1801
+ ABSL_ATTRIBUTE_ALWAYS_INLINE FailureOr<T> get(std::string_view name) const {
1802
+ // TODO(ezhulenev): Use `std::binary_search` because it's guaranteed that
1803
+ // encoded attributes are sorted by name.
1804
+ for (int64_t i = 0; i < attrs_.size(); ++i) {
1805
+ if (auto attr = attrs_[i]; attr.name == name)
1806
+ return CustomCallAttrDecoding<T, checks>::Decode(
1807
+ attr.name, attr.type_id, attr.value);
1808
+ }
1809
+ return failure();
1810
+ }
1811
+
1812
+ private:
1813
+ internal::DecodedAttrs attrs_;
1814
+ };
1815
+
1816
+ template <CustomCall::RuntimeChecks checks>
1817
+ struct CustomCallAttrDecoding<Dictionary, checks> {
1818
+ ABSL_ATTRIBUTE_ALWAYS_INLINE static FailureOr<Dictionary> Decode(
1819
+ std::string_view name, TypeID type_id, void* value) {
1820
+ if (!CustomCall::Isa<Dictionary>(checks, type_id)) return failure();
1821
+ return Dictionary(internal::DecodedAttrs(reinterpret_cast<void**>(value)));
1822
+ }
1823
+ };
1824
+
1825
+ //===----------------------------------------------------------------------===//
1826
+ // XLA Custom Call helper macro for registering custom call handlers.
1827
+ //===----------------------------------------------------------------------===//
1828
+
1829
+ #define XLA_RUNTIME_DEFINE_CUSTOM_CALL(fn, impl, checks, bind) \
1830
+ static bool fn(::xla::runtime::ExecutionContext* ctx, void** args, \
1831
+ void** attrs, void** rets) { \
1832
+ static auto* handler = bind.To<checks>(impl).release(); \
1833
+ return ::xla::runtime::succeeded( \
1834
+ xla::runtime::Executable::Call(ctx, *handler, args, attrs, rets)); \
1835
+ }
1836
+
1837
+ #define XLA_RUNTIME_DEFINE_CUSTOM_CALL_TEMPLATE(param, fn, impl, checks, bind) \
1838
+ template <param> \
1839
+ static bool fn(::xla::runtime::ExecutionContext* ctx, void** args, \
1840
+ void** attrs, void** rets) { \
1841
+ static auto* handler = bind.To<checks>(impl).release(); \
1842
+ return ::xla::runtime::succeeded( \
1843
+ xla::runtime::Executable::Call(ctx, *handler, args, attrs, rets)); \
1844
+ }
1845
+
1846
+ //===----------------------------------------------------------------------===//
1847
+ // Declare/define an explicit specialization for TypeID for types used
1848
+ // by the custom calls. This forces the compiler to emit a strong definition for
1849
+ // a class and controls which translation unit and shared object will actually
1850
+ // have it.
1851
+ //
1852
+ // See TypeID for more documentation.
1853
+ //
1854
+ // Because custom calls do not "own" the types passed across the function
1855
+ // boundary, we declare/define specializations for tagged types to avoid
1856
+ // potential conflicts with other libraries.
1857
+ //===----------------------------------------------------------------------===//
1858
+
1859
+ #define XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(T) \
1860
+ MLIR_DECLARE_EXPLICIT_TYPE_ID(::xla::runtime::Tagged<T>)
1861
+
1862
+ #define XLA_RUNTIME_DEFINE_EXPLICIT_TYPE_ID(T) \
1863
+ MLIR_DEFINE_EXPLICIT_TYPE_ID(::xla::runtime::Tagged<T>)
1864
+
1865
+ } // namespace runtime
1866
+ } // namespace xla
1867
+
1868
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(std::string_view);
1869
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::StridedMemrefView);
1870
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::MemrefView);
1871
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::FlatMemrefView);
1872
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::EmptyArray);
1873
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(xla::runtime::Dictionary);
1874
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(int32_t);
1875
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(int64_t);
1876
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(float);
1877
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(double);
1878
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span<const int32_t>);
1879
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span<const int64_t>);
1880
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span<const float>);
1881
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(absl::Span<const double>);
1882
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<bool>);
1883
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<int8_t>);
1884
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<int16_t>);
1885
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<int32_t>);
1886
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<int64_t>);
1887
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<float>);
1888
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<double>);
1889
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(
1890
+ tsl::AsyncValueRef<xla::runtime::MemrefView>);
1891
+ XLA_RUNTIME_DECLARE_EXPLICIT_TYPE_ID(tsl::AsyncValueRef<tsl::Chain>);
1892
+
1893
+ #endif // XLA_RUNTIME_CUSTOM_CALL_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/custom_call_registry.h ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_CUSTOM_CALL_REGISTRY_H_
17
+ #define XLA_RUNTIME_CUSTOM_CALL_REGISTRY_H_
18
+
19
+ #include <functional>
20
+ #include <memory>
21
+ #include <string_view>
22
+
23
+ #include "llvm/ADT/StringMap.h"
24
+ #include "xla/runtime/custom_call.h"
25
+
26
+ namespace xla {
27
+ namespace runtime {
28
+
29
+ // Dynamic custom call registry is a container for the custom calls that looks
30
+ // up the handler implementing the custom call by name at run time. It is used
31
+ // to implement a generic `rt.custom_call` runtime intrinsic.
32
+ //
33
+ // For low overhead custom calls prefer direct custom calls that linked with the
34
+ // compiled executable and bypass by-name look up.
35
+ class DynamicCustomCallRegistry {
36
+ public:
37
+ // The type for custom call registration functions.
38
+ using RegistrationFunction = void (*)(DynamicCustomCallRegistry*);
39
+
40
+ void Register(std::unique_ptr<class CustomCall> custom_call);
41
+
42
+ class CustomCall* Find(std::string_view callee) const;
43
+
44
+ private:
45
+ llvm::StringMap<std::unique_ptr<CustomCall>> custom_calls_;
46
+ };
47
+
48
+ // Direct custom call is a custom call that can be linked directly with the
49
+ // compiled executable, and doesn't have to go through the custom call look up
50
+ // by name at run time (see CustomCallRegistry).
51
+ //
52
+ // Direct custom call is a preferred way of implemenenting custom calls with
53
+ // low run time overheads, as they will become just an indirect function calls
54
+ // once LLVM ORC links them with the executable.
55
+ //
56
+ // See `ToSymbolsBinding` (in executor.h header) to convert direct custom call
57
+ // registry and type name registry to symbols binding.
58
+ class DirectCustomCallRegistry {
59
+ public:
60
+ // Function type corresponding to the direct custom call (custom calls
61
+ // linked directly with the compiled executable).
62
+ using DirectCustomCall = bool (*)(ExecutionContext* ctx, void** args,
63
+ void** attrs, void** rets);
64
+
65
+ void Register(std::string_view name, DirectCustomCall custom_call);
66
+
67
+ void ForEach(std::function<void(std::string_view, DirectCustomCall)> f) const;
68
+
69
+ private:
70
+ llvm::StringMap<DirectCustomCall> custom_calls_;
71
+ };
72
+
73
+ } // namespace runtime
74
+ } // namespace xla
75
+
76
+ #endif // XLA_RUNTIME_CUSTOM_CALL_REGISTRY_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/async_values_cache.h ADDED
@@ -0,0 +1,113 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_DEFAULT_ASYNC_VALUES_CACHE_H_
17
+ #define XLA_RUNTIME_DEFAULT_ASYNC_VALUES_CACHE_H_
18
+
19
+ #include "absl/synchronization/mutex.h"
20
+ #include "llvm/ADT/DenseMap.h"
21
+ #include "tfrt/concurrency/async_value.h" // from @tf_runtime
22
+ #include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime
23
+ #include "tfrt/concurrency/chain.h" // from @tf_runtime
24
+
25
+ namespace xla {
26
+ namespace runtime {
27
+
28
+ using tsl::AsyncValue;
29
+ using tsl::AsyncValuePtr;
30
+ using tsl::AsyncValueRef;
31
+ using tsl::Chain;
32
+ using tsl::MakeConstructedAsyncValueRef;
33
+ using tsl::MakeUnconstructedAsyncValueRef;
34
+ using tsl::RunWhenReady;
35
+
36
+ template <typename Key, typename Value>
37
+ class AsyncValuesCache {
38
+ public:
39
+ struct Entry;
40
+
41
+ AsyncValuesCache() = default;
42
+
43
+ // Returns a pointer to the cached value if it exists, otherwise returns
44
+ // nullptr. It is the caller's responsibility to form an async reference and
45
+ // extend its lifetime if the lifetime of the cached async value can be
46
+ // larger than the lifetime of the cache.
47
+ AsyncValuePtr<Value> Find(Key key) const;
48
+
49
+ // Allocates an async value in the unconstructed state to store the cached
50
+ // value with the given key.
51
+ //
52
+ // The `entry.allocated` value is `true` if the new async value was allocated,
53
+ // and the caller is responsible for eventually setting the error or emplacing
54
+ // the value. If it is false, then it means that the storage was already
55
+ // allocated, and someone else will eventually update it.
56
+ //
57
+ // The returned `entry.size` value is equal to the size of the cache. If the
58
+ // new async value was allocated, it will be reflected in the size.
59
+ Entry Allocate(Key key);
60
+
61
+ // Returns an async value that becomes available once all entries added to
62
+ // the cache are available.
63
+ AsyncValueRef<Chain> AllAvailable() const;
64
+
65
+ struct Entry {
66
+ AsyncValuePtr<Value> ptr;
67
+ bool allocated;
68
+ size_t size;
69
+ };
70
+
71
+ private:
72
+ mutable absl::Mutex mu_;
73
+ llvm::DenseMap<Key, AsyncValueRef<Value>> cache_ ABSL_GUARDED_BY(mu_);
74
+ };
75
+
76
+ template <typename Key, typename Value>
77
+ AsyncValuePtr<Value> AsyncValuesCache<Key, Value>::Find(Key key) const {
78
+ absl::MutexLock lock(&mu_);
79
+ auto it = cache_.find(key);
80
+ return it != cache_.end() ? it->getSecond().AsPtr() : AsyncValuePtr<Value>();
81
+ }
82
+
83
+ template <typename Key, typename Value>
84
+ auto AsyncValuesCache<Key, Value>::Allocate(Key key) -> Entry {
85
+ absl::MutexLock lock(&mu_);
86
+ auto it = cache_.find(key);
87
+ if (it != cache_.end())
88
+ return {it->getSecond().AsPtr(), false, cache_.size()};
89
+
90
+ AsyncValueRef<Value> allocated = MakeUnconstructedAsyncValueRef<Value>();
91
+
92
+ auto emplaced = cache_.try_emplace(key, std::move(allocated));
93
+ assert(emplaced.second && "emplace must be successful");
94
+ return {emplaced.first->getSecond().AsPtr(), true, cache_.size()};
95
+ }
96
+
97
+ template <typename Key, typename Value>
98
+ AsyncValueRef<Chain> AsyncValuesCache<Key, Value>::AllAvailable() const {
99
+ absl::MutexLock lock(&mu_);
100
+
101
+ llvm::SmallVector<AsyncValue*> avs;
102
+ avs.reserve(cache_.size());
103
+ for (auto& it : cache_) avs.push_back(it.getSecond().GetAsyncValue());
104
+
105
+ AsyncValueRef<Chain> chain = MakeConstructedAsyncValueRef<Chain>();
106
+ RunWhenReady(avs, [chain]() { chain.SetStateConcrete(); });
107
+ return chain;
108
+ }
109
+
110
+ } // namespace runtime
111
+ } // namespace xla
112
+
113
+ #endif // XLA_RUNTIME_DEFAULT_ASYNC_VALUES_CACHE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/default/memory_mapper.h ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_DEFAULT_MEMORY_MAPPER_H_
17
+ #define XLA_RUNTIME_DEFAULT_MEMORY_MAPPER_H_
18
+
19
+ #include <errno.h>
20
+
21
+ namespace xla {
22
+ namespace runtime {
23
+
24
+ // Some syscalls can be interrupted by a signal handler; retry if that happens.
25
+ template <typename FunctionType>
26
+ static auto RetryOnEINTR(FunctionType func, decltype(func()) failure_value) {
27
+ using ReturnType = decltype(func());
28
+ ReturnType ret;
29
+ do {
30
+ ret = func();
31
+ } while (ret == failure_value && errno == EINTR);
32
+ return ret;
33
+ }
34
+
35
+ } // namespace runtime
36
+ } // namespace xla
37
+
38
+ #endif // XLA_RUNTIME_DEFAULT_MEMORY_MAPPER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/diagnostics.h ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_DIAGNOSTICS_H_
17
+ #define XLA_RUNTIME_DIAGNOSTICS_H_
18
+
19
+ #include <functional>
20
+ #include <optional>
21
+ #include <string>
22
+ #include <utility>
23
+
24
+ #include "absl/status/status.h"
25
+ #include "llvm/ADT/STLExtras.h"
26
+ #include "llvm/ADT/SmallVector.h"
27
+ #include "xla/runtime/logical_result.h"
28
+ #include "tsl/platform/logging.h"
29
+
30
+ namespace xla {
31
+ namespace runtime {
32
+
33
+ // Forward declare.
34
+ class DiagnosticEngine;
35
+
36
+ // XLA runtime diagnostic engine enables XLA runtime custom calls and compiled
37
+ // programs to pass diagnostic information (e.g. detailed run time error
38
+ // information attached to the absl::Status) to the caller via the side channel,
39
+ // because the API (and ABI) of the compiled executable is very simple, and
40
+ // doesn't allow to pass complex C++ tyopes.
41
+ //
42
+ // XLA runtime diagnostics borrows a lot of ideas from the MLIR compile time
43
+ // diagnostics (which is largely based on the Swift compiler diagnostics),
44
+ // however in contrast to MLIR compilation pipelines we need to emit diagnostics
45
+ // for the run time events (vs compile time) and correlate them back to the
46
+ // location in the input module.
47
+ //
48
+ // See MLIR Diagnostics documentation: https://mlir.llvm.org/docs/Diagnostics.
49
+
50
+ //===----------------------------------------------------------------------===//
51
+ // Diagnostic
52
+ //===----------------------------------------------------------------------===//
53
+
54
+ // TODO(ezhulenev): Add location tracking to diagnostic, so that we can
55
+ // correlate emitted diagnostic to the location in the input module, and from
56
+ // there rely on the MLIR location to correlate events back to the user program
57
+ // (e.g. original JAX program written in Python).
58
+ class Diagnostic {
59
+ public:
60
+ explicit Diagnostic(absl::Status status) : status_(std::move(status)) {}
61
+
62
+ Diagnostic(Diagnostic &&) = default;
63
+ Diagnostic &operator=(Diagnostic &&) = default;
64
+
65
+ absl::Status status() const { return status_; }
66
+
67
+ private:
68
+ Diagnostic(const Diagnostic &rhs) = delete;
69
+ Diagnostic &operator=(const Diagnostic &rhs) = delete;
70
+
71
+ absl::Status status_;
72
+ };
73
+
74
+ //===----------------------------------------------------------------------===//
75
+ // InFlightDiagnostic
76
+ //===----------------------------------------------------------------------===//
77
+
78
+ // RAII wrapper around constructed, but but not yet emitted diagnostic. In
79
+ // flight diagnostic gives an opportunity to build a diagnostic before reporting
80
+ // it to the engine, similar to the builder pattern.
81
+ class InFlightDiagnostic {
82
+ public:
83
+ InFlightDiagnostic(InFlightDiagnostic &&other)
84
+ : engine_(other.engine_), diagnostic_(std::move(other.diagnostic_)) {
85
+ other.diagnostic_.reset();
86
+ other.Abandon();
87
+ }
88
+
89
+ ~InFlightDiagnostic() {
90
+ if (IsInFlight()) Report();
91
+ }
92
+
93
+ void Report();
94
+ void Abandon();
95
+
96
+ // Allow a diagnostic to be converted to 'failure'.
97
+ //
98
+ // Example:
99
+ //
100
+ // LogicalResult call(DiagnosticEngine diag, ...) {
101
+ // if (<check failed>) return diag.EmitError(InternalError("oops"));
102
+ // ...
103
+ // }
104
+ //
105
+ operator LogicalResult() const { // NOLINT
106
+ return failure();
107
+ }
108
+ template <typename T>
109
+ operator FailureOr<T>() const { // NOLINT
110
+ return failure();
111
+ }
112
+
113
+ private:
114
+ friend class DiagnosticEngine;
115
+
116
+ InFlightDiagnostic(const DiagnosticEngine *engine, Diagnostic diagnostic)
117
+ : engine_(engine), diagnostic_(std::move(diagnostic)) {}
118
+
119
+ InFlightDiagnostic &operator=(const InFlightDiagnostic &) = delete;
120
+ InFlightDiagnostic &operator=(InFlightDiagnostic &&) = delete;
121
+
122
+ bool IsActive() const { return diagnostic_.has_value(); }
123
+ bool IsInFlight() const { return engine_ != nullptr; }
124
+
125
+ // Diagnostic engine that will report this diagnostic once its ready.
126
+ const DiagnosticEngine *engine_ = nullptr;
127
+ std::optional<Diagnostic> diagnostic_;
128
+ };
129
+
130
+ //===----------------------------------------------------------------------===//
131
+ // DiagnosticEngine
132
+ //===----------------------------------------------------------------------===//
133
+
134
+ // Diagnostic engine is responsible for passing diagnostics to the user.
135
+ //
136
+ // XLA runtime users must set up diagnostic engine to report errors back to the
137
+ // caller, e.g. the handler can collect all of the emitted diagnostics into the
138
+ // string message, and pass it to the caller as the async error.
139
+ //
140
+ // Unhandled error diagnostics will be logged with the warning level.
141
+ class DiagnosticEngine {
142
+ public:
143
+ // Diagnostic handler must return success if it consumed the diagnostic, and
144
+ // failure if the engine should pass it to the next registered handler.
145
+ using HandlerTy = std::function<LogicalResult(Diagnostic &)>;
146
+
147
+ // Returns the default instance of the diagnostic engine.
148
+ static const DiagnosticEngine *DefaultDiagnosticEngine();
149
+
150
+ InFlightDiagnostic EmitError(absl::Status status) const {
151
+ return InFlightDiagnostic(this, Diagnostic(std::move(status)));
152
+ }
153
+
154
+ void AddHandler(HandlerTy handler) {
155
+ handlers_.push_back(std::move(handler));
156
+ }
157
+
158
+ void Emit(Diagnostic diagnostic) const {
159
+ for (auto &handler : llvm::reverse(handlers_)) {
160
+ if (succeeded(handler(diagnostic))) return;
161
+ }
162
+
163
+ // Log unhandled errors to the warning log.
164
+ LOG(WARNING) << "XLA runtime error: " << diagnostic.status();
165
+ }
166
+
167
+ private:
168
+ llvm::SmallVector<HandlerTy> handlers_;
169
+ };
170
+
171
+ } // namespace runtime
172
+ } // namespace xla
173
+
174
+ #endif // XLA_RUNTIME_DIAGNOSTICS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/errors.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_ERRORS_H_
17
+ #define XLA_RUNTIME_ERRORS_H_
18
+
19
+ #include <string>
20
+
21
+ #include "absl/status/status.h"
22
+ #include "absl/strings/str_format.h"
23
+
24
+ namespace xla {
25
+ namespace runtime {
26
+
27
+ template <typename... Args>
28
+ absl::Status InvalidArgument(const absl::FormatSpec<Args...>& format,
29
+ const Args&... args) {
30
+ return absl::InvalidArgumentError(absl::StrFormat(format, args...));
31
+ }
32
+
33
+ template <typename... Args>
34
+ absl::Status InternalError(const absl::FormatSpec<Args...>& format,
35
+ const Args&... args) {
36
+ return absl::InternalError(absl::StrFormat(format, args...));
37
+ }
38
+
39
+ } // namespace runtime
40
+ } // namespace xla
41
+
42
+ #endif // XLA_RUNTIME_ERRORS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/executable.h ADDED
@@ -0,0 +1,439 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_EXECUTABLE_H_
17
+ #define XLA_RUNTIME_EXECUTABLE_H_
18
+
19
+ #include <functional>
20
+ #include <memory>
21
+ #include <optional>
22
+ #include <string>
23
+ #include <string_view>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "absl/status/statusor.h"
28
+ #include "llvm/ADT/STLExtras.h"
29
+ #include "llvm/Support/MemoryBuffer.h"
30
+ #include "xla/runtime/arguments.h"
31
+ #include "xla/runtime/async_runtime.h"
32
+ #include "xla/runtime/custom_call.h"
33
+ #include "xla/runtime/custom_call_registry.h"
34
+ #include "xla/runtime/diagnostics.h"
35
+ #include "xla/runtime/execution_engine.h"
36
+ #include "xla/runtime/logical_result.h"
37
+ #include "xla/runtime/memory_mapper.h"
38
+ #include "xla/runtime/results.h"
39
+ #include "xla/runtime/type_id.h"
40
+ #include "xla/runtime/types.h"
41
+
42
+ namespace xla {
43
+ namespace runtime {
44
+
45
+ struct ExecutionContext;
46
+
47
+ struct DestroyExecutionContext {
48
+ void operator()(ExecutionContext* ctx);
49
+ };
50
+
51
+ // If executable has async results, ExecutionReference keeps that
52
+ // execution context alive. For sync executables `Execute` always returns
53
+ // ExecutionReference with nullptr.
54
+ class ExecutionReference
55
+ : public std::unique_ptr<ExecutionContext, DestroyExecutionContext> {
56
+ // Bring std::unique_ptr constructors in scope.
57
+ using std::unique_ptr<ExecutionContext, DestroyExecutionContext>::unique_ptr;
58
+ };
59
+
60
+ class FunctionRef;
61
+ class JitCompiler;
62
+
63
+ // Returns a symbols binding for running XLA executable with a custom symbols
64
+ // provided by the user.
65
+ ExecutionEngine::SymbolsBinding RuntimeSymbolsBinding(
66
+ ExecutionEngine::SymbolsBinding custom_binding);
67
+
68
+ // Converts a direct custom call and custom type id name registration functions
69
+ // (types required by the library) to the execution engine symbols binding.
70
+ // Returned symbols binding always includes type id symbols for all
71
+ // canonical types supported by the XLA runtime custom calls.
72
+ ExecutionEngine::SymbolsBinding ToSymbolsBinding(
73
+ std::function<void(DirectCustomCallRegistry&)> custom_calls = {},
74
+ std::function<void(TypeIDNameRegistry&)> types = {});
75
+
76
+ class Executable {
77
+ public:
78
+ // Forward declare types defined below.
79
+ struct ArgumentsMemoryLayout;
80
+ struct ResultsMemoryLayout;
81
+ struct CallFrame;
82
+ struct ExecuteOpts;
83
+
84
+ // Initializes call frame by adding all arguments according to the exported
85
+ // function ABI. Also allocates storage for the returned values according to
86
+ // the results memory layout.
87
+ //
88
+ // If `verify_arguments` is true (in debug mode it's always on, independent of
89
+ // the argument value) this function also verifies that arguments passed at
90
+ // run time matches the exported function signature (e.g. all statically known
91
+ // dimensions of the memrefs matches the arguments). Returns an error if finds
92
+ // a mismatch.
93
+ //
94
+ // This function leaves the execution context argument (the first argument of
95
+ // an exported function) uninitialized. It will be initialized in the
96
+ // `Execute` function right before the actual execution.
97
+ absl::Status InitializeCallFrame(unsigned ordinal, ArgumentsRef arguments,
98
+ CallFrame* call_frame,
99
+ bool verify_arguments = true) const;
100
+
101
+ absl::Status InitializeCallFrame(ArgumentsRef arguments,
102
+ CallFrame* call_frame,
103
+ bool verify_arguments = true) const {
104
+ return InitializeCallFrame(0, arguments, call_frame, verify_arguments);
105
+ }
106
+
107
+ // Converts returned values owned by the call frame using provided result
108
+ // converter. If exported function execution finished with an error (error
109
+ // flag is `true` in the call frame) returns error for all results (see
110
+ // `ResultConverter::ReturnError` documentation).
111
+ absl::Status ReturnResults(unsigned ordinal, const ResultConverter& results,
112
+ CallFrame* call_frame) const;
113
+
114
+ absl::Status ReturnResults(const ResultConverter& results,
115
+ CallFrame* call_frame) const {
116
+ return ReturnResults(0, results, call_frame);
117
+ }
118
+
119
+ // Executes exported function exported with given arguments.
120
+ //
121
+ // If `verify_arguments` is true (in debug mode it's always on, independent of
122
+ // the argument value) this function also verifies that arguments passed at
123
+ // run time matches the exported function signature. If some of the
124
+ // arguments do not match the expected type, this function allocates error
125
+ // async values for all results and returns an error.
126
+ //
127
+ // Returns exported function results via the user-provided results converter.
128
+ // If execution completed in the error state, returns error for all results.
129
+ absl::StatusOr<ExecutionReference> Execute(
130
+ unsigned ordinal, ArgumentsRef arguments, const ResultConverter& results,
131
+ const ExecuteOpts& opts, bool verify_arguments = true) const;
132
+
133
+ absl::StatusOr<ExecutionReference> Execute(
134
+ ArgumentsRef arguments, const ResultConverter& results,
135
+ const ExecuteOpts& opts, bool verify_arguments = true) const {
136
+ return Execute(0, arguments, results, opts, verify_arguments);
137
+ }
138
+
139
+ // Executes exported function using user provided call frame.
140
+ //
141
+ // It is the caller responsibility to handle the compiled function results
142
+ // stored in the call frame.
143
+ ExecutionReference Execute(unsigned ordinal, CallFrame& call_frame,
144
+ const ExecuteOpts& opts) const;
145
+
146
+ void Execute(CallFrame& call_frame, const ExecuteOpts& opts) const {
147
+ Execute(0, call_frame, opts);
148
+ }
149
+
150
+ std::string_view name() const { return name_; }
151
+
152
+ std::optional<size_t> specialization() const { return specialization_; }
153
+
154
+ // Returns the number of exported functions. Functions are indexed by their
155
+ // ordinal number in the [0, num_functions) range.
156
+ size_t num_functions() const { return functions_.size(); }
157
+
158
+ // Returns a function reference to an exported function with given ordinal.
159
+ FunctionRef function_ref(unsigned ordinal) const;
160
+
161
+ // Returns true if exported function with given ordinal has async results.
162
+ bool IsAsync(unsigned ordinal) const;
163
+ bool IsAsync() const { return IsAsync(0); }
164
+
165
+ // Returns the name of the exported function with the given ordinal.
166
+ std::string_view function_name(unsigned ordinal) const;
167
+ std::string_view function_name() const { return function_name(0); }
168
+
169
+ // Returns the number of results of the exported function with given ordinal.
170
+ unsigned num_results(unsigned ordinal) const;
171
+ unsigned num_results() const { return num_results(0); }
172
+
173
+ // Signature of the exported function with the given ordinal before lowering
174
+ // to the runtime dialects. See JitExecutable::Function's `signature` for
175
+ // more details.
176
+ const FunctionType& signature(unsigned ordinal) const;
177
+ const FunctionType& signature() const { return signature(0); }
178
+
179
+ // Signature of the exported function with the given ordinal after lowering it
180
+ // from high level dialects to the dialects supported by the XLA runtime. See
181
+ // JitExecutable::Function's `signature` for more details.
182
+ const FunctionType& runtime_signature(unsigned ordinal) const;
183
+ const FunctionType& runtime_signature() const { return runtime_signature(0); }
184
+
185
+ std::chrono::milliseconds time_to_compile() const;
186
+
187
+ // Get the object file behind this executable (on linux for example, it will
188
+ // be https://en.wikipedia.org/wiki/Executable_and_Linkable_Format
189
+ // executable). Can be null.
190
+ std::unique_ptr<llvm::MemoryBuffer> obj_file() const;
191
+
192
+ // CallFrame provides a pointer-stable storage for packed function arguments
193
+ // and storage for returned values.
194
+ struct CallFrame {
195
+ // Pointers to executable arguments.
196
+ llvm::SmallVector<void*, 32> args;
197
+
198
+ // We use single block of memory to store executable results. We need to be
199
+ // able to store pointers to async values and tokens, and strided memrefs
200
+ // which at runtime are represented as StridedMemrefType<T, rank>.
201
+ //
202
+ // Currently we only need to provide result storage for pointers and memref
203
+ // sizes and strides (int64_t type). If we'll need to support more complex
204
+ // return types we'll have to be more careful about alignment requirements.
205
+ static_assert(sizeof(uintptr_t) == sizeof(int64_t),
206
+ "uintptr_t size must be the same as int64_t");
207
+
208
+ // Memory where the executable will write its results.
209
+ llvm::SmallVector<uint8_t, 128> results;
210
+
211
+ // Tracks whether any of the outputs were set.
212
+ bool has_set_outputs = false;
213
+
214
+ // Indicates whether the execution finished with an error.
215
+ bool is_error = false;
216
+
217
+ // The error message which is available only if `is_error` is true. The
218
+ // assumption is that the error message string is owned by the compiled
219
+ // binary and the call frame can safely keep a non-owning pointer.
220
+ std::string_view error;
221
+ };
222
+
223
+ // Requirements for passing arguments to the compiled function.
224
+ struct ArgumentsMemoryLayout {
225
+ size_t num_args_ptrs = 0; // total number of required pointers
226
+ llvm::SmallVector<size_t> num_ptrs; // num_ptrs for each argument
227
+ llvm::SmallVector<size_t> offsets; // offsets into the args array
228
+ };
229
+
230
+ // Requirements for the contiguous block of memory to store compiled function
231
+ // results. When we invoke a compiled fuction we allocate a block of memory,
232
+ // and pass pointers to pre-computed offsets as output arguments to the
233
+ // function.
234
+ struct ResultsMemoryLayout {
235
+ bool has_async_results = false; // true iff returns async results
236
+ size_t size = 0; // number of bytes required
237
+ llvm::SmallVector<size_t> offsets; // offsets in the block of memory
238
+ };
239
+
240
+ struct ExecuteOpts {
241
+ // Async task runner for executing async runtime tasks. Typically it
242
+ // schedules async tasks into the underlying thread pool. It's the caller's
243
+ // responsibility to guarantee that it will outlive the execution of all
244
+ // async tasks started by the executable.
245
+ AsyncTaskRunner* async_task_runner = nullptr;
246
+
247
+ // A container for passing arbitrary user-provided data to the custom call
248
+ // handlers. Must outlive all async tasks launched by this executable.
249
+ const CustomCall::UserData* custom_call_data = nullptr;
250
+
251
+ // Dynamically registered custom calls library. These custom calls resolved
252
+ // at run time by name. In contrast to custom calls defined by the
253
+ // `DirectCustomCallRegistry` which are linked directly with the executable
254
+ // at compile time.
255
+ const DynamicCustomCallRegistry* custom_call_registry = nullptr;
256
+
257
+ // Diagnostic engine is responsible for passing runtime diagnostics back
258
+ // to the caller through the diagnostic handler.
259
+ const DiagnosticEngine* diagnostic_engine = nullptr;
260
+ };
261
+
262
+ // Function specification for loading from the object file.
263
+ struct LoadFunction {
264
+ std::string name;
265
+ FunctionType signature;
266
+ FunctionType runtime_signature;
267
+ };
268
+
269
+ // Loads executable from an object file. It is the caller responsibility to
270
+ // guarantee that signatures do match the compiled function in the object
271
+ // file, otherwise it will surely lead to crash.
272
+ static absl::StatusOr<Executable> LoadFromObjFile(
273
+ std::string_view name, std::unique_ptr<llvm::MemoryBuffer> obj_file,
274
+ std::vector<LoadFunction> load_functions,
275
+ ExecutionEngine::SymbolsBinding symbols_binding = {},
276
+ std::string_view memory_region_name = "");
277
+
278
+ // Verifies that all arguments types in the exported function signature are
279
+ // supported at run time. Returns a pre-computed layout for the function
280
+ // arguments. If some arguments are not supported returns an error.
281
+ static absl::StatusOr<ArgumentsMemoryLayout> GetArgumentsMemoryLayout(
282
+ const FunctionType& signature);
283
+
284
+ // Verifies that all results types in the exported function signature are
285
+ // supported at run time . Returns a pre-computed layout for the function
286
+ // results. If some results are not supported returns an error.
287
+ static absl::StatusOr<ResultsMemoryLayout> GetResultsMemoryLayout(
288
+ const FunctionType& signature);
289
+
290
+ // TODO(ezhulenev): The following three functions should be decoupled from
291
+ // the executable header file (maybe move them to runtime.h?) so that custom
292
+ // call implementations do not have to depend on the `executable` target.
293
+
294
+ // Returns the user data passed via the ExecuteOpts to the executable.
295
+ static const CustomCall::UserData* GetUserData(ExecutionContext* ctx);
296
+
297
+ // Returns the diagnostic engine passed via the ExecuteOpts to the executable.
298
+ static const DiagnosticEngine* GetDiagnosticEngine(ExecutionContext* ctx);
299
+
300
+ // Calls the custom call handler with the given runtime context, arguments,
301
+ // attributes and results.
302
+ static LogicalResult Call(ExecutionContext* ctx, CustomCall& call,
303
+ void** args, void** attrs, void** rets);
304
+
305
+ bool RequiresBlas(int ordinal) const {
306
+ return functions_[ordinal].requires_blas;
307
+ }
308
+
309
+ private:
310
+ friend class JitCompiler; // see `mlir/runtime/transforms/jit_compiler.h`
311
+
312
+ // Executable exports multiple functions available for users to call into. At
313
+ // run time they are referenced by their ordinal, so that we don't depend on
314
+ // expensive by-name lookup on the hot path. We keep function name only for
315
+ // debugging. Function ordinal is defined by its index in the `functions_`
316
+ // vector.
317
+ struct Function {
318
+ Function(std::string_view name, ExecutionEngine::ExportedFunctionPtr fptr,
319
+ FunctionType signature, FunctionType runtime_signature,
320
+ ArgumentsMemoryLayout arguments_memory_layout,
321
+ ResultsMemoryLayout results_memory_layout, bool requires_blas)
322
+ : name(name),
323
+ fptr(std::move(fptr)),
324
+ signature(std::move(signature)),
325
+ runtime_signature(std::move(runtime_signature)),
326
+ arguments_memory_layout(std::move(arguments_memory_layout)),
327
+ results_memory_layout(std::move(results_memory_layout)),
328
+ requires_blas(requires_blas) {}
329
+ Function(const Function&) = delete;
330
+ Function(Function&&) = default;
331
+
332
+ // Exported function name.
333
+ std::string name;
334
+
335
+ // Pointer to an exported function owned by the execution engine.
336
+ ExecutionEngine::ExportedFunctionPtr fptr;
337
+
338
+ // Signature of the exported function function before lowering to the
339
+ // runtime dialects (see JitExecutable::Function's `signature`).
340
+ FunctionType signature;
341
+
342
+ // Signature of the exported function after lowering it from high level
343
+ // dialects to the dialects supported by the XLA runtime.
344
+ //
345
+ // - Operands and results types converted to the types with well-defined ABI
346
+ // (e.g. tensors converted to memrefs).
347
+ //
348
+ // - First argument is always an execution context added to the function by
349
+ // the lowering pipeline.
350
+ //
351
+ // From this signatur, Executable infers how to pack runtime arguments
352
+ // according to the expected memory layout, and how to convert results
353
+ // returned from the JIT-compiled function into high level types (e.g. how
354
+ // to convert StridedMemrefType into Tensorflow Tensor).
355
+ //
356
+ // To infer the type of the returned value, Executable looks at the type
357
+ // defined by the `runtime_signature` to get the memory layout of the
358
+ // returned value, and at the type defined by the `signature` to get the
359
+ // type expected by the runtime.
360
+ FunctionType runtime_signature;
361
+
362
+ // Memory layout required for passing function arguments.
363
+ ArgumentsMemoryLayout arguments_memory_layout;
364
+
365
+ // Memory layout for returning function results.
366
+ ResultsMemoryLayout results_memory_layout;
367
+
368
+ // If this flag is true, then this function is outlined for cuda graph, and
369
+ // cuBlas should be initiated when capturing the cuda graph.
370
+ bool requires_blas;
371
+ };
372
+
373
+ Executable(std::string_view name,
374
+ std::unique_ptr<XlaRuntimeMemoryMapper> memory_mapper,
375
+ std::unique_ptr<ExecutionEngine> engine,
376
+ std::vector<Function> functions,
377
+ std::optional<size_t> specialization,
378
+ std::chrono::milliseconds time_to_compile)
379
+ : name_(name),
380
+ memory_mapper_(std::move(memory_mapper)),
381
+ engine_(std::move(engine)),
382
+ functions_(std::move(functions)),
383
+ specialization_(specialization),
384
+ time_to_compile_(time_to_compile) {
385
+ // All exported functions must have a non-null function pointer.
386
+ assert(llvm::all_of(functions_, [](const Function& f) { return f.fptr; }));
387
+ }
388
+
389
+ std::string name_; // name of the compiled executable
390
+
391
+ // Called by `engine_`'s destructor; must appear before it.
392
+ std::unique_ptr<XlaRuntimeMemoryMapper> memory_mapper_; // optional
393
+
394
+ // XLA runtime execution engine owns the LLVM ORC jit compilation stack.
395
+ std::unique_ptr<ExecutionEngine> engine_;
396
+
397
+ // Functions exported by this executable, indexed by function ordinal.
398
+ std::vector<Function> functions_;
399
+
400
+ // Specialization id if this executable is a specialization, or an empty
401
+ // optional if this executable is a default one.
402
+ std::optional<size_t> specialization_;
403
+
404
+ // The time it took to compile this binary.
405
+ std::chrono::milliseconds time_to_compile_;
406
+ };
407
+
408
+ // Function reference provides a function-like API for a function exported from
409
+ // the executabled with the given ordinal.
410
+ class FunctionRef {
411
+ public:
412
+ FunctionRef(const Executable* executable, unsigned ordinal);
413
+
414
+ absl::StatusOr<ExecutionReference> operator()(
415
+ ArgumentsRef arguments, const ResultConverter& results,
416
+ const Executable::ExecuteOpts& opts, bool verify_arguments = true) const;
417
+
418
+ bool RequiresBlas() const { return executable_->RequiresBlas(ordinal_); }
419
+
420
+ unsigned ordinal() const { return ordinal_; }
421
+
422
+ private:
423
+ const Executable* executable_;
424
+ unsigned ordinal_;
425
+ };
426
+
427
+ // Escape slashes, substituting them with double underscores to get a memory
428
+ // region name for the XlaRuntimeMemoryMapper.
429
+ //
430
+ // The profiler's UI might interpret slashes as callchain separators,
431
+ // whereas we want the region name to be shown in full.
432
+ inline std::string EscapeMemRegionName(std::string_view memory_region_name) {
433
+ return llvm::join(llvm::split(memory_region_name, '/'), "__");
434
+ }
435
+
436
+ } // namespace runtime
437
+ } // namespace xla
438
+
439
+ #endif // XLA_RUNTIME_EXECUTABLE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/execution_engine.h ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_EXECUTION_ENGINE_H_
17
+ #define XLA_RUNTIME_EXECUTION_ENGINE_H_
18
+
19
+ #include <functional>
20
+ #include <memory>
21
+ #include <string_view>
22
+ #include <utility>
23
+ #include <vector>
24
+
25
+ #include "absl/status/statusor.h"
26
+ #include "llvm/ExecutionEngine/JITEventListener.h"
27
+ #include "llvm/ExecutionEngine/Orc/LLJIT.h"
28
+ #include "llvm/ExecutionEngine/SectionMemoryManager.h"
29
+ #include "llvm/Support/MemoryBuffer.h"
30
+
31
+ namespace xla {
32
+ namespace runtime {
33
+
34
+ // A pre-fabricated wrapper around ORC JIT stack for running XLA executables.
35
+ //
36
+ // It allows to run jit-compiled XLA executables, AOT compile them or load
37
+ // previously AOT compiled executables.
38
+ //
39
+ // XLA executable itself is responsible for the function signature verification,
40
+ // arguments packing according to the ABI, results decoding and linking the
41
+ // executable with runtime intrinsics. Execution engine only helps with setting
42
+ // up ORC JIT stack to support the execution, but itself doesn't know what it is
43
+ // executing.
44
+ class ExecutionEngine {
45
+ public:
46
+ // Pointer to a function exported to the Xla executable.
47
+ //
48
+ // Xla exported function expects all arguments to be passed as an array of
49
+ // opaque pointers to the actual values. In C++ it would look like this:
50
+ //
51
+ // void compute(int32_t arg0, float arg1, ...);
52
+ //
53
+ // void __xla_compute(void** args) {
54
+ // int32_t arg0 = *reinterpret_cast<int32_t*>(args[0]);
55
+ // float arg1 = *reinterpret_cast<float*>(args[1]);
56
+ // ...
57
+ // compute(arg0, arg1, ...);
58
+ // }
59
+ //
60
+ // This is required to avoid dealing with ABI of the compiled function. See
61
+ // `SetUpExportedFunction` for implementation details.
62
+ using ExportedFunctionPtr = void (*)(void **);
63
+
64
+ // Callback to register symbols with the execution engine (e.g. to register
65
+ // custom runtime intrinsics for Gpu integration).
66
+ using SymbolsBinding =
67
+ std::function<llvm::orc::SymbolMap(llvm::orc::MangleAndInterner)>;
68
+
69
+ // Callback to run optimization passes on the compiled LLVM module.
70
+ using OptimizingTransformer = std::function<llvm::Error(llvm::Module *)>;
71
+
72
+ // Callback to construct an optimizing transformer for the given options.
73
+ using MakeOptimizingTransformer =
74
+ std::function<OptimizingTransformer(llvm::TargetMachine *targetMachine)>;
75
+
76
+ // Compose multiple symbol bindings into a single symbol binding function.
77
+ static SymbolsBinding BindAll(std::vector<SymbolsBinding> bindings);
78
+
79
+ //------------------------------------------------------------------------- //
80
+ // Options for creating execution engine from an LLVM module.
81
+ //------------------------------------------------------------------------- //
82
+
83
+ struct JitOptions {
84
+ // User-provided codegen optimization level.
85
+ llvm::CodeGenOptLevel opt_level = llvm::CodeGenOptLevel::Default;
86
+
87
+ // User-provided target machine specification.
88
+ std::shared_ptr<llvm::TargetMachine> target_machine = nullptr;
89
+
90
+ // User-provided builder for the optimizing transformer.
91
+ MakeOptimizingTransformer make_optimizing_transformer;
92
+
93
+ // User-provided memory mapper for allocating memory for executables.
94
+ llvm::SectionMemoryManager::MemoryMapper *section_memory_mapper = nullptr;
95
+
96
+ // User-provided bindings for symbols.
97
+ SymbolsBinding symbols_binding = nullptr;
98
+
99
+ // Notify the llvm's global GDB notifications listener.
100
+ bool enable_gdb_listener = false;
101
+
102
+ // Notify the llvm's global Perf notifications listener.
103
+ bool enable_perf_listener = false;
104
+
105
+ // Save compiled object file.
106
+ bool save_compiled_obj_file = true;
107
+ };
108
+
109
+ // Creates a new execution engine by compiling the provided LLVM module to
110
+ // a native executable using LLVM ORC stack.
111
+ static absl::StatusOr<std::unique_ptr<ExecutionEngine>> CreateFromModule(
112
+ std::unique_ptr<llvm::LLVMContext> ctx,
113
+ std::unique_ptr<llvm::Module> module, JitOptions options,
114
+ absl::Span<const std::string_view> exported);
115
+
116
+ //------------------------------------------------------------------------- //
117
+ // Options for creating execution engine from an AOT compiled object file.
118
+ //------------------------------------------------------------------------- //
119
+
120
+ struct AotOptions {
121
+ // User-provided memory mapper for allocating memory for executables.
122
+ llvm::SectionMemoryManager::MemoryMapper *section_memory_mapper = nullptr;
123
+
124
+ // User-provided bindings for symbols.
125
+ SymbolsBinding symbols_binding = nullptr;
126
+
127
+ // Notify the llvm's global GDB notifications listener.
128
+ bool enable_gdb_listener = true;
129
+
130
+ // Notify the llvm's global Perf notifications listener.
131
+ bool enable_perf_listener = true;
132
+ };
133
+
134
+ // Creates a new execution engine by loading AOT compiled XLA executable
135
+ // object file.
136
+ static absl::StatusOr<std::unique_ptr<ExecutionEngine>> CreateFromObjFile(
137
+ std::unique_ptr<llvm::MemoryBuffer>, AotOptions options,
138
+ absl::Span<const std::string_view> exported);
139
+
140
+ //------------------------------------------------------------------------- //
141
+
142
+ // Returns a pointer to the exported function.
143
+ absl::Span<const ExportedFunctionPtr> exported() const { return exported_; }
144
+
145
+ ExportedFunctionPtr exported(unsigned ordinal) const {
146
+ return exported_[ordinal];
147
+ }
148
+
149
+ // Return a memory buffer with a object file behind this execution engine. Can
150
+ // be null if execution engine didn't save the compiled object file.
151
+ std::unique_ptr<llvm::MemoryBuffer> obj_file() const;
152
+
153
+ private:
154
+ ExecutionEngine(bool enable_gdb_listener, bool enable_perf_listener);
155
+
156
+ // We build execution engine on top of the ORC LLJIT API, which owns all
157
+ // compiled/loaded object files and does the linking at run time.
158
+ //
159
+ // TODO(ezhulenev): Instead of keeping LLJIT alive we should be able to keep
160
+ // only llvm::orc::JITDylibSP owning main dylib and the object layer owning
161
+ // memory-mapped regions holding object files. Once we are done with
162
+ // executable compilation this jit is defunct because it holds an expired
163
+ // weak_ptr to an llvm::orc::TargetMachine instance.
164
+ std::unique_ptr<llvm::orc::LLJIT> jit_;
165
+
166
+ // Pointers to resolved exported functions. Indexed by function ordinal.
167
+ std::vector<ExportedFunctionPtr> exported_;
168
+
169
+ // Object file behind the compiled executable. Can be null.
170
+ std::unique_ptr<llvm::MemoryBuffer> obj_file_;
171
+
172
+ llvm::JITEventListener *gdb_listener_ = nullptr;
173
+ llvm::JITEventListener *perf_listener_ = nullptr;
174
+ };
175
+
176
+ // Emits an interface function ('exported_name') that wraps all arguments
177
+ // of a function ('original_name') into a single pointer to a ptr**,
178
+ // thereby exposing a trivial ABI. The original function is also inlined,
179
+ // if possible.
180
+ absl::Status ExportWithXlaRuntimeAbi(llvm::Module &module,
181
+ std::string_view original_name,
182
+ std::string_view exported_name);
183
+
184
+ } // namespace runtime
185
+ } // namespace xla
186
+
187
+ #endif // XLA_RUNTIME_EXECUTION_ENGINE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi.h ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_FFI_H_
17
+ #define XLA_RUNTIME_FFI_H_
18
+
19
+ #include <memory>
20
+ #include <utility>
21
+ #include <vector>
22
+
23
+ #include "xla/runtime/ffi/ffi_c_api.h"
24
+ #include "xla/runtime/module.h"
25
+
26
+ namespace xla {
27
+ namespace runtime {
28
+ namespace ffi {
29
+
30
+ // Returns FFI modules registered with an XLA runtime.
31
+ std::vector<const runtime::Module*> FfiModules();
32
+
33
+ // Exports registered FFI modules to the given custom call registry.
34
+ void ExportFfiModules(DynamicCustomCallRegistry& registry);
35
+
36
+ // XLA runtime wrapper around FFI module.
37
+ class FfiModule;
38
+
39
+ //===----------------------------------------------------------------------===//
40
+ // RAII helpers for the state instantiated by the FFI modules.
41
+ //===----------------------------------------------------------------------===//
42
+
43
+ // Deletes the FFI module `state` instantiated by the `module`.
44
+ struct FfiStateDeleter {
45
+ void operator()(XLA_FFI_Module_State* state);
46
+ const FfiModule* module;
47
+ };
48
+
49
+ // A smart pointer owning `state` instantiated by the `module`.
50
+ struct OwnedFfiState
51
+ : public std::unique_ptr<XLA_FFI_Module_State, FfiStateDeleter> {
52
+ using Base = std::unique_ptr<XLA_FFI_Module_State, FfiStateDeleter>;
53
+ OwnedFfiState(const FfiModule* module, XLA_FFI_Module_State* state);
54
+ };
55
+
56
+ //===----------------------------------------------------------------------===//
57
+ // FFI modules <-> XLA runtime integration via UserData.
58
+ //===----------------------------------------------------------------------===//
59
+
60
+ // A vector of opaque pointers to FFI modules state that is passed around inside
61
+ // `UserData` and enables FFI functions to find their state.
62
+ struct FfiStateVector {
63
+ std::vector<XLA_FFI_Module_State*> state; // indexed by module id
64
+
65
+ // If FFI module instantiates state for each execution, the state vector will
66
+ // be the owner of that state for the duration of execution.
67
+ std::vector<OwnedFfiState> per_execution_state;
68
+ };
69
+
70
+ // FfiModulesState is a container that owns the FFI modules state.
71
+ class FfiModulesState {
72
+ public:
73
+ FfiModulesState() = default;
74
+
75
+ // Instantiates `FfiModulesState` from the registered FFI module.
76
+ static absl::StatusOr<FfiModulesState> Instantiate();
77
+
78
+ absl::StatusOr<FfiStateVector> state_vector() const;
79
+
80
+ private:
81
+ explicit FfiModulesState(std::vector<std::unique_ptr<Module::State>> state);
82
+
83
+ std::vector<std::unique_ptr<Module::State>> state_;
84
+ };
85
+
86
+ // Gets the underlying FFI stream from the `user_data`.
87
+ XLA_FFI_Stream* GetXlaFfiStream(const CustomCall::UserData* user_data,
88
+ const DiagnosticEngine* diagnostic);
89
+
90
+ void RegisterXlaFfiStreamProvider(
91
+ XLA_FFI_Stream* (*)(const CustomCall::UserData*, const DiagnosticEngine*));
92
+
93
+ } // namespace ffi
94
+ } // namespace runtime
95
+ } // namespace xla
96
+
97
+ #endif // XLA_RUNTIME_FFI_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_abi.h ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_FFI_FFI_ABI_H_
17
+ #define XLA_RUNTIME_FFI_FFI_ABI_H_
18
+
19
+ #include <cstdint>
20
+
21
+ namespace xla {
22
+ namespace runtime {
23
+ namespace internal {
24
+
25
+ //===----------------------------------------------------------------------===//
26
+ // C structures that XLA uses internally to encode arguments and attributes.
27
+ //===----------------------------------------------------------------------===//
28
+
29
+ // When XLA compiles host-side executable via lowering to LLVM (see `rt-to-llvm`
30
+ // pass) it encodes arguments and attributes as `!llvm.struct<...>` types stored
31
+ // as LLVM global constants (attributes and statically known arguments) or as
32
+ // allocas on the stack. We rely on standard layout C++ structs to reinterpret
33
+ // cast arguments and attributes pointers, and convert them to user-friendly C++
34
+ // types (e.g. `EncodedMemref` to `StridedBufferArg`).
35
+ //
36
+ // See: https://en.cppreference.com/w/cpp/types/is_standard_layout
37
+
38
+ struct EncodedMemref {
39
+ uint8_t dtype;
40
+ uint8_t rank;
41
+ void* data;
42
+ int64_t dims[];
43
+ };
44
+
45
+ template <typename T>
46
+ struct EncodedArray {
47
+ int64_t size;
48
+ const T* data;
49
+ };
50
+
51
+ template <typename T>
52
+ struct EncodedDenseElements {
53
+ struct EncodedArray<T> payload;
54
+ int64_t rank;
55
+ int64_t shape[];
56
+ };
57
+
58
+ } // namespace internal
59
+ } // namespace runtime
60
+ } // namespace xla
61
+
62
+ #endif // XLA_RUNTIME_FFI_FFI_ABI_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_api.h ADDED
@@ -0,0 +1,1270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_FFI_FFI_API_H_
17
+ #define XLA_RUNTIME_FFI_FFI_API_H_
18
+
19
+ #include <algorithm>
20
+ #include <cassert>
21
+ #include <cstddef>
22
+ #include <cstdint>
23
+ #include <iostream>
24
+ #include <iterator>
25
+ #include <memory>
26
+ #include <optional>
27
+ #include <ostream>
28
+ #include <sstream>
29
+ #include <string>
30
+ #include <string_view>
31
+ #include <type_traits>
32
+ #include <utility>
33
+ #include <vector>
34
+
35
+ #include "xla/runtime/ffi/ffi_abi.h"
36
+ #include "xla/runtime/ffi/ffi_c_api.h"
37
+
38
+ namespace xla {
39
+ namespace runtime {
40
+ namespace ffi {
41
+
42
+ // Forward declare template defined below.
43
+ template <typename... Ts>
44
+ class FfiBinding;
45
+
46
+ // Forward declare template defined below.
47
+ template <typename Fn, typename... Ts>
48
+ class FfiHandler;
49
+
50
+ // FFI arguments allocated by the jit-compiled code and we need to mark all
51
+ // memory initialized to suppress memory sanitizer errors.
52
+ #if defined(MEMORY_SANITIZER)
53
+ #define XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) \
54
+ __msan_unpoison(address, size)
55
+ #else
56
+ #define XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(address, size) // empty
57
+ #endif // MEMORY_SANITIZER
58
+
59
+ //===----------------------------------------------------------------------===//
60
+ // Check struct sizes passed across the C API to detect mismatched versions.
61
+ //===----------------------------------------------------------------------===//
62
+
63
+ namespace internal {
64
+ inline void CheckStructSize(std::string_view struct_name, size_t expected_size,
65
+ size_t actual_size) {
66
+ if (expected_size != actual_size) {
67
+ std::cerr << "Unexpected " << struct_name << " size: expected "
68
+ << expected_size << " << got " << actual_size
69
+ << ". Check installed software versions." << std::endl;
70
+ std::abort();
71
+ }
72
+ }
73
+ } // namespace internal
74
+
75
+ #define CHECK_ARGS_SIZE(name, args) \
76
+ internal::CheckStructSize("XLA_FFI_##name##_Args", \
77
+ XLA_FFI_##name##_Args_STRUCT_SIZE, \
78
+ args->struct_size)
79
+
80
+ //===----------------------------------------------------------------------===//
81
+ // Span is non-owning view into contiguous values of type `T`.
82
+ //===----------------------------------------------------------------------===//
83
+
84
+ // TODO(ezhulenev): Replace with `std::span` when C++20 is available.
85
+ template <typename T>
86
+ class Span {
87
+ public:
88
+ Span(T* data, size_t size) : data_(data), size_(size) {}
89
+ Span(const std::vector<std::remove_const_t<T>>& vec) // NOLINT
90
+ : Span(vec.data(), vec.size()) {}
91
+
92
+ T& operator[](size_t index) const { return data_[index]; }
93
+
94
+ size_t size() const { return size_; }
95
+
96
+ T* begin() const { return data_; }
97
+ T* end() const { return data_ + size_; }
98
+
99
+ private:
100
+ T* data_;
101
+ size_t size_;
102
+ };
103
+
104
+ // A type for representing shaped tensors.
105
+ // TODO(ecg): expand API to be compatible with `std::mdspan`, and eventually
106
+ // (when C++23 is available) replace with `std::mdspan`.
107
+ template <typename T>
108
+ struct MdSpan {
109
+ Span<const int64_t> shape;
110
+ Span<const T> data;
111
+ };
112
+
113
+ //===----------------------------------------------------------------------===//
114
+ // XLA FFI status wrapper around error reporting APIs.
115
+ //===----------------------------------------------------------------------===//
116
+
117
+ class FfiStatus {
118
+ public:
119
+ static FfiStatus Ok() { return FfiStatus(); }
120
+
121
+ static FfiStatus Internal(std::string message) {
122
+ XLA_FFI_Error_Code errc = XLA_FFI_Error_Code_INTERNAL;
123
+ return FfiStatus(errc, message);
124
+ }
125
+
126
+ static FfiStatus InvalidArgument(std::string message) {
127
+ XLA_FFI_Error_Code errc = XLA_FFI_Error_Code_INVALID_ARGUMENT;
128
+ return FfiStatus(errc, message);
129
+ }
130
+
131
+ std::optional<XLA_FFI_Error_Code> errc() const { return errc_; }
132
+
133
+ std::string_view message() const {
134
+ return message_.has_value() ? *message_ : std::string_view();
135
+ }
136
+
137
+ const char* message_c_str() const {
138
+ return message_.has_value() ? message_->c_str() : "";
139
+ }
140
+
141
+ private:
142
+ FfiStatus() = default;
143
+
144
+ FfiStatus(XLA_FFI_Error_Code errc, std::string message)
145
+ : errc_(errc), message_(std::move(message)) {}
146
+
147
+ std::optional<XLA_FFI_Error_Code> errc_;
148
+ std::optional<std::string> message_;
149
+ };
150
+
151
+ //===----------------------------------------------------------------------===//
152
+ // XLA FFI virtual base for implementing FFI functions.
153
+ //===----------------------------------------------------------------------===//
154
+
155
+ class Ffi {
156
+ public:
157
+ virtual ~Ffi() = default;
158
+
159
+ virtual XLA_FFI_Error* operator()(const XLA_FFI_Api* api,
160
+ XLA_FFI_ExecutionContext* ctx, void** args,
161
+ void** attrs, void** rets) const = 0;
162
+
163
+ static FfiBinding<> Binding();
164
+
165
+ template <typename T>
166
+ static bool Isa(const XLA_FFI_Api* api, XLA_FFI_TypeId type_id);
167
+
168
+ template <typename T, typename U, typename... Ts>
169
+ static bool Isa(const XLA_FFI_Api* api, XLA_FFI_TypeId type_id) {
170
+ return Isa<T>(api, type_id) || Isa<U, Ts...>(api, type_id);
171
+ }
172
+ };
173
+
174
+ //===----------------------------------------------------------------------===//
175
+ // XLA FFI module is a base class for stateful and stateless FFI modules.
176
+ //===----------------------------------------------------------------------===//
177
+
178
+ class Module {
179
+ public:
180
+ virtual ~Module() = default;
181
+
182
+ struct ExportedFunction {
183
+ std::string target;
184
+ XLA_FFI_Function* function;
185
+ };
186
+
187
+ protected:
188
+ Module(const XLA_FFI_Api* api, std::string module_name,
189
+ std::vector<ExportedFunction> exported_functions,
190
+ XLA_FFI_Module_StateType state_type,
191
+ XLA_FFI_Module_CreateState* create_state,
192
+ XLA_FFI_Module_DestroyState* destroy_state)
193
+ : api_(api),
194
+ module_name_(std::move(module_name)),
195
+ exported_functions_(std::move(exported_functions)) {
196
+ Register(state_type, create_state, destroy_state);
197
+ }
198
+
199
+ private:
200
+ // Register `this` module with the XLA runtime.
201
+ void Register(XLA_FFI_Module_StateType state_type,
202
+ XLA_FFI_Module_CreateState* create_state,
203
+ XLA_FFI_Module_DestroyState* destroy_state) {
204
+ XLA_FFI_Module_Register_Args args;
205
+ args.struct_size = XLA_FFI_Module_Register_Args_STRUCT_SIZE;
206
+ args.priv = nullptr;
207
+ args.name = module_name_.c_str();
208
+ args.module = reinterpret_cast<XLA_FFI_Module*>(this);
209
+ args.state_type = state_type;
210
+ args.create_state = create_state;
211
+ args.destroy_state = destroy_state;
212
+
213
+ std::vector<const char*> exported_names;
214
+ std::vector<XLA_FFI_Function*> exported_functions;
215
+ for (auto& fn : exported_functions_) {
216
+ exported_names.push_back(fn.target.c_str());
217
+ exported_functions.push_back(fn.function);
218
+ }
219
+
220
+ args.num_exported_functions = exported_functions_.size();
221
+ args.exported_names = exported_names.data();
222
+ args.exported_functions = exported_functions.data();
223
+
224
+ api_->XLA_FFI_Module_Register(&args);
225
+ }
226
+
227
+ // Module is registered with the XLA runtime behind this API instance, and any
228
+ // module manipulation (e.g. export functions) must be done through it.
229
+ const XLA_FFI_Api* api_;
230
+
231
+ std::string module_name_;
232
+ std::vector<ExportedFunction> exported_functions_;
233
+ };
234
+
235
+ //===----------------------------------------------------------------------===//
236
+ // XLA FFI stateful module is a collection of FFI functions and a state.
237
+ //===----------------------------------------------------------------------===//
238
+
239
+ template <typename State>
240
+ class StatefulModule : public Module {
241
+ public:
242
+ // TODO(ezhulenev): To gracefully fail if state can't be created, this has to
243
+ // return `FfiStatusOr<std::unique_ptr<State>>`, but we do not have a
244
+ // `StatusOr` implementation yet and we can't depend on absl.
245
+ virtual std::unique_ptr<State> CreateState() = 0;
246
+
247
+ protected:
248
+ StatefulModule(const XLA_FFI_Api* api, std::string module_name,
249
+ std::vector<ExportedFunction> exported_functions,
250
+ bool per_execution_state = false)
251
+ : Module(api, std::move(module_name), std::move(exported_functions),
252
+ per_execution_state ? XLA_FFI_Module_State_PER_EXECUTION
253
+ : XLA_FFI_Module_State_PER_EXECUTABLE,
254
+ CreateState, DestroyState) {}
255
+
256
+ private:
257
+ // Implements `XLA_FFI_Module_CreateState` API function.
258
+ static XLA_FFI_Error* CreateState(XLA_FFI_Module_CreateState_Args* args);
259
+
260
+ // Implements `XLA_FFI_Module_DestroyState` API function.
261
+ static void DestroyState(XLA_FFI_Module_DestroyState_Args* args);
262
+ };
263
+
264
+ template <typename State>
265
+ XLA_FFI_Error* StatefulModule<State>::CreateState(
266
+ XLA_FFI_Module_CreateState_Args* args) {
267
+ CHECK_ARGS_SIZE(Module_CreateState, args);
268
+
269
+ auto* module = reinterpret_cast<StatefulModule*>(args->module);
270
+ auto* state = module->CreateState().release();
271
+ args->state = reinterpret_cast<XLA_FFI_Module_State*>(state);
272
+ return nullptr; // success
273
+ }
274
+
275
+ template <typename State>
276
+ void StatefulModule<State>::DestroyState(
277
+ XLA_FFI_Module_DestroyState_Args* args) {
278
+ CHECK_ARGS_SIZE(Module_DestroyState, args);
279
+
280
+ delete reinterpret_cast<State*>(args->state);
281
+ }
282
+
283
+ //===----------------------------------------------------------------------===//
284
+ // XLA FFI stateless module is a collection of FFI functions without a state.
285
+ //===----------------------------------------------------------------------===//
286
+
287
+ class StatelessModule : public Module {
288
+ protected:
289
+ StatelessModule(const XLA_FFI_Api* api, std::string module_name,
290
+ std::vector<ExportedFunction> exported_functions)
291
+ : Module(api, std::move(module_name), std::move(exported_functions),
292
+ /*state_type=*/XLA_FFI_Module_State_PER_EXECUTABLE,
293
+ /*create_state=*/nullptr, /*destroy_state=*/nullptr) {}
294
+ };
295
+
296
+ //===----------------------------------------------------------------------===//
297
+ // Helper macro to define a static module registration.
298
+ //===----------------------------------------------------------------------===//
299
+
300
+ #define XLA_REGISTER_FFI_MODULE(FUNC) \
301
+ XLA_REGISTER_FFI_MODULE_IMPL(FUNC, __COUNTER__)
302
+
303
+ #define XLA_REGISTER_FFI_MODULE_IMPL(FUNC, N) \
304
+ static bool xla_ffi_module_##N##_registered_ = []() { \
305
+ static auto* module = FUNC.release(); \
306
+ return module != nullptr; \
307
+ }()
308
+
309
+ //===----------------------------------------------------------------------===//
310
+ // Arguments supported by the FFI handlers.
311
+ //===----------------------------------------------------------------------===//
312
+
313
+ // This enum corresponds to xla::PrimitiveType enum defined in `hlo.proto`.
314
+ enum class PrimitiveType : uint8_t {
315
+ // Invalid primitive type to serve as default.
316
+ PRIMITIVE_TYPE_INVALID = 0,
317
+
318
+ // Predicates are two-state booleans.
319
+ PRED = 1,
320
+
321
+ // Signed integral values of fixed width.
322
+ S8 = 2,
323
+ S16 = 3,
324
+ S32 = 4,
325
+ S64 = 5,
326
+
327
+ // Unsigned integral values of fixed width.
328
+ U8 = 6,
329
+ U16 = 7,
330
+ U32 = 8,
331
+ U64 = 9,
332
+
333
+ // Floating-point values of fixed width.
334
+ //
335
+ // Note: if f16s are not natively supported on the device, they will be
336
+ // converted to f16 from f32 at arbitrary points in the computation.
337
+ F16 = 10,
338
+ F32 = 11,
339
+
340
+ // Truncated 16 bit floating-point format. This is similar to IEEE's 16 bit
341
+ // floating-point format, but uses 1 bit for the sign, 8 bits for the exponent
342
+ // and 7 bits for the mantissa.
343
+ BF16 = 16,
344
+
345
+ F64 = 12,
346
+ };
347
+
348
+ constexpr int ByteWidth(PrimitiveType type) {
349
+ switch (type) {
350
+ case PrimitiveType::PRED:
351
+ return 1;
352
+
353
+ case PrimitiveType::S8:
354
+ case PrimitiveType::U8:
355
+ return 1;
356
+
357
+ case PrimitiveType::S16:
358
+ case PrimitiveType::U16:
359
+ case PrimitiveType::F16:
360
+ case PrimitiveType::BF16:
361
+ return 2;
362
+
363
+ case PrimitiveType::S32:
364
+ case PrimitiveType::U32:
365
+ case PrimitiveType::F32:
366
+ return 4;
367
+
368
+ case PrimitiveType::S64:
369
+ case PrimitiveType::U64:
370
+ case PrimitiveType::F64:
371
+ return 8;
372
+
373
+ case PrimitiveType::PRIMITIVE_TYPE_INVALID:
374
+ assert(false && "Unsupported type");
375
+ return 0;
376
+ }
377
+ }
378
+
379
+ constexpr std::string_view PrimitiveTypeToString(PrimitiveType type) {
380
+ switch (type) {
381
+ case PrimitiveType::PRIMITIVE_TYPE_INVALID:
382
+ return "invalid";
383
+ case PrimitiveType::PRED:
384
+ return "pred";
385
+ case PrimitiveType::S8:
386
+ return "s8";
387
+ case PrimitiveType::S16:
388
+ return "s16";
389
+ case PrimitiveType::S32:
390
+ return "s32";
391
+ case PrimitiveType::S64:
392
+ return "s64";
393
+ case PrimitiveType::U8:
394
+ return "u8";
395
+ case PrimitiveType::U16:
396
+ return "u16";
397
+ case PrimitiveType::U32:
398
+ return "u32";
399
+ case PrimitiveType::U64:
400
+ return "u64";
401
+ case PrimitiveType::F16:
402
+ return "f16";
403
+ case PrimitiveType::F32:
404
+ return "f32";
405
+ case PrimitiveType::BF16:
406
+ return "bf16";
407
+ case PrimitiveType::F64:
408
+ return "f64";
409
+ }
410
+ }
411
+
412
+ // A view into the buffer argument. Buffers with non-identity layouts can be
413
+ // decoded only as a StridedBufferArg.
414
+ struct StridedBufferArg {
415
+ std::string ToString() const;
416
+
417
+ PrimitiveType dtype;
418
+ void* data;
419
+ Span<const int64_t> sizes;
420
+ Span<const int64_t> strides;
421
+ };
422
+
423
+ // A view into the buffer argument with an identity (row major) layout.
424
+ struct BufferArg {
425
+ std::string ToString() const;
426
+
427
+ PrimitiveType dtype;
428
+ void* data;
429
+ Span<const int64_t> sizes;
430
+ };
431
+
432
+ // A flat view into the buffer argument with an identity (row major) layout.
433
+ // If the memref shape and strides are not required, it is cheaper to pass the
434
+ // flat buffer argument.
435
+ struct FlatBufferArg {
436
+ std::string ToString() const;
437
+
438
+ PrimitiveType dtype;
439
+ void* data;
440
+ int64_t size_in_bytes;
441
+ };
442
+
443
+ // A type tag to represent dictionary attributes that can be decoded into
444
+ // structs using aggregate attribute decoding.
445
+ struct Dictionary {};
446
+
447
+ template <typename T>
448
+ bool Ffi::Isa(const XLA_FFI_Api* api, XLA_FFI_TypeId type_id) {
449
+ #define ISA(type, name) \
450
+ if constexpr (std::is_same_v<T, type>) \
451
+ return api->XLA_FFI_Get_##name##_TypeId() == type_id;
452
+
453
+ ISA(std::string_view, String);
454
+
455
+ ISA(float, Float);
456
+ ISA(double, Double);
457
+ ISA(bool, Int1);
458
+ ISA(int32_t, Int32);
459
+ ISA(int64_t, Int64);
460
+
461
+ ISA(Span<const float>, FloatArray);
462
+ ISA(Span<const double>, DoubleArray);
463
+ ISA(Span<const int32_t>, Int32Array);
464
+ ISA(Span<const int64_t>, Int64Array);
465
+
466
+ ISA(MdSpan<float>, FloatTensor);
467
+ ISA(MdSpan<double>, DoubleTensor);
468
+ ISA(MdSpan<int32_t>, Int32Tensor);
469
+ ISA(MdSpan<int64_t>, Int64Tensor);
470
+
471
+ ISA(StridedBufferArg, StridedBufferArg);
472
+ ISA(BufferArg, BufferArg);
473
+ ISA(Dictionary, Dictionary);
474
+
475
+ assert(false && "Unsupported type");
476
+ return false;
477
+
478
+ #undef ISA
479
+ }
480
+
481
+ //===----------------------------------------------------------------------===//
482
+ // Pretty printing for buffers.
483
+ //===----------------------------------------------------------------------===//
484
+
485
+ static void PrintArray(std::stringstream& ss, Span<const int64_t> arr) {
486
+ ss << "[";
487
+ for (unsigned i = 0; i < arr.size(); ++i)
488
+ (i > 0) ? ss << ", " << arr[i] : ss << arr[i];
489
+ ss << "]";
490
+ }
491
+
492
+ inline std::string StridedBufferArg::ToString() const {
493
+ std::stringstream ss;
494
+ ss << "Buffer: dtype=" << PrimitiveTypeToString(dtype);
495
+ ss << " sizes=";
496
+ PrintArray(ss, sizes);
497
+ ss << " strides=";
498
+ PrintArray(ss, strides);
499
+ return ss.str();
500
+ }
501
+
502
+ inline std::string BufferArg::ToString() const {
503
+ std::stringstream ss;
504
+ ss << "Buffer: dtype=" << PrimitiveTypeToString(dtype);
505
+ ss << " sizes=";
506
+ PrintArray(ss, sizes);
507
+ return ss.str();
508
+ }
509
+
510
+ inline std::string FlatBufferArg::ToString() const {
511
+ std::stringstream ss;
512
+ ss << "Buffer: dtype=" << PrimitiveTypeToString(dtype);
513
+ ss << " size=" << size_in_bytes;
514
+ return ss.str();
515
+ }
516
+
517
+ //===----------------------------------------------------------------------===//
518
+ // FFI binding describes the function signature expected by the FFI handler
519
+ // using its variadic template parameter.
520
+ //
521
+ // FFI binding:
522
+ // FfiBinding<int32_t, float>
523
+ //
524
+ // Corresponds to the function signature:
525
+ // FfiStatus MyHandler(int32_t arg0, float arg1);
526
+ //
527
+ //===----------------------------------------------------------------------===//
528
+
529
+ namespace internal {
530
+
531
+ // A type tag to distinguish arguments tied to the attributes in the
532
+ // `FfiBinding` variadic template argument.
533
+ template <typename T>
534
+ struct AttrTag {};
535
+
536
+ // A type tag to distinguish argument tied to FFI module state.
537
+ template <typename T>
538
+ struct StateTag {};
539
+
540
+ // A type tag to distinguish argument tied to XLA runtime stream.
541
+ template <typename T>
542
+ struct StreamTag {};
543
+
544
+ // Type tag to distinguish an argument tied to an "ApiPriv" argument
545
+ // to `Ffi::Binding`. This is necessary to obtain `XLA_FFI_Api.priv`
546
+ // from the foreign function. For example:
547
+ //
548
+ // static ffi::FfiStatus FooFfi(MyStruct* bar, ffi::BufferArg input) { ... }
549
+ //
550
+ // XLA_FFI_DEFINE_FUNCTION(
551
+ // FFI_Foo, FooFfi, ffi::Ffi::Binding()
552
+ // .ApriPriv<MyStruct*>
553
+ // .Arg<ffi::BufferArg>);
554
+ template <typename T>
555
+ struct ApiPrivTag {};
556
+
557
+ // A template for checking if type is a wrapped attribute or user data.
558
+ // clang-format off
559
+ template <typename> struct IsWrapped : std::false_type {};
560
+ template <typename T> struct IsWrapped<AttrTag<T>> : std::true_type {};
561
+ template <typename T> struct IsWrapped<StateTag<T>> : std::true_type {};
562
+ template <typename T> struct IsWrapped<StreamTag<T>> : std::true_type {};
563
+ template <typename T> struct IsWrapped<ApiPrivTag<T>> : std::true_type {};
564
+ // clang-format on
565
+
566
+ } // namespace internal
567
+
568
+ template <typename... Ts>
569
+ class FfiBinding {
570
+ public:
571
+ template <typename T>
572
+ FfiBinding<Ts..., T> Arg() && {
573
+ return {std::move(*this)};
574
+ }
575
+
576
+ template <typename T>
577
+ FfiBinding<Ts..., internal::AttrTag<T>> Attr(std::string attr) && {
578
+ attrs_.push_back(std::move(attr));
579
+ return {std::move(*this)};
580
+ }
581
+
582
+ template <typename T>
583
+ FfiBinding<Ts..., internal::StateTag<T>> State() && {
584
+ return {std::move(*this)};
585
+ }
586
+
587
+ template <typename T>
588
+ FfiBinding<Ts..., internal::StreamTag<T>> Stream() && {
589
+ static_assert(std::is_pointer_v<T>,
590
+ "T must be a pointer type, e.g. for GPU platform it must be "
591
+ "se::gpu::GpuStreamHandle");
592
+ return {std::move(*this)};
593
+ }
594
+
595
+ template <typename T>
596
+ FfiBinding<Ts..., internal::ApiPrivTag<T>> ApiPriv() && {
597
+ static_assert(std::is_pointer_v<T>, "T must be a pointer type");
598
+ return {std::move(*this)};
599
+ }
600
+
601
+ template <typename Fn>
602
+ std::unique_ptr<FfiHandler<Fn, Ts...>> To(Fn fn) {
603
+ return std::unique_ptr<FfiHandler<Fn, Ts...>>(
604
+ new FfiHandler<Fn, Ts...>(std::forward<Fn>(fn), std::move(attrs_)));
605
+ }
606
+
607
+ private:
608
+ template <typename...>
609
+ friend class FfiBinding;
610
+ friend class Ffi;
611
+
612
+ explicit FfiBinding() {
613
+ static_assert(sizeof...(Ts) == 0, "ffi arguments must be empty");
614
+ }
615
+
616
+ template <typename... TTs>
617
+ FfiBinding(FfiBinding<TTs...>&& other) // NOLINT
618
+ : attrs_(std::move(other.attrs_)) {}
619
+
620
+ FfiBinding(FfiBinding&) = delete;
621
+
622
+ std::vector<std::string> attrs_; // names of bound attributes
623
+ };
624
+
625
+ inline FfiBinding<> Ffi::Binding() { return FfiBinding<>(); }
626
+
627
+ //===----------------------------------------------------------------------===//
628
+ // Helpers for decoding opaque arguments and attributes' memory.
629
+ //===----------------------------------------------------------------------===//
630
+
631
+ namespace internal {
632
+
633
+ using runtime::internal::EncodedArray;
634
+ using runtime::internal::EncodedMemref;
635
+
636
+ // Decoded pair of argument type and opaque value.
637
+ struct DecodedArg {
638
+ XLA_FFI_TypeId type_id;
639
+ void* value;
640
+ };
641
+
642
+ // Decoded triple of attribute name, type and opaque value.
643
+ struct DecodedAttr {
644
+ std::string_view name;
645
+ XLA_FFI_TypeId type_id;
646
+ void* value;
647
+ };
648
+
649
+ // A convenience wrapper around opaque arguments memory.
650
+ class DecodedArgs {
651
+ public:
652
+ explicit DecodedArgs(void** args) {
653
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(args, sizeof(void*));
654
+ size_ = *reinterpret_cast<int64_t*>(args[0]);
655
+ if (size_) {
656
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(args + 1, sizeof(void*));
657
+ types_ = reinterpret_cast<void**>(args[1]);
658
+ values_ = args + 2;
659
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(types_, size_ * sizeof(void*));
660
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(values_, size_ * sizeof(void*));
661
+ }
662
+ }
663
+
664
+ int64_t size() const { return size_; }
665
+
666
+ DecodedArg operator[](size_t i) const {
667
+ DecodedArg arg;
668
+ arg.type_id = types_[i];
669
+ arg.value = values_[i];
670
+ return arg;
671
+ }
672
+
673
+ private:
674
+ int64_t size_;
675
+ void** types_ = nullptr;
676
+ void** values_ = nullptr;
677
+ };
678
+
679
+ // A convenience wrapper around opaque attributes' memory.
680
+ class DecodedAttrs {
681
+ public:
682
+ explicit DecodedAttrs(void** attrs) : encoded_(attrs + 1) {
683
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(attrs, sizeof(void*));
684
+ size_ = *reinterpret_cast<int64_t*>(attrs[0]);
685
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded_, 3 * size_ * sizeof(void*));
686
+ }
687
+
688
+ int64_t size() const { return size_; }
689
+
690
+ DecodedAttr operator[](size_t i) const {
691
+ void** attr_base = encoded_ + i * 3;
692
+
693
+ DecodedAttr attr;
694
+ auto* name = reinterpret_cast<internal::EncodedArray<char>*>(attr_base[0]);
695
+ attr.name = std::string_view(name->data, name->size);
696
+ attr.type_id = attr_base[1];
697
+ attr.value = attr_base[2];
698
+
699
+ return attr;
700
+ }
701
+
702
+ private:
703
+ void** encoded_;
704
+ int64_t size_;
705
+ };
706
+
707
+ } // namespace internal
708
+
709
+ //===----------------------------------------------------------------------===//
710
+ // XLA FFI arguments decoding implementation.
711
+ //===----------------------------------------------------------------------===//
712
+
713
+ // XLA FFI arguments decoding must be defined by specializing this template.
714
+ //
715
+ // Example: decoding for the `MyType` arguments
716
+ //
717
+ // template <>
718
+ // struct FfiArgDecoding<MyType> {
719
+ // static std::optional<MyType> Decode(ExecutionContext* ctx, TypeId type_id,
720
+ // void* value);
721
+ // };
722
+ //
723
+ template <typename T>
724
+ struct FfiArgDecoding;
725
+
726
+ // XLA FFI attribute decoding must be defined by specializing this template.
727
+ //
728
+ // Example: decoding for the `MyType` attributes
729
+ //
730
+ // template <>
731
+ // struct FfiAttrDecoding<MyType> {
732
+ // static std::optional<MyType> Decode(ExecutionContext* ctx,
733
+ // std::string_view name,
734
+ // TypeId type_id, void* value);
735
+ // }
736
+ //
737
+ template <typename T>
738
+ struct FfiAttrDecoding;
739
+
740
+ namespace internal {
741
+
742
+ // When decoding input data we need to keep track of how many arguments,
743
+ // attributes, and returns we decoded so far to index into the correct data
744
+ // structure.
745
+ struct DecodingOffsets {
746
+ int64_t args = 0;
747
+ int64_t attrs = 0;
748
+ int64_t rets = 0;
749
+ int64_t values = 0;
750
+ };
751
+
752
+ template <typename T>
753
+ struct Decode {
754
+ static std::optional<T> call(const XLA_FFI_Api* api,
755
+ XLA_FFI_ExecutionContext* ctx,
756
+ DecodingOffsets& offsets,
757
+ internal::DecodedArgs args,
758
+ const std::vector<std::string>& attrs_names,
759
+ const std::vector<size_t>& attrs_idx,
760
+ internal::DecodedAttrs attrs) {
761
+ internal::DecodedArg arg = args[offsets.args++];
762
+ return FfiArgDecoding<T>::Decode(api, arg.type_id, arg.value);
763
+ }
764
+ };
765
+
766
+ template <typename T>
767
+ struct Decode<AttrTag<T>> {
768
+ static std::optional<T> call(const XLA_FFI_Api* api,
769
+ XLA_FFI_ExecutionContext* ctx,
770
+ DecodingOffsets& offsets,
771
+ internal::DecodedArgs args,
772
+ const std::vector<std::string>& attrs_names,
773
+ const std::vector<size_t>& attrs_idx,
774
+ internal::DecodedAttrs attrs) {
775
+ // Find decoded attribute corresponding to the given attribute index.
776
+ int64_t idx = offsets.attrs++;
777
+
778
+ // Get mapping from the attribute to its index in the sorted array.
779
+ size_t i = attrs_idx[idx];
780
+
781
+ // Attribute name does not match.
782
+ if (attrs[i].name != attrs_names[idx]) return std::nullopt;
783
+
784
+ return FfiAttrDecoding<T>::Decode(api, attrs[i].name, attrs[i].type_id,
785
+ attrs[i].value);
786
+ }
787
+ };
788
+
789
+ template <typename T>
790
+ struct Decode<StateTag<T>> {
791
+ static std::optional<T*> call(const XLA_FFI_Api* api,
792
+ XLA_FFI_ExecutionContext* ctx,
793
+ DecodingOffsets& offsets, internal::DecodedArgs,
794
+ const std::vector<std::string>& attrs_names,
795
+ const std::vector<size_t>& attrs_idx,
796
+ internal::DecodedAttrs attrs) {
797
+ XLA_FFI_ExecutionContext_GetModuleState_Args args;
798
+ args.struct_size = XLA_FFI_ExecutionContext_GetModuleState_Args_STRUCT_SIZE;
799
+ args.priv = nullptr;
800
+ args.ctx = ctx;
801
+
802
+ XLA_FFI_Module_State* state =
803
+ api->XLA_FFI_ExecutionContext_GetModuleState(&args);
804
+ return reinterpret_cast<T*>(state);
805
+ }
806
+ };
807
+
808
+ template <typename T>
809
+ struct Decode<StreamTag<T>> {
810
+ static std::optional<T> call(const XLA_FFI_Api* api,
811
+ XLA_FFI_ExecutionContext* ctx,
812
+ DecodingOffsets& offsets, internal::DecodedArgs,
813
+ const std::vector<std::string>& attrs_names,
814
+ const std::vector<size_t>& attrs_idx,
815
+ internal::DecodedAttrs attrs) {
816
+ XLA_FFI_ExecutionContext_GetStream_Args args;
817
+ args.struct_size = XLA_FFI_ExecutionContext_GetStream_Args_STRUCT_SIZE;
818
+ args.priv = nullptr;
819
+ args.ctx = ctx;
820
+
821
+ XLA_FFI_Stream* stream = api->XLA_FFI_ExecutionContext_GetStream(&args);
822
+ return reinterpret_cast<T>(stream);
823
+ }
824
+ };
825
+
826
+ template <typename T>
827
+ struct Decode<ApiPrivTag<T>> {
828
+ static std::optional<T> call(const XLA_FFI_Api* api,
829
+ XLA_FFI_ExecutionContext* ctx,
830
+ DecodingOffsets& offsets, internal::DecodedArgs,
831
+ const std::vector<std::string>& attrs_names,
832
+ const std::vector<size_t>& attrs_idx,
833
+ internal::DecodedAttrs attrs) {
834
+ return reinterpret_cast<T>(api->priv);
835
+ }
836
+ };
837
+
838
+ } // namespace internal
839
+
840
+ //===----------------------------------------------------------------------===//
841
+ // Ffi handler binds concrete ffi implementation of type `Fn` to the ffi
842
+ // function signature. `Fn` can be a function pointer or a lambda.
843
+ //
844
+ // Ffi handler uses the variadic template parameter `Ts` to decode the
845
+ // opaque pointers passed to the `call` function into the C++ types that are
846
+ // forwarded to the ffi implementation.
847
+ //===----------------------------------------------------------------------===//
848
+
849
+ namespace internal {
850
+
851
+ // A helper template to extract the type of the handler argument.
852
+ // clang-format off
853
+ template <typename T> struct FnArgType { using Type = T; };
854
+ template <typename T> struct FnArgType<AttrTag<T>> { using Type = T; };
855
+ template <typename T> struct FnArgType<StateTag<T>> { using Type = T*; };
856
+ template <typename T> struct FnArgType<StreamTag<T>> { using Type = T; };
857
+ template <typename T> struct FnArgType<ApiPrivTag<T>> { using Type = T; };
858
+ // clang-format on
859
+
860
+ // A template for counting regular arguments in the Ts pack.
861
+ template <typename... Ts>
862
+ struct NumArgs;
863
+ template <>
864
+ struct NumArgs<> {
865
+ static constexpr int64_t value = 0;
866
+ };
867
+
868
+ template <typename T, typename... Ts>
869
+ struct NumArgs<T, Ts...> {
870
+ static constexpr int64_t value = !IsWrapped<T>::value + NumArgs<Ts...>::value;
871
+ };
872
+
873
+ } // namespace internal
874
+
875
+ template <typename Fn, typename... Ts>
876
+ class FfiHandler : public Ffi {
877
+ static constexpr int64_t kSize = sizeof...(Ts);
878
+ static constexpr int64_t kNumArgs = internal::NumArgs<Ts...>::value;
879
+
880
+ template <typename T>
881
+ using FnArgType = typename internal::FnArgType<T>::Type;
882
+
883
+ // Check if FFI function returns `FfiStatus`.
884
+ static constexpr bool kIsFfiStatusHandler =
885
+ std::is_invocable_r_v<FfiStatus, Fn, FnArgType<Ts>...>;
886
+ static_assert(kIsFfiStatusHandler, "unsupported FFI handler type");
887
+
888
+ static XLA_FFI_Error* ToError(const XLA_FFI_Api* api, FfiStatus status) {
889
+ if (!status.errc().has_value()) return nullptr;
890
+
891
+ XLA_FFI_Error_Create_Args args;
892
+ args.struct_size = XLA_FFI_Error_Create_Args_STRUCT_SIZE;
893
+ args.priv = nullptr;
894
+ args.errc = *status.errc();
895
+ args.message = status.message_c_str();
896
+
897
+ return api->XLA_FFI_Error_Create(&args);
898
+ }
899
+
900
+ public:
901
+ XLA_FFI_Error* operator()(const XLA_FFI_Api* api,
902
+ XLA_FFI_ExecutionContext* ctx, void** args,
903
+ void** attrs, void** rets) const final {
904
+ // Decode arguments and attributes from the opaque pointers.
905
+ internal::DecodedArgs decoded_args(args);
906
+ internal::DecodedAttrs decoded_attrs(attrs);
907
+
908
+ int64_t num_args = decoded_args.size();
909
+ int64_t num_attrs = decoded_attrs.size();
910
+
911
+ // Check that we have the correct number of arguments passed to the handler.
912
+ if (num_args != kNumArgs) {
913
+ std::ostringstream err;
914
+ err << "Wrong number of arguments: expected " << kNumArgs << " got "
915
+ << num_args;
916
+ return ToError(api, FfiStatus::InvalidArgument(err.str()));
917
+ }
918
+
919
+ // Check that we have the correct number of attributes passed to the
920
+ // handler. Each individual attribute decoding will check the name and the
921
+ // type of the attribute.
922
+ if (num_attrs != attrs_.size()) {
923
+ std::ostringstream err;
924
+ err << "Wrong number of attributes: expected " << attrs_.size() << " got "
925
+ << num_attrs;
926
+ return ToError(api, FfiStatus::InvalidArgument(err.str()));
927
+ }
928
+
929
+ // Define index sequence to access ffi handler arguments.
930
+ using Is = std::make_index_sequence<kSize>;
931
+ return call(api, ctx, decoded_args, decoded_attrs, Is{});
932
+ }
933
+
934
+ private:
935
+ template <typename...>
936
+ friend class FfiBinding;
937
+
938
+ template <size_t... Is>
939
+ XLA_FFI_Error* call(const XLA_FFI_Api* api, XLA_FFI_ExecutionContext* ctx,
940
+ internal::DecodedArgs args, internal::DecodedAttrs attrs,
941
+ std::index_sequence<Is...>) const {
942
+ // A helper structure to allow each decoder find the correct offset in the
943
+ // arguments, attributes or results.
944
+ internal::DecodingOffsets offsets;
945
+
946
+ // Decode all operands into `std::optional` containers. It is guaranteed
947
+ // that initializer list will be evaluated left-to-right, and we can rely
948
+ // on correct offsets computation.
949
+ std::tuple<std::optional<FnArgType<Ts>>...> fn_args = {
950
+ internal::Decode<Ts>::call(api, ctx, offsets, args, attrs_, attrs_idx_,
951
+ attrs)...};
952
+
953
+ // Check if all arguments, attributes and results were decoded;
954
+ bool all_decoded = (std::get<Is>(fn_args).has_value() && ...);
955
+ if (!all_decoded) {
956
+ std::array<bool, kSize> decoded = {std::get<Is>(fn_args).has_value()...};
957
+ std::string err = "Failed to decode all FFI operands (bad operands at: ";
958
+ for (size_t cnt = 0, idx = 0; idx < kSize; ++idx) {
959
+ if (!decoded[idx]) {
960
+ if (cnt++) err.append(", ");
961
+ err.append(std::to_string(idx));
962
+ }
963
+ }
964
+ err.append(")");
965
+ return ToError(api, FfiStatus::InvalidArgument(err));
966
+ }
967
+
968
+ // Custom call returns `FfiStatus`, we can call it directly.
969
+ if constexpr (kIsFfiStatusHandler) {
970
+ return ToError(api, fn_(std::move(*std::get<Is>(fn_args))...));
971
+ }
972
+
973
+ return ToError(api, FfiStatus::Ok());
974
+ }
975
+
976
+ FfiHandler(Fn fn, std::vector<std::string> attrs)
977
+ : fn_(std::move(fn)),
978
+ attrs_(std::move(attrs)),
979
+ attrs_idx_(attrs_.size()) {
980
+ // Sort attributes names.
981
+ std::vector<std::string> sorted = attrs_;
982
+ std::sort(sorted.begin(), sorted.end());
983
+
984
+ // Find the index of every attribute in the sorted attributes vector.
985
+ for (size_t i = 0; i < attrs_.size(); ++i) {
986
+ const std::string& attr = attrs_[i];
987
+ attrs_idx_[i] = std::distance(
988
+ sorted.begin(), std::find(sorted.begin(), sorted.end(), attr));
989
+ }
990
+ }
991
+
992
+ Fn fn_;
993
+
994
+ std::vector<std::string> attrs_;
995
+
996
+ // A mapping from the attribute index to its index in the lexicographically
997
+ // sorted vector of attribute names. Attributes are passed to the ffi handler
998
+ // sorted by the name, we use this index to efficiently find the decoded
999
+ // attribute entry.
1000
+ std::vector<size_t> attrs_idx_;
1001
+ };
1002
+
1003
+ //===----------------------------------------------------------------------===//
1004
+ // XLA FFI arguments decoding.
1005
+ //===----------------------------------------------------------------------===//
1006
+
1007
+ #define XLA_FFI_REGISTER_SCALAR_ARG_DECODING(T) \
1008
+ template <> \
1009
+ struct FfiArgDecoding<T> { \
1010
+ static std::optional<T> Decode(const XLA_FFI_Api* api, \
1011
+ XLA_FFI_TypeId type_id, void* value) { \
1012
+ if (!Ffi::Isa<T>(api, type_id)) { \
1013
+ return std::nullopt; \
1014
+ } \
1015
+ \
1016
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(value, sizeof(T)); \
1017
+ return *reinterpret_cast<T*>(value); \
1018
+ } \
1019
+ }
1020
+
1021
+ XLA_FFI_REGISTER_SCALAR_ARG_DECODING(int32_t);
1022
+
1023
+ #undef XLA_FFI_REGISTER_SCALAR_ARG_DECODING
1024
+
1025
+ template <>
1026
+ struct FfiArgDecoding<StridedBufferArg> {
1027
+ using EncodedMemref = internal::EncodedMemref;
1028
+
1029
+ static std::optional<StridedBufferArg> Decode(const XLA_FFI_Api* api,
1030
+ XLA_FFI_TypeId type_id,
1031
+ void* value) {
1032
+ if (!Ffi::Isa<BufferArg, StridedBufferArg>(api, type_id)) {
1033
+ return std::nullopt;
1034
+ }
1035
+
1036
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1037
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1038
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(
1039
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1040
+
1041
+ PrimitiveType dtype = static_cast<PrimitiveType>(encoded->dtype);
1042
+ return StridedBufferArg{dtype,
1043
+ encoded->data,
1044
+ {encoded->dims, encoded->rank},
1045
+ {encoded->dims + encoded->rank, encoded->rank}};
1046
+ }
1047
+ };
1048
+
1049
+ template <>
1050
+ struct FfiArgDecoding<BufferArg> {
1051
+ using EncodedMemref = internal::EncodedMemref;
1052
+
1053
+ static std::optional<BufferArg> Decode(const XLA_FFI_Api* api,
1054
+ XLA_FFI_TypeId type_id, void* value) {
1055
+ if (!Ffi::Isa<BufferArg>(api, type_id)) {
1056
+ return std::nullopt;
1057
+ }
1058
+
1059
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1060
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1061
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(
1062
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1063
+
1064
+ PrimitiveType dtype = static_cast<PrimitiveType>(encoded->dtype);
1065
+ return BufferArg{dtype, encoded->data, {encoded->dims, encoded->rank}};
1066
+ }
1067
+ };
1068
+
1069
+ template <>
1070
+ struct FfiArgDecoding<FlatBufferArg> {
1071
+ using EncodedMemref = internal::EncodedMemref;
1072
+
1073
+ static std::optional<FlatBufferArg> Decode(const XLA_FFI_Api* api,
1074
+ XLA_FFI_TypeId type_id,
1075
+ void* value) {
1076
+ if (!Ffi::Isa<BufferArg>(api, type_id)) {
1077
+ return std::nullopt;
1078
+ }
1079
+
1080
+ auto* encoded = reinterpret_cast<EncodedMemref*>(value);
1081
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(encoded, sizeof(EncodedMemref));
1082
+ XLA_FFI_ANNOTATE_MEMORY_IS_INITIALIZED(
1083
+ encoded, sizeof(EncodedMemref) + encoded->rank * sizeof(int64_t));
1084
+
1085
+ auto dtype = static_cast<PrimitiveType>(encoded->dtype);
1086
+ int64_t size_in_bytes = ByteWidth(dtype);
1087
+ for (int d = 0; d < encoded->rank; ++d) {
1088
+ size_in_bytes *= encoded->dims[d];
1089
+ }
1090
+ return FlatBufferArg{dtype, encoded->data, size_in_bytes};
1091
+ }
1092
+ };
1093
+
1094
+ //===----------------------------------------------------------------------===//
1095
+ // XLA FFI attributes decoding.
1096
+ //===----------------------------------------------------------------------===//
1097
+
1098
+ #define XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(T) \
1099
+ template <> \
1100
+ struct FfiAttrDecoding<T> { \
1101
+ static std::optional<T> Decode(const XLA_FFI_Api* api, \
1102
+ std::string_view name, \
1103
+ XLA_FFI_TypeId type_id, void* value) { \
1104
+ if (!Ffi::Isa<T>(api, type_id)) { \
1105
+ return std::nullopt; \
1106
+ } \
1107
+ \
1108
+ return *reinterpret_cast<T*>(value); \
1109
+ } \
1110
+ }
1111
+
1112
+ XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(float);
1113
+ XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(double);
1114
+ XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(bool);
1115
+ XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(int32_t);
1116
+ XLA_FFI_REGISTER_SCALAR_ATTR_DECODING(int64_t);
1117
+
1118
+ #undef XLA_FFI_REGISTER_SCALAR_ATTR_DECODING
1119
+
1120
+ // Both EncodedArray and 1-D EncodedDenseElements can be decoded as a Span.
1121
+ // Pointers to both EncodedArray and 1-D EncodedDenseElements can be
1122
+ // dereferenced as a pointer to EncodedArray.
1123
+ #define XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(T) \
1124
+ template <> \
1125
+ struct FfiAttrDecoding<Span<const T>> { \
1126
+ static std::optional<Span<const T>> Decode(const XLA_FFI_Api* api, \
1127
+ std::string_view name, \
1128
+ XLA_FFI_TypeId type_id, \
1129
+ void* value) { \
1130
+ if (!Ffi::Isa<Span<const T>, MdSpan<T>>(api, type_id)) { \
1131
+ return std::nullopt; \
1132
+ } \
1133
+ \
1134
+ auto* encoded = reinterpret_cast<internal::EncodedArray<T>*>(value); \
1135
+ return Span<const T>(encoded->data, encoded->size); \
1136
+ } \
1137
+ }
1138
+
1139
+ XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(float);
1140
+ XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(double);
1141
+ XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(bool);
1142
+ XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(int32_t);
1143
+ XLA_FFI_REGISTER_ARRAY_ATTR_DECODING(int64_t);
1144
+
1145
+ #undef XLA_FFI_REGISTER_ARRAY_ATTR_DECODING
1146
+
1147
+ template <>
1148
+ struct FfiAttrDecoding<std::string_view> {
1149
+ static std::optional<std::string_view> Decode(const XLA_FFI_Api* api,
1150
+ std::string_view name,
1151
+ XLA_FFI_TypeId type_id,
1152
+ void* value) {
1153
+ if (!Ffi::Isa<std::string_view>(api, type_id)) {
1154
+ return std::nullopt;
1155
+ }
1156
+
1157
+ auto* encoded = reinterpret_cast<internal::EncodedArray<char>*>(value);
1158
+ return std::string_view(encoded->data, encoded->size);
1159
+ }
1160
+ };
1161
+
1162
+ //===----------------------------------------------------------------------===//
1163
+ // Register an XLA FFI attribute decoding from dictionaries to structs.
1164
+ //===----------------------------------------------------------------------===//
1165
+
1166
+ template <typename T>
1167
+ struct AggregateMember {
1168
+ using Type = T;
1169
+
1170
+ explicit AggregateMember(std::string_view name) : name(name) {}
1171
+ std::string_view name;
1172
+ };
1173
+
1174
+ // Example: register decoding for a user-defined struct
1175
+ //
1176
+ // struct PairOfI64 { int64_t a; int64_t b; };
1177
+ //
1178
+ // XLA_FFI_REGISTER_AGGREGATE_ATTR_DECODING(
1179
+ // PairOfI64,
1180
+ // AggregateMember<int64_t>("a"),
1181
+ // AggregateMember<int64_t>("b"));
1182
+ //
1183
+ #define XLA_FFI_REGISTER_AGGREGATE_ATTR_DECODING(T, ...) \
1184
+ template <> \
1185
+ struct FfiAttrDecoding<T> { \
1186
+ static std::optional<T> Decode(const XLA_FFI_Api* api, \
1187
+ std::string_view name, \
1188
+ XLA_FFI_TypeId type_id, void* value) { \
1189
+ if (!Ffi::Isa<Dictionary>(api, type_id)) { \
1190
+ return std::nullopt; \
1191
+ } \
1192
+ \
1193
+ auto decoder = internal::AggregateDecoder<T>(__VA_ARGS__); \
1194
+ return decltype(decoder)::Decode(api, reinterpret_cast<void**>(value), \
1195
+ internal::AggregateNames(__VA_ARGS__)); \
1196
+ } \
1197
+ }
1198
+
1199
+ namespace internal {
1200
+ // Decodes aggregate attribute into the object of type `T` that must be
1201
+ // constructible from the `Ts` types.
1202
+ template <typename T, typename... Ts>
1203
+ struct DecodeAggregateAttr {
1204
+ static constexpr size_t kSize = sizeof...(Ts);
1205
+
1206
+ static std::optional<T> Decode(const XLA_FFI_Api* api, void** value,
1207
+ std::array<std::string_view, kSize> names) {
1208
+ internal::DecodedAttrs attrs(value);
1209
+ return Decode(api, attrs, names, std::make_index_sequence<kSize>{});
1210
+ }
1211
+
1212
+ template <size_t... Is>
1213
+ static std::optional<T> Decode(const XLA_FFI_Api* api,
1214
+ internal::DecodedAttrs attrs,
1215
+ std::array<std::string_view, kSize> names,
1216
+ std::index_sequence<Is...>) {
1217
+ // Check that the number of encoded attributes matches the signature.
1218
+ if (kSize != attrs.size()) return std::nullopt;
1219
+
1220
+ // Check that aggregate member names match the expected names.
1221
+ for (unsigned i = 0; i < kSize; ++i)
1222
+ if (attrs[i].name != names[i]) return std::nullopt;
1223
+
1224
+ // Decode all arguments into std::optional containers. It is guaranteed
1225
+ // that initializer list will be evaluated left-to-right, and we can rely
1226
+ // on correct offsets computation.
1227
+ std::tuple<std::optional<Ts>...> members = {FfiAttrDecoding<Ts>::Decode(
1228
+ api, attrs[Is].name, attrs[Is].type_id, attrs[Is].value)...};
1229
+
1230
+ bool all_decoded = (std::get<Is>(members).has_value() && ...);
1231
+ if (!all_decoded) return std::nullopt;
1232
+
1233
+ // Forward unpacked members to the type constructor.
1234
+ return T{std::move(*std::get<Is>(members))...};
1235
+ }
1236
+ };
1237
+
1238
+ template <typename... Members>
1239
+ auto AggregateNames(Members... m) {
1240
+ return std::array<std::string_view, sizeof...(Members)>{m.name...};
1241
+ }
1242
+
1243
+ template <typename T, typename... Members>
1244
+ auto AggregateDecoder(Members... m) {
1245
+ return DecodeAggregateAttr<T, typename Members::Type...>();
1246
+ }
1247
+
1248
+ } // namespace internal
1249
+
1250
+ //===----------------------------------------------------------------------===//
1251
+ // XLA FFI helper macro for registering FFI implementations.
1252
+ //===----------------------------------------------------------------------===//
1253
+
1254
+ #define XLA_FFI_DEFINE_FUNCTION(fn, impl, binding) \
1255
+ static XLA_FFI_Error* fn(XLA_FFI_Function_Args* args) { \
1256
+ ::xla::runtime::ffi::internal::CheckStructSize( \
1257
+ "XLA_FFI_Function_Args", XLA_FFI_Function_Args_STRUCT_SIZE, \
1258
+ args->struct_size); \
1259
+ static auto* handler = binding.To(impl).release(); \
1260
+ return (*handler)(args->api, args->ctx, args->args, args->attrs, \
1261
+ args->rets); \
1262
+ }
1263
+
1264
+ #undef CHECK_ARGS_SIZE
1265
+
1266
+ } // namespace ffi
1267
+ } // namespace runtime
1268
+ } // namespace xla
1269
+
1270
+ #endif // XLA_RUNTIME_FFI_FFI_API_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/ffi/ffi_c_api.h ADDED
@@ -0,0 +1,276 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_FFI_FFI_C_API_H_
17
+ #define XLA_RUNTIME_FFI_FFI_C_API_H_
18
+
19
+ #include <stddef.h>
20
+ #include <stdint.h>
21
+
22
+ // Every struct passed across the C API boundary has its size as a member, and
23
+ // we use it as a sanity check for API compatibility.
24
+ #define XLA_FFI_STRUCT_SIZE(struct_type, last_field) \
25
+ offsetof(struct_type, last_field) + sizeof(((struct_type*)0)->last_field)
26
+
27
+ #ifdef __cplusplus
28
+ extern "C" {
29
+ #endif
30
+
31
+ // Forward declare.
32
+ typedef struct XLA_FFI_Api XLA_FFI_Api;
33
+
34
+ //===----------------------------------------------------------------------===//
35
+ // XLA FFI Type checking.
36
+ //===----------------------------------------------------------------------===//
37
+
38
+ // XLA FFI passes type ids along with all arguments and attributes so that it
39
+ // should be possible to check types at run time inside the FFI handler.
40
+ typedef const void* XLA_FFI_TypeId;
41
+
42
+ typedef XLA_FFI_TypeId XLA_FFI_Get_TypeId();
43
+
44
+ //===----------------------------------------------------------------------===//
45
+ // XLA FFI Error handling.
46
+ //===----------------------------------------------------------------------===//
47
+
48
+ // XLA FFI handler must return a XLA_FFI_Error*, which is NULL if there is no
49
+ // error and set if there is. Caller allocates any returned XLA_FFI_Errors, and
50
+ // the XLA FFI is responsible for freeing them.
51
+ typedef struct XLA_FFI_Error XLA_FFI_Error;
52
+
53
+ // Codes are based on https://abseil.io/docs/cpp/guides/status-codes
54
+ typedef enum {
55
+ XLA_FFI_Error_Code_CANCELLED = 1,
56
+ XLA_FFI_Error_Code_UNKNOWN = 2,
57
+ XLA_FFI_Error_Code_INVALID_ARGUMENT = 3,
58
+ XLA_FFI_Error_Code_DEADLINE_EXCEEDED = 4,
59
+ XLA_FFI_Error_Code_NOT_FOUND = 5,
60
+ XLA_FFI_Error_Code_ALREADY_EXISTS = 6,
61
+ XLA_FFI_Error_Code_PERMISSION_DENIED = 7,
62
+ XLA_FFI_Error_Code_RESOURCE_EXHAUSTED = 8,
63
+ XLA_FFI_Error_Code_FAILED_PRECONDITION = 9,
64
+ XLA_FFI_Error_Code_ABORTED = 10,
65
+ XLA_FFI_Error_Code_OUT_OF_RANGE = 11,
66
+ XLA_FFI_Error_Code_UNIMPLEMENTED = 12,
67
+ XLA_FFI_Error_Code_INTERNAL = 13,
68
+ XLA_FFI_Error_Code_UNAVAILABLE = 14,
69
+ XLA_FFI_Error_Code_DATA_LOSS = 15,
70
+ XLA_FFI_Error_Code_UNAUTHENTICATED = 16
71
+ } XLA_FFI_Error_Code;
72
+
73
+ //===----------------------------------------------------------------------===//
74
+ // XLA FFI module defines a set of exported FFI functions and their state.
75
+ //===----------------------------------------------------------------------===//
76
+
77
+ // XLA FFI module is a way to structure FFI functions together with a state
78
+ // required for calling them. XLA runtime executable can be linked with multiple
79
+ // of such modules at run time.
80
+ typedef struct XLA_FFI_Module XLA_FFI_Module;
81
+
82
+ // XLA FFI module state can be instantiated once for each XLA executable, and
83
+ // its life time will be bound to the executable iself, or it can be
84
+ // instantiated for each separate execution.
85
+ typedef enum {
86
+ XLA_FFI_Module_State_PER_EXECUTABLE = 1,
87
+ XLA_FFI_Module_State_PER_EXECUTION = 2,
88
+ } XLA_FFI_Module_StateType;
89
+
90
+ // Exported FFI functions will have access to the state object that they can
91
+ // use to share data between different function invocations. If the state is
92
+ // instantiated for each executable, it is the user's responsibility to
93
+ // guarantee that it is thread-safe to use from multiple concurrent executions.
94
+ typedef struct XLA_FFI_Module_State XLA_FFI_Module_State;
95
+
96
+ // Creates a new per-executable module state.
97
+ typedef struct {
98
+ size_t struct_size;
99
+ void* priv;
100
+ XLA_FFI_Module* module;
101
+ XLA_FFI_Module_State* state; // out
102
+ } XLA_FFI_Module_CreateState_Args;
103
+
104
+ const size_t XLA_FFI_Module_CreateState_Args_STRUCT_SIZE =
105
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_Module_CreateState_Args, state);
106
+
107
+ typedef XLA_FFI_Error* XLA_FFI_Module_CreateState(
108
+ XLA_FFI_Module_CreateState_Args* args);
109
+
110
+ // Destroys a module state.
111
+ typedef struct {
112
+ size_t struct_size;
113
+ void* priv;
114
+ XLA_FFI_Module* module;
115
+ XLA_FFI_Module_State* state;
116
+ } XLA_FFI_Module_DestroyState_Args;
117
+
118
+ const size_t XLA_FFI_Module_DestroyState_Args_STRUCT_SIZE =
119
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_Module_DestroyState_Args, state);
120
+
121
+ typedef void XLA_FFI_Module_DestroyState(
122
+ XLA_FFI_Module_DestroyState_Args* args);
123
+
124
+ //===----------------------------------------------------------------------===//
125
+ // XLA FFI Error Reporting APIs.
126
+ //===----------------------------------------------------------------------===//
127
+
128
+ typedef struct {
129
+ size_t struct_size;
130
+ void* priv;
131
+ const char* message;
132
+ XLA_FFI_Error_Code errc;
133
+ } XLA_FFI_Error_Create_Args;
134
+
135
+ const size_t XLA_FFI_Error_Create_Args_STRUCT_SIZE =
136
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_Error_Create_Args, message);
137
+
138
+ typedef XLA_FFI_Error* XLA_FFI_Error_Create(XLA_FFI_Error_Create_Args* args);
139
+
140
+ //===----------------------------------------------------------------------===//
141
+ // XLA FFI Stream.
142
+ //===----------------------------------------------------------------------===//
143
+
144
+ // XLA FFI stream is an opaque handle to the underlying stream executor `Stream`
145
+ // implementation. In XLA:GPU it is `se::gpu::GpuStreamHandle` (when running on
146
+ // CUDA platform it is a `CUstream`).
147
+ typedef struct XLA_FFI_Stream XLA_FFI_Stream;
148
+
149
+ //===----------------------------------------------------------------------===//
150
+ // XLA FFI Execution Context.
151
+ //===----------------------------------------------------------------------===//
152
+
153
+ typedef struct XLA_FFI_ExecutionContext XLA_FFI_ExecutionContext;
154
+
155
+ // Get `XLA_FFI_Module_State` from the execution context.
156
+ typedef struct {
157
+ size_t struct_size;
158
+ void* priv;
159
+ XLA_FFI_ExecutionContext* ctx;
160
+ } XLA_FFI_ExecutionContext_GetModuleState_Args;
161
+
162
+ const size_t XLA_FFI_ExecutionContext_GetModuleState_Args_STRUCT_SIZE =
163
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_ExecutionContext_GetModuleState_Args, ctx);
164
+
165
+ typedef XLA_FFI_Module_State* XLA_FFI_ExecutionContext_GetModuleState(
166
+ XLA_FFI_ExecutionContext_GetModuleState_Args* args);
167
+
168
+ // Get `XLA_FFI_Stream` from the execution context.
169
+ typedef struct {
170
+ size_t struct_size;
171
+ void* priv;
172
+ XLA_FFI_ExecutionContext* ctx;
173
+ } XLA_FFI_ExecutionContext_GetStream_Args;
174
+
175
+ const size_t XLA_FFI_ExecutionContext_GetStream_Args_STRUCT_SIZE =
176
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_ExecutionContext_GetStream_Args, ctx);
177
+
178
+ typedef XLA_FFI_Stream* XLA_FFI_ExecutionContext_GetStream(
179
+ XLA_FFI_ExecutionContext_GetStream_Args* args);
180
+
181
+ //===----------------------------------------------------------------------===//
182
+ // XLA FFI Function API.
183
+ //===----------------------------------------------------------------------===//
184
+
185
+ // Arguments passed to an FFI function.
186
+ typedef struct {
187
+ size_t struct_size;
188
+ void* priv;
189
+ const XLA_FFI_Api* api;
190
+ XLA_FFI_ExecutionContext* ctx;
191
+ void** args;
192
+ void** attrs;
193
+ void** rets;
194
+ } XLA_FFI_Function_Args;
195
+
196
+ const size_t XLA_FFI_Function_Args_STRUCT_SIZE =
197
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_Function_Args, rets);
198
+
199
+ // XLA FFI function type that can be exported to a runtime.
200
+ typedef XLA_FFI_Error* XLA_FFI_Function(XLA_FFI_Function_Args* args);
201
+
202
+ //===----------------------------------------------------------------------===//
203
+ // XLA FFI Api.
204
+ //===----------------------------------------------------------------------===//
205
+
206
+ // Register FFI module with an XLA runtime.
207
+ typedef struct {
208
+ size_t struct_size;
209
+ void* priv;
210
+ const char* name;
211
+ XLA_FFI_Module* module;
212
+ XLA_FFI_Module_StateType state_type;
213
+ XLA_FFI_Module_CreateState* create_state;
214
+ XLA_FFI_Module_DestroyState* destroy_state;
215
+ int64_t num_exported_functions;
216
+ const char** exported_names; // length == num_exported_functions
217
+ XLA_FFI_Function** exported_functions; // length == num_exported_functions
218
+ } XLA_FFI_Module_Register_Args;
219
+
220
+ const size_t XLA_FFI_Module_Register_Args_STRUCT_SIZE =
221
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_Module_Register_Args, exported_functions);
222
+
223
+ typedef void XLA_FFI_Module_Register(XLA_FFI_Module_Register_Args* args);
224
+
225
+ #define XLA_FFI_API_STRUCT_FIELD(fn_type) fn_type* fn_type
226
+
227
+ #define XLA_FFI_API_TYPEID_FIELD(type) \
228
+ XLA_FFI_Get_TypeId* XLA_FFI_Get_##type##_TypeId
229
+
230
+ typedef struct XLA_FFI_Api {
231
+ size_t struct_size;
232
+ void* priv;
233
+
234
+ XLA_FFI_API_STRUCT_FIELD(XLA_FFI_Module_Register);
235
+
236
+ XLA_FFI_API_STRUCT_FIELD(XLA_FFI_ExecutionContext_GetModuleState);
237
+ XLA_FFI_API_STRUCT_FIELD(XLA_FFI_ExecutionContext_GetStream);
238
+
239
+ XLA_FFI_API_STRUCT_FIELD(XLA_FFI_Error_Create);
240
+
241
+ XLA_FFI_API_TYPEID_FIELD(String);
242
+ XLA_FFI_API_TYPEID_FIELD(Float);
243
+ XLA_FFI_API_TYPEID_FIELD(Double);
244
+ XLA_FFI_API_TYPEID_FIELD(Int1);
245
+ XLA_FFI_API_TYPEID_FIELD(Int32);
246
+ XLA_FFI_API_TYPEID_FIELD(Int64);
247
+
248
+ XLA_FFI_API_TYPEID_FIELD(FloatArray);
249
+ XLA_FFI_API_TYPEID_FIELD(DoubleArray);
250
+ XLA_FFI_API_TYPEID_FIELD(Int32Array);
251
+ XLA_FFI_API_TYPEID_FIELD(Int64Array);
252
+
253
+ XLA_FFI_API_TYPEID_FIELD(FloatTensor);
254
+ XLA_FFI_API_TYPEID_FIELD(DoubleTensor);
255
+ XLA_FFI_API_TYPEID_FIELD(Int32Tensor);
256
+ XLA_FFI_API_TYPEID_FIELD(Int64Tensor);
257
+
258
+ XLA_FFI_API_TYPEID_FIELD(BufferArg);
259
+ XLA_FFI_API_TYPEID_FIELD(StridedBufferArg);
260
+ XLA_FFI_API_TYPEID_FIELD(Dictionary);
261
+ } XLA_FFI_Api;
262
+
263
+ #undef XLA_FFI_API_STRUCT_FIELD
264
+ #undef XLA_FFI_API_TYPEID_FIELD
265
+
266
+ const size_t XLA_FFI_Api_STRUCT_SIZE =
267
+ XLA_FFI_STRUCT_SIZE(XLA_FFI_Api, XLA_FFI_Get_StridedBufferArg_TypeId);
268
+
269
+ // Does not pass ownership of returned XLA_FFI_Api* to caller.
270
+ const XLA_FFI_Api* GetXlaFfiApi();
271
+
272
+ #ifdef __cplusplus
273
+ }
274
+ #endif
275
+
276
+ #endif // XLA_RUNTIME_FFI_FFI_C_API_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/jit_executable.h ADDED
@@ -0,0 +1,240 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_JIT_EXECUTABLE_H_
17
+ #define XLA_RUNTIME_JIT_EXECUTABLE_H_
18
+
19
+ #include <any>
20
+ #include <memory>
21
+ #include <optional>
22
+ #include <string>
23
+ #include <string_view>
24
+ #include <utility>
25
+ #include <vector>
26
+
27
+ #include "absl/status/statusor.h"
28
+ #include "xla/mlir/runtime/transforms/jit_compiler.h"
29
+ #include "xla/runtime/async_values_cache.h" // IWYU pragma: keep
30
+ #include "xla/runtime/constraints.h"
31
+ #include "tfrt/concurrency/async_value_ref.h" // from @tf_runtime
32
+ #include "tfrt/concurrency/chain.h" // from @tf_runtime
33
+
34
+ namespace xla {
35
+ namespace runtime {
36
+
37
+ // JitExecutable owns a default executable compiled from the MLIR module (if
38
+ // operands constraints allow that), and orchestrates on-demand re-compilation
39
+ // for specific argument ranks, shapes or values depending on the operands
40
+ // constraints.
41
+ class JitExecutable {
42
+ public:
43
+ using UserData = std::any;
44
+
45
+ // XLA program can be specialized and recompiled at runtime to the concrete
46
+ // input shapes and sometimes values (e.g. reduction dimension).
47
+ enum class Specialization {
48
+ // Recompile specialized executables when needed.
49
+ kEnabled,
50
+ // Completely disable specialized executables (always call default
51
+ // executable).
52
+ kDisabled,
53
+ // Always use specialized executables, and never call default executable
54
+ // (only required for getting reproducible results in benchmarks).
55
+ kAlways,
56
+ };
57
+
58
+ struct Options {
59
+ // What level of specialization is enabled at runtime.
60
+ Specialization specialization = Specialization::kAlways;
61
+
62
+ // Options for the XLA runtime JitCompiler.
63
+ JitCompiler::Options compiler;
64
+ };
65
+
66
+ // We use `llvm::unique_function` to represent compilation task because it
67
+ // allows to capture move-only values.
68
+ using CompilationTask = llvm::unique_function<void()>;
69
+
70
+ // Compilation task runner called at runtime when specialization compilation
71
+ // is required with the `TaskFunction` that does the compilation, and updates
72
+ // the internal state of the `JitExecutable`. This runner can be used by the
73
+ // caller to offload compilation task to the specialized thread pool and
74
+ // add tracing events (e.g. add Tensorflow profiler tracing). Task runner must
75
+ // call the `TaskFunction`, otherwise it will lead to deadlock.
76
+ //
77
+ // Caller can pass arbitrary user data to the `GetExecutable` method, and it
78
+ // will be passed to the runner if recompilation is required. It is guaranteed
79
+ // that the runner will be called in the same thread as `GetExecutable`.
80
+ //
81
+ using CompilationTaskRunner =
82
+ llvm::unique_function<void(size_t, absl::Span<const ArgumentConstraint>,
83
+ ArgumentsRef, CompilationTask, UserData)>;
84
+
85
+ // Inline compilation task runner runs compilation task in the caller thread.
86
+ static void InlineCompilationTaskRunner(
87
+ size_t num_specializations,
88
+ absl::Span<const ArgumentConstraint> constraints, ArgumentsRef arguments,
89
+ CompilationTask task, UserData user_data);
90
+
91
+ // TODO(ezhulenev): Currently exported functions must be defined explicitly by
92
+ // the user. It should be possible to define exported functions implicitly by
93
+ // having `rt.export` operations in the compiled module, and export new
94
+ // functions while running compilation pipeline. Also `Executable` potentially
95
+ // might have more exported functions than the `JitExecutable` that
96
+ // instantiated it. Consider adding "private" exported functions, that are not
97
+ // visible through the `Executable` API (e.g. function references might be
98
+ // passed to custom calls, but they should not be visible to the client).
99
+ static absl::StatusOr<JitExecutable> Instantiate(
100
+ std::string_view mlir_module, Options opts,
101
+ absl::Span<const std::string_view> exported,
102
+ std::string_view memory_region_name = "",
103
+ CompilationTaskRunner runner = InlineCompilationTaskRunner);
104
+
105
+ static absl::StatusOr<JitExecutable> Instantiate(
106
+ std::string_view mlir_module, std::string_view exported, Options opts,
107
+ std::string_view memory_region_name = "",
108
+ CompilationTaskRunner runner = InlineCompilationTaskRunner) {
109
+ return Instantiate(mlir_module, opts, {exported}, memory_region_name,
110
+ std::move(runner));
111
+ }
112
+
113
+ // Returns default executable that accepts all compatible operands
114
+ // (operands rank and all static dimensions should match the operands).
115
+ tsl::AsyncValuePtr<Executable> DefaultExecutable() const;
116
+
117
+ // Returns an executable that may be specialized for the arguments. Can return
118
+ // default executable if no specialization is required, or if the specialized
119
+ // executable is not yet available.
120
+ //
121
+ // Caller can pass arbitrary data via the `user_data` argument, and it will be
122
+ // available to the compilation task runner. This can be used for tracing,
123
+ // e.g. to track what user-level requests triggered recompilation.
124
+ //
125
+ // Returns an error if the arguments do not match the expected function
126
+ // signature and specialization is not possible (without trying to compile).
127
+ // If specialization is disabled, returns the default executable without
128
+ // checking the arguments (the default executable itself will check arguments
129
+ // when called).
130
+ //
131
+ // Async values holding compilation results (executables) cached in the
132
+ // JitExecutable, and successive calls with the same arguments are cheap (the
133
+ // definition of "same" depend on the argument type specialization and chosen
134
+ // hash function, e.g. shaped arguments compared using their symbolic shape).
135
+ // If compilation fails, then the returned async value will hold a compilation
136
+ // error message. Compilation errors are never retried.
137
+ //
138
+ // Note: This function never falls back on the default executable if
139
+ // specialization compilation fails.
140
+ //
141
+ // TODO(ezhulenev): Add support for specifying exported function ordinal,
142
+ // currently this will always specialize exported function with ordinal 0.
143
+ absl::StatusOr<tsl::AsyncValuePtr<Executable>> GetExecutable(
144
+ ArgumentsRef arguments, UserData user_data = {},
145
+ const SpecializationListener* listener = nullptr);
146
+
147
+ // Returns an async value that becomes ready when all executables owned by
148
+ // this JitExecutable are compiled (no pending compilation tasks).
149
+ tsl::AsyncValueRef<tsl::Chain> AllExecutablesCompiled() const;
150
+
151
+ // JitExecutable is move-only type.
152
+ JitExecutable(const JitExecutable&) = delete;
153
+ JitExecutable(JitExecutable&&) = default;
154
+
155
+ std::string_view mlir_module() { return mlir_module_; }
156
+
157
+ unsigned num_functions() const { return functions_.size(); }
158
+
159
+ private:
160
+ // JitExecutable defines multiple exported functions that could be compiled
161
+ // into the executable. At run time they are referenced by their ordinal, so
162
+ // that we don't depend on expensive by-name lookup on the hot path. Function
163
+ // ordinal is defined by its index in the `functions_` vector.
164
+ //
165
+ // TODO(ezhulenev): Today when JitExecutable instantiates specialized
166
+ // executable via call to `GetExecutable` it can only specialize the function
167
+ // with ordinal 0. It should be possible to specialize multiple functions, and
168
+ // select which functions should be compiled at all.
169
+ struct Function {
170
+ Function(std::string_view name, FunctionType signature,
171
+ absl::Span<const ArgumentConstraint> constraints);
172
+
173
+ Function(const Function&) = delete;
174
+ Function(Function&&) = default;
175
+
176
+ // Exported function name.
177
+ std::string name;
178
+
179
+ // Signature of the exported function.
180
+ //
181
+ // This function signature is allowed to have operands and results types
182
+ // without a well-defined ABI (e.g. it can have tensors when compiled module
183
+ // defined in Tensorflow dialect), and it corresponds to the executable
184
+ // definition in one of the high level dialects (e.g. Tensorflow or mHLO).
185
+ //
186
+ // When compiled module prepared for execution, function operands and
187
+ // results are mapped to the types with well-defined ABI (e.g. tensors
188
+ // mapped to memrefs). See `runtime_signature` documentation in the
189
+ // `Executable::Function` type.
190
+ FunctionType signature;
191
+
192
+ // Exported function arguments constraints after resolving them using the
193
+ // statically known information in the function signature. If constraint
194
+ // specified by the argument attribute known to be statically satisfied by
195
+ // the argument type (e.g. rank constraint with an operand of statically
196
+ // known rank), then the constraint value for that operand will be updated
197
+ // to `kResolved`.
198
+ llvm::SmallVector<ArgumentConstraint> constraints;
199
+
200
+ // True if any of the arguments has `ArgumentConstraint::kValue` constraint.
201
+ bool has_value_constraints;
202
+
203
+ // Symbolic shape resolver assigns symbolic dimensions to runtime operands
204
+ // based on the exported function signature.
205
+ SymbolicShapesResolver symbolic_shapes_resolver;
206
+ };
207
+
208
+ JitExecutable(std::string_view mlir_module, Options opts,
209
+ std::vector<Function> functions,
210
+ std::optional<Executable> default_executable,
211
+ std::string_view memory_region_name,
212
+ CompilationTaskRunner runner);
213
+
214
+ std::string mlir_module_;
215
+ Options opts_;
216
+
217
+ // Functions exported by this jit executable, indexed by function ordinal.
218
+ std::vector<Function> functions_;
219
+
220
+ // Default executable that was not specialized to any of the arguments.
221
+ AsyncValueRef<Executable> default_executable_;
222
+ bool has_default_executable_;
223
+
224
+ // Name of the memory region where JIT'ed code is compiled to.
225
+ // This allows profilers to correctly label JIT-executed code.
226
+ // Note: this feature might only be available on some platforms, e.g. Linux.
227
+ std::string memory_region_name_;
228
+
229
+ // A custom runner for compiling specializations.
230
+ CompilationTaskRunner runner_;
231
+
232
+ // Executables specialized for the arguments shapes or/and values.
233
+ using Specializations = AsyncValuesCache<llvm::hash_code, Executable>;
234
+ std::unique_ptr<Specializations> specializations_;
235
+ };
236
+
237
+ } // namespace runtime
238
+ } // namespace xla
239
+
240
+ #endif // XLA_RUNTIME_JIT_EXECUTABLE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/logical_result.h ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_LOGICAL_RESULT_H_
17
+ #define XLA_RUNTIME_LOGICAL_RESULT_H_
18
+
19
+ #include "mlir/Support/LogicalResult.h" // from @llvm-project
20
+
21
+ namespace xla {
22
+ namespace runtime {
23
+
24
+ using ::mlir::failure; // NOLINT
25
+ using ::mlir::success; // NOLINT
26
+
27
+ using ::mlir::failed; // NOLINT
28
+ using ::mlir::succeeded; // NOLINT
29
+
30
+ using ::mlir::FailureOr; // NOLINT
31
+ using ::mlir::LogicalResult; // NOLINT
32
+
33
+ } // namespace runtime
34
+ } // namespace xla
35
+
36
+ #endif // XLA_RUNTIME_LOGICAL_RESULT_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/map_by_type.h ADDED
@@ -0,0 +1,110 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_MAP_BY_TYPE_H_
17
+ #define XLA_RUNTIME_MAP_BY_TYPE_H_
18
+
19
+ #include <algorithm>
20
+ #include <vector>
21
+
22
+ #include "llvm/ADT/SmallVector.h"
23
+ #include "xla/runtime/type_id.h"
24
+
25
+ namespace xla {
26
+ namespace runtime {
27
+
28
+ // An optimized map container for storing pointers of different types.
29
+ //
30
+ // Example:
31
+ //
32
+ // PtrMapByType<IdSet> map;
33
+ //
34
+ // int32_t i32 = 0;
35
+ // int64_t i64 = 1;
36
+ //
37
+ // map.insert(&i32);
38
+ // map.insert(&i64);
39
+ //
40
+ // assert(map.contains<int32_t*>());
41
+ // assert(map.contains<int64_t*>());
42
+ //
43
+ template <typename IdSet, unsigned n = 16>
44
+ class PtrMapByType {
45
+ public:
46
+ PtrMapByType() = default;
47
+
48
+ template <typename... Ts>
49
+ explicit PtrMapByType(Ts*... values) {
50
+ insert_all<Ts...>(values..., std::make_index_sequence<sizeof...(Ts)>{});
51
+ }
52
+
53
+ template <typename T>
54
+ T* insert(T* value) {
55
+ size_t id = GetDenseTypeId<T>();
56
+ if (id >= data_.size()) {
57
+ data_.resize(id + 1);
58
+ }
59
+ data_[id] = const_cast<std::decay_t<T>*>(value);
60
+ return value;
61
+ }
62
+
63
+ template <typename... Ts>
64
+ void insert_all(Ts*... values) {
65
+ insert_all<Ts...>(values..., std::make_index_sequence<sizeof...(Ts)>{});
66
+ }
67
+
68
+ template <typename T>
69
+ T* get() const {
70
+ size_t id = GetDenseTypeId<T>();
71
+ assert(id < data_.size());
72
+ return reinterpret_cast<T*>(data_[id]);
73
+ }
74
+
75
+ template <typename T>
76
+ T* getIfExists() const {
77
+ size_t id = GetDenseTypeId<T>();
78
+ return LLVM_LIKELY(id < data_.size()) ? reinterpret_cast<T*>(data_[id])
79
+ : nullptr;
80
+ }
81
+
82
+ template <typename T>
83
+ bool contains() const {
84
+ size_t id = GetDenseTypeId<T>();
85
+ return id < data_.size() && data_[id] != nullptr;
86
+ }
87
+
88
+ private:
89
+ template <typename T>
90
+ static size_t GetDenseTypeId() {
91
+ return DenseTypeId<IdSet>::template get<T>();
92
+ }
93
+
94
+ template <typename... Ts, size_t... Is>
95
+ void insert_all(Ts*... values, std::index_sequence<Is...>) {
96
+ static constexpr size_t kNumInserted = sizeof...(Ts);
97
+ if constexpr (kNumInserted > 0) {
98
+ std::array<size_t, kNumInserted> ids = {GetDenseTypeId<Ts>()...};
99
+ data_.resize(1 + *std::max_element(ids.begin(), ids.end()), nullptr);
100
+ ((data_[ids[Is]] = const_cast<std::decay_t<Ts>*>(values)), ...);
101
+ }
102
+ }
103
+
104
+ llvm::SmallVector<void*, n> data_;
105
+ };
106
+
107
+ } // namespace runtime
108
+ } // namespace xla
109
+
110
+ #endif // XLA_RUNTIME_MAP_BY_TYPE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memory_mapper.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_MEMORY_MAPPER_H_
17
+ #define XLA_RUNTIME_MEMORY_MAPPER_H_
18
+
19
+ #include <memory>
20
+ #include <string>
21
+ #include <string_view>
22
+ #include <system_error> // NOLINT
23
+
24
+ #include "tsl/platform/platform.h"
25
+
26
+ #if defined(PLATFORM_GOOGLE)
27
+ #include "xla/runtime/google/memory_mapper.h"
28
+ #else
29
+ #include "xla/runtime/default/memory_mapper.h"
30
+ #endif
31
+
32
+ #include "llvm/ExecutionEngine/SectionMemoryManager.h"
33
+
34
+ namespace xla {
35
+ namespace runtime {
36
+
37
+ // XLA runtime memory mapper allocates memory for XLA executables (object files)
38
+ // using `memfd_create` system call, and gives the user-friendly name to the
39
+ // file descriptor, so that for example in `perf` it should be possible to
40
+ // identify input XLA programs by name.
41
+ class XlaRuntimeMemoryMapper final
42
+ : public llvm::SectionMemoryManager::MemoryMapper {
43
+ public:
44
+ static std::unique_ptr<XlaRuntimeMemoryMapper> Create(std::string_view name);
45
+
46
+ llvm::sys::MemoryBlock allocateMappedMemory(
47
+ llvm::SectionMemoryManager::AllocationPurpose purpose, size_t len,
48
+ const llvm::sys::MemoryBlock* const near_block, unsigned prot_flags,
49
+ std::error_code& error_code) final;
50
+
51
+ std::error_code protectMappedMemory(const llvm::sys::MemoryBlock& block,
52
+ unsigned prot_flags) final;
53
+
54
+ std::error_code releaseMappedMemory(llvm::sys::MemoryBlock& block) final;
55
+
56
+ private:
57
+ explicit XlaRuntimeMemoryMapper(std::string_view name) : name_(name) {}
58
+
59
+ std::string name_;
60
+ };
61
+
62
+ } // namespace runtime
63
+ } // namespace xla
64
+
65
+ #endif // XLA_RUNTIME_MEMORY_MAPPER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/memref_view.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2023 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 XLA_RUNTIME_MEMREF_VIEW_H_
17
+ #define XLA_RUNTIME_MEMREF_VIEW_H_
18
+
19
+ #include <cstdint>
20
+
21
+ #include "absl/types/span.h"
22
+ #include "xla/xla_data.pb.h"
23
+
24
+ namespace xla {
25
+ namespace runtime {
26
+
27
+ // A view into the memref argument. Corresponds to the MemrefDesc, however it
28
+ // doesn't own the sizes/strides vectors, and cheap to pass around. Memrefs with
29
+ // non-identity layouts can be decoded only as a StridedMemrefView.
30
+ struct StridedMemrefView {
31
+ PrimitiveType dtype;
32
+ void* data;
33
+ absl::Span<const int64_t> sizes;
34
+ absl::Span<const int64_t> strides;
35
+ };
36
+
37
+ // A view into the memref argument with an identity (row major) layout.
38
+ struct MemrefView {
39
+ PrimitiveType dtype;
40
+ void* data;
41
+ absl::Span<const int64_t> sizes;
42
+ };
43
+
44
+ // A flat view into memref argument with an identity (row major) layout. If the
45
+ // memref shape and strides are not required for the custom call, it's cheaper
46
+ // to pass the flat view.
47
+ struct FlatMemrefView {
48
+ PrimitiveType dtype;
49
+ void* data;
50
+ int64_t size_in_bytes;
51
+ };
52
+
53
+ } // namespace runtime
54
+ } // namespace xla
55
+
56
+ #endif // XLA_RUNTIME_MEMREF_VIEW_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module.h ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_MODULE_H_
17
+ #define XLA_RUNTIME_MODULE_H_
18
+
19
+ #include <memory>
20
+ #include <optional>
21
+ #include <string>
22
+ #include <string_view>
23
+ #include <type_traits>
24
+ #include <utility>
25
+
26
+ #include "absl/status/status.h"
27
+ #include "absl/status/statusor.h"
28
+ #include "xla/runtime/custom_call_registry.h"
29
+
30
+ namespace xla {
31
+ namespace runtime {
32
+
33
+ template <typename S, typename R>
34
+ class StatefulModule;
35
+ class StatelessModule;
36
+
37
+ //===---------------------------------------------------------------------===///
38
+ // Xla runtime module.
39
+ //===---------------------------------------------------------------------===///
40
+
41
+ // Xla runtime module is a way to structure custom calls (external functions)
42
+ // together with the state required for calling them. Xla runtime executable can
43
+ // be linked with multiple of such modules at run time.
44
+ //
45
+ // As an example Xla Gpu has a StreamExecutor-based HAL (hardware abstraction
46
+ // layer) implemented as a runtime module. Different Xla backends can require
47
+ // different sets of modules for running executables, and some of the modules
48
+ // can be shared between backends (e.g. XProf integration).
49
+ //
50
+ // User-defined modules must inherit from `StatefulModule` or `StatelessModule`.
51
+ class Module {
52
+ public:
53
+ // When a module is instantiated for each runtime executable it can optionally
54
+ // create a state object that can be used to implement stateful functions,
55
+ // to keep a state between exported functions invocations. State can be
56
+ // accessed from different executable invocations running concurrently.
57
+ struct State {
58
+ virtual ~State() = default;
59
+ };
60
+
61
+ // StateRef is a potentially long-lived reference held by the runtime that
62
+ // must guarantee that all pointers added to the user data container are
63
+ // pointing to live objects (see `InitializeUserData` for more details).
64
+ struct StateRef {
65
+ virtual ~StateRef() = default;
66
+ };
67
+
68
+ virtual ~Module() = default;
69
+
70
+ virtual std::string_view name() const = 0;
71
+
72
+ // Creates a new per-executable module state.
73
+ virtual absl::StatusOr<std::unique_ptr<State>> CreateState() const = 0;
74
+
75
+ // Initializes `user_data` with values required for calling functions exported
76
+ // from the module. If initializing `user_data` requires creating temporaries,
77
+ // then the returned `StateRef` should guarantee their lifetime. Runtime
78
+ // itself guarantees that `state` is alive when it calls any of the exported
79
+ // functions; this means that `user_data` can safely point to `state`'s
80
+ // members.
81
+ virtual absl::StatusOr<std::unique_ptr<StateRef>> InitializeUserData(
82
+ State* state, CustomCall::UserData& user_data) const = 0;
83
+
84
+ // Exports direct custom calls provided by this module to the registry.
85
+ virtual void Export(DirectCustomCallRegistry& registry) const {}
86
+
87
+ // Exports dynamic custom calls provided by this module to the registry.
88
+ virtual void Export(DynamicCustomCallRegistry& registry) const {}
89
+
90
+ private:
91
+ template <typename S, typename R>
92
+ friend class StatefulModule;
93
+ friend class StatelessModule;
94
+
95
+ Module() = default;
96
+ };
97
+
98
+ //===---------------------------------------------------------------------===///
99
+ // Stateful and typed Xla runtime module.
100
+ //===---------------------------------------------------------------------===///
101
+
102
+ template <typename S, typename R = void>
103
+ class StatefulModule : public Module {
104
+ static_assert(std::is_base_of_v<State, S>,
105
+ "State must be derived from Module::State");
106
+
107
+ static_assert(std::is_base_of_v<StateRef, R> || std::is_void_v<R>,
108
+ "State ref must be `void` or derived from Module::StateRef");
109
+
110
+ public:
111
+ std::string_view name() const final { return name_; }
112
+
113
+ // Creates a new per-executable module State.
114
+ virtual absl::StatusOr<std::unique_ptr<S>> CreateModuleState() const = 0;
115
+
116
+ // If state ref is void then UserData initialization must return
117
+ // `absl::Status`, otherwise it must return `absl::StatusOr` with a state
118
+ // reference value.
119
+ virtual std::conditional_t<std::is_void_v<R>, absl::Status,
120
+ absl::StatusOr<std::unique_ptr<R>>>
121
+ InitializeUserData(S* state, CustomCall::UserData& user_data) const {
122
+ if constexpr (std::is_void_v<R>) {
123
+ return absl::OkStatus();
124
+ } else {
125
+ return nullptr;
126
+ }
127
+ }
128
+
129
+ protected:
130
+ explicit StatefulModule(std::string name) : name_(std::move(name)) {}
131
+
132
+ private:
133
+ absl::StatusOr<std::unique_ptr<State>> CreateState() const final {
134
+ return CreateModuleState();
135
+ }
136
+
137
+ absl::StatusOr<std::unique_ptr<StateRef>> InitializeUserData(
138
+ State* state, CustomCall::UserData& user_data) const final {
139
+ auto initialized = InitializeUserData(dynamic_cast<S*>(state), user_data);
140
+
141
+ // Convert `absl::OkStatus` to an `absl::StatusOr` with an empty state ref.
142
+ if constexpr (std::is_void_v<R>) {
143
+ if (initialized.ok()) return nullptr;
144
+ }
145
+
146
+ return initialized;
147
+ }
148
+
149
+ std::string name_;
150
+ };
151
+
152
+ //===---------------------------------------------------------------------===///
153
+ // Stateless Xla runtime module.
154
+ //===---------------------------------------------------------------------===///
155
+
156
+ class StatelessModule : public Module {
157
+ public:
158
+ std::string_view name() const final { return name_; }
159
+
160
+ virtual absl::Status InitializeUserData(
161
+ CustomCall::UserData& user_data) const {
162
+ return absl::OkStatus();
163
+ }
164
+
165
+ protected:
166
+ explicit StatelessModule(std::string name) : name_(std::move(name)) {}
167
+
168
+ private:
169
+ absl::StatusOr<std::unique_ptr<State>> CreateState() const final {
170
+ return nullptr;
171
+ }
172
+
173
+ absl::StatusOr<std::unique_ptr<StateRef>> InitializeUserData(
174
+ State* state, CustomCall::UserData& user_data) const final {
175
+ if (auto init = InitializeUserData(user_data); !init.ok()) return init;
176
+ return nullptr;
177
+ }
178
+
179
+ std::string name_;
180
+ };
181
+
182
+ } // namespace runtime
183
+ } // namespace xla
184
+
185
+ #endif // XLA_RUNTIME_MODULE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/module_registry.h ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_MODULE_REGISTRY_H_
17
+ #define XLA_RUNTIME_MODULE_REGISTRY_H_
18
+
19
+ #include <memory>
20
+ #include <utility>
21
+ #include <vector>
22
+
23
+ #include "xla/runtime/module.h"
24
+
25
+ namespace xla {
26
+ namespace runtime {
27
+
28
+ // Registers Xla runtime module with a global modules registry.
29
+ //
30
+ // TODO(ezhulenev): We need to support modules restricted for different
31
+ // platforms, e.g. we should not instantiate state for GPU modules when
32
+ // compiling a CPU executable. Xla today uses a "platform name" (Host,
33
+ // CUDA, etc...) for this.
34
+ void RegisterModule(std::unique_ptr<Module> module);
35
+
36
+ // Exports registered modules to the given custom call registry.
37
+ //
38
+ // TODO(ezhulenev): We also need to support exporting direct custom calls.
39
+ void ExportModules(DynamicCustomCallRegistry& registry);
40
+
41
+ // Helper macro to define a static module registration.
42
+ #define XLA_REGISTER_RUNTIME_MODULE(FUNC) \
43
+ XLA_REGISTER_RUNTIME_MODULE_IMPL(FUNC, __COUNTER__)
44
+
45
+ #define XLA_REGISTER_RUNTIME_MODULE_IMPL(FUNC, N) \
46
+ static bool xla_runtime_module_##N##_registered_ = []() { \
47
+ ::xla::runtime::RegisterModule(FUNC); \
48
+ return true; \
49
+ }()
50
+
51
+ // Container that owns the state of all registered modules.
52
+ class ModulesState {
53
+ public:
54
+ ModulesState() = default;
55
+
56
+ // Instantiates `ModulesState` from the registered module.
57
+ //
58
+ // TODO(ezhulenev): Take module's platform.
59
+ static absl::StatusOr<ModulesState> Instantiate();
60
+
61
+ // Initializes `UserData` from the module's state.
62
+ absl::StatusOr<std::vector<std::unique_ptr<Module::StateRef>>>
63
+ InitializeUserData(CustomCall::UserData& user_data);
64
+
65
+ private:
66
+ explicit ModulesState(
67
+ std::vector<std::pair<Module*, std::unique_ptr<Module::State>>> state);
68
+
69
+ std::vector<std::pair<Module*, std::unique_ptr<Module::State>>> state_;
70
+ };
71
+
72
+ } // namespace runtime
73
+ } // namespace xla
74
+
75
+ #endif // XLA_RUNTIME_MODULE_REGISTRY_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/results.h ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_RESULTS_H_
17
+ #define XLA_RUNTIME_RESULTS_H_
18
+
19
+ #include <type_traits>
20
+
21
+ #include "xla/runtime/logical_result.h"
22
+ #include "xla/runtime/types.h"
23
+
24
+ namespace xla {
25
+ namespace runtime {
26
+
27
+ //===----------------------------------------------------------------------===//
28
+ // Conversions from XLA executable results to C++ types.
29
+ //===----------------------------------------------------------------------===//
30
+
31
+ // The result type defines its own ABI as a required number of bytes and
32
+ // alignment, and executable returns results by writing into the requested
33
+ // memory allocated in the call frame. The user is responsible for providing
34
+ // a conversion function that converts this opaque memory back to the C++
35
+ // data type. For example memrefs returned as a `StridedMemrefType` structure,
36
+ // and it is the user responsibiity to define a conversion function that can
37
+ // convert a memref to the run time Tensor/Buffer type.
38
+ //
39
+ // It is important that the type that is written into the call frame memory has
40
+ // a standard memory layout, because we rely on `reinterpret_cast` to reinterpet
41
+ // the opaque bytes to a C struct.
42
+ //
43
+ // See https://en.cppreference.com/w/cpp/types/is_standard_layout
44
+
45
+ // Result converter is responsible for taking a pointer to the memory location
46
+ // where the executable wrote the result, and converting it to the corresponding
47
+ // run time value expected by the caller (e.g. memref descriptor to Tensor).
48
+ class ResultConverter {
49
+ public:
50
+ virtual ~ResultConverter() = default;
51
+
52
+ // Converts value `ret` of type `runtime_type` (runtime type derived from the
53
+ // original `type`) returned from the executable at `result_index` result
54
+ // position using registered conversion functions. Returns a logical result
55
+ // telling if the conversion was successful.
56
+ virtual LogicalResult ReturnValue(unsigned result_index, const Type* type,
57
+ const Type* runtime_type,
58
+ void* ret) const = 0;
59
+
60
+ // Returns error for all results. This function is called if the runtime
61
+ // fails to run the executable, or if the executable returns an error.
62
+ //
63
+ // This function is not called if an individual `ReturnValue` conversion
64
+ // fails.
65
+ //
66
+ // It is the user's responsibility to handle the case where the return value
67
+ // conversion fails, and some error value has to be returned for unhandled
68
+ // results, e.g. error async value for unconverted results.
69
+ virtual void ReturnError(const absl::Status& error) const = 0;
70
+ };
71
+
72
+ //===----------------------------------------------------------------------===//
73
+ // Result converter for functions without results (returning void).
74
+ //===----------------------------------------------------------------------===//
75
+
76
+ struct NoResultConverter : public ResultConverter {
77
+ LLVM_ATTRIBUTE_ALWAYS_INLINE
78
+ LogicalResult ReturnValue(unsigned, const Type*, const Type*,
79
+ void*) const final {
80
+ assert(false && "no result converter must never be called");
81
+ return failure();
82
+ }
83
+
84
+ void ReturnError(const absl::Status&) const final {}
85
+ };
86
+
87
+ //===----------------------------------------------------------------------===//
88
+ // Returns results using user-provided set of conversion functions.
89
+ //===----------------------------------------------------------------------===//
90
+
91
+ template <typename RetError, typename... RetValue>
92
+ class ResultConverterSet : public ResultConverter {
93
+ static_assert(sizeof...(RetValue), "result converters must be non-empty");
94
+
95
+ static_assert(std::is_invocable_v<RetError, const absl::Status&>);
96
+
97
+ static_assert(std::conjunction_v<
98
+ std::is_invocable_r<LogicalResult, RetValue, unsigned,
99
+ const Type*, const Type*, void*>...>);
100
+
101
+ public:
102
+ explicit ResultConverterSet(RetError ret_error, RetValue... ret_value)
103
+ : ret_error_(std::move(ret_error)),
104
+ ret_value_(std::forward<RetValue>(ret_value)...) {}
105
+
106
+ LogicalResult ReturnValue(unsigned result_index, const Type* type,
107
+ const Type* runtime_type, void* ret) const final {
108
+ return ReturnValue<0>(result_index, type, runtime_type, ret);
109
+ }
110
+
111
+ void ReturnError(const absl::Status& error) const final { ret_error_(error); }
112
+
113
+ private:
114
+ template <size_t idx>
115
+ LogicalResult ReturnValue(unsigned result_index, const Type* type,
116
+ const Type* runtime_type, void* ret) const {
117
+ // Try to call the user-provided converter.
118
+ auto& converter = std::get<idx>(ret_value_);
119
+ if (succeeded(converter(result_index, type, runtime_type, ret)))
120
+ return success();
121
+
122
+ // If conversion failed try the next one if available.
123
+ if constexpr (idx + 1 < sizeof...(RetValue))
124
+ return ReturnValue<idx + 1>(result_index, type, runtime_type, ret);
125
+
126
+ return failure();
127
+ }
128
+
129
+ RetError ret_error_;
130
+ std::tuple<RetValue...> ret_value_;
131
+ };
132
+
133
+ template <typename RetError, typename... RetValue>
134
+ ResultConverterSet(RetError, RetValue...)
135
+ -> ResultConverterSet<RetError, RetValue...>;
136
+
137
+ //===----------------------------------------------------------------------===//
138
+ // Helper functions for converting results of canonical types.
139
+ //===----------------------------------------------------------------------===//
140
+
141
+ namespace internal {
142
+
143
+ // This struct corresponds to the `llvm.struct` used by memref to llvm lowering
144
+ // pass to represent memref descriptors in the compilation pipeline. It is a
145
+ // type-erased version of `::mlir::StridedMemRefType<T>` template.
146
+ struct MemrefDescriptor {
147
+ void* base_ptr;
148
+ void* data_ptr;
149
+ int64_t offset;
150
+ int64_t sizes_and_strides[];
151
+ };
152
+
153
+ } // namespace internal
154
+
155
+ // Converts returned memref using user-provided converter. Converter must
156
+ // satisfy this concept:
157
+ //
158
+ // struct Converter {
159
+ // ResultType operator()(PrimitiveType element_type, void* base_ptr,
160
+ // void* data_ptr, int64_t offset,
161
+ // absl::Span<const int64_t> dims,
162
+ // absl::Span<const int64_t> strides);
163
+ // };
164
+ //
165
+ template <typename T, typename Converter>
166
+ FailureOr<T> ConvertReturnedMemref(const Converter& converter,
167
+ const Type* memref_type, void* ret) {
168
+ // Check if the runtime type is a valid memref.
169
+ auto* memref = llvm::dyn_cast<MemrefType>(memref_type);
170
+ if (!memref) return failure();
171
+
172
+ PrimitiveType element_type = memref->element_type();
173
+ size_t rank = memref->rank();
174
+
175
+ auto* desc = reinterpret_cast<internal::MemrefDescriptor*>(ret);
176
+ absl::Span<const int64_t> dims(desc->sizes_and_strides, rank);
177
+ absl::Span<const int64_t> strides(desc->sizes_and_strides + rank, rank);
178
+
179
+ return converter(element_type, desc->base_ptr, desc->data_ptr, desc->offset,
180
+ dims, strides);
181
+ }
182
+
183
+ } // namespace runtime
184
+ } // namespace xla
185
+
186
+ #endif // XLA_RUNTIME_RESULTS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/runtime.h ADDED
@@ -0,0 +1,66 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_RUNTIME_H_
17
+ #define XLA_RUNTIME_RUNTIME_H_
18
+
19
+ #include <stdint.h>
20
+
21
+ namespace xla {
22
+ namespace runtime {
23
+
24
+ //===----------------------------------------------------------------------===//
25
+ // XLA Runtime <-> XLA Executable integration API.
26
+ //===----------------------------------------------------------------------===//
27
+
28
+ // This API enables compiled XLA executables to call back into the XLA runtime
29
+ // for:
30
+ //
31
+ // - Returning results back to the caller by writing to result storage
32
+ // allocated in the call frame.
33
+ // - User friendly error reporting integrated with the high level execution
34
+ // model (errors do not crash the compiled binary).
35
+ // - Invoking custom calls registered with the XLA runtime.
36
+ //
37
+ // XLA compilation pipeline sets up passes to convert the regular functions
38
+ // to the so called "XLA entrypoint functions" integrated with the runtime using
39
+ // the API defined below, e.g. instead of conventional returns all results are
40
+ // returned via the `GetResultStorage` API. At MLIR level these operations
41
+ // correspond to the `rt` dialect, and converted to LLVM using the `rt-to-llvm`
42
+ // conversion pass.
43
+ //
44
+ // Runtime errors are reported back to the runtime via the `SetError` API.
45
+ // The compilation pipeline will automatically convert assertions in the
46
+ // entrypoint function into run-time errors.
47
+
48
+ // Opaque runtime execution context passed as the first argument to compiled
49
+ // executables and passed back to all runtime API methods.
50
+ using ExecutionContext = struct ExecutionContext;
51
+
52
+ // Returns a pointer to the memory location of the result at the given index.
53
+ void *GetResultStorage(ExecutionContext *, int64_t);
54
+
55
+ // Sets execution context to an error state.
56
+ void SetError(ExecutionContext *, const char *);
57
+
58
+ // Calls the custom call function registered with the runtime. Returns true
59
+ // if the custom call was successful.
60
+ bool CustomCall(ExecutionContext *, const char *target, void **args,
61
+ void **attrs, void **rets);
62
+
63
+ } // namespace runtime
64
+ } // namespace xla
65
+
66
+ #endif // XLA_RUNTIME_RUNTIME_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/state.h ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_STATE_H_
17
+ #define XLA_RUNTIME_STATE_H_
18
+
19
+ #include <cstddef>
20
+ #include <memory>
21
+ #include <type_traits>
22
+ #include <vector>
23
+
24
+ #include "absl/status/status.h"
25
+ #include "absl/status/statusor.h"
26
+ #include "absl/synchronization/mutex.h"
27
+
28
+ namespace xla {
29
+ namespace runtime {
30
+
31
+ // Forward declare.
32
+ template <typename T>
33
+ class State;
34
+
35
+ // StateVector is a container for keeping the state between custom call
36
+ // invocations (within same or concurrent calls to `Executable::Execute`).
37
+ //
38
+ // Every instance of the custom call in the executable must be assigned a unique
39
+ // id (dense i64 integer in the [0, num_instances) range), and the state vector
40
+ // enables efficient access to value of type `T`, with lazy initialization done
41
+ // by the custom call itself.
42
+ //
43
+ // Custom calls implement special bindings for state arguments:
44
+ //
45
+ // CustomCall::Bind("foo")
46
+ // .State<FooState>("id_attr_name")
47
+ // .To([](State<FooState> state) {
48
+ // FooState foo = state.GetOrCreate(...);
49
+ // ...
50
+ // });
51
+ //
52
+ // State snapshot must be passed via UserData:
53
+ //
54
+ // StateVector<FooState>::Snapshot snapshot = ...;
55
+ // CustomCall::UserData user_data(&snapshot, ...);
56
+ //
57
+ // See `custom_call.h` and `custom_call_test.cc` for more examples.
58
+ template <typename T>
59
+ class StateVector {
60
+ public:
61
+ explicit StateVector(size_t reserve = 0);
62
+
63
+ // Snapshot wraps the read-only state snapshot (potentially obsolete) and
64
+ // falls back on synchronized state access if it can't find an entry in its
65
+ // read-only state snapshot.
66
+ class Snapshot {
67
+ public:
68
+ // Returns a state for the given id if it's already available, or tries to
69
+ // create a new one using the user-provided `create` function. Returns an
70
+ // error if state creation fails. Failures are not cached and always
71
+ // retried.
72
+ template <typename F>
73
+ absl::StatusOr<T*> GetOrCreate(size_t id, F&& create);
74
+
75
+ absl::StatusOr<T*> Get(size_t id);
76
+
77
+ absl::Status Erase(size_t id);
78
+
79
+ // Returns a state constructed from this snapshot for a given id.
80
+ State<T> state(size_t id) { return State<T>(id, this); }
81
+
82
+ private:
83
+ friend StateVector;
84
+ Snapshot(StateVector& state, std::shared_ptr<std::vector<T*>> snapshot);
85
+
86
+ // State vector that this snapshot was taken from.
87
+ StateVector& owning_state_;
88
+
89
+ // State vector snapshot captured at construction time. It might not contain
90
+ // all the latest data available in the `owning_state_`.
91
+ std::shared_ptr<std::vector<T*>> maybe_obsolete_snapshot_;
92
+ };
93
+
94
+ Snapshot snapshot();
95
+ T* operator[](size_t id);
96
+
97
+ private:
98
+ mutable absl::Mutex mu_;
99
+
100
+ // StateVector owns the values of type `T` indexed by the key.
101
+ std::vector<std::unique_ptr<T>> vector_ ABSL_GUARDED_BY(mu_);
102
+
103
+ // A read-only snapshot of `vector_` that is updated every time a new entry
104
+ // is added to the state vector.
105
+ std::shared_ptr<std::vector<T*>> vector_snapshot_ ABSL_GUARDED_BY(mu_);
106
+ };
107
+
108
+ template <typename T>
109
+ class State {
110
+ using Snapshot = typename StateVector<T>::Snapshot;
111
+
112
+ public:
113
+ template <typename F>
114
+ absl::StatusOr<T*> GetOrCreate(F&& create) {
115
+ return snapshot_->GetOrCreate(id_, std::forward<F>(create));
116
+ }
117
+
118
+ private:
119
+ friend Snapshot;
120
+ State(size_t id, Snapshot* snapshot) : id_(id), snapshot_(snapshot) {}
121
+
122
+ size_t id_;
123
+ Snapshot* snapshot_;
124
+ };
125
+
126
+ //===----------------------------------------------------------------------===//
127
+
128
+ template <typename T>
129
+ StateVector<T>::StateVector(size_t reserve)
130
+ : vector_(reserve), vector_snapshot_(new std::vector<T*>(reserve)) {}
131
+
132
+ template <typename T>
133
+ StateVector<T>::Snapshot::Snapshot(StateVector& state,
134
+ std::shared_ptr<std::vector<T*>> snapshot)
135
+ : owning_state_(state), maybe_obsolete_snapshot_(std::move(snapshot)) {}
136
+
137
+ template <typename T>
138
+ auto StateVector<T>::snapshot() -> Snapshot {
139
+ absl::MutexLock lock(&mu_);
140
+ return Snapshot(*this, vector_snapshot_);
141
+ }
142
+
143
+ template <typename T>
144
+ T* StateVector<T>::operator[](size_t id) {
145
+ absl::MutexLock lock(&mu_);
146
+ return id < vector_.size() ? vector_[id].get() : nullptr;
147
+ }
148
+
149
+ template <typename T>
150
+ template <typename F>
151
+ absl::StatusOr<T*> StateVector<T>::Snapshot::GetOrCreate(size_t id,
152
+ F&& create) {
153
+ static_assert(std::is_invocable_r_v<absl::StatusOr<T>, F>);
154
+
155
+ // If snapshot already contains the entry, just return it.
156
+ std::vector<T*>& snapshot = *maybe_obsolete_snapshot_;
157
+ if (id < snapshot.size() && snapshot[id]) return snapshot[id];
158
+
159
+ // Otherwise go through the slow synchronized code path.
160
+ absl::MutexLock lock(&owning_state_.mu_);
161
+
162
+ // Check if value is present in the state vector, and was not captured in
163
+ // the snapshot that we have.
164
+ std::vector<std::unique_ptr<T>>& state = owning_state_.vector_;
165
+ if (id < state.size() && state[id].get()) return state[id].get();
166
+
167
+ // Try to insert a new entry.
168
+ absl::StatusOr<T> value = create();
169
+ if (!value.ok()) return value.status();
170
+
171
+ // Update the state vector.
172
+ if (id >= state.size()) state.resize(id + 1);
173
+ state[id] = std::make_unique<T>(*std::move(value));
174
+
175
+ // And take the new snapshot.
176
+ auto new_snapshot = std::make_shared<std::vector<T*>>(state.size());
177
+ for (size_t i = 0; i < state.size(); ++i) (*new_snapshot)[i] = state[i].get();
178
+
179
+ // Update the snapshot owned by the state.
180
+ owning_state_.vector_snapshot_ = std::move(new_snapshot);
181
+
182
+ return state[id].get();
183
+ }
184
+
185
+ template <typename T>
186
+ absl::StatusOr<T*> StateVector<T>::Snapshot::Get(size_t id) {
187
+ // If snapshot already contains the entry, just return it.
188
+ std::vector<T*>& snapshot = *maybe_obsolete_snapshot_;
189
+ if (id < snapshot.size() && snapshot[id]) return snapshot[id];
190
+
191
+ // Otherwise go through the slow synchronized code path.
192
+ absl::MutexLock lock(&owning_state_.mu_);
193
+
194
+ // Check if value is present in the state vector, and was not captured in
195
+ // the snapshot that we have.
196
+ std::vector<std::unique_ptr<T>>& state = owning_state_.vector_;
197
+ if (id < state.size() && state[id].get()) return state[id].get();
198
+
199
+ return absl::InternalError("Value not found in state vector");
200
+ }
201
+
202
+ template <typename T>
203
+ absl::Status StateVector<T>::Snapshot::Erase(size_t id) {
204
+ absl::MutexLock lock(&owning_state_.mu_);
205
+
206
+ std::vector<std::unique_ptr<T>>& state = owning_state_.vector_;
207
+ if (id < state.size() && state[id].get()) {
208
+ state[id].reset(nullptr);
209
+ return absl::OkStatus();
210
+ }
211
+
212
+ return absl::InternalError("Value not found in state vector");
213
+ }
214
+
215
+ } // namespace runtime
216
+ } // namespace xla
217
+
218
+ #endif // XLA_RUNTIME_STATE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/symbolic_shape.h ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_SYMBOLIC_SHAPE_H_
17
+ #define XLA_RUNTIME_SYMBOLIC_SHAPE_H_
18
+
19
+ #include <optional>
20
+
21
+ #include "absl/status/statusor.h"
22
+ #include "llvm/ADT/DenseSet.h"
23
+ #include "llvm/ADT/Hashing.h"
24
+ #include "llvm/ADT/SmallVector.h"
25
+ #include "xla/runtime/arguments.h"
26
+ #include "xla/runtime/constraints.h"
27
+
28
+ namespace xla {
29
+ namespace runtime {
30
+
31
+ // Symbolic shapes resolver computes the symbolic shapes of the arguments based
32
+ // on the function signature, and concrete shapes of the arguments at runtime.
33
+ //
34
+ // Example: dimensions that have the same symbolic shape at runtime.
35
+ //
36
+ // signature: func @compute(%arg0: tensor<?xf32>, %arg1: tensor<?xf32)
37
+ // ^ ^
38
+ // arguments: memref<123xf32> memref<123xf32>
39
+ // ^ ^
40
+ // symbolic shapes: [-2xf32] [-2xf32]
41
+ //
42
+ // Each unknown dimension in the function signature will be assigned a symbolic
43
+ // dimension. If multiple shaped arguments have unknown dimensions that are the
44
+ // same at runtime, they will be assigned the same symbolic dimensions value
45
+ // (e.g. `-2` in the example above).
46
+ //
47
+ // If an unknown dimension at runtime is equal to some statically known
48
+ // dimension in the function signature (of any shaped argument), it will be
49
+ // resolved to that statically known constant value:
50
+ //
51
+ // Example: in this example unknown dimension of `arg0` replaced with a `32`.
52
+ //
53
+ // signature: func @compute(%arg0: tensor<?xf32>, %arg1: tensor<32xf32>)
54
+ // ^ ^
55
+ // arguments: memref<32xf32> memref<32xf32>
56
+ // ^ ^
57
+ // symbolic shapes: [32xf32] [32xf32]
58
+ //
59
+ // Unknown dimensions that are `1` at runtime are always materialized as a
60
+ // statically known `1` in the symbolic shape.
61
+ class SymbolicShapesResolver {
62
+ public:
63
+ // Dimension size can be symbolic (<= -2) or static.
64
+ using SymbolicShape = llvm::SmallVector<int64_t>;
65
+ // Dimension size can be dynamic (ShapedType::kDynamic) or static.
66
+ using StaticShape = llvm::SmallVector<int64_t>;
67
+
68
+ SymbolicShapesResolver(const FunctionType& signature,
69
+ absl::Span<const ArgumentConstraint> constraints);
70
+
71
+ // Resolves symbolic shapes from the runtime arguments. Returns failure if
72
+ // runtime dimensions do not match the statically known dimensions.
73
+ absl::StatusOr<llvm::SmallVector<SymbolicShape>> Resolve(
74
+ ArgumentsRef arguments) const;
75
+
76
+ // Resolves symbolic shapes and computes the hash value from the runtime
77
+ // arguments. Returns failure if runtime dimensions do not match the
78
+ // statically known dimensions.
79
+ //
80
+ // This function might not return the same hash value as calling `Resolve` and
81
+ // then `Hash`, because it might use more efficient hashing algorithm.
82
+ absl::StatusOr<llvm::hash_code> ResolveHash(ArgumentsRef arguments) const;
83
+
84
+ // Replaces all symbolic dimensions with dynamic dimension.
85
+ static StaticShape Normalize(const SymbolicShape& shape);
86
+
87
+ // Computes a hash value of the symbolic shapes.
88
+ static llvm::hash_code Hash(absl::Span<const SymbolicShape> symbolic_shapes);
89
+
90
+ ArgumentConstraint constraint(size_t index) const;
91
+ size_t num_arguments() const;
92
+ bool has_argument_sizes(size_t index) const;
93
+ const StaticShape& argument_sizes(size_t index) const;
94
+ bool seen_static_size(size_t dim) const;
95
+
96
+ private:
97
+ // Constraints on the function arguments.
98
+ llvm::SmallVector<ArgumentConstraint> constraints_;
99
+
100
+ // Statically known sizes of shaped arguments from the function signature. For
101
+ // non-shaped arguments (e.g. opaque pointers) we keep empty shape value.
102
+ llvm::SmallVector<std::optional<StaticShape>> arguments_sizes_;
103
+
104
+ // Values of statically known dimensions sizes in the function signature.
105
+ llvm::DenseSet<int64_t> seen_static_sizes_;
106
+
107
+ // The iteration order for the arguments when resolving symbolic shapes.
108
+ llvm::SmallVector<size_t> iteration_order_;
109
+
110
+ // The iteration order for the arguments when resolving symbolic shapes hash.
111
+ llvm::SmallVector<size_t> hash_iteration_order_;
112
+ };
113
+
114
+ } // namespace runtime
115
+ } // namespace xla
116
+
117
+ #endif // XLA_RUNTIME_SYMBOLIC_SHAPE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/tracing.h ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_TRACING_H_
17
+ #define XLA_RUNTIME_TRACING_H_
18
+
19
+ #include <string_view>
20
+
21
+ #include "xla/runtime/custom_call.h"
22
+ #include "xla/runtime/type_id.h"
23
+
24
+ namespace xla {
25
+ namespace runtime {
26
+
27
+ // XLA run-time representation of the `!rt.hlo_trace` attribute.
28
+ struct HloTrace {
29
+ std::string_view hlo_op;
30
+ };
31
+
32
+ // Registers type id names for tracing attributes.
33
+ inline void PopulateTraceTypeIdNames(TypeIDNameRegistry& registry) {
34
+ registry.Register<Tagged<HloTrace>>("__type_id_hlo_trace");
35
+ }
36
+
37
+ // Register XLA runtime custom calls attribute decoding.
38
+ XLA_RUNTIME_REGISTER_AGGREGATE_ATTR_DECODING(
39
+ HloTrace, AggregateMember<std::string_view>("hlo_op"));
40
+
41
+ } // namespace runtime
42
+ } // namespace xla
43
+
44
+ #endif // XLA_RUNTIME_TRACING_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/type_id.h ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_TYPE_ID_H_
17
+ #define XLA_RUNTIME_TYPE_ID_H_
18
+
19
+ #include <atomic>
20
+ #include <cstdint>
21
+ #include <functional>
22
+ #include <memory>
23
+ #include <string>
24
+ #include <string_view>
25
+
26
+ #include "absl/container/flat_hash_map.h"
27
+ #include "mlir/Support/TypeID.h" // from @llvm-project
28
+
29
+ namespace mlir {
30
+ // Allow TypeID to be used as a key in ABSL map containers.
31
+ template <typename H>
32
+ H AbslHashValue(H h, const TypeID& type_id) {
33
+ return H::combine(std::move(h), type_id.getAsOpaquePointer());
34
+ }
35
+ } // namespace mlir
36
+
37
+ namespace xla {
38
+ namespace runtime {
39
+
40
+ using ::mlir::TypeID; // NOLINT
41
+
42
+ //===----------------------------------------------------------------------===//
43
+ // Mapping from TypeID to unique symbol name.
44
+ //===----------------------------------------------------------------------===//
45
+
46
+ // A mapping from TypeID to unique type name, because we do not have any
47
+ // standard tools to get a type name in C++. We rely on this mapping to declare
48
+ // external symbols corresponding to type ids in compiled XLA executables.
49
+ class TypeIDNameRegistry {
50
+ public:
51
+ TypeIDNameRegistry() = default;
52
+ ~TypeIDNameRegistry() = default;
53
+
54
+ template <typename T>
55
+ void Register(std::string_view type_name) {
56
+ auto inserted = type_id_name_map_.try_emplace(TypeID::get<T>(), type_name);
57
+ assert((inserted.second || inserted.first->second == type_name) &&
58
+ "conflicting typeid name registration");
59
+ (void)inserted;
60
+ }
61
+
62
+ std::string_view FindTypeIDSymbolName(TypeID type_id);
63
+
64
+ void ForEach(std::function<void(std::string_view, TypeID)> f) const {
65
+ for (auto& kv : type_id_name_map_) f(kv.second, kv.first);
66
+ }
67
+
68
+ private:
69
+ absl::flat_hash_map<TypeID, std::string> type_id_name_map_;
70
+ };
71
+
72
+ //===----------------------------------------------------------------------===//
73
+ // DenseTypeID for generating sequential type ids.
74
+ //===----------------------------------------------------------------------===//
75
+
76
+ // Forward declare
77
+ template <typename IdSet>
78
+ class DenseTypeId;
79
+
80
+ namespace internal {
81
+ template <typename IdSet, typename T>
82
+ class DenseTypeIdResolver {
83
+ friend DenseTypeId<IdSet>;
84
+ static size_t get();
85
+ };
86
+ } // namespace internal
87
+
88
+ // Use this as DenseTypeId<some_type_specific_to_your_use>, that way you are
89
+ // guaranteed to get contiguous IDs starting at 0 unique to your particular
90
+ // use case, as would be appropriate to use for indexes into a vector.
91
+ // 'some_type_specific_to_your_use' could (e.g.) be the class that contains
92
+ // that particular vector.
93
+ template <typename IdSet>
94
+ class DenseTypeId {
95
+ public:
96
+ template <typename T>
97
+ static size_t get() {
98
+ return internal::DenseTypeIdResolver<IdSet, T>::get();
99
+ }
100
+
101
+ private:
102
+ // Partial template specialization can't be declared as a friend, so we
103
+ // declare all `DenseTypeIdResolver` as a friend.
104
+ template <typename OtherIdSet, typename T>
105
+ friend class internal::DenseTypeIdResolver;
106
+
107
+ static size_t next_id() {
108
+ return next_id_.fetch_add(1, std::memory_order_relaxed);
109
+ }
110
+
111
+ static std::atomic<size_t> next_id_;
112
+ };
113
+
114
+ template <typename IdSet>
115
+ std::atomic<size_t> DenseTypeId<IdSet>::next_id_;
116
+
117
+ namespace internal {
118
+ template <typename IdSet, typename T>
119
+ size_t DenseTypeIdResolver<IdSet, T>::get() {
120
+ static const size_t id = DenseTypeId<IdSet>::next_id();
121
+ return id;
122
+ }
123
+ } // namespace internal
124
+
125
+ } // namespace runtime
126
+ } // namespace xla
127
+
128
+ // Declare/define an explicit specialization for DenseTypeId.
129
+ //
130
+ // This forces the compiler to assign a dense type id for the given type and
131
+ // avoids checking the static initialization guard if the type id defined as a
132
+ // static variable (default implementation of the DenseTypeIdResolver).
133
+ //
134
+ // Example:
135
+ //
136
+ // // Foo.h
137
+ // struct FooIdSet {};
138
+ //
139
+ // XLA_RUNTIME_DECLARE_EXPLICIT_DENSE_TYPE_ID(FooIdSet, int32_t);
140
+ //
141
+ // // Foo.cpp
142
+ // XLA_RUNTIME_DEFINE_EXPLICIT_DENSE_TYPE_ID(FooIdSet, int32_t);
143
+ //
144
+ #define XLA_RUNTIME_DECLARE_EXPLICIT_DENSE_TYPE_ID(ID_SET, T) \
145
+ namespace xla { \
146
+ namespace runtime { \
147
+ namespace internal { \
148
+ \
149
+ template <> \
150
+ class DenseTypeIdResolver<ID_SET, T> { \
151
+ public: \
152
+ static size_t get() { return id; } \
153
+ \
154
+ private: \
155
+ static size_t id; \
156
+ }; \
157
+ \
158
+ } /* namespace internal */ \
159
+ } /* namespace runtime */ \
160
+ } /* namespace xla */
161
+
162
+ #define XLA_RUNTIME_DEFINE_EXPLICIT_DENSE_TYPE_ID(ID_SET, T) \
163
+ namespace xla { \
164
+ namespace runtime { \
165
+ namespace internal { \
166
+ \
167
+ size_t DenseTypeIdResolver<ID_SET, T>::id = DenseTypeId<ID_SET>::next_id(); \
168
+ \
169
+ } /* namespace internal */ \
170
+ } /* namespace runtime */ \
171
+ } /* namespace xla */
172
+
173
+ #endif // XLA_RUNTIME_TYPE_ID_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/runtime/types.h ADDED
@@ -0,0 +1,326 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_RUNTIME_TYPES_H_
17
+ #define XLA_RUNTIME_TYPES_H_
18
+
19
+ #include <functional>
20
+ #include <limits>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <utility>
24
+ #include <vector>
25
+
26
+ #include "absl/status/status.h"
27
+ #include "absl/status/statusor.h"
28
+ #include "llvm/Support/ExtensibleRTTI.h"
29
+ #include "llvm/Support/raw_ostream.h"
30
+ #include "xla/xla_data.pb.h"
31
+
32
+ namespace xla {
33
+ namespace runtime {
34
+
35
+ //===----------------------------------------------------------------------===//
36
+ // Canonical XLA runtime types for the executable arguments.
37
+ //===----------------------------------------------------------------------===//
38
+
39
+ // Types supported by the compiled function signature. We do rely on the LLVM
40
+ // style RTTI (https://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html) to avoid
41
+ // dependency on the MLIR types at runtime, because we don't want to depend
42
+ // on any of the compiler implementation details at runtime and we want to
43
+ // support lightweight loading and execution of AOT compiled programs.
44
+ //
45
+ // We rely on the RTTI for the open class hierarchies, because we want to allow
46
+ // users to define their own types for the arguments.
47
+ //
48
+ // If the type can be passed to the compiled function as an argument or returned
49
+ // as a result, it must define its own ABI. The ABI is defined by the MLIR to
50
+ // LLVM lowering pipeline and the runtime integration (see `runtime.h`).
51
+ class Type : public llvm::RTTIExtends<Type, llvm::RTTIRoot> {
52
+ public:
53
+ static constexpr char ID = 0; // NOLINT
54
+
55
+ // Arguments to compiled functions passed as a set of pointers. For example
56
+ // memref descriptor passed in as a set of pointers to data, sizes and
57
+ // strides. See `Argument::Pack` implementation for details (in `argument.h`).
58
+ struct ArgumentAbi {
59
+ size_t num_ptrs;
60
+ };
61
+
62
+ // Compiled function returns results by writing into the pre-allocated storage
63
+ // of the given size with the requested alignment. Runtime pre-allocates
64
+ // memory required for all results in the call frame.
65
+ struct ResultAbi {
66
+ size_t size;
67
+
68
+ // TODO(ezhulenev): Add alignment to the result ABI. Alignment is an
69
+ // important part of the result ABI that we ignore today. It all doesn't
70
+ // crash only because all results happen to have a size that is multiple of
71
+ // 8 bytes, and because of that all of the results are properly aligned.
72
+ // Results memory layout in the call frame should take in account base
73
+ // pointer alignment and alignment requirements of all results.
74
+ };
75
+
76
+ // Returns an Abi if the type can be used as an argument.
77
+ virtual absl::StatusOr<ArgumentAbi> AsArgument() const {
78
+ return absl::UnimplementedError("argument ABI is not implemented");
79
+ }
80
+
81
+ // Returns an Abi if the type can be returned as a result.
82
+ virtual absl::StatusOr<ResultAbi> AsResult() const {
83
+ return absl::UnimplementedError("result ABI is not implemented");
84
+ }
85
+
86
+ virtual std::string ToString() const = 0;
87
+
88
+ protected:
89
+ Type() = default;
90
+ };
91
+
92
+ inline llvm::raw_ostream& operator<<(llvm::raw_ostream& os, const Type& type) {
93
+ return os << type.ToString();
94
+ }
95
+
96
+ //===----------------------------------------------------------------------===//
97
+ // Async Token type corresponding to the mlir::async::TokenType
98
+ //===----------------------------------------------------------------------===//
99
+
100
+ class AsyncTokenType : public llvm::RTTIExtends<AsyncTokenType, Type> {
101
+ public:
102
+ static constexpr char ID = 0; // NOLINT
103
+
104
+ absl::StatusOr<ArgumentAbi> AsArgument() const final;
105
+ absl::StatusOr<ResultAbi> AsResult() const final;
106
+
107
+ std::string ToString() const final;
108
+ };
109
+
110
+ //===----------------------------------------------------------------------===//
111
+ // Async Value type corresponding to the mlir::async::ValueType.
112
+ //===----------------------------------------------------------------------===//
113
+
114
+ class AsyncValueType : public llvm::RTTIExtends<AsyncValueType, Type> {
115
+ public:
116
+ static constexpr char ID = 0; // NOLINT
117
+
118
+ explicit AsyncValueType(std::unique_ptr<Type> value_type)
119
+ : value_type_(std::move(value_type)) {}
120
+
121
+ const Type& value_type() const { return *value_type_; }
122
+
123
+ absl::StatusOr<ArgumentAbi> AsArgument() const final;
124
+ absl::StatusOr<ResultAbi> AsResult() const final;
125
+
126
+ std::string ToString() const final;
127
+
128
+ private:
129
+ std::unique_ptr<Type> value_type_;
130
+ };
131
+
132
+ //===----------------------------------------------------------------------===//
133
+ // Scalar type corresponding to mlir::IntegerType or mlir::FloatType.
134
+ //===----------------------------------------------------------------------===//
135
+
136
+ class ScalarType : public llvm::RTTIExtends<ScalarType, Type> {
137
+ public:
138
+ static constexpr char ID = 0; // NOLINT
139
+
140
+ explicit ScalarType(PrimitiveType type) : type_(type) {}
141
+
142
+ PrimitiveType type() const { return type_; }
143
+
144
+ absl::StatusOr<ArgumentAbi> AsArgument() const final;
145
+ absl::StatusOr<ResultAbi> AsResult() const final;
146
+
147
+ std::string ToString() const final;
148
+
149
+ private:
150
+ PrimitiveType type_;
151
+ };
152
+
153
+ //===----------------------------------------------------------------------===//
154
+ // Tuple type corresponding to mlir::TupleType.
155
+ //===----------------------------------------------------------------------===//
156
+
157
+ class TupleType : public llvm::RTTIExtends<TupleType, Type> {
158
+ public:
159
+ static constexpr char ID = 0; // NOLINT
160
+
161
+ explicit TupleType(llvm::SmallVector<std::unique_ptr<Type>> elems)
162
+ : elems_(std::move(elems)) {}
163
+
164
+ std::string ToString() const final;
165
+
166
+ // Note: the AsArgument() and AsResult() methods are unimplemented, because
167
+ // this type is not meant to be used without expansion at run time.
168
+
169
+ private:
170
+ llvm::SmallVector<std::unique_ptr<Type>> elems_;
171
+ };
172
+
173
+ //===----------------------------------------------------------------------===//
174
+ // Ranked Tensor type corresponding to the mlir::RankedTensorType.
175
+ //===----------------------------------------------------------------------===//
176
+
177
+ class RankedTensorType : public llvm::RTTIExtends<RankedTensorType, Type> {
178
+ public:
179
+ static constexpr char ID = 0; // NOLINT
180
+ static constexpr int64_t kDynamic = std::numeric_limits<int64_t>::min();
181
+
182
+ static constexpr bool IsDynamic(int64_t dim) { return dim == kDynamic; }
183
+
184
+ RankedTensorType(absl::Span<const int64_t> sizes, PrimitiveType element_type)
185
+ : sizes_(sizes.begin(), sizes.end()), element_type_(element_type) {}
186
+
187
+ absl::Span<const int64_t> sizes() const { return sizes_; }
188
+ unsigned rank() const { return sizes_.size(); }
189
+ PrimitiveType element_type() const { return element_type_; }
190
+
191
+ std::string ToString() const final;
192
+
193
+ private:
194
+ std::vector<int64_t> sizes_;
195
+ PrimitiveType element_type_;
196
+ };
197
+
198
+ //===----------------------------------------------------------------------===//
199
+ // Unranked Tensor type corresponding to the mlir::UnrankedTensorType.
200
+ //===----------------------------------------------------------------------===//
201
+
202
+ class UnrankedTensorType : public llvm::RTTIExtends<UnrankedTensorType, Type> {
203
+ public:
204
+ static constexpr char ID = 0; // NOLINT
205
+
206
+ explicit UnrankedTensorType(PrimitiveType element_type)
207
+ : element_type_(element_type) {}
208
+
209
+ PrimitiveType element_type() const { return element_type_; }
210
+
211
+ std::string ToString() const final;
212
+
213
+ private:
214
+ PrimitiveType element_type_;
215
+ };
216
+
217
+ //===----------------------------------------------------------------------===//
218
+ // Ranked Memref type corresponding to the mlir::MemrefType.
219
+ //===----------------------------------------------------------------------===//
220
+
221
+ class MemrefType : public llvm::RTTIExtends<MemrefType, Type> {
222
+ public:
223
+ static constexpr char ID = 0; // NOLINT
224
+ static constexpr int64_t kDynamic = std::numeric_limits<int64_t>::min();
225
+
226
+ static constexpr bool IsDynamic(int64_t dim) { return dim == kDynamic; }
227
+
228
+ MemrefType(absl::Span<const int64_t> sizes, PrimitiveType element_type)
229
+ : sizes_(sizes.begin(), sizes.end()), element_type_(element_type) {}
230
+
231
+ absl::Span<const int64_t> sizes() const { return sizes_; }
232
+ int64_t size(size_t dim) const { return sizes_[dim]; }
233
+ unsigned rank() const { return sizes_.size(); }
234
+ PrimitiveType element_type() const { return element_type_; }
235
+
236
+ absl::StatusOr<ArgumentAbi> AsArgument() const final;
237
+ absl::StatusOr<ResultAbi> AsResult() const final;
238
+
239
+ std::string ToString() const final;
240
+
241
+ private:
242
+ std::vector<int64_t> sizes_;
243
+ PrimitiveType element_type_;
244
+ };
245
+
246
+ //===----------------------------------------------------------------------===//
247
+ // Unranked Memref type corresponding to the mlir::UnrankedMemrefType.
248
+ //===----------------------------------------------------------------------===//
249
+
250
+ class UnrankedMemrefType : public llvm::RTTIExtends<UnrankedMemrefType, Type> {
251
+ public:
252
+ static constexpr char ID = 0; // NOLINT
253
+
254
+ explicit UnrankedMemrefType(PrimitiveType element_type)
255
+ : element_type_(element_type) {}
256
+
257
+ PrimitiveType element_type() const { return element_type_; }
258
+
259
+ std::string ToString() const final;
260
+
261
+ private:
262
+ PrimitiveType element_type_;
263
+ };
264
+
265
+ //===----------------------------------------------------------------------===//
266
+ // Corresponds to the RT dialect's ExecutionContextType.
267
+ //===----------------------------------------------------------------------===//
268
+
269
+ class ExecutionContextOperandType
270
+ : public llvm::RTTIExtends<ExecutionContextOperandType, Type> {
271
+ public:
272
+ static constexpr char ID = 0; // NOLINT
273
+
274
+ absl::StatusOr<ArgumentAbi> AsArgument() const final;
275
+
276
+ std::string ToString() const final;
277
+ };
278
+
279
+ //===----------------------------------------------------------------------===//
280
+ // Corresponds to the RT dialect's OpaqueType.
281
+ //===----------------------------------------------------------------------===//
282
+
283
+ class OpaqueOperandType : public llvm::RTTIExtends<OpaqueOperandType, Type> {
284
+ public:
285
+ static constexpr char ID = 0; // NOLINT
286
+
287
+ absl::StatusOr<ArgumentAbi> AsArgument() const final;
288
+
289
+ std::string ToString() const final;
290
+ };
291
+
292
+ //===----------------------------------------------------------------------===//
293
+ // Compiled function signature type corresponding to the mlir::FunctionType.
294
+ //===----------------------------------------------------------------------===//
295
+
296
+ // TODO(ezhulenev): Make function type copyable (replace std::unique_ptr with
297
+ // std::shared ptr).
298
+ class FunctionType {
299
+ public:
300
+ const Type* operand(unsigned index) const { return operands_[index].get(); }
301
+ const Type* result(unsigned index) const { return results_[index].get(); }
302
+
303
+ unsigned num_operands() const { return operands_.size(); }
304
+ unsigned num_results() const { return results_.size(); }
305
+
306
+ FunctionType(std::vector<std::unique_ptr<Type>> operands,
307
+ std::vector<std::unique_ptr<Type>> results)
308
+ : operands_(std::move(operands)), results_(std::move(results)) {}
309
+
310
+ void insert_operand(unsigned index, std::unique_ptr<Type> operand) {
311
+ operands_.insert(operands_.begin() + index, std::move(operand));
312
+ }
313
+
314
+ void insert_result(unsigned index, std::unique_ptr<Type> result) {
315
+ results_.insert(results_.begin() + index, std::move(result));
316
+ }
317
+
318
+ private:
319
+ std::vector<std::unique_ptr<Type>> operands_;
320
+ std::vector<std::unique_ptr<Type>> results_;
321
+ };
322
+
323
+ } // namespace runtime
324
+ } // namespace xla
325
+
326
+ #endif // XLA_RUNTIME_TYPES_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/algebraic_simplifier.h ADDED
@@ -0,0 +1,617 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 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 XLA_SERVICE_ALGEBRAIC_SIMPLIFIER_H_
17
+ #define XLA_SERVICE_ALGEBRAIC_SIMPLIFIER_H_
18
+
19
+ #include <array>
20
+ #include <cstdint>
21
+ #include <functional>
22
+ #include <memory>
23
+ #include <optional>
24
+ #include <string>
25
+ #include <tuple>
26
+ #include <utility>
27
+ #include <vector>
28
+
29
+ #include "absl/container/inlined_vector.h"
30
+ #include "xla/hlo/ir/dfs_hlo_visitor_with_default.h"
31
+ #include "xla/hlo/ir/hlo_instruction.h"
32
+ #include "xla/hlo/ir/hlo_module.h"
33
+ #include "xla/service/hlo_pass_interface.h"
34
+ #include "xla/util.h"
35
+
36
+ namespace xla {
37
+
38
+ class AlgebraicSimplifierOptions {
39
+ public:
40
+ // Platform dependent callback to determine if a reshape `from_shape` to
41
+ // `to_shape` is a bitcast.
42
+ using ReshapeIsBitcastCallback =
43
+ std::function<bool(const Shape& from_shape, const Shape& to_shape)>;
44
+ // Platform dependent callback to determine if a set of reverse dimensions is
45
+ // lowerable
46
+ using ConvIsLowerableCallback = std::function<bool(HloInstruction* window)>;
47
+
48
+ explicit AlgebraicSimplifierOptions(
49
+ ReshapeIsBitcastCallback reshape_is_bitcast_callback = {},
50
+ ConvIsLowerableCallback conv_is_lowerable_callback = {})
51
+ : reshape_is_bitcast_callback_(std::move(reshape_is_bitcast_callback)),
52
+ conv_is_lowerable_callback_(std::move(conv_is_lowerable_callback)) {}
53
+
54
+ // Use the platform specific callback if set. It is not sensible to return
55
+ // true here if the options are not layout sensitive.
56
+ bool ReshapeIsBitcast(const Shape& from_shape, const Shape& to_shape) const {
57
+ if (!is_layout_sensitive_) {
58
+ return false;
59
+ }
60
+ if (!reshape_is_bitcast_callback_) {
61
+ return ShapeUtil::ReshapeIsBitcast(from_shape, to_shape);
62
+ }
63
+ return reshape_is_bitcast_callback_(from_shape, to_shape);
64
+ }
65
+
66
+ // Use the platform specific callback if set. Otherwise, return true.
67
+ bool ConvIsLowerable(HloInstruction* reverse_dims) const {
68
+ if (!conv_is_lowerable_callback_) {
69
+ return true;
70
+ }
71
+ return conv_is_lowerable_callback_(reverse_dims);
72
+ }
73
+
74
+ // If is_layout_sensitive is true, then the simplifier preserves layout during
75
+ // transformation. Otherwise, layout is ignored.
76
+ void set_is_layout_sensitive(bool is_layout_sensitive) {
77
+ is_layout_sensitive_ = is_layout_sensitive;
78
+ }
79
+
80
+ bool is_layout_sensitive() const { return is_layout_sensitive_; }
81
+
82
+ void set_use_associative_reordering(bool use_associative_reordering) {
83
+ use_associative_reordering_ = use_associative_reordering;
84
+ }
85
+
86
+ bool use_associative_reordering() const {
87
+ return use_associative_reordering_;
88
+ }
89
+
90
+ void set_associative_reordering_threshold(
91
+ double associative_reordering_threshold) {
92
+ associative_reordering_threshold_ = associative_reordering_threshold;
93
+ }
94
+
95
+ double associative_reordering_threshold() const {
96
+ return associative_reordering_threshold_;
97
+ }
98
+
99
+ // Enable dot simplification on platforms where it is profitable.
100
+ void set_enable_dot_strength_reduction(bool enable_dot_strength_reduction) {
101
+ enable_dot_strength_reduction_ = enable_dot_strength_reduction;
102
+ }
103
+
104
+ bool enable_dot_strength_reduction() const {
105
+ return enable_dot_strength_reduction_;
106
+ }
107
+
108
+ // Enable dot->multiple rewrite for dot as an outer-product
109
+ void set_enable_dot_to_multiply_rewrite(bool enable_dot_to_multiply_rewrite) {
110
+ enable_dot_to_multiply_rewrite_ = enable_dot_to_multiply_rewrite;
111
+ }
112
+
113
+ bool enable_dot_to_multiply_rewrite() const {
114
+ return enable_dot_to_multiply_rewrite_;
115
+ }
116
+
117
+ // This platform will not run the DotDecomposer to canonicalize dots.
118
+ void set_supports_non_canonical_dots(bool supports_non_canonical_dots) {
119
+ supports_non_canonical_dots_ = supports_non_canonical_dots;
120
+ }
121
+ bool supports_non_canonical_dots() const {
122
+ return supports_non_canonical_dots_;
123
+ }
124
+
125
+ // Enable convolution simplification on platforms where it is profitable.
126
+ void set_enable_conv_simplification(bool enable_conv_simplification) {
127
+ enable_conv_simplification_ = enable_conv_simplification;
128
+ }
129
+ bool enable_conv_simplification() const {
130
+ return enable_conv_simplification_;
131
+ }
132
+
133
+ // Enable convolution operand swapping on platforms where it is supported.
134
+ void set_enable_conv_operand_swap(bool enable_conv_operand_swap) {
135
+ enable_conv_operand_swap_ = enable_conv_operand_swap;
136
+ }
137
+ bool enable_conv_operand_swap() const { return enable_conv_operand_swap_; }
138
+
139
+ // Move constant scalar multiply to one operand or output of convolutions with
140
+ // the smallest tensor size, to reduce the number of scalar multiply.
141
+ void set_enable_scalar_multiply_reduction(
142
+ bool enable_scalar_multiply_reduction) {
143
+ enable_scalar_multiply_reduction_ = enable_scalar_multiply_reduction;
144
+ }
145
+
146
+ bool enable_scalar_multiply_reduction() const {
147
+ return enable_scalar_multiply_reduction_;
148
+ }
149
+
150
+ // Also the algebraic simplifer to treat floating point values like real
151
+ // numbers.
152
+ void set_enable_floats_are_real(bool enable_floats_are_real) {
153
+ enable_floats_are_real_ = enable_floats_are_real;
154
+ }
155
+
156
+ bool enable_floats_are_real() const { return enable_floats_are_real_; }
157
+
158
+ // If enable_window_reduce_replacement is true, the kReduceWindow instruction
159
+ // can be optimized by replacement with simpler operations.
160
+ void set_enable_window_reduce_to_reduce_replacement(
161
+ bool enable_window_reduce_to_reduce_replacement) {
162
+ enable_window_reduce_to_reduce_replacement_ =
163
+ enable_window_reduce_to_reduce_replacement;
164
+ }
165
+
166
+ bool enable_window_reduce_to_reduce_replacement() const {
167
+ return enable_window_reduce_to_reduce_replacement_;
168
+ }
169
+
170
+ // Sets the size of a gather operand that can be unrolled into many selects.
171
+ void set_very_small_gather_size(int64_t size) {
172
+ very_small_gather_size_ = size;
173
+ }
174
+
175
+ int64_t very_small_gather_size() const { return very_small_gather_size_; }
176
+
177
+ void set_cudnn_batchnorm_forward_training_metadata(const std::string& c) {
178
+ metadata_.cudnn_batchnorm_forward_training_metadata = c;
179
+ }
180
+
181
+ const std::string& get_cudnn_batchnorm_forward_training_metadata() const {
182
+ return metadata_.cudnn_batchnorm_forward_training_metadata;
183
+ }
184
+
185
+ void set_enable_reduce_of_reshape(bool enable_reduce_of_reshape) {
186
+ enable_reduce_of_reshape_ = enable_reduce_of_reshape;
187
+ }
188
+
189
+ bool enable_reduce_of_reshape() const { return enable_reduce_of_reshape_; }
190
+
191
+ void set_enable_negative_padding_replacement(
192
+ bool enable_negative_padding_replacement) {
193
+ enable_negative_padding_replacement_ = enable_negative_padding_replacement;
194
+ }
195
+
196
+ bool enable_negative_padding_replacement() const {
197
+ return enable_negative_padding_replacement_;
198
+ }
199
+
200
+ void set_enable_sink_broadcast(bool enable_sink_broadcast) {
201
+ enable_sink_broadcast_ = enable_sink_broadcast;
202
+ }
203
+
204
+ bool enable_sink_broadcast() const { return enable_sink_broadcast_; }
205
+
206
+ // If true, always simplify reduce(transpose(x)) and reduce(reshape(x)), even
207
+ // if the transpose/reshape has multiple users. This can be beneficial
208
+ // on platforms where the extra transpose/reshape isn't as expensive as
209
+ // the optimization benefits brought about by simplifying the graph.
210
+ bool unconditionally_simplify_reduce_of_transpose_or_reshape() const {
211
+ return unconditionally_simplify_reduce_of_transpose_or_reshape_;
212
+ }
213
+ void set_unconditionally_simplify_reduce_of_transpose_or_reshape(bool val) {
214
+ unconditionally_simplify_reduce_of_transpose_or_reshape_ = val;
215
+ }
216
+
217
+ // If true, min(x, NaN) = NaN. If false, min(x, NaN) = x.
218
+ //
219
+ // TODO(b/209827141): Remove this and make minmax_propagate_nan
220
+ // unconditionally true.
221
+ bool minmax_propagate_nan() const { return minmax_propagate_nan_; }
222
+ void set_minmax_propagate_nan(bool val) { minmax_propagate_nan_ = val; }
223
+
224
+ // When true, always replaces Reduce(concat({a,b,...})) with
225
+ // map(reduce(a),map(reduce(b),...,)). If false, only does the replacement if
226
+ // the shapes of a,b,... have the same dimensions.
227
+ bool enable_unconditional_reduce_of_concat_replacement() const {
228
+ return enable_unconditional_reduce_of_concat_replacement_;
229
+ }
230
+ void set_enable_unconditional_reduce_of_concat_replacement(
231
+ bool enable_unconditional_reduce_of_concat_replacement) {
232
+ enable_unconditional_reduce_of_concat_replacement_ =
233
+ enable_unconditional_reduce_of_concat_replacement;
234
+ }
235
+
236
+ private:
237
+ // Metadata struct can be used to store any metadata information encapsulated
238
+ // with the AlgebraicSimplierOptions that can be later used in an
239
+ // AlgebraicSimplifier pass. For example,
240
+ // cudnn_batchnorm_forward_training_metadata can be used to store the name of
241
+ // a custom call. If the custom call is
242
+ // __cudnn$batchNormalizationForwardTraining, the output with index 2 is
243
+ // guaranteed to be positive. This property has been used to recursively
244
+ // determine if the operand of an instruction is always positive.
245
+ struct Metadata {
246
+ std::string cudnn_batchnorm_forward_training_metadata{""};
247
+ Metadata() {}
248
+ };
249
+ ReshapeIsBitcastCallback reshape_is_bitcast_callback_;
250
+ ConvIsLowerableCallback conv_is_lowerable_callback_;
251
+ bool is_layout_sensitive_{false};
252
+ bool enable_dot_strength_reduction_{true};
253
+ bool supports_non_canonical_dots_{true};
254
+ bool enable_dot_to_multiply_rewrite_{true};
255
+ bool enable_conv_simplification_{true};
256
+ bool enable_conv_operand_swap_{true};
257
+ bool enable_scalar_multiply_reduction_{false};
258
+ bool enable_floats_are_real_{false};
259
+ bool enable_window_reduce_to_reduce_replacement_{true};
260
+ bool enable_reduce_of_reshape_{true};
261
+ bool enable_negative_padding_replacement_{true};
262
+ bool enable_sink_broadcast_{true};
263
+ bool unconditionally_simplify_reduce_of_transpose_or_reshape_{false};
264
+ int64_t very_small_gather_size_{4};
265
+ bool minmax_propagate_nan_{true};
266
+ bool enable_unconditional_reduce_of_concat_replacement_{true};
267
+ bool use_associative_reordering_{false};
268
+ double associative_reordering_threshold_{2.0};
269
+ Metadata metadata_;
270
+ };
271
+
272
+ // A pass which performs algebraic simplifications.
273
+ class AlgebraicSimplifier : public HloModulePass {
274
+ public:
275
+ // If is_layout_sensitive is true, then the simplifier preserves layout during
276
+ // transformation. Otherwise, layout is ignored.
277
+ explicit AlgebraicSimplifier(const AlgebraicSimplifierOptions& options)
278
+ : options_(options) {}
279
+ ~AlgebraicSimplifier() override = default;
280
+ absl::string_view name() const override { return "algsimp"; }
281
+
282
+ // Run algebraic simplification on the given computation. Returns whether the
283
+ // computation was changed.
284
+ using HloPassInterface::Run;
285
+ StatusOr<bool> Run(
286
+ HloModule* module,
287
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
288
+
289
+ // Create constant from literal with tiles and element size updated in the
290
+ // constant's layout.
291
+ std::unique_ptr<HloInstruction> CreateConstantWithLayoutUpdated(
292
+ Literal literal) {
293
+ auto constant = HloInstruction::CreateConstant(std::move(literal));
294
+ UpdateLayout(constant->mutable_shape());
295
+ return constant;
296
+ }
297
+
298
+ protected:
299
+ AlgebraicSimplifierOptions options_;
300
+ };
301
+
302
+ // AlgebraicSimplifierVisitor traverses the HLO computation and reduces certain
303
+ // algebraic expressions to simplified forms. Note: This only supports
304
+ // simplifications that simply look at the operands of an instruction. For the
305
+ // more general case a worklist based approach would be needed.
306
+ class AlgebraicSimplifierVisitor : public DfsHloRewriteVisitor {
307
+ public:
308
+ explicit AlgebraicSimplifierVisitor(const AlgebraicSimplifierOptions& options,
309
+ AlgebraicSimplifier* simplifier)
310
+ : options_(options), simplifier_(simplifier) {}
311
+
312
+ Status HandleAbs(HloInstruction* abs) override;
313
+
314
+ Status HandleAdd(HloInstruction* add) override;
315
+
316
+ Status HandleAnd(HloInstruction* logical_and) override;
317
+
318
+ Status HandleBitcast(HloInstruction* bitcast) override;
319
+
320
+ Status HandleBitcastConvert(HloInstruction* bitcast) override;
321
+
322
+ Status HandleBroadcast(HloInstruction* broadcast) override;
323
+
324
+ Status HandleCompare(HloInstruction* compare) override;
325
+
326
+ Status HandleConcatenate(HloInstruction* concatenate) override;
327
+
328
+ Status HandleConstant(HloInstruction* constant) override;
329
+
330
+ Status HandleCopy(HloInstruction* copy) override;
331
+
332
+ Status HandleConvert(HloInstruction* convert) override;
333
+
334
+ Status HandleComplex(HloInstruction* complex) override;
335
+
336
+ Status HandleReal(HloInstruction* real) override;
337
+
338
+ Status HandleImag(HloInstruction* imag) override;
339
+
340
+ Status HandleIota(HloInstruction* instruction) override;
341
+
342
+ Status HandleConvolution(HloInstruction* convolution) override;
343
+
344
+ Status HandleDivide(HloInstruction* divide) override;
345
+
346
+ Status HandleDot(HloInstruction* dot) override;
347
+
348
+ Status HandleGather(HloInstruction* gather) override;
349
+
350
+ Status HandleGetTupleElement(HloInstruction* get_tuple_element) override;
351
+
352
+ Status HandleLog(HloInstruction* log) override;
353
+
354
+ Status HandleMaximum(HloInstruction* maximum) override;
355
+
356
+ Status HandleMinimum(HloInstruction* minimum) override;
357
+
358
+ Status HandleClamp(HloInstruction* clamp) override;
359
+
360
+ Status HandleMultiply(HloInstruction* multiply) override;
361
+
362
+ Status HandleNegate(HloInstruction* negate) override;
363
+
364
+ Status HandleNot(HloInstruction* logical_not) override;
365
+
366
+ Status HandleOptimizationBarrier(HloInstruction* barrier) override;
367
+
368
+ Status HandleOr(HloInstruction* logical_or) override;
369
+
370
+ Status HandlePad(HloInstruction* pad) override;
371
+
372
+ Status HandlePower(HloInstruction* power) override;
373
+
374
+ Status HandleRemainder(HloInstruction* remainder) override;
375
+
376
+ Status HandleReshape(HloInstruction* reshape) override;
377
+
378
+ Status HandleReduce(HloInstruction* hlo) override;
379
+
380
+ Status HandleReduceWindow(HloInstruction* hlo) override;
381
+
382
+ Status HandleReverse(HloInstruction* reverse) override;
383
+
384
+ Status HandleRsqrt(HloInstruction* rsqrt) override;
385
+
386
+ Status HandleSlice(HloInstruction* slice) override;
387
+
388
+ Status HandleSqrt(HloInstruction* sqrt) override;
389
+
390
+ Status HandleDynamicSlice(HloInstruction* dynamic_slice) override;
391
+
392
+ Status HandleDynamicUpdateSlice(
393
+ HloInstruction* dynamic_update_slice) override;
394
+ Status HandleScatter(HloInstruction* hlo) override;
395
+
396
+ Status HandleSelect(HloInstruction* select) override;
397
+
398
+ Status HandleSort(HloInstruction* sort) override;
399
+
400
+ Status HandleTranspose(HloInstruction* transpose) override;
401
+
402
+ Status HandleSubtract(HloInstruction* sub) override;
403
+
404
+ Status HandleMap(HloInstruction* map) override;
405
+
406
+ // Runs the visitor on a computation.
407
+ bool Run(HloComputation* computation,
408
+ const AlgebraicSimplifierOptions& options,
409
+ AlgebraicSimplifier* simplifier);
410
+
411
+ // Compute a function that maps from bitcasted dimensions to the resulting
412
+ // ones. Returns the function as a vector if successful; std::optional
413
+ // otherwise.
414
+ static std::optional<std::vector<std::vector<int64_t>>> ComputeBitcastDimMap(
415
+ const Shape& bitcast_shape, const Shape& operand_shape);
416
+ // Invert the directions of the given bitcast dimension map.
417
+ static std::vector<std::vector<int64_t>> InvertBitcastDimMap(
418
+ const Shape& original_shape, const Shape& bitcast_shape,
419
+ const std::vector<std::vector<int64_t>>& original_map);
420
+
421
+ // Modify the layout dimensions of result_shape, so that it becomes the
422
+ // re-shaped result of applying bitcast to the original_shape, by using
423
+ // dim_map to re-shape layout dimensions of original_shape. Returns the
424
+ // result_shape with modified layout if the conversion succeeds; Returns
425
+ // std::nullopt if fails.
426
+ static std::optional<Shape> ReshapeLayoutDimensions(
427
+ const Shape& original_shape, const Shape& result_shape,
428
+ const std::vector<std::vector<int64_t>>& original_map,
429
+ const std::vector<std::vector<int64_t>>& result_map);
430
+
431
+ // Allow backend constraints on tiling etc. to invalidate optimizations.
432
+ virtual bool IsValidLayout(const Shape& shape) { return true; }
433
+ // Allow backend targets to determine whether a layout is inefficient.
434
+ virtual bool ShouldStrengthReduceDotToReduce(const HloInstruction* hlo) {
435
+ return true;
436
+ }
437
+
438
+ protected:
439
+ // The backend-specific options selected for the algebraic simplifier.
440
+ const AlgebraicSimplifierOptions& options_;
441
+
442
+ private:
443
+ // Removes degenerate dimension from dot.
444
+ StatusOr<bool> RemoveDegenerateDimensionFromDot(HloInstruction* dot);
445
+
446
+ // Moves the transpose to the broadcast if possible. Can also be called with a
447
+ // bitcast transpose.
448
+ Status SimplifyTransposeOfBroadcast(HloInstruction* transpose,
449
+ absl::Span<const int64_t> dimensions);
450
+
451
+ // Converts to primitive type if the input hlo is not that type, otherwise
452
+ // returns the original hlo.
453
+ HloInstruction* AsType(HloInstruction* hlo,
454
+ const PrimitiveType element_type) {
455
+ if (hlo->shape().element_type() == element_type) {
456
+ return hlo;
457
+ }
458
+ Shape changed_shape =
459
+ ShapeUtil::ChangeElementType(hlo->shape(), element_type);
460
+ simplifier_->UpdateLayout(&changed_shape);
461
+ return computation_->AddInstruction(
462
+ HloInstruction::CreateConvert(changed_shape, hlo));
463
+ }
464
+
465
+ // Transposes a dot operand such that the batch dimensions are the most major,
466
+ // and the contracting dimensions are most minor.
467
+ StatusOr<HloInstruction*> NormalizeDotOperandToBatchMajorAndContractingMinor(
468
+ HloInstruction* dot_operand, absl::Span<const int64_t> batch_dimensions,
469
+ absl::Span<const int64_t> contracting_dimensions);
470
+
471
+ // Simplify dot(transpose(a), transpose(b)) to transpose(dot(b,a)) (or
472
+ // transpose(dot(a,b)) if only the batch dims are transposed).
473
+ //
474
+ // Requires the dot has been canonicalized by DotDecomposer into
475
+ //
476
+ // LHS [batch dims..., non-contracting dim, contracting dim]
477
+ // RHS [batch dims..., contracting dim, non-contracting dim].
478
+ StatusOr<bool> RemoveTransposesFromDotOperands(HloInstruction* dot);
479
+
480
+ // Helper method to perform and add reduction on a list of dimensions.
481
+ HloInstruction* AddReduce(HloInstruction* hlo, absl::Span<const int64_t> dims,
482
+ PrimitiveType type);
483
+
484
+ // Move scalar multiply to the smallest side of convolution to
485
+ // reduce multiply computations.
486
+ Status ScalarMultiplyReduction(HloInstruction* dot);
487
+
488
+ // Convenience method for replacing an instruction with a bitcast. If operand
489
+ // is not null, then the bitcast will use the specified operand instead of the
490
+ // operand of the instruction.
491
+ void ReplaceWithBitcast(HloInstruction* instruction,
492
+ HloInstruction* operand = nullptr);
493
+
494
+ // Change copy(bitcast...(copy)) into copy(bitcast) or bitcast(copy) so that
495
+ // the replicated copies are combined when allowed by layout/tiling assignment
496
+ // constraints.
497
+ bool SwapCopyBitcastCopy(HloInstruction* root_copy);
498
+
499
+ // Replace old instruction with new instruction if old and new instructions
500
+ // are compatible (have the same shape and replacement preserves sharding).
501
+ // Updates uses and root instruction. Returns whether a replacement was made.
502
+ bool ReplaceInstructionIfCompatible(HloInstruction* old_instruction,
503
+ HloInstruction* new_instruction);
504
+ // Similar to above but tuplizes `new_instructions` if there are more than 1
505
+ // instructions.
506
+ bool ReplaceInstructionIfCompatible(
507
+ HloInstruction* old_instruction,
508
+ absl::Span<HloInstruction* const> new_instructions);
509
+
510
+ // Returns whether the shape of the output of the given instructions are the
511
+ // same for the purposes of simplification. If options_.is_layout_sensitive()
512
+ // is true, then this tests shape equality including layout
513
+ // (ShapeUtil::Equal). If options_.is_layout_sensitive() is false, then the
514
+ // tests shape compatibility (ShapeUtil::Compatible).
515
+ bool SameShape(const HloInstruction* lhs, const HloInstruction* rhs) const;
516
+
517
+ // Same as above but takes shape arguments directly.
518
+ bool SameShape(const Shape& lhs, const Shape& rhs) const;
519
+
520
+ // A Broadcast that feeds an element-wise operation with a unique non-scalar
521
+ // operand can sink to after the operation.
522
+ StatusOr<bool> TryToSinkBroadcastAfterOpWithUniqueNonScalarOperand(
523
+ HloInstruction* broadcast);
524
+
525
+ StatusOr<HloInstruction*> OptimizeDotOfConcat(HloInstruction* dot);
526
+ StatusOr<HloInstruction*> OptimizeDotOfConcatHelper(
527
+ HloInstruction* dot, HloInstruction* lhs, int64_t lhs_contracting_dim,
528
+ HloInstruction* rhs, int64_t rhs_contracting_dim, bool swapped);
529
+
530
+ StatusOr<HloInstruction*> OptimizeDotOfGather(HloInstruction* dot);
531
+
532
+ StatusOr<HloInstruction*> OptimizeDotOfReorderContractingDims(
533
+ HloInstruction* dot);
534
+
535
+ StatusOr<HloInstruction*> AssociativeReorderDotOperator(HloInstruction* dot);
536
+
537
+ HloComputation* GetOrCreateScalarAddComputation(PrimitiveType type) {
538
+ HloComputation*& scalar_add_computation = scalar_add_computations_[type];
539
+ if (scalar_add_computation) {
540
+ return scalar_add_computation;
541
+ }
542
+
543
+ HloComputation::Builder b("scalar_add_computation");
544
+ Shape shape = ShapeUtil::MakeShape(type, {});
545
+ simplifier_->UpdateLayout(&shape);
546
+ auto scalar_lhs = b.AddInstruction(
547
+ HloInstruction::CreateParameter(0, shape, "scalar_lhs"));
548
+ auto scalar_rhs = b.AddInstruction(
549
+ HloInstruction::CreateParameter(1, shape, "scalar_rhs"));
550
+ auto scalar_op = b.AddInstruction(HloInstruction::CreateBinary(
551
+ shape, HloOpcode::kAdd, scalar_lhs, scalar_rhs));
552
+ scalar_add_computation =
553
+ computation_->parent()->AddEmbeddedComputation(b.Build(scalar_op));
554
+ return scalar_add_computation;
555
+ }
556
+
557
+ // Tries to fold a kPad in the input or filter into the convolution
558
+ // instruction's window.
559
+ virtual StatusOr<bool> FoldConvInputPad(HloInstruction* convolution);
560
+ StatusOr<bool> FoldConvFilterPad(HloInstruction* convolution);
561
+
562
+ // Tries to swap convolution operands if they would result in a more efficient
563
+ // convolution.
564
+ StatusOr<bool> SwapConvOperands(HloInstruction* convolution);
565
+
566
+ // Tries to use a kDot in place of the given convolution.
567
+ StatusOr<bool> SimplifyConvToDot(HloInstruction* convolution);
568
+ // Tries to use a multiplication in place of the given convolution.
569
+ StatusOr<bool> SimplifyConvToMultiply(HloInstruction* convolution);
570
+
571
+ // Tries to simplify a slice where the result of the slice is a scalar.
572
+ StatusOr<bool> TrySimplifyScalarSlice(HloInstruction* slice);
573
+
574
+ // Tries to convert slice(reshape(X)) into reshape(slice(X))
575
+ StatusOr<bool> TryToReorderSliceAndReshape(HloInstruction* slice);
576
+
577
+ // Tries to convert slice(reverse(X)) into reverse(slice(X))
578
+ StatusOr<bool> TryToReorderSliceAndReverse(HloInstruction* slice);
579
+
580
+ // Tries to simplify `(and (< a N) (< a K))` in cases where `N <= K` into
581
+ // `(< a N)`. This is crucial for being able to figure out the loop trip
582
+ // count.
583
+ //
584
+ // Assumes that the input is conjunction.
585
+ StatusOr<bool> TrySimplifyTautologicalCompare(HloInstruction* conjunction);
586
+
587
+ // Tries to simlplify (bitcast-convert (concat (bitcast-convert A) ...)) where
588
+ // the types of inner and outer bitcast-convert cancel out.
589
+ StatusOr<bool> TrySimplifyTautologicalBitcastConvert(HloInstruction* bitcast);
590
+
591
+ // Tries to remove surrounding converts around a binary op where the op has a
592
+ // more precise type than its inputs and output.
593
+ //
594
+ // convert<TS>(bin_op<TL>(convert<TL>(data1<TS>),
595
+ // convert<TL>(data2<TS>)))
596
+ // where TS is a smaller point type than TL (ex, TS=fp16, TL=fp32)
597
+ // ->
598
+ // bin_op<TS>(data1<TS>, data2<TS>)
599
+ Status TryRemoveUpcastAndDowncastSurroundingBinaryOp(
600
+ HloInstruction* convert_instruction);
601
+
602
+ // Useful when we want to use the same visitor over multiple computations.
603
+ void ResetState(HloComputation* computation);
604
+
605
+ // Current HloComputation instance the AlgebraicSimplifierVisitor is
606
+ // traversing.
607
+ HloComputation* computation_;
608
+
609
+ // Cached computation for adding two scalars of a given type.
610
+ absl::flat_hash_map<PrimitiveType, HloComputation*> scalar_add_computations_;
611
+
612
+ AlgebraicSimplifier* simplifier_ = nullptr;
613
+ };
614
+
615
+ } // namespace xla
616
+
617
+ #endif // XLA_SERVICE_ALGEBRAIC_SIMPLIFIER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_broadcast_reorder.h ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 XLA_SERVICE_ALL_GATHER_BROADCAST_REORDER_H_
17
+ #define XLA_SERVICE_ALL_GATHER_BROADCAST_REORDER_H_
18
+
19
+ #include "xla/hlo/ir/hlo_module.h"
20
+ #include "xla/service/hlo_pass_interface.h"
21
+ #include "xla/statusor.h"
22
+
23
+ namespace xla {
24
+
25
+ // A pass that reorders all-gather(broadcast(x)) -> broadcast(all-gather(x)).
26
+ // The intent is to reduce the size of all-gather when possible by doing an
27
+ // all-gather on the (smaller) pre-broadcasted data and then applying the
28
+ // broadcast.
29
+ class AllGatherBroadcastReorder : public HloModulePass {
30
+ public:
31
+ absl::string_view name() const override { return "all-gather-bcast-reorder"; }
32
+
33
+ using HloPassInterface::Run;
34
+ StatusOr<bool> Run(
35
+ HloModule* module,
36
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
37
+ };
38
+
39
+ } // namespace xla
40
+
41
+ #endif // XLA_SERVICE_ALL_GATHER_BROADCAST_REORDER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_combiner.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 XLA_SERVICE_ALL_GATHER_COMBINER_H_
17
+ #define XLA_SERVICE_ALL_GATHER_COMBINER_H_
18
+
19
+ #include "absl/strings/string_view.h"
20
+ #include "xla/hlo/ir/hlo_module.h"
21
+ #include "xla/service/hlo_pass_interface.h"
22
+ #include "xla/statusor.h"
23
+ #include "xla/xla_data.pb.h"
24
+
25
+ namespace xla {
26
+
27
+ // Combines small non-dependent AllGather ops into larger combined
28
+ // AllGather ops. A typical AllGather implementation has a minimum
29
+ // latency-induced time for a AllGather op so a single combined op can be
30
+ // more efficient than many small ones.
31
+ class AllGatherCombiner : public HloModulePass {
32
+ public:
33
+ AllGatherCombiner(int64_t combine_threshold_in_bytes,
34
+ int64_t combine_threshold_count, bool combine_by_dim);
35
+
36
+ absl::string_view name() const override { return "all-gather-combiner"; }
37
+
38
+ using HloPassInterface::Run;
39
+ StatusOr<bool> Run(
40
+ HloModule* module,
41
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
42
+
43
+ private:
44
+ // Combine all gather ops up to this threshold.
45
+ int64_t combine_threshold_in_bytes_;
46
+
47
+ // Combine all gather ops up to this threshold (number of operands).
48
+ int64_t combine_threshold_count_;
49
+
50
+ // Combine all-gather ops with the same gather dimension.
51
+ bool combine_by_dim_;
52
+ };
53
+
54
+ } // namespace xla
55
+
56
+ #endif // XLA_SERVICE_ALL_GATHER_COMBINER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_gather_decomposer.h ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 XLA_SERVICE_ALL_GATHER_DECOMPOSER_H_
17
+ #define XLA_SERVICE_ALL_GATHER_DECOMPOSER_H_
18
+
19
+ #include "xla/hlo/ir/hlo_instructions.h"
20
+ #include "xla/hlo/ir/hlo_module.h"
21
+ #include "xla/service/hlo_pass_interface.h"
22
+
23
+ namespace xla {
24
+
25
+ // AllGatherDecomposer is a pass which converts unsupported all-gathers into
26
+ // dynamic-update-slices and all-reduces.
27
+ class AllGatherDecomposer : public HloModulePass {
28
+ public:
29
+ explicit AllGatherDecomposer(
30
+ std::function<bool(const HloAllGatherInstruction&)> should_decompose)
31
+ : should_decompose_(std::move(should_decompose)) {}
32
+ AllGatherDecomposer()
33
+ : should_decompose_(
34
+ [](const HloAllGatherInstruction& ag) { return true; }) {}
35
+ absl::string_view name() const override { return "all_gather_decomposer"; }
36
+
37
+ // Run AllGatherDecomposer pass on computations in 'module'.
38
+ // Returns whether the 'module' was changed.
39
+ using HloPassInterface::Run;
40
+ StatusOr<bool> Run(
41
+ HloModule* module,
42
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
43
+
44
+ private:
45
+ std::function<bool(const HloAllGatherInstruction&)> should_decompose_;
46
+ };
47
+
48
+ } // namespace xla
49
+
50
+ #endif // XLA_SERVICE_ALL_GATHER_DECOMPOSER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_combiner.h ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 XLA_SERVICE_ALL_REDUCE_COMBINER_H_
17
+ #define XLA_SERVICE_ALL_REDUCE_COMBINER_H_
18
+
19
+ #include "absl/strings/string_view.h"
20
+ #include "xla/array2d.h"
21
+ #include "xla/hlo/ir/hlo_module.h"
22
+ #include "xla/service/hlo_pass_interface.h"
23
+ #include "xla/statusor.h"
24
+ #include "xla/xla_data.pb.h"
25
+
26
+ namespace xla {
27
+
28
+ // Combines small non-dependent AllReduce ops into larger combined
29
+ // AllReduce ops. A typical AllReduce implementation has a minimum
30
+ // latency-induced time for a AllReduce op so a single combined op can be
31
+ // more efficient than many small ones.
32
+ class AllReduceCombiner : public HloModulePass {
33
+ public:
34
+ AllReduceCombiner(int64_t combine_threshold_in_bytes,
35
+ int64_t combine_threshold_count);
36
+
37
+ absl::string_view name() const override { return "all-reduce-combiner"; }
38
+
39
+ using HloPassInterface::Run;
40
+ StatusOr<bool> Run(
41
+ HloModule* module,
42
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
43
+
44
+ private:
45
+ // Combine all reduce ops up to this threshold.
46
+ int64_t combine_threshold_in_bytes_;
47
+
48
+ // Combine all reduce ops up to this threshold (number of operands).
49
+ int64_t combine_threshold_count_;
50
+ };
51
+
52
+ } // namespace xla
53
+
54
+ #endif // XLA_SERVICE_ALL_REDUCE_COMBINER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_contiguous.h ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 XLA_SERVICE_ALL_REDUCE_CONTIGUOUS_H_
17
+ #define XLA_SERVICE_ALL_REDUCE_CONTIGUOUS_H_
18
+
19
+ #include "xla/hlo/ir/hlo_module.h"
20
+ #include "xla/service/hlo_pass_interface.h"
21
+ #include "xla/statusor.h"
22
+
23
+ namespace xla {
24
+
25
+ // Concatenates all-reduce operands together, so the all-reduce is performed
26
+ // over a single, contiguous buffer.
27
+ class AllReduceContiguous : public HloModulePass {
28
+ public:
29
+ absl::string_view name() const override { return "all-reduce-contiguous"; }
30
+
31
+ using HloPassInterface::Run;
32
+ StatusOr<bool> Run(
33
+ HloModule* module,
34
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
35
+ };
36
+
37
+ } // namespace xla
38
+
39
+ #endif // XLA_SERVICE_ALL_REDUCE_CONTIGUOUS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_folder.h ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 XLA_SERVICE_ALL_REDUCE_FOLDER_H_
17
+ #define XLA_SERVICE_ALL_REDUCE_FOLDER_H_
18
+
19
+ #include "xla/hlo/ir/hlo_module.h"
20
+ #include "xla/service/hlo_pass_interface.h"
21
+ #include "xla/statusor.h"
22
+
23
+ namespace xla {
24
+
25
+ // A pass that folds an all-reduce feeding into another all-reduce by expanding
26
+ // the replica groups. As an example:
27
+ //
28
+ // ar0 = all-reduce(x) replica_groups={{0,1},{2,3},{4,5},{6,7}}
29
+ // ar1 = all-reduce(all-reduce0) replica_groups={{0,2},{1,3},{4,6},{5,7}}
30
+ //
31
+ // Can be combined into a single all-reduce:
32
+ //
33
+ // ar1 = all-reduce(x) replica_groups={{0,1,2,3},{4,5,6,7}}
34
+ //
35
+
36
+ class AllReduceFolder : public HloModulePass {
37
+ public:
38
+ absl::string_view name() const override { return "all-reduce-folder"; }
39
+
40
+ using HloPassInterface::Run;
41
+ StatusOr<bool> Run(
42
+ HloModule* module,
43
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
44
+ };
45
+
46
+ } // namespace xla
47
+
48
+ #endif // XLA_SERVICE_ALL_REDUCE_FOLDER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_key.h ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 XLA_SERVICE_ALL_REDUCE_KEY_H_
17
+ #define XLA_SERVICE_ALL_REDUCE_KEY_H_
18
+
19
+ #include <tuple>
20
+ #include <vector>
21
+
22
+ #include "xla/hlo/ir/hlo_instruction.h"
23
+ #include "xla/service/hlo_domain_map.h"
24
+
25
+ namespace xla {
26
+
27
+ // Encapsulates all of the properties which must match for two all-reduce
28
+ // instructions to be compatible with each other (and hence be possible to
29
+ // combine the instructions).
30
+ using AllReduceKey =
31
+ std::tuple<HloOpcode, PrimitiveType,
32
+ /*domain metadata id*/ int64_t,
33
+ /*has channel id*/ bool,
34
+ /*use_global_device_ids*/ bool,
35
+ /*replica_groups*/ std::vector<std::vector<int64_t>>>;
36
+
37
+ std::optional<AllReduceKey> GetAllReduceKey(
38
+ const HloInstruction* instruction, const HloDomainMap* domain_map = nullptr,
39
+ bool ignore_replica_groups = false);
40
+
41
+ } // namespace xla
42
+
43
+ #endif // XLA_SERVICE_ALL_REDUCE_KEY_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_promotion.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_SERVICE_ALL_REDUCE_PROMOTION_H_
17
+ #define XLA_SERVICE_ALL_REDUCE_PROMOTION_H_
18
+
19
+ #include <utility>
20
+ #include "xla/service/change_op_data_type.h"
21
+
22
+ namespace xla {
23
+
24
+ class AllReducePromotion : public HloModulePass {
25
+ public:
26
+ explicit AllReducePromotion(
27
+ absl::Span<std::pair<PrimitiveType, PrimitiveType> const> from_to_types);
28
+ absl::string_view name() const override { return "all-reduce-promotion"; }
29
+
30
+ using HloPassInterface::Run;
31
+ StatusOr<bool> Run(
32
+ HloModule* module,
33
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
34
+
35
+ private:
36
+ ChangeOpDataType pass_;
37
+ };
38
+
39
+ } // namespace xla
40
+ #endif // XLA_SERVICE_ALL_REDUCE_PROMOTION_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_reduce_reassociate.h ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 XLA_SERVICE_ALL_REDUCE_REASSOCIATE_H_
17
+ #define XLA_SERVICE_ALL_REDUCE_REASSOCIATE_H_
18
+
19
+ #include "xla/hlo/ir/hlo_module.h"
20
+ #include "xla/service/hlo_pass_interface.h"
21
+ #include "xla/statusor.h"
22
+
23
+ namespace xla {
24
+
25
+ // A pass that reassociates all-reduce feeding into compatible elementwise
26
+ // operations. As an example: add(all-reduce(x), all-reduce(y)) will be replaced
27
+ // with all-reduce(add(x,y)). Mathematically, this is replacing
28
+ // add(x0, x1, ... xk) + add(y0, y1, ... yk) with
29
+ // add((x0+y0), (x1+y), ... (xk+yk)
30
+ //
31
+ // i.e., reassociating the reduction operation.
32
+
33
+ class AllReduceReassociate : public HloModulePass {
34
+ public:
35
+ explicit AllReduceReassociate(bool reassociate_converted_ar = false)
36
+ : reassociate_converted_ar_(reassociate_converted_ar) {}
37
+
38
+ absl::string_view name() const override { return "all-reduce-reassociate"; }
39
+
40
+ using HloPassInterface::Run;
41
+ StatusOr<bool> Run(
42
+ HloModule* module,
43
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
44
+
45
+ private:
46
+ // Specify whether we should reassociate allreduces that are consumed by
47
+ // Convert nodes.
48
+ bool reassociate_converted_ar_;
49
+ };
50
+
51
+ } // namespace xla
52
+
53
+ #endif // XLA_SERVICE_ALL_REDUCE_REASSOCIATE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/all_to_all_decomposer.h ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 XLA_SERVICE_ALL_TO_ALL_DECOMPOSER_H_
17
+ #define XLA_SERVICE_ALL_TO_ALL_DECOMPOSER_H_
18
+
19
+ #include "xla/hlo/ir/hlo_instruction.h"
20
+ #include "xla/service/op_expander_pass.h"
21
+
22
+ namespace xla {
23
+
24
+ // AllToAllDecomposer is a pass which converts unsupported array all_to_all
25
+ // into tuple all_to_all or array all_to_all with a minimum rank where the split
26
+ // dimension is the size of the replica_groups.
27
+ class AllToAllDecomposer : public OpExpanderPass {
28
+ public:
29
+ explicit AllToAllDecomposer(bool decompose_to_tuple = true,
30
+ int64_t min_array_rank = 0)
31
+ : decompose_to_tuple_(decompose_to_tuple),
32
+ min_array_rank_(min_array_rank) {}
33
+ ~AllToAllDecomposer() override = default;
34
+ absl::string_view name() const override { return "all_to_all_decomposer"; }
35
+
36
+ private:
37
+ bool InstructionMatchesPattern(HloInstruction* instruction) override;
38
+ StatusOr<HloInstruction*> ExpandInstruction(
39
+ HloInstruction* instruction) override;
40
+ bool decompose_to_tuple_;
41
+ int64_t min_array_rank_;
42
+ };
43
+
44
+ } // namespace xla
45
+
46
+ #endif // XLA_SERVICE_ALL_TO_ALL_DECOMPOSER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/allocation_tracker.h ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 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 XLA_SERVICE_ALLOCATION_TRACKER_H_
17
+ #define XLA_SERVICE_ALLOCATION_TRACKER_H_
18
+
19
+ #include <map>
20
+ #include <memory>
21
+ #include <set>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "absl/container/flat_hash_map.h"
26
+ #include "xla/service/backend.h"
27
+ #include "xla/statusor.h"
28
+ #include "xla/types.h"
29
+ #include "xla/xla_data.pb.h"
30
+
31
+ namespace xla {
32
+
33
+ // Tracks allocations for the XLA service; allocations can be registered
34
+ // with shape/device/tag and resolved from a handle for later use.
35
+ class AllocationTracker {
36
+ public:
37
+ // The allocator is used for deallocating memory when allocations are
38
+ // deregistered. All registered allocations must have the same platform as the
39
+ // allocator.
40
+ AllocationTracker(Backend* backend) : backend_(backend), next_handle_(1) {}
41
+
42
+ // Registers a shaped buffer of device memory, and returns a corresponding
43
+ // handle that can be used for talking to XLA clients. The given shaped buffer
44
+ // will be treated as the buffer corresponding to the only replica.
45
+ StatusOr<GlobalDataHandle> Register(ScopedShapedBuffer shaped_buffer,
46
+ const std::string& tag);
47
+
48
+ // Registers a vector of shaped buffers of device memory, one per replica, and
49
+ // returns a corresponding handle that can be used for talking to XLA clients.
50
+ StatusOr<GlobalDataHandle> RegisterReplicatedBuffers(
51
+ std::vector<ScopedShapedBuffer> replicated_buffers,
52
+ const std::string& tag);
53
+
54
+ // Unregister the allocation for the given data handle.
55
+ Status Unregister(const GlobalDataHandle& data);
56
+
57
+ // Returns a vector of global data handles that point to the tuple elements.
58
+ StatusOr<std::vector<GlobalDataHandle>> DeconstructTuple(
59
+ const GlobalDataHandle& Data);
60
+
61
+ // Resolve a handle from an XLA client to a vector of shaped buffers, one per
62
+ // replica, or provide an error status to say whether any of those buffers
63
+ // were not found (or found, but found deallocated).
64
+ StatusOr<std::vector<const ShapedBuffer*>> Resolve(
65
+ const GlobalDataHandle& data) const;
66
+
67
+ // Resolves a handle from an XLA client and replica id to a shaped buffer, or
68
+ // provide an error status to say whether it was not found (or found, but
69
+ // found deallocated).
70
+ StatusOr<const ShapedBuffer*> ResolveForReplica(const GlobalDataHandle& data,
71
+ int replica_id) const;
72
+
73
+ private:
74
+ // Data structure encapsulating single memory allocation on the device.
75
+ struct Allocation {
76
+ // The pointer to this allocation.
77
+ se::OwningDeviceMemory device_memory;
78
+
79
+ // This is the number of times this memory allocation is referred to by
80
+ // registered data handles.
81
+ int ref_count;
82
+ };
83
+
84
+ // Internal helper which resolves the given GlobalDataHandle to a
85
+ // list of ScopedShapedBuffers.
86
+ StatusOr<std::vector<const ShapedBuffer*>> ResolveInternal(
87
+ const GlobalDataHandle& data) const ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
88
+
89
+ // Internal helper which registers a vector of shaped buffers, one per
90
+ // replica. ShapedBufferTy is either ScopedShapedBuffer or ShapedBuffer. If
91
+ // it's ShapedBuffer, all of the given buffers must already be tracked by this
92
+ // object -- presumably this is a call from DeconstructTuple.
93
+ template <typename ShapedBufferTy>
94
+ StatusOr<GlobalDataHandle> RegisterInternal(
95
+ std::vector<ShapedBufferTy> replicated_buffers, const std::string& tag)
96
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
97
+
98
+ // Adds the given device address to the allocation tracker, or if it already
99
+ // exists, then increment its reference count.
100
+ void AddAllocationOrIncrementRefCount(se::DeviceMemoryBase device_memory,
101
+ int device_ordinal)
102
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
103
+
104
+ // Decrements the reference count of the given device memory. Then, if it is
105
+ // zero, deallocate the memory.
106
+ Status DecrementRefCount(se::DeviceMemoryBase device_memory,
107
+ int device_ordinal)
108
+ ABSL_EXCLUSIVE_LOCKS_REQUIRED(mutex_);
109
+
110
+ // A map from device memory opaque value to allocation. One such map is
111
+ // maintained per device ordinal.
112
+ using AllocationMap = absl::flat_hash_map<const void*, Allocation>;
113
+
114
+ mutable absl::Mutex mutex_;
115
+
116
+ // Backend to use with this tracker. The backend supplies the memory allocator
117
+ // to use when deallocating memory.
118
+ Backend* backend_;
119
+
120
+ // The next handle to assign to an allocation, guarded by the same mutex as
121
+ // the mapping as they'll be mutated at the same time.
122
+ int64_t next_handle_ ABSL_GUARDED_BY(mutex_);
123
+
124
+ // A map from device ordinal to AllocationMap.
125
+ absl::flat_hash_map<int, AllocationMap> opaque_to_allocation_map_
126
+ ABSL_GUARDED_BY(mutex_);
127
+
128
+ // A map from data handle to a vector of shaped buffers that represent the
129
+ // buffers for different replicas.
130
+ //
131
+ // The ShapedBuffers in this map's vectors need to be unique_ptrs, because our
132
+ // public API returns pointers to them. We expect the concrete class to be
133
+ // ShapedBuffer and never ScopedShapedBuffer; deallocation of buffers is
134
+ // handled by opaque_to_allocation_map_.
135
+ //
136
+ // The elements of the vectors need to be unique_ptrs because we return
137
+ // pointers to them. (In theory we could use std::list or something instead,
138
+ // but we also want to be able to null out these elements.)
139
+ //
140
+ // The reason that the elements can't be unique_ptr<ScopedShapedBuffer>s is
141
+ // the existence of DeconstructTuple(). This function allows us to create a
142
+ // non-owning "view" into a tuple's sub-buffers. The sub-buffers are then
143
+ // free'd when both the view *and* the original tuple are Unregistered. This
144
+ // refcounting is managed in opaque_to_allocation_map_.
145
+ absl::flat_hash_map<int64_t, std::vector<std::unique_ptr<ShapedBuffer>>>
146
+ handle_to_shaped_buffers_ ABSL_GUARDED_BY(mutex_);
147
+
148
+ AllocationTracker(const AllocationTracker&) = delete;
149
+ AllocationTracker& operator=(const AllocationTracker&) = delete;
150
+ };
151
+
152
+ } // namespace xla
153
+
154
+ #endif // XLA_SERVICE_ALLOCATION_TRACKER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/async_collective_creator.h ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 XLA_SERVICE_ASYNC_COLLECTIVE_CREATOR_H_
17
+ #define XLA_SERVICE_ASYNC_COLLECTIVE_CREATOR_H_
18
+
19
+ #include <functional>
20
+ #include <utility>
21
+ #include <vector>
22
+
23
+ #include "xla/service/hlo_pass_interface.h"
24
+
25
+ namespace xla {
26
+
27
+ // Transforms each all-reduce instruction to a pair of all-reduce-start and
28
+ // all-reduce-done.
29
+ class AsyncCollectiveCreator : public HloModulePass {
30
+ public:
31
+ // Function to query the shape of the "context" for collectives that use
32
+ // HLO async-start/async-done.
33
+ using ContextShapeQuery =
34
+ std::function<std::vector<Shape>(const HloInstruction*)>;
35
+ struct CollectiveCreatorConfig {
36
+ HloPredicate convert_all_reduce = HloPredicateFalse;
37
+ HloPredicate convert_all_gather = HloPredicateFalse;
38
+ HloPredicate convert_collective_permute = HloPredicateFalse;
39
+ HloPredicate convert_all_to_all = HloPredicateFalse;
40
+ HloPredicate convert_reduce_scatter = HloPredicateFalse;
41
+ ContextShapeQuery get_context_shapes = [](const HloInstruction*) {
42
+ return std::vector<Shape>{};
43
+ };
44
+ };
45
+ explicit AsyncCollectiveCreator(CollectiveCreatorConfig creator_config)
46
+ : config_(std::move(creator_config)) {}
47
+ absl::string_view name() const override { return "async-collective-creator"; }
48
+
49
+ using HloPassInterface::Run;
50
+ StatusOr<bool> Run(
51
+ HloModule* module,
52
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
53
+
54
+ private:
55
+ CollectiveCreatorConfig config_;
56
+ };
57
+
58
+ } // namespace xla
59
+
60
+ #endif // XLA_SERVICE_ASYNC_COLLECTIVE_CREATOR_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/backend.h ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 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 XLA_SERVICE_BACKEND_H_
17
+ #define XLA_SERVICE_BACKEND_H_
18
+
19
+ #include <functional>
20
+ #include <memory>
21
+ #include <optional>
22
+ #include <set>
23
+ #include <string>
24
+ #include <vector>
25
+
26
+ #include "absl/container/flat_hash_map.h"
27
+ #include "absl/strings/str_cat.h"
28
+ #include "absl/types/span.h"
29
+ #include "xla/service/compiler.h"
30
+ #include "xla/service/computation_placer.h"
31
+ #include "xla/service/stream_pool.h"
32
+ #include "xla/service/transfer_manager.h"
33
+ #include "xla/statusor.h"
34
+ #include "xla/stream_executor/device_memory_allocator.h"
35
+ #include "xla/stream_executor/stream_executor.h"
36
+
37
+ namespace Eigen {
38
+ struct ThreadPoolDevice;
39
+ }
40
+
41
+ namespace xla {
42
+
43
+ // Options to configure the backend when it is created.
44
+ class BackendOptions {
45
+ public:
46
+ // Set the platform backing the backend, or nullptr for the default platform.
47
+ BackendOptions& set_platform(se::Platform* platform);
48
+ se::Platform* platform() const;
49
+
50
+ // Sets the thread pool size for parallel execution of an individual operator.
51
+ // The default value of -1 will result in initializing the thread pool with
52
+ // the number of threads equal to the number of cores in the system.
53
+ BackendOptions& set_intra_op_parallelism_threads(int num_threads);
54
+ int intra_op_parallelism_threads() const;
55
+
56
+ // Sets the allowed_devices for selectively constructing stream executors
57
+ // on the platform.
58
+ BackendOptions& set_allowed_devices(
59
+ const std::optional<std::set<int>>& allowed_devices);
60
+ const std::optional<std::set<int>>& allowed_devices() const;
61
+
62
+ private:
63
+ se::Platform* platform_ = nullptr;
64
+ int intra_op_parallelism_threads_ = -1;
65
+ std::optional<std::set<int>> allowed_devices_;
66
+ };
67
+
68
+ // Class which encapsulates an XLA backend. It includes everything necessary
69
+ // to compile and execute computations on a particular platform.
70
+ //
71
+ // It also offers a pooling API for creation/use of initialized streams:
72
+ //
73
+ // StreamPool::Ptr stream = backend->BorrowStream().value();
74
+ class Backend {
75
+ public:
76
+ // Creates a new backend.
77
+ static StatusOr<std::unique_ptr<Backend>> CreateBackend(
78
+ const BackendOptions& options);
79
+
80
+ // Creates a backend for the default platform. The default platform is defined
81
+ // in PlatformUtil.
82
+ static StatusOr<std::unique_ptr<Backend>> CreateDefaultBackend();
83
+
84
+ ~Backend();
85
+
86
+ // Accessors for the various objects.
87
+ se::Platform* platform() const { return platform_; }
88
+ Compiler* compiler() const { return compiler_; }
89
+ se::DeviceMemoryAllocator* memory_allocator() const {
90
+ return memory_allocator_.get();
91
+ }
92
+ std::shared_ptr<se::DeviceMemoryAllocator> shared_memory_allocator() const {
93
+ return memory_allocator_;
94
+ }
95
+ TransferManager* transfer_manager() const { return transfer_manager_; }
96
+ ComputationPlacer* computation_placer() const { return computation_placer_; }
97
+
98
+ // Returns the number of devices of the platform type which are visible. Not
99
+ // all of these devices may be usable by XLA.
100
+ int device_count() const { return stream_executors_.size(); }
101
+
102
+ // Returns the device ordinal number of the default device.
103
+ int default_device_ordinal() const;
104
+
105
+ // Returns stream executors of all supported devices for this backend. The
106
+ // executors are ordered by the device ordinal.
107
+ const std::vector<se::StreamExecutor*>& stream_executors() const {
108
+ return stream_executors_;
109
+ }
110
+
111
+ // Returns the stream executor for the given device ordinal.
112
+ StatusOr<se::StreamExecutor*> stream_executor(int device_ordinal) const;
113
+
114
+ // Returns the stream executor for the default device ordinal. This stream
115
+ // executor can only be used when the number of computations is 1 (replication
116
+ // can be > 1).
117
+ se::StreamExecutor* default_stream_executor() const {
118
+ CHECK(!stream_executors_.empty());
119
+ return stream_executors_[0];
120
+ }
121
+
122
+ // Borrows a stream for use by the caller with a given priority, either by
123
+ // grabbing it from an internal pool, or by constructing/initializating it,
124
+ // and returns the result to the caller.
125
+ StatusOr<StreamPool::Ptr> BorrowStream(
126
+ int device_ordinal,
127
+ se::StreamPriority priority = se::StreamPriority::Default);
128
+ StatusOr<StreamPool::Ptr> BorrowStream(
129
+ se::StreamExecutor* executor,
130
+ se::StreamPriority priority = se::StreamPriority::Default);
131
+ StatusOr<std::vector<StreamPool::Ptr>> BorrowStreams(
132
+ int device_ordinal, int num_streams,
133
+ se::StreamPriority priority = se::StreamPriority::Default);
134
+
135
+ // Returns a function to borrow streams with a given priority,
136
+ // as `BorrowStreams` above does.
137
+ // Purely for convenience, the caller could rather make this anonymous
138
+ // function itself.
139
+ std::function<StatusOr<std::vector<StreamPool::Ptr>>(int, int,
140
+ se::StreamPriority)>
141
+ StreamBorrowerWithPriority() {
142
+ return [this](int device_ordinal, int num_streams,
143
+ se::StreamPriority priority) {
144
+ return BorrowStreams(device_ordinal, num_streams, priority);
145
+ };
146
+ }
147
+
148
+ // Returns whether the given device ordinal of the backend is supported.
149
+ bool device_ordinal_supported(int device_ordinal) const {
150
+ return (device_ordinal >= 0 && device_ordinal < device_count() &&
151
+ stream_executors_[device_ordinal] != nullptr);
152
+ }
153
+
154
+ // Return a string identifier for the given device, eg: "GPU:3".
155
+ std::string device_name(int device_ordinal) const {
156
+ return absl::StrCat(platform_->Name(), ":", device_ordinal);
157
+ }
158
+
159
+ // Returns true if the devices with the given ordinals are equivalent from
160
+ // XLA's perspective. That is, an executable compiled for one device would
161
+ // be equivalent to an executable compiled for the other.
162
+ StatusOr<bool> devices_equivalent(int device_ordinal_a, int device_ordinal_b);
163
+
164
+ // For the host platform, returns the configured eigen threadpool device to be
165
+ // used for scheduling work. For other platforms, returns NULL.
166
+ const Eigen::ThreadPoolDevice* eigen_intra_op_thread_pool_device() const;
167
+ tsl::thread::ThreadPool* eigen_intra_op_thread_pool() const;
168
+
169
+ // Resets the devices associated with this backend.
170
+ Status ResetDevices();
171
+
172
+ private:
173
+ Backend(se::Platform* platform, Compiler* compiler,
174
+ absl::Span<se::StreamExecutor* const> stream_executors,
175
+ TransferManager* transfer_manager,
176
+ ComputationPlacer* computation_placer,
177
+ int intra_op_parallelism_threads);
178
+ Backend(const Backend&) = delete;
179
+ Backend& operator=(const Backend&) = delete;
180
+
181
+ se::Platform* platform_;
182
+ Compiler* compiler_;
183
+ TransferManager* transfer_manager_;
184
+ ComputationPlacer* computation_placer_;
185
+
186
+ // Vector of stream executors. stream_executors_[0] is the default executor.
187
+ std::vector<se::StreamExecutor*> stream_executors_;
188
+
189
+ absl::Mutex mu_;
190
+
191
+ // Mapping from stream executor to stream pools, used by `BorrowStream` above.
192
+ absl::flat_hash_map<se::StreamExecutor*, std::unique_ptr<StreamPool>>
193
+ stream_pools_ ABSL_GUARDED_BY(mu_);
194
+
195
+ // The default memory allocator to use.
196
+ // This must be a shared_ptr, as this is passed all the way down to the
197
+ // cluster compilation. This allows asynchronous compilation to hold a
198
+ // referecence until the compilation is finished.
199
+ std::shared_ptr<se::StreamExecutorMemoryAllocator> memory_allocator_;
200
+
201
+ // For the CPU backend, an Eigen threadpool device for use by Eigen code.
202
+ struct IntraOpThreadPool;
203
+ std::unique_ptr<IntraOpThreadPool> intra_op_thread_pool_;
204
+ };
205
+
206
+ } // namespace xla
207
+
208
+ #endif // XLA_SERVICE_BACKEND_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batch_dot_simplification.h ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef XLA_SERVICE_BATCH_DOT_SIMPLIFICATION_H_
17
+ #define XLA_SERVICE_BATCH_DOT_SIMPLIFICATION_H_
18
+
19
+ #include "xla/hlo/ir/hlo_module.h"
20
+ #include "xla/service/hlo_pass_interface.h"
21
+
22
+ namespace xla {
23
+ // Simplifies batch dot operations.
24
+ //
25
+ // Normally these would live in the algebraic simplifier, but we want to run
26
+ // this to fixpoint (this pass reaches fixed point in one execution) before we
27
+ // run the DotDecomposer.
28
+ class BatchDotSimplification : public HloModulePass {
29
+ public:
30
+ using HloPassInterface::Run;
31
+ StatusOr<bool> Run(
32
+ HloModule* module,
33
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
34
+ absl::string_view name() const override;
35
+
36
+ private:
37
+ StatusOr<bool> ElideDegenerateBatchDimensionFromBatchDot(
38
+ HloInstruction* batch_dot);
39
+ };
40
+ } // namespace xla
41
+
42
+ #endif // XLA_SERVICE_BATCH_DOT_SIMPLIFICATION_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/batchnorm_expander.h ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 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 XLA_SERVICE_BATCHNORM_EXPANDER_H_
17
+ #define XLA_SERVICE_BATCHNORM_EXPANDER_H_
18
+
19
+ #include <utility>
20
+
21
+ #include "xla/hlo/ir/hlo_module.h"
22
+ #include "xla/service/hlo_pass_interface.h"
23
+
24
+ namespace xla {
25
+
26
+ // A pass which rewrites batch norm operations into more operations. Breaking a
27
+ // big operation into smaller operations helps leverage our generic fusion
28
+ // logic.
29
+ class BatchNormExpander : public HloModulePass {
30
+ public:
31
+ // When use_fusion is set, a multi-output fusion node is created.
32
+ explicit BatchNormExpander(bool rewrite_training_op = false,
33
+ bool rewrite_inference_op = false,
34
+ bool rewrite_grad_op = false)
35
+ : rewrite_training_op_(rewrite_training_op),
36
+ rewrite_inference_op_(rewrite_inference_op),
37
+ rewrite_grad_op_(rewrite_grad_op) {}
38
+ ~BatchNormExpander() override = default;
39
+ absl::string_view name() const override { return "batchnorm_expander"; }
40
+
41
+ // Run operation expander on the given computation. Returns whether the
42
+ // computation was changed.
43
+ using HloPassInterface::Run;
44
+ StatusOr<bool> Run(
45
+ HloModule* module,
46
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
47
+
48
+ private:
49
+ bool rewrite_training_op_;
50
+ bool rewrite_inference_op_;
51
+ bool rewrite_grad_op_;
52
+ };
53
+
54
+ } // namespace xla
55
+
56
+ #endif // XLA_SERVICE_BATCHNORM_EXPANDER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/bitcast_dtypes_expander.h ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2021 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 "xla/hlo/ir/hlo_instructions.h"
17
+ #include "xla/hlo/ir/hlo_module.h"
18
+ #include "xla/service/hlo_pass_interface.h"
19
+ #include "xla/service/op_expander_pass.h"
20
+ #include "xla/statusor.h"
21
+
22
+ #ifndef XLA_SERVICE_BITCAST_DTYPES_EXPANDER_H_
23
+ #define XLA_SERVICE_BITCAST_DTYPES_EXPANDER_H_
24
+
25
+ namespace xla {
26
+
27
+ // A pass which expands bitcast-convert between differently sized dtypes to a
28
+ // reduction.
29
+ class BitcastDtypesExpander : public OpExpanderPass {
30
+ public:
31
+ absl::string_view name() const override { return "bitcast_dtypes_expander"; }
32
+
33
+ protected:
34
+ bool InstructionMatchesPattern(HloInstruction* instruction) override;
35
+
36
+ StatusOr<HloInstruction*> ExpandInstruction(
37
+ HloInstruction* instruction) override;
38
+
39
+ private:
40
+ absl::flat_hash_map<std::string, HloComputation*> computation_cache_;
41
+ };
42
+
43
+ } // namespace xla
44
+
45
+ #endif // XLA_SERVICE_BITCAST_DTYPES_EXPANDER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/broadcast_canonicalizer.h ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2022 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 XLA_SERVICE_BROADCAST_CANONICALIZER_H_
17
+ #define XLA_SERVICE_BROADCAST_CANONICALIZER_H_
18
+
19
+ #include <optional>
20
+
21
+ #include "xla/service/hlo_pass_interface.h"
22
+
23
+ namespace xla {
24
+
25
+ // This transform ensures that dimensions in all broadcast operations are
26
+ // sorted.
27
+ class BroadcastCanonicalizer : public HloModulePass {
28
+ public:
29
+ explicit BroadcastCanonicalizer();
30
+
31
+ absl::string_view name() const override { return "broadcast_canonicalizer"; }
32
+ using HloPassInterface::Run;
33
+ StatusOr<bool> Run(
34
+ HloModule* module,
35
+ const absl::flat_hash_set<absl::string_view>& execution_threads) override;
36
+ };
37
+
38
+ } // namespace xla
39
+
40
+ #endif // XLA_SERVICE_BROADCAST_CANONICALIZER_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.h ADDED
@@ -0,0 +1,793 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 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 XLA_SERVICE_BUFFER_ASSIGNMENT_H_
17
+ #define XLA_SERVICE_BUFFER_ASSIGNMENT_H_
18
+
19
+ #include <functional>
20
+ #include <iosfwd>
21
+ #include <memory>
22
+ #include <string>
23
+ #include <vector>
24
+
25
+ #include "absl/container/flat_hash_map.h"
26
+ #include "absl/container/flat_hash_set.h"
27
+ #include "absl/types/span.h"
28
+ #include "xla/hlo/ir/hlo_computation.h"
29
+ #include "xla/hlo/ir/hlo_instruction.h"
30
+ #include "xla/hlo/ir/hlo_module.h"
31
+ #include "xla/hlo/utils/hlo_live_range.h"
32
+ #include "xla/service/buffer_assignment.pb.h"
33
+ #include "xla/service/heap_simulator.h"
34
+ #include "xla/service/hlo.pb.h"
35
+ #include "xla/service/hlo_alias_analysis.h"
36
+ #include "xla/service/hlo_dataflow_analysis.h"
37
+ #include "xla/service/logical_buffer.h"
38
+ #include "xla/service/memory_space_assignment/memory_space_assignment.h"
39
+ #include "xla/service/tuple_points_to_analysis.h"
40
+ #include "xla/statusor.h"
41
+ #include "xla/types.h"
42
+ #include "tsl/platform/logging.h"
43
+
44
+ namespace xla {
45
+
46
+ // Walk the call graph of the HLO module and place each computation into either
47
+ // thread_local_computations or global_computations depending upon whether the
48
+ // computation requires thread-local allocations or global allocations. The
49
+ // elements in thread_local_computations and global_computations are in post
50
+ // order (if computation A has an instruction which calls computation B, then A
51
+ // will appear after B in the vector).
52
+ Status GatherComputationsByAllocationType(
53
+ const HloModule* module,
54
+ std::vector<const HloComputation*>* thread_local_computations,
55
+ std::vector<const HloComputation*>* global_computations);
56
+
57
+ // This class abstracts an allocation of contiguous memory which can hold the
58
+ // values described by LogicalBuffers. Each LogicalBuffer occupies a sub-range
59
+ // of the allocation, represented by a Slice. A single BufferAllocation may hold
60
+ // LogicalBuffers with disjoint liveness, which may have overlapping Slices. A
61
+ // single BufferAllocation may also hold LogicalBuffers with overlapping
62
+ // liveness, which must have disjoint Slices.
63
+ //
64
+ // The abstraction includes information required by the backends for allocation,
65
+ // use, and deallocation of the buffer. This includes the LogicalBuffers which
66
+ // are held in this allocation through the execution of the computation.
67
+ class BufferAllocation {
68
+ public:
69
+ // Holds a unique identifier for each allocation. Values are assigned
70
+ // contiguously and can be used as array indexes.
71
+ using Index = int64_t;
72
+
73
+ BufferAllocation(Index index, int64_t size, LogicalBuffer::Color color)
74
+ : index_(index), size_(size), color_(color) {}
75
+ ~BufferAllocation() {}
76
+
77
+ // Returns the index of this allocation.
78
+ Index index() const { return index_; }
79
+
80
+ // Whether this allocation is used in a parallel calling context such as
81
+ // inside of a map or reduce computation. Such allocations need to be thread
82
+ // local.
83
+ bool is_thread_local() const { return is_thread_local_; }
84
+ void set_is_thread_local(bool is_thread_local) {
85
+ is_thread_local_ = is_thread_local;
86
+ }
87
+
88
+ // Whether this allocation can be used by more than one logical buffer.
89
+ bool is_reusable() const {
90
+ // We do not reuse thread-local buffers for now, because they are
91
+ // dynamically allocated and their lifetimes are hard to compute.
92
+ //
93
+ // TODO(b/34669761): Don't reuse tuple buffers because the GPU backend
94
+ // assumes longer buffer liveness than indicated by the analysis.
95
+ return !is_thread_local() && !is_tuple();
96
+ }
97
+
98
+ // Whether this allocation is readonly i.e. backed by memory we cannot write
99
+ // to.
100
+ bool is_readonly() const {
101
+ // Entry parameters are generally readonly, except when they are aliased
102
+ // with any output.
103
+ return (is_entry_computation_parameter() &&
104
+ !is_parameter_aliased_with_output_) ||
105
+ is_constant();
106
+ }
107
+
108
+ bool is_tuple() const { return is_tuple_; }
109
+ void set_is_tuple(bool is_tuple) { is_tuple_ = is_tuple; }
110
+
111
+ // Whether this allocation holds a LogicalBuffer from a parameter of the entry
112
+ // computation. These buffers have lifetimes which may be longer than the
113
+ // XLA computation.
114
+ bool is_entry_computation_parameter() const {
115
+ return is_entry_computation_parameter_;
116
+ }
117
+
118
+ // Whether this allocation holds a constant. On the CPU and GPU backends
119
+ // constant allocations are not allocated dynamically, instead we resolve
120
+ // references to these buffer allocations to a global in the readonly section
121
+ // of the binary.
122
+ bool is_constant() const { return is_constant_; }
123
+
124
+ // If this allocation holds a Buffer from a parameter of the entry
125
+ // computation, this methods returns the parameter number. CHECKs otherwise.
126
+ int64_t parameter_number() const {
127
+ CHECK(is_entry_computation_parameter_);
128
+ return parameter_number_;
129
+ }
130
+
131
+ // If this allocation is for a parameter of the entry computation, this
132
+ // function returns which subshape of the parameter the allocation is for.
133
+ const ShapeIndex& param_shape_index() const {
134
+ CHECK(is_entry_computation_parameter_);
135
+ return param_shape_index_;
136
+ }
137
+
138
+ // Returns whether this allocation is assigned a LogicalBuffer which may
139
+ // be live out of the entry computation.
140
+ bool maybe_live_out() const { return maybe_live_out_; }
141
+
142
+ void set_maybe_live_out(bool value) { maybe_live_out_ = value; }
143
+
144
+ // Returns the size of the allocation. Necessarily this must be at least as
145
+ // large as any LogicalBuffer assigned to this allocation.
146
+ int64_t size() const { return size_; }
147
+
148
+ // Returns the color of the allocation. Only logical buffers with a matching
149
+ // color can reside in this allocation.
150
+ LogicalBuffer::Color color() const { return color_; }
151
+
152
+ struct OffsetSize {
153
+ int64_t offset = 0;
154
+ int64_t size = 0;
155
+ };
156
+
157
+ // Access to the logical buffers assigned to this allocation, and their
158
+ // associated logical offsets and sizes.
159
+ const absl::flat_hash_map<const HloValue*, OffsetSize>& assigned_buffers()
160
+ const {
161
+ return assigned_buffers_;
162
+ }
163
+
164
+ // A Slice represents a contiguous portion of a memory allocation. It is used
165
+ // to identify the memory range that a LogicalBuffer corresponds to.
166
+ class Slice {
167
+ public:
168
+ Slice() {}
169
+ Slice(const BufferAllocation* allocation, int64_t offset, int64_t size)
170
+ : allocation_(allocation), offset_(offset), size_(size) {}
171
+
172
+ const BufferAllocation* allocation() const { return allocation_; }
173
+ Index index() const { return allocation_->index(); }
174
+ int64_t offset() const { return offset_; }
175
+ int64_t size() const { return size_; }
176
+
177
+ bool operator==(const Slice& other) const {
178
+ return index() == other.index() && offset_ == other.offset_ &&
179
+ size_ == other.size_;
180
+ }
181
+ bool operator!=(const Slice& other) const { return !(*this == other); }
182
+ bool operator<(const Slice& other) const {
183
+ if (index() != other.index()) return index() < other.index();
184
+ if (offset_ != other.offset_) return offset_ < other.offset_;
185
+ return size_ < other.size_;
186
+ }
187
+
188
+ // Returns true iff this slice's memory range has a non-empty intersection
189
+ // with the other slice's memory range.
190
+ bool OverlapsWith(const Slice& other) const {
191
+ const int64_t end = offset_ + size_;
192
+ const int64_t other_end = other.offset_ + other.size_;
193
+ return index() == other.index() && offset_ < other_end &&
194
+ end > other.offset_;
195
+ }
196
+
197
+ template <typename H>
198
+ friend H AbslHashValue(H h, const Slice& s) {
199
+ return H::combine(std::move(h), s.index(), s.offset(), s.size());
200
+ }
201
+
202
+ std::string ToString() const;
203
+
204
+ private:
205
+ const BufferAllocation* allocation_ = nullptr;
206
+ int64_t offset_ = 0;
207
+ int64_t size_ = 0;
208
+ };
209
+
210
+ // GetSlice returns the Slice of contiguous memory that holds the value
211
+ // described by the given 'buffer'.
212
+ // REQUIRES: 'buffer' must be assigned to this allocation.
213
+ Slice GetSlice(const HloValue& buffer) const;
214
+
215
+ std::string ToString() const;
216
+ BufferAllocationProto ToProto() const;
217
+
218
+ // Whether the buffer is a parameter to or live out of the entry computation.
219
+ bool IsInputOrOutput() const {
220
+ return is_entry_computation_parameter() || maybe_live_out();
221
+ }
222
+
223
+ // Whether the buffer is a temporary buffer allocated before
224
+ // Executable::ExecuteOnStream.
225
+ bool IsPreallocatedTempBuffer() const {
226
+ // Parameters do not need temporary buffers.
227
+ return !is_entry_computation_parameter() &&
228
+ // LogicalBuffers that maybe pointed to by the output should live out
229
+ // of the computation.
230
+ !maybe_live_out() &&
231
+ // Thread-local buffers are allocated using `alloca`s.
232
+ !is_thread_local() &&
233
+ // Constant buffers are allocated as global values.
234
+ !is_constant();
235
+ }
236
+
237
+ // Add a heap trace which was used to assign slices to logical buffers in this
238
+ // allocation. A single BufferAllocation may include multiple heap traces
239
+ // in the case of the temporary block where there is a heap trace per
240
+ // computation.
241
+ void AddHeapTrace(const HeapSimulatorTrace& heap_trace) {
242
+ heap_traces_.push_back(heap_trace);
243
+ heap_traces_.back().set_buffer_allocation_index(index());
244
+ }
245
+
246
+ // Return the set of heap traces used to assign slices to logical buffers in
247
+ // this allocation.
248
+ const std::vector<HeapSimulatorTrace> HeapTraces() const {
249
+ return heap_traces_;
250
+ }
251
+
252
+ // Returns the LogicalBuffers which are live at the point of peak memory usage
253
+ // for this allocation. The point of peak memory usage is the point at which
254
+ // the total size of all live logical buffers is maximal. If peak memory is
255
+ // reached at multiple points, the set of logical buffers live at the earliest
256
+ // maximal point is returned. The vector is stably sorted by
257
+ // BufferValue::Index.
258
+ const std::vector<const HloValue*>& PeakMemoryLogicalBuffers() const {
259
+ return peak_buffers_;
260
+ }
261
+
262
+ // Get the number of bytes lost to fragmentation. This is equal to the
263
+ // difference between the size of the allocation and the size of the maximal
264
+ // live set.
265
+ int64_t fragmentation_bytes() const { return fragmentation_bytes_; }
266
+
267
+ bool operator==(const BufferAllocation& other) const {
268
+ return index_ == other.index_;
269
+ }
270
+ bool operator!=(const BufferAllocation& other) const {
271
+ return !(*this == other);
272
+ }
273
+ bool operator<(const BufferAllocation& other) const {
274
+ return index() < other.index();
275
+ }
276
+
277
+ void set_entry_computation_parameter(int64_t parameter_number,
278
+ ShapeIndex param_shape_index,
279
+ bool parameter_aliased_with_output) {
280
+ is_entry_computation_parameter_ = true;
281
+ is_parameter_aliased_with_output_ = parameter_aliased_with_output;
282
+ parameter_number_ = parameter_number;
283
+ param_shape_index_ = std::move(param_shape_index);
284
+ }
285
+
286
+ void set_constant(bool is_constant) { is_constant_ = is_constant; }
287
+
288
+ private:
289
+ // Only BufferAssigner and BufferAssignment can modify BufferAllocation.
290
+ friend class BufferAssigner;
291
+ friend class BufferAssignment;
292
+
293
+ // Adds a LogicalBuffer to the set assigned to this buffer.
294
+ void AddAssignment(const HloValue& buffer, int64_t offset, int64_t size);
295
+
296
+ void set_index(Index index) { index_ = index; }
297
+ void set_size(int64_t size) { size_ = size; }
298
+
299
+ // The index of the allocation in the BufferAssignment.
300
+ Index index_;
301
+
302
+ // Size of the allocation in bytes.
303
+ int64_t size_;
304
+
305
+ // Whether this buffer needs to be thread-local.
306
+ bool is_thread_local_ = false;
307
+
308
+ // Whether this buffer holds a tuple.
309
+ bool is_tuple_ = false;
310
+
311
+ // Color of the allocation.
312
+ LogicalBuffer::Color color_;
313
+
314
+ // Whether this allocation holds an entry computation parameter. Entry
315
+ // computation parameters are special because they have lifetimes which may
316
+ // outlast the computation.
317
+ bool is_entry_computation_parameter_ = false;
318
+
319
+ // Whether this entry computation parameter is aliased with output.
320
+ bool is_parameter_aliased_with_output_ = false;
321
+
322
+ // If this allocation holds an entry computation parameter, this field
323
+ // indicates the index (starting from 0) of the parameter.
324
+ int64_t parameter_number_ = 0;
325
+
326
+ // If this buffer is for an entry computation parameter, which subshape of the
327
+ // parameter is it for?
328
+ ShapeIndex param_shape_index_;
329
+
330
+ // Whether the allocation contains a LogicalBuffer which may be live-out of
331
+ // the entry computation. Note that this flag is conservatively computed by
332
+ // TuplePointsToAnalysis. That is, an allocation marked `maybe_live_out_`
333
+ // might not actually escape.
334
+ bool maybe_live_out_ = false;
335
+
336
+ // See comment on the is_constant() accessor.
337
+ bool is_constant_ = false;
338
+
339
+ // Mapping from the set of buffers assigned to this allocation to their
340
+ // logical offsets and sizes.
341
+ absl::flat_hash_map<const HloValue*, OffsetSize> assigned_buffers_;
342
+
343
+ int64_t fragmentation_bytes_ = 0;
344
+ std::vector<HeapSimulatorTrace> heap_traces_;
345
+
346
+ // Set of buffers live at the point of peak memory usage for this allocation.
347
+ std::vector<const HloValue*> peak_buffers_;
348
+ };
349
+
350
+ // Add stream operators for nicer output of CHECK/RET_CHECK failures.
351
+ std::ostream& operator<<(std::ostream& out, const BufferAllocation& s);
352
+ std::ostream& operator<<(std::ostream& out, const BufferAllocation::Slice& s);
353
+
354
+ // This class encapsulates an assignment of the LogicalBuffers in an XLA
355
+ // module to a set of BufferAllocations.
356
+ class BufferAssignment {
357
+ public:
358
+ // This is a think wrapper around BufferIsolationConfig. Please see the
359
+ // documentation for BufferIsolationConfig for details on how buffer isolation
360
+ // works. hlo_value_compare is the concrete implementation of the HloValue
361
+ // comparison that uses the isolation_order_salt value in the
362
+ // BufferIsolationConfig.
363
+ struct BufferIsolationOptions {
364
+ std::function<bool(const HloValue*, const HloValue*)> hlo_value_compare;
365
+ buffer_assignment::BufferIsolationConfig config;
366
+ };
367
+
368
+ // Returns the vector containing all buffer allocations in this assignment.
369
+ const std::vector<BufferAllocation>& Allocations() const {
370
+ return allocations_;
371
+ }
372
+
373
+ // This is similar to copying Allocations(), but since it's moved out, it
374
+ // preserves the addresses. Since BufferAllocation::Slice keeps a
375
+ // BufferAllocation*, and some backends keep BufferAllocation::Slice in
376
+ // xla::Executables, migrating off the use of addresses can be hard.
377
+ std::vector<BufferAllocation> ReleaseAllocations() {
378
+ return std::move(allocations_);
379
+ }
380
+
381
+ // Returns the total size allocation holding all temporary buffers.
382
+ int64_t temp_allocation_total_size() const {
383
+ return temp_allocation_total_size_;
384
+ }
385
+
386
+ uint64_t multiheap_size_constraint_per_heap() const {
387
+ return multiheap_size_constraint_per_heap_;
388
+ }
389
+
390
+ // Returns whether the given buffer has been assigned an allocation.
391
+ bool HasAllocation(const HloValue& value) const;
392
+
393
+ // Returns whether the given (logical) buffer with the id has been assigned an
394
+ // allocation.
395
+ bool HasAllocation(HloValue::Id value_id) const;
396
+
397
+ bool HasAllocation(const HloBuffer& buffer) const;
398
+
399
+ // Returns the allocation that a particular LogicalBuffer has been assigned
400
+ // to. CHECKs if buffer has not been assigned an allocation.
401
+ const BufferAllocation& GetAssignedAllocation(const HloValue& value) const;
402
+
403
+ const BufferAllocation& GetAssignedAllocation(
404
+ const HloBuffer& hlo_buffer) const;
405
+
406
+ // Returns the allocation with the given index. CHECKs if no allocation exists
407
+ // with the given index.
408
+ const BufferAllocation& GetAllocation(BufferAllocation::Index index) const;
409
+
410
+ // Returns the allocation with the given instruction and shape index. nullptr
411
+ // if no allocation exists.
412
+ const BufferAllocation* GetInstructionAllocation(
413
+ const HloInstruction* hlo, const ShapeIndex& shape_index) const;
414
+
415
+ // Builds and returns a vector containing the slices which might contain the
416
+ // subvalue at the given index of given instruction.
417
+ std::set<BufferAllocation::Slice> GetAllSlices(
418
+ const HloInstruction* instruction, const ShapeIndex& index) const;
419
+
420
+ // Convenience function which returns whether the buffer of the
421
+ // instruction at the given index is assigned an allocation.
422
+ bool HasAllocationAt(const HloInstruction* instruction,
423
+ const ShapeIndex& index) const;
424
+
425
+ // Convenience function which returns whether the top-level buffer of the
426
+ // instruction (index == {}) is assigned an allocation.
427
+ bool HasTopLevelAllocation(const HloInstruction* instruction) const;
428
+
429
+ // Convenience function which returns the unique slice containing the buffer
430
+ // at the given index of the given instruction. If a slice is not assigned or
431
+ // the slice cannot be determined at compile time then an error is returned.
432
+ StatusOr<BufferAllocation::Slice> GetUniqueSlice(
433
+ const HloInstruction* instruction, const ShapeIndex& index) const;
434
+ // Like GetUniqueSlice but fixes the index to the top-level of the shape
435
+ // (index = {}).
436
+ StatusOr<BufferAllocation::Slice> GetUniqueTopLevelSlice(
437
+ const HloInstruction* instruction) const;
438
+ // Like GetUniqueTopLevelSlice but returns the slice for the output of the
439
+ // entry computation of the HLO module (ie, the result of the XLA
440
+ // computation).
441
+ StatusOr<BufferAllocation::Slice> GetUniqueTopLevelOutputSlice() const;
442
+
443
+ // Returns the set BufferValues which may be the source of the value at the
444
+ // given index and instruction.
445
+ const std::vector<const HloValue*>& GetSourceBuffers(
446
+ const HloInstruction* instruction, const ShapeIndex& index) const {
447
+ return dataflow_analysis().GetValueSet(instruction, index).values();
448
+ }
449
+
450
+ // Returns true if 'hlo_a{shape_index_a}' and 'hlo_b{shape_index_b}'
451
+ // share the same BufferAllocation::Slice.
452
+ // Returns false otherwise.
453
+ // REQUIRES: BufferAssignment assigned allocations to both instructions.
454
+ bool SharesSliceAtIndex(const HloInstruction* hlo_a,
455
+ const ShapeIndex& shape_index_a,
456
+ const HloInstruction* hlo_b,
457
+ const ShapeIndex& shape_index_b) const;
458
+
459
+ // Returns true if the top-level buffers of hlo_a and hlo_b are the same.
460
+ // REQUIRES: HasTopLevelAllocation(hlo_a) && HasTopLevelAllocation(hlo_b).
461
+ bool SharesTopLevelSlice(const HloInstruction* hlo_a,
462
+ const HloInstruction* hlo_b) const {
463
+ return SharesSliceAtIndex(hlo_a, {}, hlo_b, {});
464
+ }
465
+
466
+ // Returns true if hlo_a and hlo_b both have at least one buffer assigned for
467
+ // their top-level and each of their nested shape indices, and if hlo_a's
468
+ // buffers are all different from hlo_b's buffers.
469
+ bool HaveDisjointSlices(const HloInstruction* hlo_a,
470
+ const HloInstruction* hlo_b) const;
471
+
472
+ const HloDataflowAnalysis& dataflow_analysis() const {
473
+ return alias_analysis_->dataflow_analysis();
474
+ }
475
+
476
+ HloAliasAnalysis& alias_analysis() const { return *alias_analysis_; }
477
+
478
+ const HloOrdering& hlo_ordering() const { return *hlo_ordering_; }
479
+
480
+ // Returns the HloLiveRange object used to construct this assignment.
481
+ const HloLiveRange& hlo_live_range() const { return *hlo_live_range_; }
482
+
483
+ std::string ToString() const;
484
+ // Verbose string tailored to debugging OOMs, includes the Hlo op metadata for
485
+ // every buffer associated with each allocation.
486
+ std::string ToVerboseString(size_t max_buffers_to_show) const;
487
+ std::string BufferInfoString() const;
488
+
489
+ // Convert BufferAssignment to or from a proto.
490
+ BufferAssignmentProto ToProto() const;
491
+ static StatusOr<std::unique_ptr<BufferAssignment>> FromProto(
492
+ const BufferAssignmentProto& proto, const HloModule* module,
493
+ BufferValue::SizeFunction buffer_size,
494
+ HloDataflowAnalysis::CanShareBuffer can_share_buffer);
495
+
496
+ // Statistics for the assignment. Values initialized to -1 are not always
497
+ // collected; fragmentation is only collected for instructions that have a
498
+ // sequential total ordering.
499
+ struct Stats {
500
+ int64_t parameter_allocation_count = 0;
501
+ int64_t parameter_allocation_bytes = 0;
502
+ int64_t constant_allocation_count = 0;
503
+ int64_t constant_allocation_bytes = 0;
504
+ int64_t maybe_live_out_allocation_count = 0;
505
+ int64_t maybe_live_out_allocation_bytes = 0;
506
+ int64_t preallocated_temp_allocation_count = 0;
507
+ int64_t preallocated_temp_allocation_bytes = 0;
508
+ int64_t preallocated_temp_fragmentation_bytes = -1;
509
+ int64_t total_allocation_count = 0;
510
+ int64_t total_allocation_bytes = 0;
511
+ int64_t total_fragmentation_bytes = -1;
512
+
513
+ std::string ToString() const;
514
+ };
515
+ const Stats& GetStats() const { return stats_; }
516
+
517
+ private:
518
+ // Only BufferAssigner can build or modify BufferAssignments.
519
+ friend class BufferAssigner;
520
+
521
+ BufferAssignment(const HloModule* module,
522
+ std::unique_ptr<HloOrdering> hlo_ordering,
523
+ BufferValue::SizeFunction buffer_size,
524
+ LogicalBuffer::AlignmentFunction color_alignment,
525
+ std::unique_ptr<HloAliasAnalysis> alias_analysis,
526
+ std::unique_ptr<HloLiveRange> hlo_live_range)
527
+ : module_(module),
528
+ hlo_ordering_(std::move(hlo_ordering)),
529
+ buffer_size_(std::move(buffer_size)),
530
+ color_alignment_(std::move(color_alignment)),
531
+ alias_analysis_(std::move(alias_analysis)),
532
+ hlo_live_range_(std::move(hlo_live_range)) {
533
+ int32_t raw_value = module->config()
534
+ .debug_options()
535
+ .xla_multiheap_size_constraint_per_heap();
536
+ // -1 means no constraint.
537
+ multiheap_size_constraint_per_heap_ =
538
+ (raw_value == -1) ? UINT64_MAX : raw_value;
539
+ }
540
+
541
+ // Creates and returns a new BufferAllocation, with no assigned
542
+ // LogicalBuffers. Ownership is maintained internally.
543
+ BufferAllocation* NewEmptyAllocation(int64_t size,
544
+ LogicalBuffer::Color color);
545
+
546
+ // Helper that calls NewEmptyAllocation and AddAssignment in one call,
547
+ // creating an allocation containing a single LogicalBuffer.
548
+ BufferAllocation* NewAllocation(const HloBuffer& buffer, int64_t size);
549
+
550
+ // Adds a LogicalBuffer to the set assigned to the given allocation.
551
+ void AddAssignment(BufferAllocation* allocation, const HloBuffer& buffer,
552
+ int64_t offset, int64_t size);
553
+
554
+ void AddAssignment(BufferAllocation* allocation, const HloValue& value,
555
+ int64_t offset, int64_t size);
556
+
557
+ // Returns the HloModule used to construct this assignment.
558
+ const HloModule& module() const { return *module_; }
559
+
560
+ // Mutable accessors for allocations.
561
+ BufferAllocation* GetMutableAssignedAllocation(const HloBuffer& buffer);
562
+ BufferAllocation* GetMutableAllocation(BufferAllocation::Index index);
563
+
564
+ int64_t HloBufferSize(const HloBuffer& buffer) {
565
+ auto iter = cached_buffer_sizes_.find(buffer.id());
566
+ if (iter != cached_buffer_sizes_.end()) return iter->second;
567
+ int64_t result = 0;
568
+ for (const HloValue* value : buffer.values()) {
569
+ result = std::max(result, buffer_size_(*value));
570
+ }
571
+ cached_buffer_sizes_.insert({buffer.id(), result});
572
+ return result;
573
+ }
574
+
575
+ // Combines allocations of temporary buffers into one big BufferAllocation.
576
+ void CombineTempAllocations(
577
+ const absl::flat_hash_set<BufferValue::Color>& private_stack_colors);
578
+
579
+ // Computes stats for the assignment, to be retrieved by GetStats.
580
+ Status ComputeSummaryStats();
581
+
582
+ // The vector of buffer allocations. Indexed by BufferAllocation::Index.
583
+ std::vector<BufferAllocation> allocations_;
584
+
585
+ // The total size of all temporary buffers.
586
+ int64_t temp_allocation_total_size_ = 0;
587
+
588
+ uint64_t multiheap_size_constraint_per_heap_;
589
+
590
+ // Maps Buffers to the index of the BufferAllocation which holds the buffer.
591
+ absl::flat_hash_map<const HloValue*, BufferAllocation::Index>
592
+ allocation_index_for_value_;
593
+
594
+ const HloModule* module_;
595
+
596
+ const std::unique_ptr<HloOrdering> hlo_ordering_;
597
+
598
+ // Function which returns the buffer size for a given logical buffer (shape).
599
+ BufferValue::SizeFunction buffer_size_;
600
+
601
+ // Function which returns the alignment for a given logical buffer color.
602
+ LogicalBuffer::AlignmentFunction color_alignment_;
603
+
604
+ std::unique_ptr<HloAliasAnalysis> alias_analysis_;
605
+
606
+ std::unique_ptr<HloLiveRange> hlo_live_range_;
607
+
608
+ Stats stats_;
609
+
610
+ absl::flat_hash_map<HloBuffer::Id, int64_t> cached_buffer_sizes_;
611
+
612
+ BufferAssignment(const BufferAssignment&) = delete;
613
+ BufferAssignment& operator=(const BufferAssignment&) = delete;
614
+ };
615
+
616
+ // A class which constructs a buffer assignment.
617
+ class BufferAssigner {
618
+ public:
619
+ using Colorer = std::function<Status(HloAliasAnalysis*, const HloOrdering&)>;
620
+ using MustNotLiveOut =
621
+ std::function<bool(const HloInstruction*, const ShapeIndex&)>;
622
+ using PrivateStacks = absl::flat_hash_map<BufferValue::Color,
623
+ std::vector<const HloComputation*>>;
624
+
625
+ static Colorer DefaultColorer() {
626
+ return [](HloAliasAnalysis* alias_analysis, const HloOrdering&) {
627
+ for (HloValue* value : alias_analysis->dataflow_analysis().values()) {
628
+ const HloPosition& defining_position = value->defining_position();
629
+ if (defining_position.shape().has_layout()) {
630
+ value->set_color(BufferValue::Color(
631
+ defining_position.shape().layout().memory_space()));
632
+ } else {
633
+ value->set_color(BufferValue::Color(0));
634
+ }
635
+ }
636
+ return OkStatus();
637
+ };
638
+ }
639
+
640
+ // Returns false if a buffer cannot be assigned to given allocation.
641
+
642
+ // Build and return a BufferAssignment for the given module. The given
643
+ // HloOrdering is used to determine buffer liveness. buffer_size and
644
+ // color_alignment are functions which returns the size and alignment of a
645
+ // LogicalBuffer. If preset_assignments is provided, those pre-set assignment
646
+ // offsets will be used. The caller guarantees that those assignments are
647
+ // valid and they do not overwrite each other.
648
+ static StatusOr<std::unique_ptr<BufferAssignment>> Run(
649
+ const HloModule* module, std::unique_ptr<HloOrdering> hlo_ordering,
650
+ BufferValue::SizeFunction buffer_size,
651
+ LogicalBuffer::AlignmentFunction color_alignment,
652
+ bool allocate_buffers_for_constants = false,
653
+ Colorer colorer = DefaultColorer(),
654
+ std::optional<MustNotLiveOut> must_not_live_out = std::nullopt,
655
+ HloDataflowAnalysis::CanShareBuffer can_share_buffer = nullptr,
656
+ std::unique_ptr<memory_space_assignment::PresetAssignments>
657
+ preset_assignments = {},
658
+ const PrivateStacks& private_stacks = {},
659
+ GlobalDecreasingSizeBestFitHeap<HloValue>::BufferIntervalCompare
660
+ heap_buffer_interval_compare = nullptr,
661
+ std::optional<BufferAssignment::BufferIsolationOptions>
662
+ isolation_options = std::nullopt);
663
+
664
+ private:
665
+ BufferAssigner(bool allocate_buffers_for_constants, Colorer colorer,
666
+ std::optional<MustNotLiveOut> must_not_live_out,
667
+ std::unique_ptr<memory_space_assignment::PresetAssignments>
668
+ preset_assignments)
669
+ : allocate_buffers_for_constants_(allocate_buffers_for_constants),
670
+ colorer_(colorer),
671
+ must_not_live_out_(must_not_live_out),
672
+ preset_assignments_(std::move(preset_assignments)) {}
673
+ virtual ~BufferAssigner() = default;
674
+
675
+ // Create a buffer assignment.
676
+ StatusOr<std::unique_ptr<BufferAssignment>> CreateAssignment(
677
+ const HloModule* module, std::unique_ptr<HloOrdering> hlo_ordering,
678
+ BufferValue::SizeFunction buffer_size,
679
+ LogicalBuffer::AlignmentFunction color_alignment,
680
+ HloDataflowAnalysis::CanShareBuffer can_share_buffer,
681
+ const PrivateStacks& private_stacks,
682
+ GlobalDecreasingSizeBestFitHeap<HloValue>::BufferIntervalCompare
683
+ heap_buffer_interval_compare,
684
+ std::optional<BufferAssignment::BufferIsolationOptions>
685
+ isolation_options);
686
+
687
+ // Assigns buffers to the instructions in the given computations. "assignment"
688
+ // is modified to reflect the new buffer assignments. If is_thread_local is
689
+ // true, then all assigned buffers have the is_thread_local flag set to
690
+ // true.
691
+ Status AssignBuffersForComputations(
692
+ const std::vector<const HloComputation*>& computations,
693
+ bool is_thread_local,
694
+ absl::flat_hash_map<const HloComputation*,
695
+ absl::flat_hash_set<const HloValue*>>*
696
+ buffers_to_assign_sequentially,
697
+ BufferAssignment* assignment);
698
+
699
+ // Returns true if buffer's live range interferences with buffer2's.
700
+ bool LiveRangeInterferes(const HloValue* buffer1, const HloValue* buffer2,
701
+ BufferAssignment* assignment);
702
+
703
+ // Assigns pre-set assignments, if provided. These assignments will be added
704
+ // to assigned_buffers and skip buffer allocation.
705
+ Status AssignPresetBuffers(
706
+ absl::flat_hash_set<const HloBuffer*>* assigned_buffers,
707
+ BufferAssignment* assignment);
708
+
709
+ // Assigns a single hlo buffer to an HLO allocation.
710
+ Status AssignSingleHloBuffer(
711
+ const HloBuffer* hlo_buffer, bool is_thread_local,
712
+ absl::flat_hash_map<const HloComputation*,
713
+ absl::flat_hash_set<const HloValue*>>*
714
+ buffers_to_assign_sequentially,
715
+ std::vector<BufferAllocation::Index>* allocation_indices,
716
+ BufferAssignment* assignment);
717
+
718
+ // Assigns 'buffers_to_assign_sequentially' using heap simulation, assuming
719
+ // the HLO instructions will be executed in the sequential order given by
720
+ // assignment->liveness().hlo_ordering().SequentialOrder. If
721
+ // 'run_whole_module_heap_simulation' is true, the heap simulation will be run
722
+ // assuming all global computations are sequentially ordered.
723
+ Status AssignBuffersWithSequentialOrdering(
724
+ const absl::flat_hash_map<const HloComputation*,
725
+ absl::flat_hash_set<const HloValue*>>&
726
+ buffers_to_assign_sequentially,
727
+ bool run_whole_module_heap_simulation, BufferAssignment* assignment,
728
+ const PrivateStacks& private_stacks,
729
+ GlobalDecreasingSizeBestFitHeap<HloValue>::BufferIntervalCompare
730
+ heap_buffer_interval_compare,
731
+ std::optional<BufferAssignment::BufferIsolationOptions>
732
+ isolation_options);
733
+
734
+ // Isolates the buffers packed by heap simulator using the provided isolation
735
+ // options. Please see the documentation for BufferIsolationConfig for more
736
+ // details.
737
+ void IsolateHeapBuffers(
738
+ std::optional<BufferAssignment::BufferIsolationOptions> isolation_options,
739
+ const BufferAssignment* assignment, LogicalBuffer::Color color,
740
+ HeapSimulator::Result<HloValue>& result) const;
741
+
742
+ // Uses the results of the heap simulator to create a single allocation, with
743
+ // LogicalBuffers packed to specific offsets.
744
+ void AssignBuffersFromHeapSimulator(
745
+ HeapSimulator::Result<HloValue>& result, BufferAssignment* assignment,
746
+ LogicalBuffer::Color color,
747
+ std::optional<BufferAssignment::BufferIsolationOptions>
748
+ isolation_options);
749
+
750
+ // Tries to assign the given instruction to the given buffer. Returns if the
751
+ // assignment was successful.
752
+ bool MaybeAssignBuffer(BufferAllocation* allocation, const HloBuffer& buffer,
753
+ BufferAssignment* assignment);
754
+
755
+ // Split a set of buffers into several sets, each of which contains buffers
756
+ // colored with the same color.
757
+ absl::flat_hash_map<LogicalBuffer::Color,
758
+ absl::flat_hash_set<const HloValue*>>
759
+ SplitBuffersByColor(
760
+ const absl::flat_hash_set<const HloValue*>& buffers) const;
761
+
762
+ // Split a set of buffers into several sets, each of which contains buffers
763
+ // with defining instructions that are dominated by the given private stack
764
+ // computation. This function CHECK-fails if there are outstanding buffers
765
+ // that do not have a dominating private stack computation.
766
+ absl::flat_hash_map<const HloComputation*,
767
+ absl::flat_hash_set<const HloValue*>>
768
+ SplitBuffersByPrivateStackComputation(
769
+ const absl::flat_hash_set<const HloValue*>& buffers,
770
+ absl::Span<const HloComputation* const> private_stack_computations,
771
+ const CallGraph& call_graph) const;
772
+
773
+ // If true, allocate buffers for constant instructions.
774
+ bool allocate_buffers_for_constants_;
775
+
776
+ // Functor used to assign colors to newly allocated logical buffers.
777
+ Colorer colorer_;
778
+
779
+ // An optional function that returns true if the given instruction can't live
780
+ // out of a computation.
781
+ std::optional<MustNotLiveOut> must_not_live_out_;
782
+
783
+ // Description of any buffer offsets that are already set by an earlier pass.
784
+ std::unique_ptr<memory_space_assignment::PresetAssignments>
785
+ preset_assignments_;
786
+
787
+ BufferAssigner(const BufferAssigner&) = delete;
788
+ BufferAssigner& operator=(const BufferAssigner&) = delete;
789
+ };
790
+
791
+ } // namespace xla
792
+
793
+ #endif // XLA_SERVICE_BUFFER_ASSIGNMENT_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_assignment.pb.h ADDED
@@ -0,0 +1,416 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Generated by the protocol buffer compiler. DO NOT EDIT!
2
+ // source: xla/service/buffer_assignment.proto
3
+
4
+ #ifndef GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fbuffer_5fassignment_2eproto
5
+ #define GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fbuffer_5fassignment_2eproto
6
+
7
+ #include <limits>
8
+ #include <string>
9
+
10
+ #include <google/protobuf/port_def.inc>
11
+ #if PROTOBUF_VERSION < 3021000
12
+ #error This file was generated by a newer version of protoc which is
13
+ #error incompatible with your Protocol Buffer headers. Please update
14
+ #error your headers.
15
+ #endif
16
+ #if 3021009 < PROTOBUF_MIN_PROTOC_VERSION
17
+ #error This file was generated by an older version of protoc which is
18
+ #error incompatible with your Protocol Buffer headers. Please
19
+ #error regenerate this file with a newer version of protoc.
20
+ #endif
21
+
22
+ #include <google/protobuf/port_undef.inc>
23
+ #include <google/protobuf/io/coded_stream.h>
24
+ #include <google/protobuf/arena.h>
25
+ #include <google/protobuf/arenastring.h>
26
+ #include <google/protobuf/generated_message_util.h>
27
+ #include <google/protobuf/metadata_lite.h>
28
+ #include <google/protobuf/generated_message_reflection.h>
29
+ #include <google/protobuf/message.h>
30
+ #include <google/protobuf/repeated_field.h> // IWYU pragma: export
31
+ #include <google/protobuf/extension_set.h> // IWYU pragma: export
32
+ #include <google/protobuf/unknown_field_set.h>
33
+ // @@protoc_insertion_point(includes)
34
+ #include <google/protobuf/port_def.inc>
35
+ #define PROTOBUF_INTERNAL_EXPORT_xla_2fservice_2fbuffer_5fassignment_2eproto
36
+ PROTOBUF_NAMESPACE_OPEN
37
+ namespace internal {
38
+ class AnyMetadata;
39
+ } // namespace internal
40
+ PROTOBUF_NAMESPACE_CLOSE
41
+
42
+ // Internal implementation detail -- do not use these members.
43
+ struct TableStruct_xla_2fservice_2fbuffer_5fassignment_2eproto {
44
+ static const uint32_t offsets[];
45
+ };
46
+ extern const ::PROTOBUF_NAMESPACE_ID::internal::DescriptorTable descriptor_table_xla_2fservice_2fbuffer_5fassignment_2eproto;
47
+ namespace xla {
48
+ namespace buffer_assignment {
49
+ class BufferIsolationConfig;
50
+ struct BufferIsolationConfigDefaultTypeInternal;
51
+ extern BufferIsolationConfigDefaultTypeInternal _BufferIsolationConfig_default_instance_;
52
+ } // namespace buffer_assignment
53
+ } // namespace xla
54
+ PROTOBUF_NAMESPACE_OPEN
55
+ template<> ::xla::buffer_assignment::BufferIsolationConfig* Arena::CreateMaybeMessage<::xla::buffer_assignment::BufferIsolationConfig>(Arena*);
56
+ PROTOBUF_NAMESPACE_CLOSE
57
+ namespace xla {
58
+ namespace buffer_assignment {
59
+
60
+ // ===================================================================
61
+
62
+ class BufferIsolationConfig final :
63
+ public ::PROTOBUF_NAMESPACE_ID::Message /* @@protoc_insertion_point(class_definition:xla.buffer_assignment.BufferIsolationConfig) */ {
64
+ public:
65
+ inline BufferIsolationConfig() : BufferIsolationConfig(nullptr) {}
66
+ ~BufferIsolationConfig() override;
67
+ explicit PROTOBUF_CONSTEXPR BufferIsolationConfig(::PROTOBUF_NAMESPACE_ID::internal::ConstantInitialized);
68
+
69
+ BufferIsolationConfig(const BufferIsolationConfig& from);
70
+ BufferIsolationConfig(BufferIsolationConfig&& from) noexcept
71
+ : BufferIsolationConfig() {
72
+ *this = ::std::move(from);
73
+ }
74
+
75
+ inline BufferIsolationConfig& operator=(const BufferIsolationConfig& from) {
76
+ CopyFrom(from);
77
+ return *this;
78
+ }
79
+ inline BufferIsolationConfig& operator=(BufferIsolationConfig&& from) noexcept {
80
+ if (this == &from) return *this;
81
+ if (GetOwningArena() == from.GetOwningArena()
82
+ #ifdef PROTOBUF_FORCE_COPY_IN_MOVE
83
+ && GetOwningArena() != nullptr
84
+ #endif // !PROTOBUF_FORCE_COPY_IN_MOVE
85
+ ) {
86
+ InternalSwap(&from);
87
+ } else {
88
+ CopyFrom(from);
89
+ }
90
+ return *this;
91
+ }
92
+
93
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* descriptor() {
94
+ return GetDescriptor();
95
+ }
96
+ static const ::PROTOBUF_NAMESPACE_ID::Descriptor* GetDescriptor() {
97
+ return default_instance().GetMetadata().descriptor;
98
+ }
99
+ static const ::PROTOBUF_NAMESPACE_ID::Reflection* GetReflection() {
100
+ return default_instance().GetMetadata().reflection;
101
+ }
102
+ static const BufferIsolationConfig& default_instance() {
103
+ return *internal_default_instance();
104
+ }
105
+ static inline const BufferIsolationConfig* internal_default_instance() {
106
+ return reinterpret_cast<const BufferIsolationConfig*>(
107
+ &_BufferIsolationConfig_default_instance_);
108
+ }
109
+ static constexpr int kIndexInFileMessages =
110
+ 0;
111
+
112
+ friend void swap(BufferIsolationConfig& a, BufferIsolationConfig& b) {
113
+ a.Swap(&b);
114
+ }
115
+ inline void Swap(BufferIsolationConfig* other) {
116
+ if (other == this) return;
117
+ #ifdef PROTOBUF_FORCE_COPY_IN_SWAP
118
+ if (GetOwningArena() != nullptr &&
119
+ GetOwningArena() == other->GetOwningArena()) {
120
+ #else // PROTOBUF_FORCE_COPY_IN_SWAP
121
+ if (GetOwningArena() == other->GetOwningArena()) {
122
+ #endif // !PROTOBUF_FORCE_COPY_IN_SWAP
123
+ InternalSwap(other);
124
+ } else {
125
+ ::PROTOBUF_NAMESPACE_ID::internal::GenericSwap(this, other);
126
+ }
127
+ }
128
+ void UnsafeArenaSwap(BufferIsolationConfig* other) {
129
+ if (other == this) return;
130
+ GOOGLE_DCHECK(GetOwningArena() == other->GetOwningArena());
131
+ InternalSwap(other);
132
+ }
133
+
134
+ // implements Message ----------------------------------------------
135
+
136
+ BufferIsolationConfig* New(::PROTOBUF_NAMESPACE_ID::Arena* arena = nullptr) const final {
137
+ return CreateMaybeMessage<BufferIsolationConfig>(arena);
138
+ }
139
+ using ::PROTOBUF_NAMESPACE_ID::Message::CopyFrom;
140
+ void CopyFrom(const BufferIsolationConfig& from);
141
+ using ::PROTOBUF_NAMESPACE_ID::Message::MergeFrom;
142
+ void MergeFrom( const BufferIsolationConfig& from) {
143
+ BufferIsolationConfig::MergeImpl(*this, from);
144
+ }
145
+ private:
146
+ static void MergeImpl(::PROTOBUF_NAMESPACE_ID::Message& to_msg, const ::PROTOBUF_NAMESPACE_ID::Message& from_msg);
147
+ public:
148
+ PROTOBUF_ATTRIBUTE_REINITIALIZES void Clear() final;
149
+ bool IsInitialized() const final;
150
+
151
+ size_t ByteSizeLong() const final;
152
+ const char* _InternalParse(const char* ptr, ::PROTOBUF_NAMESPACE_ID::internal::ParseContext* ctx) final;
153
+ uint8_t* _InternalSerialize(
154
+ uint8_t* target, ::PROTOBUF_NAMESPACE_ID::io::EpsCopyOutputStream* stream) const final;
155
+ int GetCachedSize() const final { return _impl_._cached_size_.Get(); }
156
+
157
+ private:
158
+ void SharedCtor(::PROTOBUF_NAMESPACE_ID::Arena* arena, bool is_message_owned);
159
+ void SharedDtor();
160
+ void SetCachedSize(int size) const final;
161
+ void InternalSwap(BufferIsolationConfig* other);
162
+
163
+ private:
164
+ friend class ::PROTOBUF_NAMESPACE_ID::internal::AnyMetadata;
165
+ static ::PROTOBUF_NAMESPACE_ID::StringPiece FullMessageName() {
166
+ return "xla.buffer_assignment.BufferIsolationConfig";
167
+ }
168
+ protected:
169
+ explicit BufferIsolationConfig(::PROTOBUF_NAMESPACE_ID::Arena* arena,
170
+ bool is_message_owned = false);
171
+ public:
172
+
173
+ static const ClassData _class_data_;
174
+ const ::PROTOBUF_NAMESPACE_ID::Message::ClassData*GetClassData() const final;
175
+
176
+ ::PROTOBUF_NAMESPACE_ID::Metadata GetMetadata() const final;
177
+
178
+ // nested types ----------------------------------------------------
179
+
180
+ // accessors -------------------------------------------------------
181
+
182
+ enum : int {
183
+ kIsolationColorsFieldNumber = 5,
184
+ kBaseOffsetBytesFieldNumber = 1,
185
+ kIsolationFuelFieldNumber = 2,
186
+ kIsolationPaddingBytesFieldNumber = 3,
187
+ kIsolationOrderSaltFieldNumber = 4,
188
+ };
189
+ // repeated int32 isolation_colors = 5;
190
+ int isolation_colors_size() const;
191
+ private:
192
+ int _internal_isolation_colors_size() const;
193
+ public:
194
+ void clear_isolation_colors();
195
+ private:
196
+ int32_t _internal_isolation_colors(int index) const;
197
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >&
198
+ _internal_isolation_colors() const;
199
+ void _internal_add_isolation_colors(int32_t value);
200
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >*
201
+ _internal_mutable_isolation_colors();
202
+ public:
203
+ int32_t isolation_colors(int index) const;
204
+ void set_isolation_colors(int index, int32_t value);
205
+ void add_isolation_colors(int32_t value);
206
+ const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >&
207
+ isolation_colors() const;
208
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >*
209
+ mutable_isolation_colors();
210
+
211
+ // int64 base_offset_bytes = 1;
212
+ void clear_base_offset_bytes();
213
+ int64_t base_offset_bytes() const;
214
+ void set_base_offset_bytes(int64_t value);
215
+ private:
216
+ int64_t _internal_base_offset_bytes() const;
217
+ void _internal_set_base_offset_bytes(int64_t value);
218
+ public:
219
+
220
+ // int64 isolation_fuel = 2;
221
+ void clear_isolation_fuel();
222
+ int64_t isolation_fuel() const;
223
+ void set_isolation_fuel(int64_t value);
224
+ private:
225
+ int64_t _internal_isolation_fuel() const;
226
+ void _internal_set_isolation_fuel(int64_t value);
227
+ public:
228
+
229
+ // int64 isolation_padding_bytes = 3;
230
+ void clear_isolation_padding_bytes();
231
+ int64_t isolation_padding_bytes() const;
232
+ void set_isolation_padding_bytes(int64_t value);
233
+ private:
234
+ int64_t _internal_isolation_padding_bytes() const;
235
+ void _internal_set_isolation_padding_bytes(int64_t value);
236
+ public:
237
+
238
+ // uint64 isolation_order_salt = 4;
239
+ void clear_isolation_order_salt();
240
+ uint64_t isolation_order_salt() const;
241
+ void set_isolation_order_salt(uint64_t value);
242
+ private:
243
+ uint64_t _internal_isolation_order_salt() const;
244
+ void _internal_set_isolation_order_salt(uint64_t value);
245
+ public:
246
+
247
+ // @@protoc_insertion_point(class_scope:xla.buffer_assignment.BufferIsolationConfig)
248
+ private:
249
+ class _Internal;
250
+
251
+ template <typename T> friend class ::PROTOBUF_NAMESPACE_ID::Arena::InternalHelper;
252
+ typedef void InternalArenaConstructable_;
253
+ typedef void DestructorSkippable_;
254
+ struct Impl_ {
255
+ ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t > isolation_colors_;
256
+ mutable std::atomic<int> _isolation_colors_cached_byte_size_;
257
+ int64_t base_offset_bytes_;
258
+ int64_t isolation_fuel_;
259
+ int64_t isolation_padding_bytes_;
260
+ uint64_t isolation_order_salt_;
261
+ mutable ::PROTOBUF_NAMESPACE_ID::internal::CachedSize _cached_size_;
262
+ };
263
+ union { Impl_ _impl_; };
264
+ friend struct ::TableStruct_xla_2fservice_2fbuffer_5fassignment_2eproto;
265
+ };
266
+ // ===================================================================
267
+
268
+
269
+ // ===================================================================
270
+
271
+ #ifdef __GNUC__
272
+ #pragma GCC diagnostic push
273
+ #pragma GCC diagnostic ignored "-Wstrict-aliasing"
274
+ #endif // __GNUC__
275
+ // BufferIsolationConfig
276
+
277
+ // int64 base_offset_bytes = 1;
278
+ inline void BufferIsolationConfig::clear_base_offset_bytes() {
279
+ _impl_.base_offset_bytes_ = int64_t{0};
280
+ }
281
+ inline int64_t BufferIsolationConfig::_internal_base_offset_bytes() const {
282
+ return _impl_.base_offset_bytes_;
283
+ }
284
+ inline int64_t BufferIsolationConfig::base_offset_bytes() const {
285
+ // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.base_offset_bytes)
286
+ return _internal_base_offset_bytes();
287
+ }
288
+ inline void BufferIsolationConfig::_internal_set_base_offset_bytes(int64_t value) {
289
+
290
+ _impl_.base_offset_bytes_ = value;
291
+ }
292
+ inline void BufferIsolationConfig::set_base_offset_bytes(int64_t value) {
293
+ _internal_set_base_offset_bytes(value);
294
+ // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.base_offset_bytes)
295
+ }
296
+
297
+ // int64 isolation_fuel = 2;
298
+ inline void BufferIsolationConfig::clear_isolation_fuel() {
299
+ _impl_.isolation_fuel_ = int64_t{0};
300
+ }
301
+ inline int64_t BufferIsolationConfig::_internal_isolation_fuel() const {
302
+ return _impl_.isolation_fuel_;
303
+ }
304
+ inline int64_t BufferIsolationConfig::isolation_fuel() const {
305
+ // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_fuel)
306
+ return _internal_isolation_fuel();
307
+ }
308
+ inline void BufferIsolationConfig::_internal_set_isolation_fuel(int64_t value) {
309
+
310
+ _impl_.isolation_fuel_ = value;
311
+ }
312
+ inline void BufferIsolationConfig::set_isolation_fuel(int64_t value) {
313
+ _internal_set_isolation_fuel(value);
314
+ // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_fuel)
315
+ }
316
+
317
+ // int64 isolation_padding_bytes = 3;
318
+ inline void BufferIsolationConfig::clear_isolation_padding_bytes() {
319
+ _impl_.isolation_padding_bytes_ = int64_t{0};
320
+ }
321
+ inline int64_t BufferIsolationConfig::_internal_isolation_padding_bytes() const {
322
+ return _impl_.isolation_padding_bytes_;
323
+ }
324
+ inline int64_t BufferIsolationConfig::isolation_padding_bytes() const {
325
+ // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_padding_bytes)
326
+ return _internal_isolation_padding_bytes();
327
+ }
328
+ inline void BufferIsolationConfig::_internal_set_isolation_padding_bytes(int64_t value) {
329
+
330
+ _impl_.isolation_padding_bytes_ = value;
331
+ }
332
+ inline void BufferIsolationConfig::set_isolation_padding_bytes(int64_t value) {
333
+ _internal_set_isolation_padding_bytes(value);
334
+ // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_padding_bytes)
335
+ }
336
+
337
+ // uint64 isolation_order_salt = 4;
338
+ inline void BufferIsolationConfig::clear_isolation_order_salt() {
339
+ _impl_.isolation_order_salt_ = uint64_t{0u};
340
+ }
341
+ inline uint64_t BufferIsolationConfig::_internal_isolation_order_salt() const {
342
+ return _impl_.isolation_order_salt_;
343
+ }
344
+ inline uint64_t BufferIsolationConfig::isolation_order_salt() const {
345
+ // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_order_salt)
346
+ return _internal_isolation_order_salt();
347
+ }
348
+ inline void BufferIsolationConfig::_internal_set_isolation_order_salt(uint64_t value) {
349
+
350
+ _impl_.isolation_order_salt_ = value;
351
+ }
352
+ inline void BufferIsolationConfig::set_isolation_order_salt(uint64_t value) {
353
+ _internal_set_isolation_order_salt(value);
354
+ // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_order_salt)
355
+ }
356
+
357
+ // repeated int32 isolation_colors = 5;
358
+ inline int BufferIsolationConfig::_internal_isolation_colors_size() const {
359
+ return _impl_.isolation_colors_.size();
360
+ }
361
+ inline int BufferIsolationConfig::isolation_colors_size() const {
362
+ return _internal_isolation_colors_size();
363
+ }
364
+ inline void BufferIsolationConfig::clear_isolation_colors() {
365
+ _impl_.isolation_colors_.Clear();
366
+ }
367
+ inline int32_t BufferIsolationConfig::_internal_isolation_colors(int index) const {
368
+ return _impl_.isolation_colors_.Get(index);
369
+ }
370
+ inline int32_t BufferIsolationConfig::isolation_colors(int index) const {
371
+ // @@protoc_insertion_point(field_get:xla.buffer_assignment.BufferIsolationConfig.isolation_colors)
372
+ return _internal_isolation_colors(index);
373
+ }
374
+ inline void BufferIsolationConfig::set_isolation_colors(int index, int32_t value) {
375
+ _impl_.isolation_colors_.Set(index, value);
376
+ // @@protoc_insertion_point(field_set:xla.buffer_assignment.BufferIsolationConfig.isolation_colors)
377
+ }
378
+ inline void BufferIsolationConfig::_internal_add_isolation_colors(int32_t value) {
379
+ _impl_.isolation_colors_.Add(value);
380
+ }
381
+ inline void BufferIsolationConfig::add_isolation_colors(int32_t value) {
382
+ _internal_add_isolation_colors(value);
383
+ // @@protoc_insertion_point(field_add:xla.buffer_assignment.BufferIsolationConfig.isolation_colors)
384
+ }
385
+ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >&
386
+ BufferIsolationConfig::_internal_isolation_colors() const {
387
+ return _impl_.isolation_colors_;
388
+ }
389
+ inline const ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >&
390
+ BufferIsolationConfig::isolation_colors() const {
391
+ // @@protoc_insertion_point(field_list:xla.buffer_assignment.BufferIsolationConfig.isolation_colors)
392
+ return _internal_isolation_colors();
393
+ }
394
+ inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >*
395
+ BufferIsolationConfig::_internal_mutable_isolation_colors() {
396
+ return &_impl_.isolation_colors_;
397
+ }
398
+ inline ::PROTOBUF_NAMESPACE_ID::RepeatedField< int32_t >*
399
+ BufferIsolationConfig::mutable_isolation_colors() {
400
+ // @@protoc_insertion_point(field_mutable_list:xla.buffer_assignment.BufferIsolationConfig.isolation_colors)
401
+ return _internal_mutable_isolation_colors();
402
+ }
403
+
404
+ #ifdef __GNUC__
405
+ #pragma GCC diagnostic pop
406
+ #endif // __GNUC__
407
+
408
+ // @@protoc_insertion_point(namespace_scope)
409
+
410
+ } // namespace buffer_assignment
411
+ } // namespace xla
412
+
413
+ // @@protoc_insertion_point(global_scope)
414
+
415
+ #include <google/protobuf/port_undef.inc>
416
+ #endif // GOOGLE_PROTOBUF_INCLUDED_GOOGLE_PROTOBUF_INCLUDED_xla_2fservice_2fbuffer_5fassignment_2eproto
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value.h ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef XLA_SERVICE_BUFFER_VALUE_H_
17
+ #define XLA_SERVICE_BUFFER_VALUE_H_
18
+
19
+ #include <functional>
20
+ #include <string>
21
+
22
+ #include "absl/types/span.h"
23
+ #include "xla/hlo/ir/hlo_instruction.h"
24
+ #include "xla/service/hlo.pb.h"
25
+ #include "xla/shape_util.h"
26
+ #include "xla/types.h"
27
+ #include "xla/xla_data.pb.h"
28
+ #include "tsl/platform/logging.h"
29
+
30
+ namespace xla {
31
+
32
+ // Abstract class describing a value used by one of the dataflow analyses -
33
+ // TuplePointsToAnalysis or HloDataflowAnalysis.
34
+ // TODO(b/78906445) Delete this class when TuplePointsToAnalysis is unused.
35
+ //
36
+ // XLA arrays are trivially a single BufferValue. Tuples are made up of more
37
+ // than one BufferValue: an BufferValue for the pointer vector, and an
38
+ // BufferValue for each child element.
39
+ //
40
+ // Every BufferValue is defined by a particular instruction and most
41
+ // instructions define only a single BufferValue. Instructions which define a
42
+ // single BufferValue include array-shaped instructions such as Add but also
43
+ // includes Tuple-shaped instructions such as Tuple. The Tuple instruction
44
+ // defines a single BufferValue which is a vector of pointers to the values
45
+ // containing the Tuple instruction's operands. Though the result of the Tuple
46
+ // instruction includes multiple values only the top-level BufferValue (the
47
+ // vector of pointers) is defined by the Tuple instruction. The values
48
+ // containing the tuple elements are defined by earlier instructions, usually
49
+ // the operands of the Tuple instruction.
50
+ //
51
+ // Instructions which construct both the tuple *and* the tuple elements define
52
+ // more than one BufferValue. This includes (at least) tuple-shaped Constant,
53
+ // Parameter, Infeed and While instructions. These tuple-shaped instructions do
54
+ // not assemble a tuple from existing BufferValues like the Tuple instruction
55
+ // does, but rather define all the BufferValues in the tuple.
56
+ //
57
+ // Some instructions, such as Bitcast, define no buffers. These instructions
58
+ // simply forward buffers from their operands.
59
+ //
60
+ // The BufferValue object describes which HLO instruction defines a buffer and
61
+ // where within that instruction's output shape the buffer is defined. The
62
+ // location within the output shape is indicated by BufferValue::index() which
63
+ // is defined identically to the index used in ShapeUtil::GetSubshape().
64
+ // Examples:
65
+ //
66
+ // %add = Add(%foo, %bar)
67
+ // %tuple_constant = Constant({1, {42, 43}})
68
+ //
69
+ // %add defines a single array-shaped buffer BufferValue(%add, {}) which holds
70
+ // the array result of the add operation. The nested-tuple-shaped
71
+ // %tuple_constant defines 5 buffers described by the following BufferValue
72
+ // objects:
73
+ //
74
+ // BufferValue(%tuple_constant, {}) // "Top-level" buffer: vector of
75
+ // // pointers to BufferValues at
76
+ // // indices {0} and {1}
77
+ // BufferValue(%tuple_constant, {0}) // Holds value "1"
78
+ // BufferValue(%tuple_constant, {1}) // Holds nested tuple: vector of
79
+ // // pointers to BufferValues at
80
+ // // indices {1, 0} and {1, 1}
81
+ // BufferValue(%tuple_constant, {1, 0}) // Holds value "42"
82
+ // BufferValue(%tuple_constant, {1, 1}) // Holds value "43"
83
+
84
+ class BufferValue {
85
+ public:
86
+ using Color = int64_t;
87
+
88
+ // Id is a unique identifier for the BufferValue to facilitate efficient
89
+ // collections of BufferValues with stable iteration order.
90
+ using Id = int64_t;
91
+
92
+ // Functions which return the size and alignment of a logical buffer in bytes.
93
+ using SizeFunction = std::function<int64_t(const BufferValue&)>;
94
+ using AlignmentFunction = std::function<int64_t(BufferValue::Color)>;
95
+
96
+ // Prevent value being copied, allowing comparison by pointer,
97
+ BufferValue(const BufferValue&) = delete;
98
+ BufferValue& operator=(const BufferValue&) = delete;
99
+ // ... but allow moves.
100
+ BufferValue(BufferValue&&) = default;
101
+ BufferValue& operator=(BufferValue&&) = default;
102
+
103
+ virtual ~BufferValue() {}
104
+
105
+ Id id() const { return id_; }
106
+
107
+ // Return the instruction that defines the buffer.
108
+ virtual HloInstruction* instruction() const = 0;
109
+
110
+ // Return the index within the output of the instruction where the buffer is
111
+ // defined. Index used defined as in ShapeUtil::GetSubshape()
112
+ virtual const ShapeIndex& index() const = 0;
113
+
114
+ // Return the color of the BufferValue. Differently colored buffers can not be
115
+ // parts of the same allocation.
116
+ ABSL_DEPRECATED("Use Layout::memory_space instead.")
117
+ Color color() const {
118
+ CHECK_NE(color_, kInvalidColor)
119
+ << "Should not query the color of a buffer that was never colored";
120
+ return color_;
121
+ }
122
+
123
+ ABSL_DEPRECATED("Use Layout::memory_space instead.")
124
+ void set_color(Color color) {
125
+ CHECK_NE(color, kInvalidColor)
126
+ << "Should not set the color of a buffer to the invalid color";
127
+ color_ = color;
128
+ }
129
+
130
+ ABSL_DEPRECATED("Use Layout::memory_space instead.")
131
+ bool has_color() const { return color_ != kInvalidColor; }
132
+
133
+ // Return the shape of the buffer. This reference points into the shape field
134
+ // of the instruction defining the buffer. Therefore, the returned shape will
135
+ // contain the layout of instruction, if any.
136
+ virtual const Shape& shape() const = 0;
137
+
138
+ // Returns true if this buffer is the top-level output buffer of the defining
139
+ // HLO instruction. This is equivalent to index == {}.
140
+ bool IsTopLevel() const { return index().empty(); }
141
+
142
+ // Whether this buffer contains a tuple.
143
+ bool IsTuple() const { return is_tuple_; }
144
+
145
+ // Whether this buffer contains an array.
146
+ bool IsArray() const { return is_array_; }
147
+
148
+ bool operator<(const BufferValue& other) const { return id_ < other.id_; }
149
+
150
+ virtual std::string ToString() const = 0;
151
+
152
+ // TODO(lauj) rename LogicalBufferProto to BufferValueProto.
153
+ LogicalBufferProto ToProto(const SizeFunction& size_fn) const;
154
+
155
+ // Returns the LogicalBufferProto::Location that serializes the given
156
+ // instruction and index.
157
+ static LogicalBufferProto::Location ToLocationProto(
158
+ const HloInstruction& instruction, const ShapeIndex& index);
159
+
160
+ static constexpr Color kInvalidColor = -1;
161
+
162
+ protected:
163
+ BufferValue(HloInstruction* instruction, const ShapeIndex& index, Id id);
164
+
165
+ private:
166
+ // The defining instruction and index are not stored here; they can be found
167
+ // in the LogicalBuffer and HloValue subclasses. This class exists only to
168
+ // support migrations from TuplePointsToAnalysis to HloDataflowAnalysis, by
169
+ // allowing abstract use of LogicalBuffer or HloValue. After those migrations
170
+ // are complete, this class should be deleted (b/78906445). Because we plan to
171
+ // delete LogicalBuffer and this class, we don't refactor all the shared
172
+ // features from LogicalBuffer and HloValue into this class.
173
+ Id id_ : 62;
174
+ bool is_array_ : 1;
175
+ bool is_tuple_ : 1;
176
+ Color color_ = kInvalidColor;
177
+ };
178
+
179
+ std::ostream& operator<<(std::ostream& out, const BufferValue& buffer);
180
+
181
+ } // namespace xla
182
+
183
+ #endif // XLA_SERVICE_BUFFER_VALUE_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/buffer_value_containers.h ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ #ifndef XLA_SERVICE_BUFFER_VALUE_CONTAINERS_H_
17
+ #define XLA_SERVICE_BUFFER_VALUE_CONTAINERS_H_
18
+
19
+ #include "absl/container/flat_hash_set.h"
20
+ #include "xla/service/buffer_value.h"
21
+ #include "xla/service/logical_buffer.h"
22
+ #include "tsl/lib/gtl/compactptrset.h"
23
+
24
+ namespace xla {
25
+
26
+ // Define various containers of BufferValues, and utilities to convert from
27
+ // containers of LogicalBuffers to containers of BufferValues.
28
+
29
+ using BufferValueCompactPointerSet =
30
+ tsl::gtl::CompactPointerSet<const BufferValue*>;
31
+ template <class LogicalBufferContainerT>
32
+ BufferValueCompactPointerSet ToBufferValueCompactPointerSet(
33
+ const LogicalBufferContainerT& logical_buffer_container) {
34
+ BufferValueCompactPointerSet output;
35
+ for (const LogicalBuffer* buffer : logical_buffer_container) {
36
+ output.insert(buffer);
37
+ }
38
+ return output;
39
+ }
40
+
41
+ using BufferValueFlatSet = absl::flat_hash_set<const BufferValue*>;
42
+ template <class LogicalBufferContainerT>
43
+ BufferValueFlatSet ToBufferValueFlatSet(
44
+ const LogicalBufferContainerT& logical_buffer_container) {
45
+ BufferValueFlatSet output;
46
+ output.reserve(logical_buffer_container.size());
47
+ for (const LogicalBuffer* buffer : logical_buffer_container) {
48
+ output.insert(buffer);
49
+ }
50
+ return output;
51
+ }
52
+
53
+ } // namespace xla
54
+
55
+ #endif // XLA_SERVICE_BUFFER_VALUE_CONTAINERS_H_
miniconda3/envs/active_proaction/lib/python3.10/site-packages/tensorflow/include/xla/service/call_graph.h ADDED
@@ -0,0 +1,386 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* Copyright 2017 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
+ // Call graph for an HLO module.
17
+
18
+ #ifndef XLA_SERVICE_CALL_GRAPH_H_
19
+ #define XLA_SERVICE_CALL_GRAPH_H_
20
+
21
+ #include <memory>
22
+ #include <ostream>
23
+
24
+ #include "absl/container/flat_hash_map.h"
25
+ #include "absl/container/flat_hash_set.h"
26
+ #include "absl/functional/function_ref.h"
27
+ #include "xla/hlo/ir/hlo_computation.h"
28
+ #include "xla/hlo/ir/hlo_instruction.h"
29
+ #include "xla/hlo/ir/hlo_module.h"
30
+
31
+ namespace xla {
32
+
33
+ // The context in which a computation is called by another computation.
34
+ enum class CallContext {
35
+ // In an embedded call context, the body of the function cannot allocate
36
+ // buffers.
37
+ kEmbedded,
38
+
39
+ // A control flow call context can allocate buffers.
40
+ kControlFlow,
41
+
42
+ // A computation is called from both an embedded and control flow context.
43
+ kBoth,
44
+
45
+ // During call graph construction kNone is used to indicate that the context
46
+ // has not been determined. This is the top value for the context
47
+ // lattice. After construction, no call sites or call graph nodes should have
48
+ // this value.
49
+ kNone
50
+ };
51
+
52
+ std::string CallContextToString(CallContext context);
53
+ std::ostream& operator<<(std::ostream& out, const CallContext& context);
54
+
55
+ CallContext GetInstructionCallContext(HloOpcode opcode);
56
+
57
+ // Represents an HLO instruction which calls one or more computations.
58
+ class CallSite {
59
+ public:
60
+ CallSite(HloInstruction* instruction,
61
+ absl::Span<HloComputation* const> called_computations,
62
+ CallContext context)
63
+ : instruction_(CHECK_NOTNULL(instruction)),
64
+ called_computations_(called_computations.begin(),
65
+ called_computations.end()),
66
+ context_(context) {}
67
+
68
+ // Returns the instruction associated with this call site.
69
+ HloInstruction* instruction() const { return instruction_; }
70
+
71
+ // Returns the computations called at this call site.
72
+ absl::Span<HloComputation* const> called_computations() const {
73
+ return called_computations_;
74
+ }
75
+
76
+ // Returns the context in which computations are called at this call site.
77
+ CallContext context() const { return context_; }
78
+
79
+ std::string ToString() const;
80
+
81
+ private:
82
+ // The calling instruction.
83
+ HloInstruction* instruction_;
84
+
85
+ // The computations called by this callsite.
86
+ const absl::InlinedVector<HloComputation*, 2> called_computations_;
87
+
88
+ // The context in which the computations are called.
89
+ const CallContext context_;
90
+ };
91
+
92
+ // A node in the call graph representing an HLO computation.
93
+ class CallGraphNode {
94
+ public:
95
+ explicit CallGraphNode(HloComputation* computation);
96
+
97
+ // Returns the computation represented by this call graph node.
98
+ HloComputation* computation() const { return computation_; }
99
+
100
+ // Returns the call sites in this computation. These are the instructions in
101
+ // this computation which call other computations.
102
+ absl::Span<const CallSite> callsites() const { return callsites_; }
103
+
104
+ // Returns the callsite associated with the given instruction. If this
105
+ // instruction calls no computations nullptr is returned.
106
+ // Prerequisite: instruction is in the computation associated with this call
107
+ // graph node.
108
+ const CallSite* GetCallSite(const HloInstruction* instruction) const;
109
+
110
+ // Returns the computations called by this computation.
111
+ absl::Span<HloComputation* const> callees() const { return callees_; }
112
+
113
+ // Returns the call sites in other computations which call this computation.
114
+ absl::Span<const CallSite> caller_callsites() const {
115
+ return caller_callsites_;
116
+ }
117
+
118
+ // Returns the computations which call this computation.
119
+ absl::Span<HloComputation* const> callers() const { return callers_; }
120
+
121
+ // Returns the context in which this computation is called.
122
+ CallContext context() const { return context_; }
123
+
124
+ // Returns the depth of this node in the call graph. The depth is defined as
125
+ // the length of the longest call chain from a computation with no callers
126
+ // (usually the entry computation node) to this node.
127
+ int depth() const { return depth_; }
128
+
129
+ absl::string_view ToString() const;
130
+
131
+ CallGraphNode(const CallGraphNode&) = delete;
132
+ CallGraphNode& operator=(const CallGraphNode&) = delete;
133
+ CallGraphNode(CallGraphNode&&) = default;
134
+ CallGraphNode& operator=(CallGraphNode&&) = default;
135
+
136
+ private:
137
+ // Only CallGraph can modify CallGraphNode.
138
+ friend class CallGraph;
139
+
140
+ // Sets the context in which this computation is called.
141
+ void set_context(CallContext value) { context_ = value; }
142
+
143
+ // Sets the depth of this node in the graph.
144
+ void set_depth(int value) { depth_ = value; }
145
+
146
+ // Adds a callsite which calls this computation. Updates callers to include
147
+ // the calling computation.
148
+ void AddCallerCallSite(const CallSite& caller_callsite);
149
+
150
+ // If instruction calls any computations adds a call site for this instruction
151
+ // to the call graph node. If the instruction calls no computations then no
152
+ // call site is added.
153
+ void AddCallSiteForInstruction(
154
+ HloInstruction* instruction,
155
+ const absl::flat_hash_set<absl::string_view>& execution_threads = {});
156
+
157
+ // Computation represented by this call graph node.
158
+ HloComputation* computation_;
159
+
160
+ // The computations called by this computation. The vector is used for a
161
+ // stable ordering and the set enables fast membership testing.
162
+ absl::InlinedVector<HloComputation*, 1> callees_;
163
+ absl::flat_hash_set<HloComputation*> callee_set_;
164
+
165
+ // The computations which call this computation. The vector is used for a
166
+ // stable ordering and the set enables fast membership testing.
167
+ absl::InlinedVector<HloComputation*, 1> callers_;
168
+ absl::flat_hash_set<HloComputation*> caller_set_;
169
+
170
+ // The call sites in this computation
171
+ absl::InlinedVector<CallSite, 1> callsites_;
172
+
173
+ // The map from instruction to index in callsites_ for looking up the callsite
174
+ // (if any) associated with a particular instruction in this computation.
175
+ absl::flat_hash_map<const HloInstruction*, int64_t> callsite_instructions_;
176
+
177
+ // The call sites in other computations which call this computation.
178
+ absl::InlinedVector<CallSite, 1> caller_callsites_;
179
+
180
+ // The context in which this computation is called.
181
+ CallContext context_ = CallContext::kNone;
182
+
183
+ // The depth of this node in the call graph.
184
+ int depth_ = 0;
185
+ };
186
+
187
+ // The call graph for an HLO module. The graph includes a node for each
188
+ // computation in the module.
189
+ class CallGraph {
190
+ public:
191
+ using VisitorFunction = absl::FunctionRef<Status(const CallGraphNode&)>;
192
+
193
+ // Builds and returns a call graph for the given HLO module. If a non-empty
194
+ // execution_threads is provided, only computations that are in
195
+ // execution_threads will be part of the returned call graph.
196
+ static std::unique_ptr<CallGraph> Build(
197
+ const HloModule* module,
198
+ const absl::flat_hash_set<absl::string_view>& execution_threads = {});
199
+
200
+ // Returns the node associated with the given computation.
201
+ const CallGraphNode& GetNode(const HloComputation* computation) const;
202
+ CallGraphNode& GetNode(const HloComputation* computation);
203
+
204
+ // Returns the vector of all nodes in the call graph.
205
+ const std::vector<CallGraphNode>& nodes() const { return nodes_; }
206
+
207
+ // Calls the given function on each node in the call graph. Nodes are visited
208
+ // in post order (callees before callers). If visit_unreachable_nodes is true
209
+ // then all nodes in the call graph are visited. Otherwise only those nodes
210
+ // reachable from the entry computation are visited.
211
+ Status VisitNodes(VisitorFunction visitor_func,
212
+ bool visit_unreachable_nodes = true) const;
213
+
214
+ // Returns true if 'a' dominates 'b' in the call graph. Computation 'a'
215
+ // dominates computation 'b' iff all callgraph paths in the caller-to-callee
216
+ // direction from a root computation to 'b' pass through computation
217
+ // 'a'. Trivially, a computation dominates itself.
218
+ bool Dominates(const HloComputation* a, const HloComputation* b) const;
219
+
220
+ // Returns whether 'instruction' is contained in 'computation' either directly
221
+ // ('instruction->parent' is 'computation') or indirectly ('computation'
222
+ // dominates 'instruction->parent' in the call graph).
223
+ bool InstructionIsNestedIn(const HloInstruction* instruction,
224
+ const HloComputation* computation) const {
225
+ return Dominates(computation, instruction->parent());
226
+ }
227
+
228
+ // Returns the nearest call graph ancestors of instructions 'a' and 'b' for
229
+ // which the ancestors are in the same computation. An instruction is an call
230
+ // graph ancestor of 'a' if the instruction calls the computation containing
231
+ // 'a' either directly or transitively. Degeneratively an instruction is an
232
+ // ancestor of itself. nullptr is returned if there is no common ancestor or
233
+ // if the caller chain of 'a' or 'b' diverges (has multiple callers) before
234
+ // the nearest common ancestor.
235
+ //
236
+ // Example:
237
+ //
238
+ // Entry computation:
239
+ // %x = Call(A, {Constant(42.0)})
240
+ // %y = Call(B, {%x})
241
+ //
242
+ // Computation A:
243
+ // %a = Negate(Param())
244
+ //
245
+ // Computation B:
246
+ // %b = Exp(Param());
247
+ //
248
+ // If called with %a and %b, this function would return (%x, %y). %x is an
249
+ // ancestor of %a, and %y is an ancestor of %b, and %x and %y are in the same
250
+ // computation.
251
+ std::pair<HloInstruction*, HloInstruction*> NearestAncestorsInSameComputation(
252
+ HloInstruction* a, HloInstruction* b) const;
253
+
254
+ // Given a set of instructions within a computation, returns nearest common
255
+ // ancestors as Hlo instructions (There could be multiple nearest common
256
+ // ancestors in a DAG). If the given instructions are not in the same
257
+ // computation, this function would report FAILURE.
258
+ //
259
+ // Unlike the `NearestAncestorsInSameComputation` defined above, it:
260
+ //
261
+ // (1) Only compute the nearest common ancestors within a computation, instead
262
+ // of across computations (that's the function
263
+ // `ComputationsNearestCommonAncestors` that defined below).
264
+ //
265
+ // (2) Takes in **a set of** Hlo instructions, instead of two Hlo
266
+ // instructions, and find their nearest common ancestors.
267
+ //
268
+ // Example:
269
+ //
270
+ // Computation A:
271
+ // %p0 = Param(0)
272
+ // %p1 = Param(1)
273
+ // %p2 = Param(2)
274
+ // %add0 = Add(%p0, %p1)
275
+ // %mul0 = Mul(%p1, %p2)
276
+ // %sub0 = Sub(%add0, %mul0)
277
+ //
278
+ // If called with {%p0, %p1}, this function would return {%add0}.
279
+ //
280
+ // Please check the detailed example in
281
+ // `CallGraphTest.NearestCommonAncestorInstructions`.
282
+ absl::flat_hash_set<const HloInstruction*> NearestCommonAncestorInstructions(
283
+ std::vector<const HloInstruction*> instructions);
284
+
285
+ // Given a set of computations within a module, returns nearest common
286
+ // ancestors as Hlo computations (There could be multiple nearest common
287
+ // ancestors in a DAG).
288
+ //
289
+ // Entry_computation:
290
+ // %x = Call(A, {Constant(42.0)})
291
+ // %y = Call(B, {%x})
292
+ //
293
+ // Computation_A:
294
+ // %a = Negate(Param())
295
+ //
296
+ // Computation_B:
297
+ // %b = Exp(Param());
298
+ //
299
+ // If called with {Computation_A, Computation_B}, this function would return
300
+ // {Entry_computation}.
301
+ //
302
+ // Please check the detailed example in
303
+ // `CallGraphTest.NearestCommonAncestorComputations`.
304
+ absl::flat_hash_set<const HloComputation*> NearestCommonAncestorComputations(
305
+ std::vector<const HloComputation*> computations);
306
+
307
+ // A template helper function that computes the nearest common ancestors among
308
+ // instructions/computations. `T` can be either `HloInstruction` or
309
+ // `HloComputation`. Computing nearest common ancestors are basically the same
310
+ // for HloInstruction and HloComputation. The only difference is that they
311
+ // require different ways to access the ancestors of one node. Specifically,
312
+ // the ancestors are users_instruction for instructions, and are
313
+ // caller_computations for computations.
314
+ //
315
+ // The overall idea is to conduct BFS from the `starting_nodes`, and keep
316
+ // track of the visited ancestors of each node. For each BFS step, we check if
317
+ // there is a common node in all the visited ancestors, and if yes, that
318
+ // common node is the nearest ancestor we are looking for. Note that, since we
319
+ // are traversing DAG, there could be multiple nearest common ancestors. And
320
+ // there must be at least one common ancestor (i.e., entry computations among
321
+ // computations or root instruction among instructions).
322
+ template <typename T>
323
+ absl::flat_hash_set<const T*> NearestCommonAncestorsHelper(
324
+ std::vector<const T*>& starting_nodes);
325
+
326
+ // Returns whether the call graph is flattened. A call graph is flattened if
327
+ // every computation called in a sequential context (eg, kWhile or kCall) has
328
+ // zero or one callsite, and no computation is called from both a parallel and
329
+ // sequential context. The call graph of a module can be flattened with
330
+ // FlattenCallGraph.
331
+ bool IsFlattened() const;
332
+
333
+ // Returns a vector of instructions calling the passed computation.
334
+ // (Often a vector of size 1.)
335
+ std::vector<HloInstruction*> GetComputationCallers(
336
+ const HloComputation* c) const;
337
+
338
+ std::string ToString() const;
339
+
340
+ private:
341
+ explicit CallGraph(
342
+ const HloModule* module,
343
+ const absl::flat_hash_set<absl::string_view>& execution_threads = {});
344
+
345
+ // Not copyable.
346
+ CallGraph(const CallGraph&) = delete;
347
+ CallGraph& operator=(const CallGraph&) = delete;
348
+
349
+ // Sets the call contexts for every node in the graph.
350
+ void SetCallContexts();
351
+
352
+ // Sets the call node depths for every node in the graph.
353
+ void SetNodeDepths();
354
+
355
+ // Helper method for VisitNodes(). Traverses the call graph from 'node' in DFS
356
+ // post order (callee before caller) calling visitor_func on each node. Adds
357
+ // nodes to 'visited' as each node is visited. Skips nodes already in
358
+ // 'visited'.
359
+ Status VisitNodesInternal(
360
+ VisitorFunction visitor_func, const CallGraphNode& node,
361
+ absl::flat_hash_set<const CallGraphNode*>* visited) const;
362
+
363
+ // Recursive helper for computing whether 'a' dominates 'b' in the call
364
+ // graph. 'b_ancestor' is the currently visited node (which starts at 'b'),
365
+ // and 'visited' is the set of computations which have been visited.
366
+ bool DominatesHelper(
367
+ const HloComputation* a, const HloComputation* b,
368
+ absl::flat_hash_set<const HloComputation*>* visited) const;
369
+
370
+ // The HLO module represented by this call graph.
371
+ const HloModule* module_ = nullptr;
372
+
373
+ // Vector of all nodes in the call graph.
374
+ std::vector<CallGraphNode> nodes_;
375
+
376
+ // Map from HLO computation to the index of the corresponding call graph node
377
+ // in nodes_.
378
+ absl::flat_hash_map<const HloComputation*, int64_t> node_indices_;
379
+
380
+ // The execution threads that the call graph is built for.
381
+ absl::flat_hash_set<absl::string_view> execution_threads_;
382
+ };
383
+
384
+ } // namespace xla
385
+
386
+ #endif // XLA_SERVICE_CALL_GRAPH_H_